Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
NullComparison
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
3 / 3
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 getSqlExpression
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Finder\Output;
6
7use Cosray\Context;
8use Cosray\Exception\ParserOutputException;
9use Cosray\Finder\Input\Token;
10use Cosray\Finder\Input\TokenType;
11
12final readonly class NullComparison extends Expression implements Output
13{
14    public function __construct(
15        private Token $left,
16        private Token $operator,
17        private Token $right,
18        private Context $context,
19        private array $builtins,
20    ) {}
21
22    public function get(): string
23    {
24        // Both compile to a subquery rather than to an operand, so there is
25        // nothing to put on the left of `IS NULL`.
26        foreach ([$this->left, $this->right] as $token) {
27            if ($token->type === TokenType::Path || $token->type === TokenType::Reference) {
28                throw new ParserOutputException(
29                    $token,
30                    'Path and reference expressions cannot be compared to null.',
31                );
32            }
33        }
34
35        switch ($this->operator->type) {
36            case TokenType::Equal:
37                return $this->getSqlExpression(true);
38            case TokenType::Unequal:
39                return $this->getSqlExpression(false);
40        }
41
42        throw new ParserOutputException(
43            $this->operator,
44            'Only equal (=) or unequal (!=) operators are allowed in queries with an null value.',
45        );
46    }
47
48    private function getSqlExpression(bool $equal): string
49    {
50        return sprintf(
51            '%s %s %s',
52            $this->getOperand($this->left, $this->context->db, $this->builtins, $this->context),
53            $equal ? 'IS' : 'IS NOT',
54            $this->getOperand($this->right, $this->context->db, $this->builtins, $this->context),
55        );
56    }
57}