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;
11use Override;
12
13final readonly class NullComparison extends Expression implements Output
14{
15    /** @param array<string, string> $builtins */
16    public function __construct(
17        private Token $left,
18        private Token $operator,
19        private Token $right,
20        private Context $context,
21        private array $builtins,
22    ) {}
23
24    #[Override]
25    public function get(): string
26    {
27        // Both compile to a subquery rather than to an operand, so there is
28        // nothing to put on the left of `IS NULL`.
29        foreach ([$this->left, $this->right] as $token) {
30            if ($token->type === TokenType::Path || $token->type === TokenType::Reference) {
31                throw new ParserOutputException(
32                    $token,
33                    'Path and reference expressions cannot be compared to null.',
34                );
35            }
36        }
37
38        switch ($this->operator->type) {
39            case TokenType::Equal:
40                return $this->getSqlExpression(true);
41            case TokenType::Unequal:
42                return $this->getSqlExpression(false);
43        }
44
45        throw new ParserOutputException(
46            $this->operator,
47            'Only equal (=) or unequal (!=) operators are allowed in queries with an null value.',
48        );
49    }
50
51    private function getSqlExpression(bool $equal): string
52    {
53        return sprintf(
54            '%s %s %s',
55            $this->getOperand($this->left, $this->context->db, $this->builtins, $this->context),
56            $equal ? 'IS' : 'IS NOT',
57            $this->getOperand($this->right, $this->context->db, $this->builtins, $this->context),
58        );
59    }
60}