vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php line 355

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM\Query;
  4. use Doctrine\Common\Lexer\Token;
  5. use Doctrine\Deprecations\Deprecation;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Doctrine\ORM\Mapping\ClassMetadata;
  8. use Doctrine\ORM\Query;
  9. use Doctrine\ORM\Query\AST\Functions;
  10. use LogicException;
  11. use ReflectionClass;
  12. use function array_intersect;
  13. use function array_search;
  14. use function assert;
  15. use function class_exists;
  16. use function count;
  17. use function explode;
  18. use function implode;
  19. use function in_array;
  20. use function interface_exists;
  21. use function is_string;
  22. use function sprintf;
  23. use function str_contains;
  24. use function strlen;
  25. use function strpos;
  26. use function strrpos;
  27. use function strtolower;
  28. use function substr;
  29. /**
  30.  * An LL(*) recursive-descent parser for the context-free grammar of the Doctrine Query Language.
  31.  * Parses a DQL query, reports any errors in it, and generates an AST.
  32.  *
  33.  * @psalm-import-type AssociationMapping from ClassMetadata
  34.  * @psalm-type DqlToken = Token<Lexer::T_*, string>
  35.  * @psalm-type QueryComponent = array{
  36.  *                 metadata?: ClassMetadata<object>,
  37.  *                 parent?: string|null,
  38.  *                 relation?: AssociationMapping|null,
  39.  *                 map?: string|null,
  40.  *                 resultVariable?: AST\Node|string,
  41.  *                 nestingLevel: int,
  42.  *                 token: DqlToken,
  43.  *             }
  44.  */
  45. class Parser
  46. {
  47.     /**
  48.      * @readonly Maps BUILT-IN string function names to AST class names.
  49.      * @psalm-var array<string, class-string<Functions\FunctionNode>>
  50.      */
  51.     private static $stringFunctions = [
  52.         'concat'    => Functions\ConcatFunction::class,
  53.         'substring' => Functions\SubstringFunction::class,
  54.         'trim'      => Functions\TrimFunction::class,
  55.         'lower'     => Functions\LowerFunction::class,
  56.         'upper'     => Functions\UpperFunction::class,
  57.         'identity'  => Functions\IdentityFunction::class,
  58.     ];
  59.     /**
  60.      * @readonly Maps BUILT-IN numeric function names to AST class names.
  61.      * @psalm-var array<string, class-string<Functions\FunctionNode>>
  62.      */
  63.     private static $numericFunctions = [
  64.         'length'    => Functions\LengthFunction::class,
  65.         'locate'    => Functions\LocateFunction::class,
  66.         'abs'       => Functions\AbsFunction::class,
  67.         'sqrt'      => Functions\SqrtFunction::class,
  68.         'mod'       => Functions\ModFunction::class,
  69.         'size'      => Functions\SizeFunction::class,
  70.         'date_diff' => Functions\DateDiffFunction::class,
  71.         'bit_and'   => Functions\BitAndFunction::class,
  72.         'bit_or'    => Functions\BitOrFunction::class,
  73.         // Aggregate functions
  74.         'min'       => Functions\MinFunction::class,
  75.         'max'       => Functions\MaxFunction::class,
  76.         'avg'       => Functions\AvgFunction::class,
  77.         'sum'       => Functions\SumFunction::class,
  78.         'count'     => Functions\CountFunction::class,
  79.     ];
  80.     /**
  81.      * @readonly Maps BUILT-IN datetime function names to AST class names.
  82.      * @psalm-var array<string, class-string<Functions\FunctionNode>>
  83.      */
  84.     private static $datetimeFunctions = [
  85.         'current_date'      => Functions\CurrentDateFunction::class,
  86.         'current_time'      => Functions\CurrentTimeFunction::class,
  87.         'current_timestamp' => Functions\CurrentTimestampFunction::class,
  88.         'date_add'          => Functions\DateAddFunction::class,
  89.         'date_sub'          => Functions\DateSubFunction::class,
  90.     ];
  91.     /*
  92.      * Expressions that were encountered during parsing of identifiers and expressions
  93.      * and still need to be validated.
  94.      */
  95.     /** @psalm-var list<array{token: DqlToken|null, expression: mixed, nestingLevel: int}> */
  96.     private $deferredIdentificationVariables = [];
  97.     /** @psalm-var list<array{token: DqlToken|null, expression: AST\PartialObjectExpression, nestingLevel: int}> */
  98.     private $deferredPartialObjectExpressions = [];
  99.     /** @psalm-var list<array{token: DqlToken|null, expression: AST\PathExpression, nestingLevel: int}> */
  100.     private $deferredPathExpressions = [];
  101.     /** @psalm-var list<array{token: DqlToken|null, expression: mixed, nestingLevel: int}> */
  102.     private $deferredResultVariables = [];
  103.     /** @psalm-var list<array{token: DqlToken|null, expression: AST\NewObjectExpression, nestingLevel: int}> */
  104.     private $deferredNewObjectExpressions = [];
  105.     /**
  106.      * The lexer.
  107.      *
  108.      * @var Lexer
  109.      */
  110.     private $lexer;
  111.     /**
  112.      * The parser result.
  113.      *
  114.      * @var ParserResult
  115.      */
  116.     private $parserResult;
  117.     /**
  118.      * The EntityManager.
  119.      *
  120.      * @var EntityManagerInterface
  121.      */
  122.     private $em;
  123.     /**
  124.      * The Query to parse.
  125.      *
  126.      * @var Query
  127.      */
  128.     private $query;
  129.     /**
  130.      * Map of declared query components in the parsed query.
  131.      *
  132.      * @psalm-var array<string, QueryComponent>
  133.      */
  134.     private $queryComponents = [];
  135.     /**
  136.      * Keeps the nesting level of defined ResultVariables.
  137.      *
  138.      * @var int
  139.      */
  140.     private $nestingLevel 0;
  141.     /**
  142.      * Any additional custom tree walkers that modify the AST.
  143.      *
  144.      * @psalm-var list<class-string<TreeWalker>>
  145.      */
  146.     private $customTreeWalkers = [];
  147.     /**
  148.      * The custom last tree walker, if any, that is responsible for producing the output.
  149.      *
  150.      * @var class-string<SqlWalker>|null
  151.      */
  152.     private $customOutputWalker;
  153.     /** @psalm-var array<string, AST\SelectExpression> */
  154.     private $identVariableExpressions = [];
  155.     /**
  156.      * Creates a new query parser object.
  157.      *
  158.      * @param Query $query The Query to parse.
  159.      */
  160.     public function __construct(Query $query)
  161.     {
  162.         $this->query        $query;
  163.         $this->em           $query->getEntityManager();
  164.         $this->lexer        = new Lexer((string) $query->getDQL());
  165.         $this->parserResult = new ParserResult();
  166.     }
  167.     /**
  168.      * Sets a custom tree walker that produces output.
  169.      * This tree walker will be run last over the AST, after any other walkers.
  170.      *
  171.      * @param string $className
  172.      * @psalm-param class-string<SqlWalker> $className
  173.      *
  174.      * @return void
  175.      */
  176.     public function setCustomOutputTreeWalker($className)
  177.     {
  178.         $this->customOutputWalker $className;
  179.     }
  180.     /**
  181.      * Adds a custom tree walker for modifying the AST.
  182.      *
  183.      * @param string $className
  184.      * @psalm-param class-string<TreeWalker> $className
  185.      *
  186.      * @return void
  187.      */
  188.     public function addCustomTreeWalker($className)
  189.     {
  190.         $this->customTreeWalkers[] = $className;
  191.     }
  192.     /**
  193.      * Gets the lexer used by the parser.
  194.      *
  195.      * @return Lexer
  196.      */
  197.     public function getLexer()
  198.     {
  199.         return $this->lexer;
  200.     }
  201.     /**
  202.      * Gets the ParserResult that is being filled with information during parsing.
  203.      *
  204.      * @return ParserResult
  205.      */
  206.     public function getParserResult()
  207.     {
  208.         return $this->parserResult;
  209.     }
  210.     /**
  211.      * Gets the EntityManager used by the parser.
  212.      *
  213.      * @return EntityManagerInterface
  214.      */
  215.     public function getEntityManager()
  216.     {
  217.         return $this->em;
  218.     }
  219.     /**
  220.      * Parses and builds AST for the given Query.
  221.      *
  222.      * @return AST\SelectStatement|AST\UpdateStatement|AST\DeleteStatement
  223.      */
  224.     public function getAST()
  225.     {
  226.         // Parse & build AST
  227.         $AST $this->QueryLanguage();
  228.         // Process any deferred validations of some nodes in the AST.
  229.         // This also allows post-processing of the AST for modification purposes.
  230.         $this->processDeferredIdentificationVariables();
  231.         if ($this->deferredPartialObjectExpressions) {
  232.             $this->processDeferredPartialObjectExpressions();
  233.         }
  234.         if ($this->deferredPathExpressions) {
  235.             $this->processDeferredPathExpressions();
  236.         }
  237.         if ($this->deferredResultVariables) {
  238.             $this->processDeferredResultVariables();
  239.         }
  240.         if ($this->deferredNewObjectExpressions) {
  241.             $this->processDeferredNewObjectExpressions($AST);
  242.         }
  243.         $this->processRootEntityAliasSelected();
  244.         // TODO: Is there a way to remove this? It may impact the mixed hydration resultset a lot!
  245.         $this->fixIdentificationVariableOrder($AST);
  246.         return $AST;
  247.     }
  248.     /**
  249.      * Attempts to match the given token with the current lookahead token.
  250.      *
  251.      * If they match, updates the lookahead token; otherwise raises a syntax
  252.      * error.
  253.      *
  254.      * @param Lexer::T_* $token The token type.
  255.      *
  256.      * @return void
  257.      *
  258.      * @throws QueryException If the tokens don't match.
  259.      */
  260.     public function match($token)
  261.     {
  262.         $lookaheadType $this->lexer->lookahead->type ?? null;
  263.         // Short-circuit on first condition, usually types match
  264.         if ($lookaheadType === $token) {
  265.             $this->lexer->moveNext();
  266.             return;
  267.         }
  268.         // If parameter is not identifier (1-99) must be exact match
  269.         if ($token Lexer::T_IDENTIFIER) {
  270.             $this->syntaxError($this->lexer->getLiteral($token));
  271.         }
  272.         // If parameter is keyword (200+) must be exact match
  273.         if ($token Lexer::T_IDENTIFIER) {
  274.             $this->syntaxError($this->lexer->getLiteral($token));
  275.         }
  276.         // If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+)
  277.         if ($token === Lexer::T_IDENTIFIER && $lookaheadType Lexer::T_IDENTIFIER) {
  278.             $this->syntaxError($this->lexer->getLiteral($token));
  279.         }
  280.         $this->lexer->moveNext();
  281.     }
  282.     /**
  283.      * Frees this parser, enabling it to be reused.
  284.      *
  285.      * @param bool $deep     Whether to clean peek and reset errors.
  286.      * @param int  $position Position to reset.
  287.      *
  288.      * @return void
  289.      */
  290.     public function free($deep false$position 0)
  291.     {
  292.         // WARNING! Use this method with care. It resets the scanner!
  293.         $this->lexer->resetPosition($position);
  294.         // Deep = true cleans peek and also any previously defined errors
  295.         if ($deep) {
  296.             $this->lexer->resetPeek();
  297.         }
  298.         $this->lexer->token     null;
  299.         $this->lexer->lookahead null;
  300.     }
  301.     /**
  302.      * Parses a query string.
  303.      *
  304.      * @return ParserResult
  305.      */
  306.     public function parse()
  307.     {
  308.         $AST $this->getAST();
  309.         $customWalkers $this->query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
  310.         if ($customWalkers !== false) {
  311.             $this->customTreeWalkers $customWalkers;
  312.         }
  313.         $customOutputWalker $this->query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER);
  314.         if ($customOutputWalker !== false) {
  315.             $this->customOutputWalker $customOutputWalker;
  316.         }
  317.         // Run any custom tree walkers over the AST
  318.         if ($this->customTreeWalkers) {
  319.             $treeWalkerChain = new TreeWalkerChain($this->query$this->parserResult$this->queryComponents);
  320.             foreach ($this->customTreeWalkers as $walker) {
  321.                 $treeWalkerChain->addTreeWalker($walker);
  322.             }
  323.             switch (true) {
  324.                 case $AST instanceof AST\UpdateStatement:
  325.                     $treeWalkerChain->walkUpdateStatement($AST);
  326.                     break;
  327.                 case $AST instanceof AST\DeleteStatement:
  328.                     $treeWalkerChain->walkDeleteStatement($AST);
  329.                     break;
  330.                 case $AST instanceof AST\SelectStatement:
  331.                 default:
  332.                     $treeWalkerChain->walkSelectStatement($AST);
  333.             }
  334.             $this->queryComponents $treeWalkerChain->getQueryComponents();
  335.         }
  336.         $outputWalkerClass $this->customOutputWalker ?: SqlWalker::class;
  337.         $outputWalker      = new $outputWalkerClass($this->query$this->parserResult$this->queryComponents);
  338.         // Assign an SQL executor to the parser result
  339.         $this->parserResult->setSqlExecutor($outputWalker->getExecutor($AST));
  340.         return $this->parserResult;
  341.     }
  342.     /**
  343.      * Fixes order of identification variables.
  344.      *
  345.      * They have to appear in the select clause in the same order as the
  346.      * declarations (from ... x join ... y join ... z ...) appear in the query
  347.      * as the hydration process relies on that order for proper operation.
  348.      *
  349.      * @param AST\SelectStatement|AST\DeleteStatement|AST\UpdateStatement $AST
  350.      */
  351.     private function fixIdentificationVariableOrder(AST\Node $AST): void
  352.     {
  353.         if (count($this->identVariableExpressions) <= 1) {
  354.             return;
  355.         }
  356.         assert($AST instanceof AST\SelectStatement);
  357.         foreach ($this->queryComponents as $dqlAlias => $qComp) {
  358.             if (! isset($this->identVariableExpressions[$dqlAlias])) {
  359.                 continue;
  360.             }
  361.             $expr $this->identVariableExpressions[$dqlAlias];
  362.             $key  array_search($expr$AST->selectClause->selectExpressionstrue);
  363.             unset($AST->selectClause->selectExpressions[$key]);
  364.             $AST->selectClause->selectExpressions[] = $expr;
  365.         }
  366.     }
  367.     /**
  368.      * Generates a new syntax error.
  369.      *
  370.      * @param string       $expected Expected string.
  371.      * @param mixed[]|null $token    Got token.
  372.      * @psalm-param DqlToken|null $token
  373.      *
  374.      * @return void
  375.      * @psalm-return no-return
  376.      *
  377.      * @throws QueryException
  378.      */
  379.     public function syntaxError($expected ''$token null)
  380.     {
  381.         if ($token === null) {
  382.             $token $this->lexer->lookahead;
  383.         }
  384.         $tokenPos $token->position ?? '-1';
  385.         $message  sprintf('line 0, col %d: Error: '$tokenPos);
  386.         $message .= $expected !== '' sprintf('Expected %s, got '$expected) : 'Unexpected ';
  387.         $message .= $this->lexer->lookahead === null 'end of string.' sprintf("'%s'"$token->value);
  388.         throw QueryException::syntaxError($messageQueryException::dqlError($this->query->getDQL() ?? ''));
  389.     }
  390.     /**
  391.      * Generates a new semantical error.
  392.      *
  393.      * @param string       $message Optional message.
  394.      * @param mixed[]|null $token   Optional token.
  395.      * @psalm-param DqlToken|null $token
  396.      *
  397.      * @return void
  398.      * @psalm-return no-return
  399.      *
  400.      * @throws QueryException
  401.      */
  402.     public function semanticalError($message ''$token null)
  403.     {
  404.         if ($token === null) {
  405.             $token $this->lexer->lookahead ?? new Token('fake token'420);
  406.         }
  407.         // Minimum exposed chars ahead of token
  408.         $distance 12;
  409.         // Find a position of a final word to display in error string
  410.         $dql    $this->query->getDQL();
  411.         $length strlen($dql);
  412.         $pos    $token->position $distance;
  413.         $pos    strpos($dql' '$length $pos $pos $length);
  414.         $length $pos !== false $pos $token->position $distance;
  415.         $tokenPos $token->position $token->position '-1';
  416.         $tokenStr substr($dql$token->position$length);
  417.         // Building informative message
  418.         $message 'line 0, col ' $tokenPos " near '" $tokenStr "': Error: " $message;
  419.         throw QueryException::semanticalError($messageQueryException::dqlError($this->query->getDQL()));
  420.     }
  421.     /**
  422.      * Peeks beyond the matched closing parenthesis and returns the first token after that one.
  423.      *
  424.      * @param bool $resetPeek Reset peek after finding the closing parenthesis.
  425.      *
  426.      * @return mixed[]
  427.      * @psalm-return DqlToken|null
  428.      */
  429.     private function peekBeyondClosingParenthesis(bool $resetPeek true)
  430.     {
  431.         $token        $this->lexer->peek();
  432.         $numUnmatched 1;
  433.         while ($numUnmatched && $token !== null) {
  434.             switch ($token->type) {
  435.                 case Lexer::T_OPEN_PARENTHESIS:
  436.                     ++$numUnmatched;
  437.                     break;
  438.                 case Lexer::T_CLOSE_PARENTHESIS:
  439.                     --$numUnmatched;
  440.                     break;
  441.                 default:
  442.                     // Do nothing
  443.             }
  444.             $token $this->lexer->peek();
  445.         }
  446.         if ($resetPeek) {
  447.             $this->lexer->resetPeek();
  448.         }
  449.         return $token;
  450.     }
  451.     /**
  452.      * Checks if the given token indicates a mathematical operator.
  453.      *
  454.      * @psalm-param DqlToken|null $token
  455.      */
  456.     private function isMathOperator($token): bool
  457.     {
  458.         return $token !== null && in_array($token->type, [Lexer::T_PLUSLexer::T_MINUSLexer::T_DIVIDELexer::T_MULTIPLY], true);
  459.     }
  460.     /**
  461.      * Checks if the next-next (after lookahead) token starts a function.
  462.      *
  463.      * @return bool TRUE if the next-next tokens start a function, FALSE otherwise.
  464.      */
  465.     private function isFunction(): bool
  466.     {
  467.         assert($this->lexer->lookahead !== null);
  468.         $lookaheadType $this->lexer->lookahead->type;
  469.         $peek          $this->lexer->peek();
  470.         $this->lexer->resetPeek();
  471.         return $lookaheadType >= Lexer::T_IDENTIFIER && $peek !== null && $peek->type === Lexer::T_OPEN_PARENTHESIS;
  472.     }
  473.     /**
  474.      * Checks whether the given token type indicates an aggregate function.
  475.      *
  476.      * @psalm-param Lexer::T_* $tokenType
  477.      *
  478.      * @return bool TRUE if the token type is an aggregate function, FALSE otherwise.
  479.      */
  480.     private function isAggregateFunction(int $tokenType): bool
  481.     {
  482.         return in_array(
  483.             $tokenType,
  484.             [Lexer::T_AVGLexer::T_MINLexer::T_MAXLexer::T_SUMLexer::T_COUNT],
  485.             true
  486.         );
  487.     }
  488.     /**
  489.      * Checks whether the current lookahead token of the lexer has the type T_ALL, T_ANY or T_SOME.
  490.      */
  491.     private function isNextAllAnySome(): bool
  492.     {
  493.         assert($this->lexer->lookahead !== null);
  494.         return in_array(
  495.             $this->lexer->lookahead->type,
  496.             [Lexer::T_ALLLexer::T_ANYLexer::T_SOME],
  497.             true
  498.         );
  499.     }
  500.     /**
  501.      * Validates that the given <tt>IdentificationVariable</tt> is semantically correct.
  502.      * It must exist in query components list.
  503.      */
  504.     private function processDeferredIdentificationVariables(): void
  505.     {
  506.         foreach ($this->deferredIdentificationVariables as $deferredItem) {
  507.             $identVariable $deferredItem['expression'];
  508.             // Check if IdentificationVariable exists in queryComponents
  509.             if (! isset($this->queryComponents[$identVariable])) {
  510.                 $this->semanticalError(
  511.                     sprintf("'%s' is not defined."$identVariable),
  512.                     $deferredItem['token']
  513.                 );
  514.             }
  515.             $qComp $this->queryComponents[$identVariable];
  516.             // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
  517.             if (! isset($qComp['metadata'])) {
  518.                 $this->semanticalError(
  519.                     sprintf("'%s' does not point to a Class."$identVariable),
  520.                     $deferredItem['token']
  521.                 );
  522.             }
  523.             // Validate if identification variable nesting level is lower or equal than the current one
  524.             if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
  525.                 $this->semanticalError(
  526.                     sprintf("'%s' is used outside the scope of its declaration."$identVariable),
  527.                     $deferredItem['token']
  528.                 );
  529.             }
  530.         }
  531.     }
  532.     /**
  533.      * Validates that the given <tt>NewObjectExpression</tt>.
  534.      */
  535.     private function processDeferredNewObjectExpressions(AST\SelectStatement $AST): void
  536.     {
  537.         foreach ($this->deferredNewObjectExpressions as $deferredItem) {
  538.             $expression    $deferredItem['expression'];
  539.             $token         $deferredItem['token'];
  540.             $className     $expression->className;
  541.             $args          $expression->args;
  542.             $fromClassName $AST->fromClause->identificationVariableDeclarations[0]->rangeVariableDeclaration->abstractSchemaName ?? null;
  543.             // If the namespace is not given then assumes the first FROM entity namespace
  544.             if (! str_contains($className'\\') && ! class_exists($className) && is_string($fromClassName) && str_contains($fromClassName'\\')) {
  545.                 $namespace substr($fromClassName0strrpos($fromClassName'\\'));
  546.                 $fqcn      $namespace '\\' $className;
  547.                 if (class_exists($fqcn)) {
  548.                     $expression->className $fqcn;
  549.                     $className             $fqcn;
  550.                 }
  551.             }
  552.             if (! class_exists($className)) {
  553.                 $this->semanticalError(sprintf('Class "%s" is not defined.'$className), $token);
  554.             }
  555.             $class = new ReflectionClass($className);
  556.             if (! $class->isInstantiable()) {
  557.                 $this->semanticalError(sprintf('Class "%s" can not be instantiated.'$className), $token);
  558.             }
  559.             if ($class->getConstructor() === null) {
  560.                 $this->semanticalError(sprintf('Class "%s" has not a valid constructor.'$className), $token);
  561.             }
  562.             if ($class->getConstructor()->getNumberOfRequiredParameters() > count($args)) {
  563.                 $this->semanticalError(sprintf('Number of arguments does not match with "%s" constructor declaration.'$className), $token);
  564.             }
  565.         }
  566.     }
  567.     /**
  568.      * Validates that the given <tt>PartialObjectExpression</tt> is semantically correct.
  569.      * It must exist in query components list.
  570.      */
  571.     private function processDeferredPartialObjectExpressions(): void
  572.     {
  573.         foreach ($this->deferredPartialObjectExpressions as $deferredItem) {
  574.             $expr  $deferredItem['expression'];
  575.             $class $this->getMetadataForDqlAlias($expr->identificationVariable);
  576.             foreach ($expr->partialFieldSet as $field) {
  577.                 if (isset($class->fieldMappings[$field])) {
  578.                     continue;
  579.                 }
  580.                 if (
  581.                     isset($class->associationMappings[$field]) &&
  582.                     $class->associationMappings[$field]['isOwningSide'] &&
  583.                     $class->associationMappings[$field]['type'] & ClassMetadata::TO_ONE
  584.                 ) {
  585.                     continue;
  586.                 }
  587.                 $this->semanticalError(sprintf(
  588.                     "There is no mapped field named '%s' on class %s.",
  589.                     $field,
  590.                     $class->name
  591.                 ), $deferredItem['token']);
  592.             }
  593.             if (array_intersect($class->identifier$expr->partialFieldSet) !== $class->identifier) {
  594.                 $this->semanticalError(
  595.                     'The partial field selection of class ' $class->name ' must contain the identifier.',
  596.                     $deferredItem['token']
  597.                 );
  598.             }
  599.         }
  600.     }
  601.     /**
  602.      * Validates that the given <tt>ResultVariable</tt> is semantically correct.
  603.      * It must exist in query components list.
  604.      */
  605.     private function processDeferredResultVariables(): void
  606.     {
  607.         foreach ($this->deferredResultVariables as $deferredItem) {
  608.             $resultVariable $deferredItem['expression'];
  609.             // Check if ResultVariable exists in queryComponents
  610.             if (! isset($this->queryComponents[$resultVariable])) {
  611.                 $this->semanticalError(
  612.                     sprintf("'%s' is not defined."$resultVariable),
  613.                     $deferredItem['token']
  614.                 );
  615.             }
  616.             $qComp $this->queryComponents[$resultVariable];
  617.             // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
  618.             if (! isset($qComp['resultVariable'])) {
  619.                 $this->semanticalError(
  620.                     sprintf("'%s' does not point to a ResultVariable."$resultVariable),
  621.                     $deferredItem['token']
  622.                 );
  623.             }
  624.             // Validate if identification variable nesting level is lower or equal than the current one
  625.             if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
  626.                 $this->semanticalError(
  627.                     sprintf("'%s' is used outside the scope of its declaration."$resultVariable),
  628.                     $deferredItem['token']
  629.                 );
  630.             }
  631.         }
  632.     }
  633.     /**
  634.      * Validates that the given <tt>PathExpression</tt> is semantically correct for grammar rules:
  635.      *
  636.      * AssociationPathExpression             ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
  637.      * SingleValuedPathExpression            ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
  638.      * StateFieldPathExpression              ::= IdentificationVariable "." StateField
  639.      * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField
  640.      * CollectionValuedPathExpression        ::= IdentificationVariable "." CollectionValuedAssociationField
  641.      */
  642.     private function processDeferredPathExpressions(): void
  643.     {
  644.         foreach ($this->deferredPathExpressions as $deferredItem) {
  645.             $pathExpression $deferredItem['expression'];
  646.             $class $this->getMetadataForDqlAlias($pathExpression->identificationVariable);
  647.             $field $pathExpression->field;
  648.             if ($field === null) {
  649.                 $field $pathExpression->field $class->identifier[0];
  650.             }
  651.             // Check if field or association exists
  652.             if (! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) {
  653.                 $this->semanticalError(
  654.                     'Class ' $class->name ' has no field or association named ' $field,
  655.                     $deferredItem['token']
  656.                 );
  657.             }
  658.             $fieldType AST\PathExpression::TYPE_STATE_FIELD;
  659.             if (isset($class->associationMappings[$field])) {
  660.                 $assoc $class->associationMappings[$field];
  661.                 $fieldType $assoc['type'] & ClassMetadata::TO_ONE
  662.                     AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION
  663.                     AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION;
  664.             }
  665.             // Validate if PathExpression is one of the expected types
  666.             $expectedType $pathExpression->expectedType;
  667.             if (! ($expectedType $fieldType)) {
  668.                 // We need to recognize which was expected type(s)
  669.                 $expectedStringTypes = [];
  670.                 // Validate state field type
  671.                 if ($expectedType AST\PathExpression::TYPE_STATE_FIELD) {
  672.                     $expectedStringTypes[] = 'StateFieldPathExpression';
  673.                 }
  674.                 // Validate single valued association (*-to-one)
  675.                 if ($expectedType AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) {
  676.                     $expectedStringTypes[] = 'SingleValuedAssociationField';
  677.                 }
  678.                 // Validate single valued association (*-to-many)
  679.                 if ($expectedType AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION) {
  680.                     $expectedStringTypes[] = 'CollectionValuedAssociationField';
  681.                 }
  682.                 // Build the error message
  683.                 $semanticalError  'Invalid PathExpression. ';
  684.                 $semanticalError .= count($expectedStringTypes) === 1
  685.                     'Must be a ' $expectedStringTypes[0] . '.'
  686.                     implode(' or '$expectedStringTypes) . ' expected.';
  687.                 $this->semanticalError($semanticalError$deferredItem['token']);
  688.             }
  689.             // We need to force the type in PathExpression
  690.             $pathExpression->type $fieldType;
  691.         }
  692.     }
  693.     private function processRootEntityAliasSelected(): void
  694.     {
  695.         if (! count($this->identVariableExpressions)) {
  696.             return;
  697.         }
  698.         foreach ($this->identVariableExpressions as $dqlAlias => $expr) {
  699.             if (isset($this->queryComponents[$dqlAlias]) && ! isset($this->queryComponents[$dqlAlias]['parent'])) {
  700.                 return;
  701.             }
  702.         }
  703.         $this->semanticalError('Cannot select entity through identification variables without choosing at least one root entity alias.');
  704.     }
  705.     /**
  706.      * QueryLanguage ::= SelectStatement | UpdateStatement | DeleteStatement
  707.      *
  708.      * @return AST\SelectStatement|AST\UpdateStatement|AST\DeleteStatement
  709.      */
  710.     public function QueryLanguage()
  711.     {
  712.         $statement null;
  713.         $this->lexer->moveNext();
  714.         switch ($this->lexer->lookahead->type ?? null) {
  715.             case Lexer::T_SELECT:
  716.                 $statement $this->SelectStatement();
  717.                 break;
  718.             case Lexer::T_UPDATE:
  719.                 $statement $this->UpdateStatement();
  720.                 break;
  721.             case Lexer::T_DELETE:
  722.                 $statement $this->DeleteStatement();
  723.                 break;
  724.             default:
  725.                 $this->syntaxError('SELECT, UPDATE or DELETE');
  726.                 break;
  727.         }
  728.         // Check for end of string
  729.         if ($this->lexer->lookahead !== null) {
  730.             $this->syntaxError('end of string');
  731.         }
  732.         return $statement;
  733.     }
  734.     /**
  735.      * SelectStatement ::= SelectClause FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
  736.      *
  737.      * @return AST\SelectStatement
  738.      */
  739.     public function SelectStatement()
  740.     {
  741.         $selectStatement = new AST\SelectStatement($this->SelectClause(), $this->FromClause());
  742.         $selectStatement->whereClause   $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
  743.         $selectStatement->groupByClause $this->lexer->isNextToken(Lexer::T_GROUP) ? $this->GroupByClause() : null;
  744.         $selectStatement->havingClause  $this->lexer->isNextToken(Lexer::T_HAVING) ? $this->HavingClause() : null;
  745.         $selectStatement->orderByClause $this->lexer->isNextToken(Lexer::T_ORDER) ? $this->OrderByClause() : null;
  746.         return $selectStatement;
  747.     }
  748.     /**
  749.      * UpdateStatement ::= UpdateClause [WhereClause]
  750.      *
  751.      * @return AST\UpdateStatement
  752.      */
  753.     public function UpdateStatement()
  754.     {
  755.         $updateStatement = new AST\UpdateStatement($this->UpdateClause());
  756.         $updateStatement->whereClause $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
  757.         return $updateStatement;
  758.     }
  759.     /**
  760.      * DeleteStatement ::= DeleteClause [WhereClause]
  761.      *
  762.      * @return AST\DeleteStatement
  763.      */
  764.     public function DeleteStatement()
  765.     {
  766.         $deleteStatement = new AST\DeleteStatement($this->DeleteClause());
  767.         $deleteStatement->whereClause $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
  768.         return $deleteStatement;
  769.     }
  770.     /**
  771.      * IdentificationVariable ::= identifier
  772.      *
  773.      * @return string
  774.      */
  775.     public function IdentificationVariable()
  776.     {
  777.         $this->match(Lexer::T_IDENTIFIER);
  778.         assert($this->lexer->token !== null);
  779.         $identVariable $this->lexer->token->value;
  780.         $this->deferredIdentificationVariables[] = [
  781.             'expression'   => $identVariable,
  782.             'nestingLevel' => $this->nestingLevel,
  783.             'token'        => $this->lexer->token,
  784.         ];
  785.         return $identVariable;
  786.     }
  787.     /**
  788.      * AliasIdentificationVariable = identifier
  789.      *
  790.      * @return string
  791.      */
  792.     public function AliasIdentificationVariable()
  793.     {
  794.         $this->match(Lexer::T_IDENTIFIER);
  795.         assert($this->lexer->token !== null);
  796.         $aliasIdentVariable $this->lexer->token->value;
  797.         $exists             = isset($this->queryComponents[$aliasIdentVariable]);
  798.         if ($exists) {
  799.             $this->semanticalError(
  800.                 sprintf("'%s' is already defined."$aliasIdentVariable),
  801.                 $this->lexer->token
  802.             );
  803.         }
  804.         return $aliasIdentVariable;
  805.     }
  806.     /**
  807.      * AbstractSchemaName ::= fully_qualified_name | aliased_name | identifier
  808.      *
  809.      * @return string
  810.      */
  811.     public function AbstractSchemaName()
  812.     {
  813.         if ($this->lexer->isNextToken(Lexer::T_FULLY_QUALIFIED_NAME)) {
  814.             $this->match(Lexer::T_FULLY_QUALIFIED_NAME);
  815.             assert($this->lexer->token !== null);
  816.             return $this->lexer->token->value;
  817.         }
  818.         if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) {
  819.             $this->match(Lexer::T_IDENTIFIER);
  820.             assert($this->lexer->token !== null);
  821.             return $this->lexer->token->value;
  822.         }
  823.         $this->match(Lexer::T_ALIASED_NAME);
  824.         assert($this->lexer->token !== null);
  825.         Deprecation::trigger(
  826.             'doctrine/orm',
  827.             'https://github.com/doctrine/orm/issues/8818',
  828.             'Short namespace aliases such as "%s" are deprecated and will be removed in Doctrine ORM 3.0.',
  829.             $this->lexer->token->value
  830.         );
  831.         [$namespaceAlias$simpleClassName] = explode(':'$this->lexer->token->value);
  832.         return $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' $simpleClassName;
  833.     }
  834.     /**
  835.      * Validates an AbstractSchemaName, making sure the class exists.
  836.      *
  837.      * @param string $schemaName The name to validate.
  838.      *
  839.      * @throws QueryException if the name does not exist.
  840.      */
  841.     private function validateAbstractSchemaName(string $schemaName): void
  842.     {
  843.         assert($this->lexer->token !== null);
  844.         if (! (class_exists($schemaNametrue) || interface_exists($schemaNametrue))) {
  845.             $this->semanticalError(
  846.                 sprintf("Class '%s' is not defined."$schemaName),
  847.                 $this->lexer->token
  848.             );
  849.         }
  850.     }
  851.     /**
  852.      * AliasResultVariable ::= identifier
  853.      *
  854.      * @return string
  855.      */
  856.     public function AliasResultVariable()
  857.     {
  858.         $this->match(Lexer::T_IDENTIFIER);
  859.         assert($this->lexer->token !== null);
  860.         $resultVariable $this->lexer->token->value;
  861.         $exists         = isset($this->queryComponents[$resultVariable]);
  862.         if ($exists) {
  863.             $this->semanticalError(
  864.                 sprintf("'%s' is already defined."$resultVariable),
  865.                 $this->lexer->token
  866.             );
  867.         }
  868.         return $resultVariable;
  869.     }
  870.     /**
  871.      * ResultVariable ::= identifier
  872.      *
  873.      * @return string
  874.      */
  875.     public function ResultVariable()
  876.     {
  877.         $this->match(Lexer::T_IDENTIFIER);
  878.         assert($this->lexer->token !== null);
  879.         $resultVariable $this->lexer->token->value;
  880.         // Defer ResultVariable validation
  881.         $this->deferredResultVariables[] = [
  882.             'expression'   => $resultVariable,
  883.             'nestingLevel' => $this->nestingLevel,
  884.             'token'        => $this->lexer->token,
  885.         ];
  886.         return $resultVariable;
  887.     }
  888.     /**
  889.      * JoinAssociationPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField)
  890.      *
  891.      * @return AST\JoinAssociationPathExpression
  892.      */
  893.     public function JoinAssociationPathExpression()
  894.     {
  895.         $identVariable $this->IdentificationVariable();
  896.         if (! isset($this->queryComponents[$identVariable])) {
  897.             $this->semanticalError(
  898.                 'Identification Variable ' $identVariable ' used in join path expression but was not defined before.'
  899.             );
  900.         }
  901.         $this->match(Lexer::T_DOT);
  902.         $this->match(Lexer::T_IDENTIFIER);
  903.         assert($this->lexer->token !== null);
  904.         $field $this->lexer->token->value;
  905.         // Validate association field
  906.         $class $this->getMetadataForDqlAlias($identVariable);
  907.         if (! $class->hasAssociation($field)) {
  908.             $this->semanticalError('Class ' $class->name ' has no association named ' $field);
  909.         }
  910.         return new AST\JoinAssociationPathExpression($identVariable$field);
  911.     }
  912.     /**
  913.      * Parses an arbitrary path expression and defers semantical validation
  914.      * based on expected types.
  915.      *
  916.      * PathExpression ::= IdentificationVariable {"." identifier}*
  917.      *
  918.      * @param int $expectedTypes
  919.      * @psalm-param int-mask-of<AST\PathExpression::TYPE_*> $expectedTypes
  920.      *
  921.      * @return AST\PathExpression
  922.      */
  923.     public function PathExpression($expectedTypes)
  924.     {
  925.         $identVariable $this->IdentificationVariable();
  926.         $field         null;
  927.         assert($this->lexer->token !== null);
  928.         if ($this->lexer->isNextToken(Lexer::T_DOT)) {
  929.             $this->match(Lexer::T_DOT);
  930.             $this->match(Lexer::T_IDENTIFIER);
  931.             $field $this->lexer->token->value;
  932.             while ($this->lexer->isNextToken(Lexer::T_DOT)) {
  933.                 $this->match(Lexer::T_DOT);
  934.                 $this->match(Lexer::T_IDENTIFIER);
  935.                 $field .= '.' $this->lexer->token->value;
  936.             }
  937.         }
  938.         // Creating AST node
  939.         $pathExpr = new AST\PathExpression($expectedTypes$identVariable$field);
  940.         // Defer PathExpression validation if requested to be deferred
  941.         $this->deferredPathExpressions[] = [
  942.             'expression'   => $pathExpr,
  943.             'nestingLevel' => $this->nestingLevel,
  944.             'token'        => $this->lexer->token,
  945.         ];
  946.         return $pathExpr;
  947.     }
  948.     /**
  949.      * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
  950.      *
  951.      * @return AST\PathExpression
  952.      */
  953.     public function AssociationPathExpression()
  954.     {
  955.         return $this->PathExpression(
  956.             AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION |
  957.             AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION
  958.         );
  959.     }
  960.     /**
  961.      * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
  962.      *
  963.      * @return AST\PathExpression
  964.      */
  965.     public function SingleValuedPathExpression()
  966.     {
  967.         return $this->PathExpression(
  968.             AST\PathExpression::TYPE_STATE_FIELD |
  969.             AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION
  970.         );
  971.     }
  972.     /**
  973.      * StateFieldPathExpression ::= IdentificationVariable "." StateField
  974.      *
  975.      * @return AST\PathExpression
  976.      */
  977.     public function StateFieldPathExpression()
  978.     {
  979.         return $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD);
  980.     }
  981.     /**
  982.      * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField
  983.      *
  984.      * @return AST\PathExpression
  985.      */
  986.     public function SingleValuedAssociationPathExpression()
  987.     {
  988.         return $this->PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION);
  989.     }
  990.     /**
  991.      * CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField
  992.      *
  993.      * @return AST\PathExpression
  994.      */
  995.     public function CollectionValuedPathExpression()
  996.     {
  997.         return $this->PathExpression(AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION);
  998.     }
  999.     /**
  1000.      * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression}
  1001.      *
  1002.      * @return AST\SelectClause
  1003.      */
  1004.     public function SelectClause()
  1005.     {
  1006.         $isDistinct false;
  1007.         $this->match(Lexer::T_SELECT);
  1008.         // Check for DISTINCT
  1009.         if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
  1010.             $this->match(Lexer::T_DISTINCT);
  1011.             $isDistinct true;
  1012.         }
  1013.         // Process SelectExpressions (1..N)
  1014.         $selectExpressions   = [];
  1015.         $selectExpressions[] = $this->SelectExpression();
  1016.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1017.             $this->match(Lexer::T_COMMA);
  1018.             $selectExpressions[] = $this->SelectExpression();
  1019.         }
  1020.         return new AST\SelectClause($selectExpressions$isDistinct);
  1021.     }
  1022.     /**
  1023.      * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression
  1024.      *
  1025.      * @return AST\SimpleSelectClause
  1026.      */
  1027.     public function SimpleSelectClause()
  1028.     {
  1029.         $isDistinct false;
  1030.         $this->match(Lexer::T_SELECT);
  1031.         if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
  1032.             $this->match(Lexer::T_DISTINCT);
  1033.             $isDistinct true;
  1034.         }
  1035.         return new AST\SimpleSelectClause($this->SimpleSelectExpression(), $isDistinct);
  1036.     }
  1037.     /**
  1038.      * UpdateClause ::= "UPDATE" AbstractSchemaName ["AS"] AliasIdentificationVariable "SET" UpdateItem {"," UpdateItem}*
  1039.      *
  1040.      * @return AST\UpdateClause
  1041.      */
  1042.     public function UpdateClause()
  1043.     {
  1044.         $this->match(Lexer::T_UPDATE);
  1045.         assert($this->lexer->lookahead !== null);
  1046.         $token              $this->lexer->lookahead;
  1047.         $abstractSchemaName $this->AbstractSchemaName();
  1048.         $this->validateAbstractSchemaName($abstractSchemaName);
  1049.         if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1050.             $this->match(Lexer::T_AS);
  1051.         }
  1052.         $aliasIdentificationVariable $this->AliasIdentificationVariable();
  1053.         $class $this->em->getClassMetadata($abstractSchemaName);
  1054.         // Building queryComponent
  1055.         $queryComponent = [
  1056.             'metadata'     => $class,
  1057.             'parent'       => null,
  1058.             'relation'     => null,
  1059.             'map'          => null,
  1060.             'nestingLevel' => $this->nestingLevel,
  1061.             'token'        => $token,
  1062.         ];
  1063.         $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;
  1064.         $this->match(Lexer::T_SET);
  1065.         $updateItems   = [];
  1066.         $updateItems[] = $this->UpdateItem();
  1067.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1068.             $this->match(Lexer::T_COMMA);
  1069.             $updateItems[] = $this->UpdateItem();
  1070.         }
  1071.         $updateClause                              = new AST\UpdateClause($abstractSchemaName$updateItems);
  1072.         $updateClause->aliasIdentificationVariable $aliasIdentificationVariable;
  1073.         return $updateClause;
  1074.     }
  1075.     /**
  1076.      * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName ["AS"] AliasIdentificationVariable
  1077.      *
  1078.      * @return AST\DeleteClause
  1079.      */
  1080.     public function DeleteClause()
  1081.     {
  1082.         $this->match(Lexer::T_DELETE);
  1083.         if ($this->lexer->isNextToken(Lexer::T_FROM)) {
  1084.             $this->match(Lexer::T_FROM);
  1085.         }
  1086.         assert($this->lexer->lookahead !== null);
  1087.         $token              $this->lexer->lookahead;
  1088.         $abstractSchemaName $this->AbstractSchemaName();
  1089.         $this->validateAbstractSchemaName($abstractSchemaName);
  1090.         $deleteClause = new AST\DeleteClause($abstractSchemaName);
  1091.         if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1092.             $this->match(Lexer::T_AS);
  1093.         }
  1094.         $aliasIdentificationVariable $this->lexer->isNextToken(Lexer::T_IDENTIFIER)
  1095.             ? $this->AliasIdentificationVariable()
  1096.             : 'alias_should_have_been_set';
  1097.         $deleteClause->aliasIdentificationVariable $aliasIdentificationVariable;
  1098.         $class                                     $this->em->getClassMetadata($deleteClause->abstractSchemaName);
  1099.         // Building queryComponent
  1100.         $queryComponent = [
  1101.             'metadata'     => $class,
  1102.             'parent'       => null,
  1103.             'relation'     => null,
  1104.             'map'          => null,
  1105.             'nestingLevel' => $this->nestingLevel,
  1106.             'token'        => $token,
  1107.         ];
  1108.         $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;
  1109.         return $deleteClause;
  1110.     }
  1111.     /**
  1112.      * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}*
  1113.      *
  1114.      * @return AST\FromClause
  1115.      */
  1116.     public function FromClause()
  1117.     {
  1118.         $this->match(Lexer::T_FROM);
  1119.         $identificationVariableDeclarations   = [];
  1120.         $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();
  1121.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1122.             $this->match(Lexer::T_COMMA);
  1123.             $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();
  1124.         }
  1125.         return new AST\FromClause($identificationVariableDeclarations);
  1126.     }
  1127.     /**
  1128.      * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}*
  1129.      *
  1130.      * @return AST\SubselectFromClause
  1131.      */
  1132.     public function SubselectFromClause()
  1133.     {
  1134.         $this->match(Lexer::T_FROM);
  1135.         $identificationVariables   = [];
  1136.         $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
  1137.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1138.             $this->match(Lexer::T_COMMA);
  1139.             $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
  1140.         }
  1141.         return new AST\SubselectFromClause($identificationVariables);
  1142.     }
  1143.     /**
  1144.      * WhereClause ::= "WHERE" ConditionalExpression
  1145.      *
  1146.      * @return AST\WhereClause
  1147.      */
  1148.     public function WhereClause()
  1149.     {
  1150.         $this->match(Lexer::T_WHERE);
  1151.         return new AST\WhereClause($this->ConditionalExpression());
  1152.     }
  1153.     /**
  1154.      * HavingClause ::= "HAVING" ConditionalExpression
  1155.      *
  1156.      * @return AST\HavingClause
  1157.      */
  1158.     public function HavingClause()
  1159.     {
  1160.         $this->match(Lexer::T_HAVING);
  1161.         return new AST\HavingClause($this->ConditionalExpression());
  1162.     }
  1163.     /**
  1164.      * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}*
  1165.      *
  1166.      * @return AST\GroupByClause
  1167.      */
  1168.     public function GroupByClause()
  1169.     {
  1170.         $this->match(Lexer::T_GROUP);
  1171.         $this->match(Lexer::T_BY);
  1172.         $groupByItems = [$this->GroupByItem()];
  1173.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1174.             $this->match(Lexer::T_COMMA);
  1175.             $groupByItems[] = $this->GroupByItem();
  1176.         }
  1177.         return new AST\GroupByClause($groupByItems);
  1178.     }
  1179.     /**
  1180.      * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}*
  1181.      *
  1182.      * @return AST\OrderByClause
  1183.      */
  1184.     public function OrderByClause()
  1185.     {
  1186.         $this->match(Lexer::T_ORDER);
  1187.         $this->match(Lexer::T_BY);
  1188.         $orderByItems   = [];
  1189.         $orderByItems[] = $this->OrderByItem();
  1190.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1191.             $this->match(Lexer::T_COMMA);
  1192.             $orderByItems[] = $this->OrderByItem();
  1193.         }
  1194.         return new AST\OrderByClause($orderByItems);
  1195.     }
  1196.     /**
  1197.      * Subselect ::= SimpleSelectClause SubselectFromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
  1198.      *
  1199.      * @return AST\Subselect
  1200.      */
  1201.     public function Subselect()
  1202.     {
  1203.         // Increase query nesting level
  1204.         $this->nestingLevel++;
  1205.         $subselect = new AST\Subselect($this->SimpleSelectClause(), $this->SubselectFromClause());
  1206.         $subselect->whereClause   $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
  1207.         $subselect->groupByClause $this->lexer->isNextToken(Lexer::T_GROUP) ? $this->GroupByClause() : null;
  1208.         $subselect->havingClause  $this->lexer->isNextToken(Lexer::T_HAVING) ? $this->HavingClause() : null;
  1209.         $subselect->orderByClause $this->lexer->isNextToken(Lexer::T_ORDER) ? $this->OrderByClause() : null;
  1210.         // Decrease query nesting level
  1211.         $this->nestingLevel--;
  1212.         return $subselect;
  1213.     }
  1214.     /**
  1215.      * UpdateItem ::= SingleValuedPathExpression "=" NewValue
  1216.      *
  1217.      * @return AST\UpdateItem
  1218.      */
  1219.     public function UpdateItem()
  1220.     {
  1221.         $pathExpr $this->SingleValuedPathExpression();
  1222.         $this->match(Lexer::T_EQUALS);
  1223.         return new AST\UpdateItem($pathExpr$this->NewValue());
  1224.     }
  1225.     /**
  1226.      * GroupByItem ::= IdentificationVariable | ResultVariable | SingleValuedPathExpression
  1227.      *
  1228.      * @return string|AST\PathExpression
  1229.      */
  1230.     public function GroupByItem()
  1231.     {
  1232.         // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression
  1233.         $glimpse $this->lexer->glimpse();
  1234.         if ($glimpse !== null && $glimpse->type === Lexer::T_DOT) {
  1235.             return $this->SingleValuedPathExpression();
  1236.         }
  1237.         assert($this->lexer->lookahead !== null);
  1238.         // Still need to decide between IdentificationVariable or ResultVariable
  1239.         $lookaheadValue $this->lexer->lookahead->value;
  1240.         if (! isset($this->queryComponents[$lookaheadValue])) {
  1241.             $this->semanticalError('Cannot group by undefined identification or result variable.');
  1242.         }
  1243.         return isset($this->queryComponents[$lookaheadValue]['metadata'])
  1244.             ? $this->IdentificationVariable()
  1245.             : $this->ResultVariable();
  1246.     }
  1247.     /**
  1248.      * OrderByItem ::= (
  1249.      *      SimpleArithmeticExpression | SingleValuedPathExpression | CaseExpression |
  1250.      *      ScalarExpression | ResultVariable | FunctionDeclaration
  1251.      * ) ["ASC" | "DESC"]
  1252.      *
  1253.      * @return AST\OrderByItem
  1254.      */
  1255.     public function OrderByItem()
  1256.     {
  1257.         $this->lexer->peek(); // lookahead => '.'
  1258.         $this->lexer->peek(); // lookahead => token after '.'
  1259.         $peek $this->lexer->peek(); // lookahead => token after the token after the '.'
  1260.         $this->lexer->resetPeek();
  1261.         $glimpse $this->lexer->glimpse();
  1262.         assert($this->lexer->lookahead !== null);
  1263.         switch (true) {
  1264.             case $this->isMathOperator($peek):
  1265.                 $expr $this->SimpleArithmeticExpression();
  1266.                 break;
  1267.             case $glimpse !== null && $glimpse->type === Lexer::T_DOT:
  1268.                 $expr $this->SingleValuedPathExpression();
  1269.                 break;
  1270.             case $this->lexer->peek() && $this->isMathOperator($this->peekBeyondClosingParenthesis()):
  1271.                 $expr $this->ScalarExpression();
  1272.                 break;
  1273.             case $this->lexer->lookahead->type === Lexer::T_CASE:
  1274.                 $expr $this->CaseExpression();
  1275.                 break;
  1276.             case $this->isFunction():
  1277.                 $expr $this->FunctionDeclaration();
  1278.                 break;
  1279.             default:
  1280.                 $expr $this->ResultVariable();
  1281.                 break;
  1282.         }
  1283.         $type 'ASC';
  1284.         $item = new AST\OrderByItem($expr);
  1285.         switch (true) {
  1286.             case $this->lexer->isNextToken(Lexer::T_DESC):
  1287.                 $this->match(Lexer::T_DESC);
  1288.                 $type 'DESC';
  1289.                 break;
  1290.             case $this->lexer->isNextToken(Lexer::T_ASC):
  1291.                 $this->match(Lexer::T_ASC);
  1292.                 break;
  1293.             default:
  1294.                 // Do nothing
  1295.         }
  1296.         $item->type $type;
  1297.         return $item;
  1298.     }
  1299.     /**
  1300.      * NewValue ::= SimpleArithmeticExpression | StringPrimary | DatetimePrimary | BooleanPrimary |
  1301.      *      EnumPrimary | SimpleEntityExpression | "NULL"
  1302.      *
  1303.      * NOTE: Since it is not possible to correctly recognize individual types, here is the full
  1304.      * grammar that needs to be supported:
  1305.      *
  1306.      * NewValue ::= SimpleArithmeticExpression | "NULL"
  1307.      *
  1308.      * SimpleArithmeticExpression covers all *Primary grammar rules and also SimpleEntityExpression
  1309.      *
  1310.      * @return AST\ArithmeticExpression|AST\InputParameter|null
  1311.      */
  1312.     public function NewValue()
  1313.     {
  1314.         if ($this->lexer->isNextToken(Lexer::T_NULL)) {
  1315.             $this->match(Lexer::T_NULL);
  1316.             return null;
  1317.         }
  1318.         if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
  1319.             $this->match(Lexer::T_INPUT_PARAMETER);
  1320.             assert($this->lexer->token !== null);
  1321.             return new AST\InputParameter($this->lexer->token->value);
  1322.         }
  1323.         return $this->ArithmeticExpression();
  1324.     }
  1325.     /**
  1326.      * IdentificationVariableDeclaration ::= RangeVariableDeclaration [IndexBy] {Join}*
  1327.      *
  1328.      * @return AST\IdentificationVariableDeclaration
  1329.      */
  1330.     public function IdentificationVariableDeclaration()
  1331.     {
  1332.         $joins                    = [];
  1333.         $rangeVariableDeclaration $this->RangeVariableDeclaration();
  1334.         $indexBy                  $this->lexer->isNextToken(Lexer::T_INDEX)
  1335.             ? $this->IndexBy()
  1336.             : null;
  1337.         $rangeVariableDeclaration->isRoot true;
  1338.         while (
  1339.             $this->lexer->isNextToken(Lexer::T_LEFT) ||
  1340.             $this->lexer->isNextToken(Lexer::T_INNER) ||
  1341.             $this->lexer->isNextToken(Lexer::T_JOIN)
  1342.         ) {
  1343.             $joins[] = $this->Join();
  1344.         }
  1345.         return new AST\IdentificationVariableDeclaration(
  1346.             $rangeVariableDeclaration,
  1347.             $indexBy,
  1348.             $joins
  1349.         );
  1350.     }
  1351.     /**
  1352.      * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration
  1353.      *
  1354.      * {Internal note: WARNING: Solution is harder than a bare implementation.
  1355.      * Desired EBNF support:
  1356.      *
  1357.      * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration | (AssociationPathExpression ["AS"] AliasIdentificationVariable)
  1358.      *
  1359.      * It demands that entire SQL generation to become programmatical. This is
  1360.      * needed because association based subselect requires "WHERE" conditional
  1361.      * expressions to be injected, but there is no scope to do that. Only scope
  1362.      * accessible is "FROM", prohibiting an easy implementation without larger
  1363.      * changes.}
  1364.      *
  1365.      * @return AST\IdentificationVariableDeclaration
  1366.      */
  1367.     public function SubselectIdentificationVariableDeclaration()
  1368.     {
  1369.         /*
  1370.         NOT YET IMPLEMENTED!
  1371.         $glimpse = $this->lexer->glimpse();
  1372.         if ($glimpse->type == Lexer::T_DOT) {
  1373.             $associationPathExpression = $this->AssociationPathExpression();
  1374.             if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1375.                 $this->match(Lexer::T_AS);
  1376.             }
  1377.             $aliasIdentificationVariable = $this->AliasIdentificationVariable();
  1378.             $identificationVariable      = $associationPathExpression->identificationVariable;
  1379.             $field                       = $associationPathExpression->associationField;
  1380.             $class       = $this->queryComponents[$identificationVariable]['metadata'];
  1381.             $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']);
  1382.             // Building queryComponent
  1383.             $joinQueryComponent = array(
  1384.                 'metadata'     => $targetClass,
  1385.                 'parent'       => $identificationVariable,
  1386.                 'relation'     => $class->getAssociationMapping($field),
  1387.                 'map'          => null,
  1388.                 'nestingLevel' => $this->nestingLevel,
  1389.                 'token'        => $this->lexer->lookahead
  1390.             );
  1391.             $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;
  1392.             return new AST\SubselectIdentificationVariableDeclaration(
  1393.                 $associationPathExpression, $aliasIdentificationVariable
  1394.             );
  1395.         }
  1396.         */
  1397.         return $this->IdentificationVariableDeclaration();
  1398.     }
  1399.     /**
  1400.      * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN"
  1401.      *          (JoinAssociationDeclaration | RangeVariableDeclaration)
  1402.      *          ["WITH" ConditionalExpression]
  1403.      *
  1404.      * @return AST\Join
  1405.      */
  1406.     public function Join()
  1407.     {
  1408.         // Check Join type
  1409.         $joinType AST\Join::JOIN_TYPE_INNER;
  1410.         switch (true) {
  1411.             case $this->lexer->isNextToken(Lexer::T_LEFT):
  1412.                 $this->match(Lexer::T_LEFT);
  1413.                 $joinType AST\Join::JOIN_TYPE_LEFT;
  1414.                 // Possible LEFT OUTER join
  1415.                 if ($this->lexer->isNextToken(Lexer::T_OUTER)) {
  1416.                     $this->match(Lexer::T_OUTER);
  1417.                     $joinType AST\Join::JOIN_TYPE_LEFTOUTER;
  1418.                 }
  1419.                 break;
  1420.             case $this->lexer->isNextToken(Lexer::T_INNER):
  1421.                 $this->match(Lexer::T_INNER);
  1422.                 break;
  1423.             default:
  1424.                 // Do nothing
  1425.         }
  1426.         $this->match(Lexer::T_JOIN);
  1427.         $next $this->lexer->glimpse();
  1428.         assert($next !== null);
  1429.         $joinDeclaration $next->type === Lexer::T_DOT $this->JoinAssociationDeclaration() : $this->RangeVariableDeclaration();
  1430.         $adhocConditions $this->lexer->isNextToken(Lexer::T_WITH);
  1431.         $join            = new AST\Join($joinType$joinDeclaration);
  1432.         // Describe non-root join declaration
  1433.         if ($joinDeclaration instanceof AST\RangeVariableDeclaration) {
  1434.             $joinDeclaration->isRoot false;
  1435.         }
  1436.         // Check for ad-hoc Join conditions
  1437.         if ($adhocConditions) {
  1438.             $this->match(Lexer::T_WITH);
  1439.             $join->conditionalExpression $this->ConditionalExpression();
  1440.         }
  1441.         return $join;
  1442.     }
  1443.     /**
  1444.      * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable
  1445.      *
  1446.      * @return AST\RangeVariableDeclaration
  1447.      *
  1448.      * @throws QueryException
  1449.      */
  1450.     public function RangeVariableDeclaration()
  1451.     {
  1452.         if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS) && $this->lexer->glimpse()->type === Lexer::T_SELECT) {
  1453.             $this->semanticalError('Subquery is not supported here'$this->lexer->token);
  1454.         }
  1455.         $abstractSchemaName $this->AbstractSchemaName();
  1456.         $this->validateAbstractSchemaName($abstractSchemaName);
  1457.         if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1458.             $this->match(Lexer::T_AS);
  1459.         }
  1460.         assert($this->lexer->lookahead !== null);
  1461.         $token                       $this->lexer->lookahead;
  1462.         $aliasIdentificationVariable $this->AliasIdentificationVariable();
  1463.         $classMetadata               $this->em->getClassMetadata($abstractSchemaName);
  1464.         // Building queryComponent
  1465.         $queryComponent = [
  1466.             'metadata'     => $classMetadata,
  1467.             'parent'       => null,
  1468.             'relation'     => null,
  1469.             'map'          => null,
  1470.             'nestingLevel' => $this->nestingLevel,
  1471.             'token'        => $token,
  1472.         ];
  1473.         $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;
  1474.         return new AST\RangeVariableDeclaration($abstractSchemaName$aliasIdentificationVariable);
  1475.     }
  1476.     /**
  1477.      * JoinAssociationDeclaration ::= JoinAssociationPathExpression ["AS"] AliasIdentificationVariable [IndexBy]
  1478.      *
  1479.      * @return AST\JoinAssociationDeclaration
  1480.      */
  1481.     public function JoinAssociationDeclaration()
  1482.     {
  1483.         $joinAssociationPathExpression $this->JoinAssociationPathExpression();
  1484.         if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1485.             $this->match(Lexer::T_AS);
  1486.         }
  1487.         assert($this->lexer->lookahead !== null);
  1488.         $aliasIdentificationVariable $this->AliasIdentificationVariable();
  1489.         $indexBy                     $this->lexer->isNextToken(Lexer::T_INDEX) ? $this->IndexBy() : null;
  1490.         $identificationVariable $joinAssociationPathExpression->identificationVariable;
  1491.         $field                  $joinAssociationPathExpression->associationField;
  1492.         $class       $this->getMetadataForDqlAlias($identificationVariable);
  1493.         $targetClass $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']);
  1494.         // Building queryComponent
  1495.         $joinQueryComponent = [
  1496.             'metadata'     => $targetClass,
  1497.             'parent'       => $joinAssociationPathExpression->identificationVariable,
  1498.             'relation'     => $class->getAssociationMapping($field),
  1499.             'map'          => null,
  1500.             'nestingLevel' => $this->nestingLevel,
  1501.             'token'        => $this->lexer->lookahead,
  1502.         ];
  1503.         $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;
  1504.         return new AST\JoinAssociationDeclaration($joinAssociationPathExpression$aliasIdentificationVariable$indexBy);
  1505.     }
  1506.     /**
  1507.      * PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet
  1508.      * PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}"
  1509.      *
  1510.      * @return AST\PartialObjectExpression
  1511.      */
  1512.     public function PartialObjectExpression()
  1513.     {
  1514.         Deprecation::trigger(
  1515.             'doctrine/orm',
  1516.             'https://github.com/doctrine/orm/issues/8471',
  1517.             'PARTIAL syntax in DQL is deprecated.'
  1518.         );
  1519.         $this->match(Lexer::T_PARTIAL);
  1520.         $partialFieldSet = [];
  1521.         $identificationVariable $this->IdentificationVariable();
  1522.         $this->match(Lexer::T_DOT);
  1523.         $this->match(Lexer::T_OPEN_CURLY_BRACE);
  1524.         $this->match(Lexer::T_IDENTIFIER);
  1525.         assert($this->lexer->token !== null);
  1526.         $field $this->lexer->token->value;
  1527.         // First field in partial expression might be embeddable property
  1528.         while ($this->lexer->isNextToken(Lexer::T_DOT)) {
  1529.             $this->match(Lexer::T_DOT);
  1530.             $this->match(Lexer::T_IDENTIFIER);
  1531.             $field .= '.' $this->lexer->token->value;
  1532.         }
  1533.         $partialFieldSet[] = $field;
  1534.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1535.             $this->match(Lexer::T_COMMA);
  1536.             $this->match(Lexer::T_IDENTIFIER);
  1537.             $field $this->lexer->token->value;
  1538.             while ($this->lexer->isNextToken(Lexer::T_DOT)) {
  1539.                 $this->match(Lexer::T_DOT);
  1540.                 $this->match(Lexer::T_IDENTIFIER);
  1541.                 $field .= '.' $this->lexer->token->value;
  1542.             }
  1543.             $partialFieldSet[] = $field;
  1544.         }
  1545.         $this->match(Lexer::T_CLOSE_CURLY_BRACE);
  1546.         $partialObjectExpression = new AST\PartialObjectExpression($identificationVariable$partialFieldSet);
  1547.         // Defer PartialObjectExpression validation
  1548.         $this->deferredPartialObjectExpressions[] = [
  1549.             'expression'   => $partialObjectExpression,
  1550.             'nestingLevel' => $this->nestingLevel,
  1551.             'token'        => $this->lexer->token,
  1552.         ];
  1553.         return $partialObjectExpression;
  1554.     }
  1555.     /**
  1556.      * NewObjectExpression ::= "NEW" AbstractSchemaName "(" NewObjectArg {"," NewObjectArg}* ")"
  1557.      *
  1558.      * @return AST\NewObjectExpression
  1559.      */
  1560.     public function NewObjectExpression()
  1561.     {
  1562.         $this->match(Lexer::T_NEW);
  1563.         $className $this->AbstractSchemaName(); // note that this is not yet validated
  1564.         $token     $this->lexer->token;
  1565.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  1566.         $args[] = $this->NewObjectArg();
  1567.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1568.             $this->match(Lexer::T_COMMA);
  1569.             $args[] = $this->NewObjectArg();
  1570.         }
  1571.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  1572.         $expression = new AST\NewObjectExpression($className$args);
  1573.         // Defer NewObjectExpression validation
  1574.         $this->deferredNewObjectExpressions[] = [
  1575.             'token'        => $token,
  1576.             'expression'   => $expression,
  1577.             'nestingLevel' => $this->nestingLevel,
  1578.         ];
  1579.         return $expression;
  1580.     }
  1581.     /**
  1582.      * NewObjectArg ::= ScalarExpression | "(" Subselect ")"
  1583.      *
  1584.      * @return mixed
  1585.      */
  1586.     public function NewObjectArg()
  1587.     {
  1588.         assert($this->lexer->lookahead !== null);
  1589.         $token $this->lexer->lookahead;
  1590.         $peek  $this->lexer->glimpse();
  1591.         assert($peek !== null);
  1592.         if ($token->type === Lexer::T_OPEN_PARENTHESIS && $peek->type === Lexer::T_SELECT) {
  1593.             $this->match(Lexer::T_OPEN_PARENTHESIS);
  1594.             $expression $this->Subselect();
  1595.             $this->match(Lexer::T_CLOSE_PARENTHESIS);
  1596.             return $expression;
  1597.         }
  1598.         return $this->ScalarExpression();
  1599.     }
  1600.     /**
  1601.      * IndexBy ::= "INDEX" "BY" SingleValuedPathExpression
  1602.      *
  1603.      * @return AST\IndexBy
  1604.      */
  1605.     public function IndexBy()
  1606.     {
  1607.         $this->match(Lexer::T_INDEX);
  1608.         $this->match(Lexer::T_BY);
  1609.         $pathExpr $this->SingleValuedPathExpression();
  1610.         // Add the INDEX BY info to the query component
  1611.         $this->queryComponents[$pathExpr->identificationVariable]['map'] = $pathExpr->field;
  1612.         return new AST\IndexBy($pathExpr);
  1613.     }
  1614.     /**
  1615.      * ScalarExpression ::= SimpleArithmeticExpression | StringPrimary | DateTimePrimary |
  1616.      *                      StateFieldPathExpression | BooleanPrimary | CaseExpression |
  1617.      *                      InstanceOfExpression
  1618.      *
  1619.      * @return mixed One of the possible expressions or subexpressions.
  1620.      */
  1621.     public function ScalarExpression()
  1622.     {
  1623.         assert($this->lexer->token !== null);
  1624.         assert($this->lexer->lookahead !== null);
  1625.         $lookahead $this->lexer->lookahead->type;
  1626.         $peek      $this->lexer->glimpse();
  1627.         switch (true) {
  1628.             case $lookahead === Lexer::T_INTEGER:
  1629.             case $lookahead === Lexer::T_FLOAT:
  1630.             // SimpleArithmeticExpression : (- u.value ) or ( + u.value )  or ( - 1 ) or ( + 1 )
  1631.             case $lookahead === Lexer::T_MINUS:
  1632.             case $lookahead === Lexer::T_PLUS:
  1633.                 return $this->SimpleArithmeticExpression();
  1634.             case $lookahead === Lexer::T_STRING:
  1635.                 return $this->StringPrimary();
  1636.             case $lookahead === Lexer::T_TRUE:
  1637.             case $lookahead === Lexer::T_FALSE:
  1638.                 $this->match($lookahead);
  1639.                 return new AST\Literal(AST\Literal::BOOLEAN$this->lexer->token->value);
  1640.             case $lookahead === Lexer::T_INPUT_PARAMETER:
  1641.                 switch (true) {
  1642.                     case $this->isMathOperator($peek):
  1643.                         // :param + u.value
  1644.                         return $this->SimpleArithmeticExpression();
  1645.                     default:
  1646.                         return $this->InputParameter();
  1647.                 }
  1648.             case $lookahead === Lexer::T_CASE:
  1649.             case $lookahead === Lexer::T_COALESCE:
  1650.             case $lookahead === Lexer::T_NULLIF:
  1651.                 // Since NULLIF and COALESCE can be identified as a function,
  1652.                 // we need to check these before checking for FunctionDeclaration
  1653.                 return $this->CaseExpression();
  1654.             case $lookahead === Lexer::T_OPEN_PARENTHESIS:
  1655.                 return $this->SimpleArithmeticExpression();
  1656.             // this check must be done before checking for a filed path expression
  1657.             case $this->isFunction():
  1658.                 $this->lexer->peek(); // "("
  1659.                 switch (true) {
  1660.                     case $this->isMathOperator($this->peekBeyondClosingParenthesis()):
  1661.                         // SUM(u.id) + COUNT(u.id)
  1662.                         return $this->SimpleArithmeticExpression();
  1663.                     default:
  1664.                         // IDENTITY(u)
  1665.                         return $this->FunctionDeclaration();
  1666.                 }
  1667.                 break;
  1668.             // it is no function, so it must be a field path
  1669.             case $lookahead === Lexer::T_IDENTIFIER:
  1670.                 $this->lexer->peek(); // lookahead => '.'
  1671.                 $this->lexer->peek(); // lookahead => token after '.'
  1672.                 $peek $this->lexer->peek(); // lookahead => token after the token after the '.'
  1673.                 $this->lexer->resetPeek();
  1674.                 if ($this->isMathOperator($peek)) {
  1675.                     return $this->SimpleArithmeticExpression();
  1676.                 }
  1677.                 return $this->StateFieldPathExpression();
  1678.             default:
  1679.                 $this->syntaxError();
  1680.         }
  1681.     }
  1682.     /**
  1683.      * CaseExpression ::= GeneralCaseExpression | SimpleCaseExpression | CoalesceExpression | NullifExpression
  1684.      * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END"
  1685.      * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression
  1686.      * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END"
  1687.      * CaseOperand ::= StateFieldPathExpression | TypeDiscriminator
  1688.      * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression
  1689.      * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")"
  1690.      * NullifExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")"
  1691.      *
  1692.      * @return mixed One of the possible expressions or subexpressions.
  1693.      */
  1694.     public function CaseExpression()
  1695.     {
  1696.         assert($this->lexer->lookahead !== null);
  1697.         $lookahead $this->lexer->lookahead->type;
  1698.         switch ($lookahead) {
  1699.             case Lexer::T_NULLIF:
  1700.                 return $this->NullIfExpression();
  1701.             case Lexer::T_COALESCE:
  1702.                 return $this->CoalesceExpression();
  1703.             case Lexer::T_CASE:
  1704.                 $this->lexer->resetPeek();
  1705.                 $peek $this->lexer->peek();
  1706.                 assert($peek !== null);
  1707.                 if ($peek->type === Lexer::T_WHEN) {
  1708.                     return $this->GeneralCaseExpression();
  1709.                 }
  1710.                 return $this->SimpleCaseExpression();
  1711.             default:
  1712.                 // Do nothing
  1713.                 break;
  1714.         }
  1715.         $this->syntaxError();
  1716.     }
  1717.     /**
  1718.      * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")"
  1719.      *
  1720.      * @return AST\CoalesceExpression
  1721.      */
  1722.     public function CoalesceExpression()
  1723.     {
  1724.         $this->match(Lexer::T_COALESCE);
  1725.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  1726.         // Process ScalarExpressions (1..N)
  1727.         $scalarExpressions   = [];
  1728.         $scalarExpressions[] = $this->ScalarExpression();
  1729.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  1730.             $this->match(Lexer::T_COMMA);
  1731.             $scalarExpressions[] = $this->ScalarExpression();
  1732.         }
  1733.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  1734.         return new AST\CoalesceExpression($scalarExpressions);
  1735.     }
  1736.     /**
  1737.      * NullIfExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")"
  1738.      *
  1739.      * @return AST\NullIfExpression
  1740.      */
  1741.     public function NullIfExpression()
  1742.     {
  1743.         $this->match(Lexer::T_NULLIF);
  1744.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  1745.         $firstExpression $this->ScalarExpression();
  1746.         $this->match(Lexer::T_COMMA);
  1747.         $secondExpression $this->ScalarExpression();
  1748.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  1749.         return new AST\NullIfExpression($firstExpression$secondExpression);
  1750.     }
  1751.     /**
  1752.      * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END"
  1753.      *
  1754.      * @return AST\GeneralCaseExpression
  1755.      */
  1756.     public function GeneralCaseExpression()
  1757.     {
  1758.         $this->match(Lexer::T_CASE);
  1759.         // Process WhenClause (1..N)
  1760.         $whenClauses = [];
  1761.         do {
  1762.             $whenClauses[] = $this->WhenClause();
  1763.         } while ($this->lexer->isNextToken(Lexer::T_WHEN));
  1764.         $this->match(Lexer::T_ELSE);
  1765.         $scalarExpression $this->ScalarExpression();
  1766.         $this->match(Lexer::T_END);
  1767.         return new AST\GeneralCaseExpression($whenClauses$scalarExpression);
  1768.     }
  1769.     /**
  1770.      * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END"
  1771.      * CaseOperand ::= StateFieldPathExpression | TypeDiscriminator
  1772.      *
  1773.      * @return AST\SimpleCaseExpression
  1774.      */
  1775.     public function SimpleCaseExpression()
  1776.     {
  1777.         $this->match(Lexer::T_CASE);
  1778.         $caseOperand $this->StateFieldPathExpression();
  1779.         // Process SimpleWhenClause (1..N)
  1780.         $simpleWhenClauses = [];
  1781.         do {
  1782.             $simpleWhenClauses[] = $this->SimpleWhenClause();
  1783.         } while ($this->lexer->isNextToken(Lexer::T_WHEN));
  1784.         $this->match(Lexer::T_ELSE);
  1785.         $scalarExpression $this->ScalarExpression();
  1786.         $this->match(Lexer::T_END);
  1787.         return new AST\SimpleCaseExpression($caseOperand$simpleWhenClauses$scalarExpression);
  1788.     }
  1789.     /**
  1790.      * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression
  1791.      *
  1792.      * @return AST\WhenClause
  1793.      */
  1794.     public function WhenClause()
  1795.     {
  1796.         $this->match(Lexer::T_WHEN);
  1797.         $conditionalExpression $this->ConditionalExpression();
  1798.         $this->match(Lexer::T_THEN);
  1799.         return new AST\WhenClause($conditionalExpression$this->ScalarExpression());
  1800.     }
  1801.     /**
  1802.      * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression
  1803.      *
  1804.      * @return AST\SimpleWhenClause
  1805.      */
  1806.     public function SimpleWhenClause()
  1807.     {
  1808.         $this->match(Lexer::T_WHEN);
  1809.         $conditionalExpression $this->ScalarExpression();
  1810.         $this->match(Lexer::T_THEN);
  1811.         return new AST\SimpleWhenClause($conditionalExpression$this->ScalarExpression());
  1812.     }
  1813.     /**
  1814.      * SelectExpression ::= (
  1815.      *     IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration |
  1816.      *     PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression
  1817.      * ) [["AS"] ["HIDDEN"] AliasResultVariable]
  1818.      *
  1819.      * @return AST\SelectExpression
  1820.      */
  1821.     public function SelectExpression()
  1822.     {
  1823.         assert($this->lexer->lookahead !== null);
  1824.         $expression    null;
  1825.         $identVariable null;
  1826.         $peek          $this->lexer->glimpse();
  1827.         $lookaheadType $this->lexer->lookahead->type;
  1828.         assert($peek !== null);
  1829.         switch (true) {
  1830.             // ScalarExpression (u.name)
  1831.             case $lookaheadType === Lexer::T_IDENTIFIER && $peek->type === Lexer::T_DOT:
  1832.                 $expression $this->ScalarExpression();
  1833.                 break;
  1834.             // IdentificationVariable (u)
  1835.             case $lookaheadType === Lexer::T_IDENTIFIER && $peek->type !== Lexer::T_OPEN_PARENTHESIS:
  1836.                 $expression $identVariable $this->IdentificationVariable();
  1837.                 break;
  1838.             // CaseExpression (CASE ... or NULLIF(...) or COALESCE(...))
  1839.             case $lookaheadType === Lexer::T_CASE:
  1840.             case $lookaheadType === Lexer::T_COALESCE:
  1841.             case $lookaheadType === Lexer::T_NULLIF:
  1842.                 $expression $this->CaseExpression();
  1843.                 break;
  1844.             // DQL Function (SUM(u.value) or SUM(u.value) + 1)
  1845.             case $this->isFunction():
  1846.                 $this->lexer->peek(); // "("
  1847.                 switch (true) {
  1848.                     case $this->isMathOperator($this->peekBeyondClosingParenthesis()):
  1849.                         // SUM(u.id) + COUNT(u.id)
  1850.                         $expression $this->ScalarExpression();
  1851.                         break;
  1852.                     default:
  1853.                         // IDENTITY(u)
  1854.                         $expression $this->FunctionDeclaration();
  1855.                         break;
  1856.                 }
  1857.                 break;
  1858.             // PartialObjectExpression (PARTIAL u.{id, name})
  1859.             case $lookaheadType === Lexer::T_PARTIAL:
  1860.                 $expression    $this->PartialObjectExpression();
  1861.                 $identVariable $expression->identificationVariable;
  1862.                 break;
  1863.             // Subselect
  1864.             case $lookaheadType === Lexer::T_OPEN_PARENTHESIS && $peek->type === Lexer::T_SELECT:
  1865.                 $this->match(Lexer::T_OPEN_PARENTHESIS);
  1866.                 $expression $this->Subselect();
  1867.                 $this->match(Lexer::T_CLOSE_PARENTHESIS);
  1868.                 break;
  1869.             // Shortcut: ScalarExpression => SimpleArithmeticExpression
  1870.             case $lookaheadType === Lexer::T_OPEN_PARENTHESIS:
  1871.             case $lookaheadType === Lexer::T_INTEGER:
  1872.             case $lookaheadType === Lexer::T_STRING:
  1873.             case $lookaheadType === Lexer::T_FLOAT:
  1874.             // SimpleArithmeticExpression : (- u.value ) or ( + u.value )
  1875.             case $lookaheadType === Lexer::T_MINUS:
  1876.             case $lookaheadType === Lexer::T_PLUS:
  1877.                 $expression $this->SimpleArithmeticExpression();
  1878.                 break;
  1879.             // NewObjectExpression (New ClassName(id, name))
  1880.             case $lookaheadType === Lexer::T_NEW:
  1881.                 $expression $this->NewObjectExpression();
  1882.                 break;
  1883.             default:
  1884.                 $this->syntaxError(
  1885.                     'IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression',
  1886.                     $this->lexer->lookahead
  1887.                 );
  1888.         }
  1889.         // [["AS"] ["HIDDEN"] AliasResultVariable]
  1890.         $mustHaveAliasResultVariable false;
  1891.         if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1892.             $this->match(Lexer::T_AS);
  1893.             $mustHaveAliasResultVariable true;
  1894.         }
  1895.         $hiddenAliasResultVariable false;
  1896.         if ($this->lexer->isNextToken(Lexer::T_HIDDEN)) {
  1897.             $this->match(Lexer::T_HIDDEN);
  1898.             $hiddenAliasResultVariable true;
  1899.         }
  1900.         $aliasResultVariable null;
  1901.         if ($mustHaveAliasResultVariable || $this->lexer->isNextToken(Lexer::T_IDENTIFIER)) {
  1902.             assert($expression instanceof AST\Node || is_string($expression));
  1903.             $token               $this->lexer->lookahead;
  1904.             $aliasResultVariable $this->AliasResultVariable();
  1905.             // Include AliasResultVariable in query components.
  1906.             $this->queryComponents[$aliasResultVariable] = [
  1907.                 'resultVariable' => $expression,
  1908.                 'nestingLevel'   => $this->nestingLevel,
  1909.                 'token'          => $token,
  1910.             ];
  1911.         }
  1912.         // AST
  1913.         $expr = new AST\SelectExpression($expression$aliasResultVariable$hiddenAliasResultVariable);
  1914.         if ($identVariable) {
  1915.             $this->identVariableExpressions[$identVariable] = $expr;
  1916.         }
  1917.         return $expr;
  1918.     }
  1919.     /**
  1920.      * SimpleSelectExpression ::= (
  1921.      *      StateFieldPathExpression | IdentificationVariable | FunctionDeclaration |
  1922.      *      AggregateExpression | "(" Subselect ")" | ScalarExpression
  1923.      * ) [["AS"] AliasResultVariable]
  1924.      *
  1925.      * @return AST\SimpleSelectExpression
  1926.      */
  1927.     public function SimpleSelectExpression()
  1928.     {
  1929.         assert($this->lexer->lookahead !== null);
  1930.         $peek $this->lexer->glimpse();
  1931.         assert($peek !== null);
  1932.         switch ($this->lexer->lookahead->type) {
  1933.             case Lexer::T_IDENTIFIER:
  1934.                 switch (true) {
  1935.                     case $peek->type === Lexer::T_DOT:
  1936.                         $expression $this->StateFieldPathExpression();
  1937.                         return new AST\SimpleSelectExpression($expression);
  1938.                     case $peek->type !== Lexer::T_OPEN_PARENTHESIS:
  1939.                         $expression $this->IdentificationVariable();
  1940.                         return new AST\SimpleSelectExpression($expression);
  1941.                     case $this->isFunction():
  1942.                         // SUM(u.id) + COUNT(u.id)
  1943.                         if ($this->isMathOperator($this->peekBeyondClosingParenthesis())) {
  1944.                             return new AST\SimpleSelectExpression($this->ScalarExpression());
  1945.                         }
  1946.                         // COUNT(u.id)
  1947.                         if ($this->isAggregateFunction($this->lexer->lookahead->type)) {
  1948.                             return new AST\SimpleSelectExpression($this->AggregateExpression());
  1949.                         }
  1950.                         // IDENTITY(u)
  1951.                         return new AST\SimpleSelectExpression($this->FunctionDeclaration());
  1952.                     default:
  1953.                         // Do nothing
  1954.                 }
  1955.                 break;
  1956.             case Lexer::T_OPEN_PARENTHESIS:
  1957.                 if ($peek->type !== Lexer::T_SELECT) {
  1958.                     // Shortcut: ScalarExpression => SimpleArithmeticExpression
  1959.                     $expression $this->SimpleArithmeticExpression();
  1960.                     return new AST\SimpleSelectExpression($expression);
  1961.                 }
  1962.                 // Subselect
  1963.                 $this->match(Lexer::T_OPEN_PARENTHESIS);
  1964.                 $expression $this->Subselect();
  1965.                 $this->match(Lexer::T_CLOSE_PARENTHESIS);
  1966.                 return new AST\SimpleSelectExpression($expression);
  1967.             default:
  1968.                 // Do nothing
  1969.         }
  1970.         $this->lexer->peek();
  1971.         $expression $this->ScalarExpression();
  1972.         $expr       = new AST\SimpleSelectExpression($expression);
  1973.         if ($this->lexer->isNextToken(Lexer::T_AS)) {
  1974.             $this->match(Lexer::T_AS);
  1975.         }
  1976.         if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) {
  1977.             $token                             $this->lexer->lookahead;
  1978.             $resultVariable                    $this->AliasResultVariable();
  1979.             $expr->fieldIdentificationVariable $resultVariable;
  1980.             // Include AliasResultVariable in query components.
  1981.             $this->queryComponents[$resultVariable] = [
  1982.                 'resultvariable' => $expr,
  1983.                 'nestingLevel'   => $this->nestingLevel,
  1984.                 'token'          => $token,
  1985.             ];
  1986.         }
  1987.         return $expr;
  1988.     }
  1989.     /**
  1990.      * ConditionalExpression ::= ConditionalTerm {"OR" ConditionalTerm}*
  1991.      *
  1992.      * @return AST\ConditionalExpression|AST\ConditionalFactor|AST\ConditionalPrimary|AST\ConditionalTerm
  1993.      */
  1994.     public function ConditionalExpression()
  1995.     {
  1996.         $conditionalTerms   = [];
  1997.         $conditionalTerms[] = $this->ConditionalTerm();
  1998.         while ($this->lexer->isNextToken(Lexer::T_OR)) {
  1999.             $this->match(Lexer::T_OR);
  2000.             $conditionalTerms[] = $this->ConditionalTerm();
  2001.         }
  2002.         // Phase 1 AST optimization: Prevent AST\ConditionalExpression
  2003.         // if only one AST\ConditionalTerm is defined
  2004.         if (count($conditionalTerms) === 1) {
  2005.             return $conditionalTerms[0];
  2006.         }
  2007.         return new AST\ConditionalExpression($conditionalTerms);
  2008.     }
  2009.     /**
  2010.      * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}*
  2011.      *
  2012.      * @return AST\ConditionalFactor|AST\ConditionalPrimary|AST\ConditionalTerm
  2013.      */
  2014.     public function ConditionalTerm()
  2015.     {
  2016.         $conditionalFactors   = [];
  2017.         $conditionalFactors[] = $this->ConditionalFactor();
  2018.         while ($this->lexer->isNextToken(Lexer::T_AND)) {
  2019.             $this->match(Lexer::T_AND);
  2020.             $conditionalFactors[] = $this->ConditionalFactor();
  2021.         }
  2022.         // Phase 1 AST optimization: Prevent AST\ConditionalTerm
  2023.         // if only one AST\ConditionalFactor is defined
  2024.         if (count($conditionalFactors) === 1) {
  2025.             return $conditionalFactors[0];
  2026.         }
  2027.         return new AST\ConditionalTerm($conditionalFactors);
  2028.     }
  2029.     /**
  2030.      * ConditionalFactor ::= ["NOT"] ConditionalPrimary
  2031.      *
  2032.      * @return AST\ConditionalFactor|AST\ConditionalPrimary
  2033.      */
  2034.     public function ConditionalFactor()
  2035.     {
  2036.         $not false;
  2037.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2038.             $this->match(Lexer::T_NOT);
  2039.             $not true;
  2040.         }
  2041.         $conditionalPrimary $this->ConditionalPrimary();
  2042.         // Phase 1 AST optimization: Prevent AST\ConditionalFactor
  2043.         // if only one AST\ConditionalPrimary is defined
  2044.         if (! $not) {
  2045.             return $conditionalPrimary;
  2046.         }
  2047.         return new AST\ConditionalFactor($conditionalPrimary$not);
  2048.     }
  2049.     /**
  2050.      * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
  2051.      *
  2052.      * @return AST\ConditionalPrimary
  2053.      */
  2054.     public function ConditionalPrimary()
  2055.     {
  2056.         $condPrimary = new AST\ConditionalPrimary();
  2057.         if (! $this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
  2058.             $condPrimary->simpleConditionalExpression $this->SimpleConditionalExpression();
  2059.             return $condPrimary;
  2060.         }
  2061.         // Peek beyond the matching closing parenthesis ')'
  2062.         $peek $this->peekBeyondClosingParenthesis();
  2063.         if (
  2064.             $peek !== null && (
  2065.             in_array($peek->value, ['=''<''<=''<>''>''>=''!='], true) ||
  2066.             in_array($peek->type, [Lexer::T_NOTLexer::T_BETWEENLexer::T_LIKELexer::T_INLexer::T_ISLexer::T_EXISTS], true) ||
  2067.             $this->isMathOperator($peek)
  2068.             )
  2069.         ) {
  2070.             $condPrimary->simpleConditionalExpression $this->SimpleConditionalExpression();
  2071.             return $condPrimary;
  2072.         }
  2073.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  2074.         $condPrimary->conditionalExpression $this->ConditionalExpression();
  2075.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2076.         return $condPrimary;
  2077.     }
  2078.     /**
  2079.      * SimpleConditionalExpression ::=
  2080.      *      ComparisonExpression | BetweenExpression | LikeExpression |
  2081.      *      InExpression | NullComparisonExpression | ExistsExpression |
  2082.      *      EmptyCollectionComparisonExpression | CollectionMemberExpression |
  2083.      *      InstanceOfExpression
  2084.      *
  2085.      * @return (AST\BetweenExpression|
  2086.      *         AST\CollectionMemberExpression|
  2087.      *         AST\ComparisonExpression|
  2088.      *         AST\EmptyCollectionComparisonExpression|
  2089.      *         AST\ExistsExpression|
  2090.      *         AST\InExpression|
  2091.      *         AST\InstanceOfExpression|
  2092.      *         AST\LikeExpression|
  2093.      *         AST\NullComparisonExpression)
  2094.      */
  2095.     public function SimpleConditionalExpression()
  2096.     {
  2097.         assert($this->lexer->lookahead !== null);
  2098.         if ($this->lexer->isNextToken(Lexer::T_EXISTS)) {
  2099.             return $this->ExistsExpression();
  2100.         }
  2101.         $token     $this->lexer->lookahead;
  2102.         $peek      $this->lexer->glimpse();
  2103.         $lookahead $token;
  2104.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2105.             $token $this->lexer->glimpse();
  2106.         }
  2107.         assert($token !== null);
  2108.         assert($peek !== null);
  2109.         if ($token->type === Lexer::T_IDENTIFIER || $token->type === Lexer::T_INPUT_PARAMETER || $this->isFunction()) {
  2110.             // Peek beyond the matching closing parenthesis.
  2111.             $beyond $this->lexer->peek();
  2112.             switch ($peek->value) {
  2113.                 case '(':
  2114.                     // Peeks beyond the matched closing parenthesis.
  2115.                     $token $this->peekBeyondClosingParenthesis(false);
  2116.                     assert($token !== null);
  2117.                     if ($token->type === Lexer::T_NOT) {
  2118.                         $token $this->lexer->peek();
  2119.                         assert($token !== null);
  2120.                     }
  2121.                     if ($token->type === Lexer::T_IS) {
  2122.                         $lookahead $this->lexer->peek();
  2123.                     }
  2124.                     break;
  2125.                 default:
  2126.                     // Peek beyond the PathExpression or InputParameter.
  2127.                     $token $beyond;
  2128.                     while ($token->value === '.') {
  2129.                         $this->lexer->peek();
  2130.                         $token $this->lexer->peek();
  2131.                         assert($token !== null);
  2132.                     }
  2133.                     // Also peek beyond a NOT if there is one.
  2134.                     assert($token !== null);
  2135.                     if ($token->type === Lexer::T_NOT) {
  2136.                         $token $this->lexer->peek();
  2137.                         assert($token !== null);
  2138.                     }
  2139.                     // We need to go even further in case of IS (differentiate between NULL and EMPTY)
  2140.                     $lookahead $this->lexer->peek();
  2141.             }
  2142.             assert($lookahead !== null);
  2143.             // Also peek beyond a NOT if there is one.
  2144.             if ($lookahead->type === Lexer::T_NOT) {
  2145.                 $lookahead $this->lexer->peek();
  2146.             }
  2147.             $this->lexer->resetPeek();
  2148.         }
  2149.         if ($token->type === Lexer::T_BETWEEN) {
  2150.             return $this->BetweenExpression();
  2151.         }
  2152.         if ($token->type === Lexer::T_LIKE) {
  2153.             return $this->LikeExpression();
  2154.         }
  2155.         if ($token->type === Lexer::T_IN) {
  2156.             return $this->InExpression();
  2157.         }
  2158.         if ($token->type === Lexer::T_INSTANCE) {
  2159.             return $this->InstanceOfExpression();
  2160.         }
  2161.         if ($token->type === Lexer::T_MEMBER) {
  2162.             return $this->CollectionMemberExpression();
  2163.         }
  2164.         assert($lookahead !== null);
  2165.         if ($token->type === Lexer::T_IS && $lookahead->type === Lexer::T_NULL) {
  2166.             return $this->NullComparisonExpression();
  2167.         }
  2168.         if ($token->type === Lexer::T_IS && $lookahead->type === Lexer::T_EMPTY) {
  2169.             return $this->EmptyCollectionComparisonExpression();
  2170.         }
  2171.         return $this->ComparisonExpression();
  2172.     }
  2173.     /**
  2174.      * EmptyCollectionComparisonExpression ::= CollectionValuedPathExpression "IS" ["NOT"] "EMPTY"
  2175.      *
  2176.      * @return AST\EmptyCollectionComparisonExpression
  2177.      */
  2178.     public function EmptyCollectionComparisonExpression()
  2179.     {
  2180.         $pathExpression $this->CollectionValuedPathExpression();
  2181.         $this->match(Lexer::T_IS);
  2182.         $not false;
  2183.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2184.             $this->match(Lexer::T_NOT);
  2185.             $not true;
  2186.         }
  2187.         $this->match(Lexer::T_EMPTY);
  2188.         return new AST\EmptyCollectionComparisonExpression(
  2189.             $pathExpression,
  2190.             $not
  2191.         );
  2192.     }
  2193.     /**
  2194.      * CollectionMemberExpression ::= EntityExpression ["NOT"] "MEMBER" ["OF"] CollectionValuedPathExpression
  2195.      *
  2196.      * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
  2197.      * SimpleEntityExpression ::= IdentificationVariable | InputParameter
  2198.      *
  2199.      * @return AST\CollectionMemberExpression
  2200.      */
  2201.     public function CollectionMemberExpression()
  2202.     {
  2203.         $not        false;
  2204.         $entityExpr $this->EntityExpression();
  2205.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2206.             $this->match(Lexer::T_NOT);
  2207.             $not true;
  2208.         }
  2209.         $this->match(Lexer::T_MEMBER);
  2210.         if ($this->lexer->isNextToken(Lexer::T_OF)) {
  2211.             $this->match(Lexer::T_OF);
  2212.         }
  2213.         return new AST\CollectionMemberExpression(
  2214.             $entityExpr,
  2215.             $this->CollectionValuedPathExpression(),
  2216.             $not
  2217.         );
  2218.     }
  2219.     /**
  2220.      * Literal ::= string | char | integer | float | boolean
  2221.      *
  2222.      * @return AST\Literal
  2223.      */
  2224.     public function Literal()
  2225.     {
  2226.         assert($this->lexer->lookahead !== null);
  2227.         assert($this->lexer->token !== null);
  2228.         switch ($this->lexer->lookahead->type) {
  2229.             case Lexer::T_STRING:
  2230.                 $this->match(Lexer::T_STRING);
  2231.                 return new AST\Literal(AST\Literal::STRING$this->lexer->token->value);
  2232.             case Lexer::T_INTEGER:
  2233.             case Lexer::T_FLOAT:
  2234.                 $this->match(
  2235.                     $this->lexer->isNextToken(Lexer::T_INTEGER) ? Lexer::T_INTEGER Lexer::T_FLOAT
  2236.                 );
  2237.                 return new AST\Literal(AST\Literal::NUMERIC$this->lexer->token->value);
  2238.             case Lexer::T_TRUE:
  2239.             case Lexer::T_FALSE:
  2240.                 $this->match(
  2241.                     $this->lexer->isNextToken(Lexer::T_TRUE) ? Lexer::T_TRUE Lexer::T_FALSE
  2242.                 );
  2243.                 return new AST\Literal(AST\Literal::BOOLEAN$this->lexer->token->value);
  2244.             default:
  2245.                 $this->syntaxError('Literal');
  2246.         }
  2247.     }
  2248.     /**
  2249.      * InParameter ::= ArithmeticExpression | InputParameter
  2250.      *
  2251.      * @return AST\InputParameter|AST\ArithmeticExpression
  2252.      */
  2253.     public function InParameter()
  2254.     {
  2255.         assert($this->lexer->lookahead !== null);
  2256.         if ($this->lexer->lookahead->type === Lexer::T_INPUT_PARAMETER) {
  2257.             return $this->InputParameter();
  2258.         }
  2259.         return $this->ArithmeticExpression();
  2260.     }
  2261.     /**
  2262.      * InputParameter ::= PositionalParameter | NamedParameter
  2263.      *
  2264.      * @return AST\InputParameter
  2265.      */
  2266.     public function InputParameter()
  2267.     {
  2268.         $this->match(Lexer::T_INPUT_PARAMETER);
  2269.         assert($this->lexer->token !== null);
  2270.         return new AST\InputParameter($this->lexer->token->value);
  2271.     }
  2272.     /**
  2273.      * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")"
  2274.      *
  2275.      * @return AST\ArithmeticExpression
  2276.      */
  2277.     public function ArithmeticExpression()
  2278.     {
  2279.         $expr = new AST\ArithmeticExpression();
  2280.         if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
  2281.             $peek $this->lexer->glimpse();
  2282.             assert($peek !== null);
  2283.             if ($peek->type === Lexer::T_SELECT) {
  2284.                 $this->match(Lexer::T_OPEN_PARENTHESIS);
  2285.                 $expr->subselect $this->Subselect();
  2286.                 $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2287.                 return $expr;
  2288.             }
  2289.         }
  2290.         $expr->simpleArithmeticExpression $this->SimpleArithmeticExpression();
  2291.         return $expr;
  2292.     }
  2293.     /**
  2294.      * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}*
  2295.      *
  2296.      * @return AST\SimpleArithmeticExpression|AST\ArithmeticTerm
  2297.      */
  2298.     public function SimpleArithmeticExpression()
  2299.     {
  2300.         $terms   = [];
  2301.         $terms[] = $this->ArithmeticTerm();
  2302.         while (($isPlus $this->lexer->isNextToken(Lexer::T_PLUS)) || $this->lexer->isNextToken(Lexer::T_MINUS)) {
  2303.             $this->match($isPlus Lexer::T_PLUS Lexer::T_MINUS);
  2304.             assert($this->lexer->token !== null);
  2305.             $terms[] = $this->lexer->token->value;
  2306.             $terms[] = $this->ArithmeticTerm();
  2307.         }
  2308.         // Phase 1 AST optimization: Prevent AST\SimpleArithmeticExpression
  2309.         // if only one AST\ArithmeticTerm is defined
  2310.         if (count($terms) === 1) {
  2311.             return $terms[0];
  2312.         }
  2313.         return new AST\SimpleArithmeticExpression($terms);
  2314.     }
  2315.     /**
  2316.      * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}*
  2317.      *
  2318.      * @return AST\ArithmeticTerm
  2319.      */
  2320.     public function ArithmeticTerm()
  2321.     {
  2322.         $factors   = [];
  2323.         $factors[] = $this->ArithmeticFactor();
  2324.         while (($isMult $this->lexer->isNextToken(Lexer::T_MULTIPLY)) || $this->lexer->isNextToken(Lexer::T_DIVIDE)) {
  2325.             $this->match($isMult Lexer::T_MULTIPLY Lexer::T_DIVIDE);
  2326.             assert($this->lexer->token !== null);
  2327.             $factors[] = $this->lexer->token->value;
  2328.             $factors[] = $this->ArithmeticFactor();
  2329.         }
  2330.         // Phase 1 AST optimization: Prevent AST\ArithmeticTerm
  2331.         // if only one AST\ArithmeticFactor is defined
  2332.         if (count($factors) === 1) {
  2333.             return $factors[0];
  2334.         }
  2335.         return new AST\ArithmeticTerm($factors);
  2336.     }
  2337.     /**
  2338.      * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary
  2339.      *
  2340.      * @return AST\ArithmeticFactor
  2341.      */
  2342.     public function ArithmeticFactor()
  2343.     {
  2344.         $sign null;
  2345.         $isPlus $this->lexer->isNextToken(Lexer::T_PLUS);
  2346.         if ($isPlus || $this->lexer->isNextToken(Lexer::T_MINUS)) {
  2347.             $this->match($isPlus Lexer::T_PLUS Lexer::T_MINUS);
  2348.             $sign $isPlus;
  2349.         }
  2350.         $primary $this->ArithmeticPrimary();
  2351.         // Phase 1 AST optimization: Prevent AST\ArithmeticFactor
  2352.         // if only one AST\ArithmeticPrimary is defined
  2353.         if ($sign === null) {
  2354.             return $primary;
  2355.         }
  2356.         return new AST\ArithmeticFactor($primary$sign);
  2357.     }
  2358.     /**
  2359.      * ArithmeticPrimary ::= SingleValuedPathExpression | Literal | ParenthesisExpression
  2360.      *          | FunctionsReturningNumerics | AggregateExpression | FunctionsReturningStrings
  2361.      *          | FunctionsReturningDatetime | IdentificationVariable | ResultVariable
  2362.      *          | InputParameter | CaseExpression
  2363.      *
  2364.      * @return AST\Node|string
  2365.      */
  2366.     public function ArithmeticPrimary()
  2367.     {
  2368.         if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
  2369.             $this->match(Lexer::T_OPEN_PARENTHESIS);
  2370.             $expr $this->SimpleArithmeticExpression();
  2371.             $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2372.             return new AST\ParenthesisExpression($expr);
  2373.         }
  2374.         assert($this->lexer->lookahead !== null);
  2375.         switch ($this->lexer->lookahead->type) {
  2376.             case Lexer::T_COALESCE:
  2377.             case Lexer::T_NULLIF:
  2378.             case Lexer::T_CASE:
  2379.                 return $this->CaseExpression();
  2380.             case Lexer::T_IDENTIFIER:
  2381.                 $peek $this->lexer->glimpse();
  2382.                 if ($peek !== null && $peek->value === '(') {
  2383.                     return $this->FunctionDeclaration();
  2384.                 }
  2385.                 if ($peek !== null && $peek->value === '.') {
  2386.                     return $this->SingleValuedPathExpression();
  2387.                 }
  2388.                 if (isset($this->queryComponents[$this->lexer->lookahead->value]['resultVariable'])) {
  2389.                     return $this->ResultVariable();
  2390.                 }
  2391.                 return $this->StateFieldPathExpression();
  2392.             case Lexer::T_INPUT_PARAMETER:
  2393.                 return $this->InputParameter();
  2394.             default:
  2395.                 $peek $this->lexer->glimpse();
  2396.                 if ($peek !== null && $peek->value === '(') {
  2397.                     return $this->FunctionDeclaration();
  2398.                 }
  2399.                 return $this->Literal();
  2400.         }
  2401.     }
  2402.     /**
  2403.      * StringExpression ::= StringPrimary | ResultVariable | "(" Subselect ")"
  2404.      *
  2405.      * @return AST\Subselect|AST\Node|string
  2406.      */
  2407.     public function StringExpression()
  2408.     {
  2409.         $peek $this->lexer->glimpse();
  2410.         assert($peek !== null);
  2411.         // Subselect
  2412.         if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS) && $peek->type === Lexer::T_SELECT) {
  2413.             $this->match(Lexer::T_OPEN_PARENTHESIS);
  2414.             $expr $this->Subselect();
  2415.             $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2416.             return $expr;
  2417.         }
  2418.         assert($this->lexer->lookahead !== null);
  2419.         // ResultVariable (string)
  2420.         if (
  2421.             $this->lexer->isNextToken(Lexer::T_IDENTIFIER) &&
  2422.             isset($this->queryComponents[$this->lexer->lookahead->value]['resultVariable'])
  2423.         ) {
  2424.             return $this->ResultVariable();
  2425.         }
  2426.         return $this->StringPrimary();
  2427.     }
  2428.     /**
  2429.      * StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression | CaseExpression
  2430.      *
  2431.      * @return AST\Node
  2432.      */
  2433.     public function StringPrimary()
  2434.     {
  2435.         assert($this->lexer->lookahead !== null);
  2436.         $lookaheadType $this->lexer->lookahead->type;
  2437.         switch ($lookaheadType) {
  2438.             case Lexer::T_IDENTIFIER:
  2439.                 $peek $this->lexer->glimpse();
  2440.                 assert($peek !== null);
  2441.                 if ($peek->value === '.') {
  2442.                     return $this->StateFieldPathExpression();
  2443.                 }
  2444.                 if ($peek->value === '(') {
  2445.                     // do NOT directly go to FunctionsReturningString() because it doesn't check for custom functions.
  2446.                     return $this->FunctionDeclaration();
  2447.                 }
  2448.                 $this->syntaxError("'.' or '('");
  2449.                 break;
  2450.             case Lexer::T_STRING:
  2451.                 $this->match(Lexer::T_STRING);
  2452.                 assert($this->lexer->token !== null);
  2453.                 return new AST\Literal(AST\Literal::STRING$this->lexer->token->value);
  2454.             case Lexer::T_INPUT_PARAMETER:
  2455.                 return $this->InputParameter();
  2456.             case Lexer::T_CASE:
  2457.             case Lexer::T_COALESCE:
  2458.             case Lexer::T_NULLIF:
  2459.                 return $this->CaseExpression();
  2460.             default:
  2461.                 assert($lookaheadType !== null);
  2462.                 if ($this->isAggregateFunction($lookaheadType)) {
  2463.                     return $this->AggregateExpression();
  2464.                 }
  2465.         }
  2466.         $this->syntaxError(
  2467.             'StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression'
  2468.         );
  2469.     }
  2470.     /**
  2471.      * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
  2472.      *
  2473.      * @return AST\InputParameter|AST\PathExpression
  2474.      */
  2475.     public function EntityExpression()
  2476.     {
  2477.         $glimpse $this->lexer->glimpse();
  2478.         assert($glimpse !== null);
  2479.         if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER) && $glimpse->value === '.') {
  2480.             return $this->SingleValuedAssociationPathExpression();
  2481.         }
  2482.         return $this->SimpleEntityExpression();
  2483.     }
  2484.     /**
  2485.      * SimpleEntityExpression ::= IdentificationVariable | InputParameter
  2486.      *
  2487.      * @return AST\InputParameter|AST\PathExpression
  2488.      */
  2489.     public function SimpleEntityExpression()
  2490.     {
  2491.         if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
  2492.             return $this->InputParameter();
  2493.         }
  2494.         return $this->StateFieldPathExpression();
  2495.     }
  2496.     /**
  2497.      * AggregateExpression ::=
  2498.      *  ("AVG" | "MAX" | "MIN" | "SUM" | "COUNT") "(" ["DISTINCT"] SimpleArithmeticExpression ")"
  2499.      *
  2500.      * @return AST\AggregateExpression
  2501.      */
  2502.     public function AggregateExpression()
  2503.     {
  2504.         assert($this->lexer->lookahead !== null);
  2505.         $lookaheadType $this->lexer->lookahead->type;
  2506.         $isDistinct    false;
  2507.         if (! in_array($lookaheadType, [Lexer::T_COUNTLexer::T_AVGLexer::T_MAXLexer::T_MINLexer::T_SUM], true)) {
  2508.             $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT');
  2509.         }
  2510.         $this->match($lookaheadType);
  2511.         assert($this->lexer->token !== null);
  2512.         $functionName $this->lexer->token->value;
  2513.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  2514.         if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
  2515.             $this->match(Lexer::T_DISTINCT);
  2516.             $isDistinct true;
  2517.         }
  2518.         $pathExp $this->SimpleArithmeticExpression();
  2519.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2520.         return new AST\AggregateExpression($functionName$pathExp$isDistinct);
  2521.     }
  2522.     /**
  2523.      * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")"
  2524.      *
  2525.      * @return AST\QuantifiedExpression
  2526.      */
  2527.     public function QuantifiedExpression()
  2528.     {
  2529.         assert($this->lexer->lookahead !== null);
  2530.         $lookaheadType $this->lexer->lookahead->type;
  2531.         $value         $this->lexer->lookahead->value;
  2532.         if (! in_array($lookaheadType, [Lexer::T_ALLLexer::T_ANYLexer::T_SOME], true)) {
  2533.             $this->syntaxError('ALL, ANY or SOME');
  2534.         }
  2535.         $this->match($lookaheadType);
  2536.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  2537.         $qExpr       = new AST\QuantifiedExpression($this->Subselect());
  2538.         $qExpr->type $value;
  2539.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2540.         return $qExpr;
  2541.     }
  2542.     /**
  2543.      * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression
  2544.      *
  2545.      * @return AST\BetweenExpression
  2546.      */
  2547.     public function BetweenExpression()
  2548.     {
  2549.         $not        false;
  2550.         $arithExpr1 $this->ArithmeticExpression();
  2551.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2552.             $this->match(Lexer::T_NOT);
  2553.             $not true;
  2554.         }
  2555.         $this->match(Lexer::T_BETWEEN);
  2556.         $arithExpr2 $this->ArithmeticExpression();
  2557.         $this->match(Lexer::T_AND);
  2558.         $arithExpr3 $this->ArithmeticExpression();
  2559.         return new AST\BetweenExpression($arithExpr1$arithExpr2$arithExpr3$not);
  2560.     }
  2561.     /**
  2562.      * ComparisonExpression ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression )
  2563.      *
  2564.      * @return AST\ComparisonExpression
  2565.      */
  2566.     public function ComparisonExpression()
  2567.     {
  2568.         $this->lexer->glimpse();
  2569.         $leftExpr  $this->ArithmeticExpression();
  2570.         $operator  $this->ComparisonOperator();
  2571.         $rightExpr $this->isNextAllAnySome()
  2572.             ? $this->QuantifiedExpression()
  2573.             : $this->ArithmeticExpression();
  2574.         return new AST\ComparisonExpression($leftExpr$operator$rightExpr);
  2575.     }
  2576.     /**
  2577.      * InExpression ::= SingleValuedPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")"
  2578.      *
  2579.      * @return AST\InListExpression|AST\InSubselectExpression
  2580.      */
  2581.     public function InExpression()
  2582.     {
  2583.         $expression $this->ArithmeticExpression();
  2584.         $not false;
  2585.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2586.             $this->match(Lexer::T_NOT);
  2587.             $not true;
  2588.         }
  2589.         $this->match(Lexer::T_IN);
  2590.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  2591.         if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
  2592.             $inExpression = new AST\InSubselectExpression(
  2593.                 $expression,
  2594.                 $this->Subselect(),
  2595.                 $not
  2596.             );
  2597.         } else {
  2598.             $literals = [$this->InParameter()];
  2599.             while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  2600.                 $this->match(Lexer::T_COMMA);
  2601.                 $literals[] = $this->InParameter();
  2602.             }
  2603.             $inExpression = new AST\InListExpression(
  2604.                 $expression,
  2605.                 $literals,
  2606.                 $not
  2607.             );
  2608.         }
  2609.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2610.         return $inExpression;
  2611.     }
  2612.     /**
  2613.      * InstanceOfExpression ::= IdentificationVariable ["NOT"] "INSTANCE" ["OF"] (InstanceOfParameter | "(" InstanceOfParameter {"," InstanceOfParameter}* ")")
  2614.      *
  2615.      * @return AST\InstanceOfExpression
  2616.      */
  2617.     public function InstanceOfExpression()
  2618.     {
  2619.         $identificationVariable $this->IdentificationVariable();
  2620.         $not false;
  2621.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2622.             $this->match(Lexer::T_NOT);
  2623.             $not true;
  2624.         }
  2625.         $this->match(Lexer::T_INSTANCE);
  2626.         $this->match(Lexer::T_OF);
  2627.         $exprValues $this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)
  2628.             ? $this->InstanceOfParameterList()
  2629.             : [$this->InstanceOfParameter()];
  2630.         return new AST\InstanceOfExpression(
  2631.             $identificationVariable,
  2632.             $exprValues,
  2633.             $not
  2634.         );
  2635.     }
  2636.     /** @return non-empty-list<AST\InputParameter|string> */
  2637.     public function InstanceOfParameterList(): array
  2638.     {
  2639.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  2640.         $exprValues = [$this->InstanceOfParameter()];
  2641.         while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
  2642.             $this->match(Lexer::T_COMMA);
  2643.             $exprValues[] = $this->InstanceOfParameter();
  2644.         }
  2645.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2646.         return $exprValues;
  2647.     }
  2648.     /**
  2649.      * InstanceOfParameter ::= AbstractSchemaName | InputParameter
  2650.      *
  2651.      * @return AST\InputParameter|string
  2652.      */
  2653.     public function InstanceOfParameter()
  2654.     {
  2655.         if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
  2656.             $this->match(Lexer::T_INPUT_PARAMETER);
  2657.             assert($this->lexer->token !== null);
  2658.             return new AST\InputParameter($this->lexer->token->value);
  2659.         }
  2660.         $abstractSchemaName $this->AbstractSchemaName();
  2661.         $this->validateAbstractSchemaName($abstractSchemaName);
  2662.         return $abstractSchemaName;
  2663.     }
  2664.     /**
  2665.      * LikeExpression ::= StringExpression ["NOT"] "LIKE" StringPrimary ["ESCAPE" char]
  2666.      *
  2667.      * @return AST\LikeExpression
  2668.      */
  2669.     public function LikeExpression()
  2670.     {
  2671.         $stringExpr $this->StringExpression();
  2672.         $not        false;
  2673.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2674.             $this->match(Lexer::T_NOT);
  2675.             $not true;
  2676.         }
  2677.         $this->match(Lexer::T_LIKE);
  2678.         if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
  2679.             $this->match(Lexer::T_INPUT_PARAMETER);
  2680.             assert($this->lexer->token !== null);
  2681.             $stringPattern = new AST\InputParameter($this->lexer->token->value);
  2682.         } else {
  2683.             $stringPattern $this->StringPrimary();
  2684.         }
  2685.         $escapeChar null;
  2686.         if ($this->lexer->lookahead !== null && $this->lexer->lookahead->type === Lexer::T_ESCAPE) {
  2687.             $this->match(Lexer::T_ESCAPE);
  2688.             $this->match(Lexer::T_STRING);
  2689.             assert($this->lexer->token !== null);
  2690.             $escapeChar = new AST\Literal(AST\Literal::STRING$this->lexer->token->value);
  2691.         }
  2692.         return new AST\LikeExpression($stringExpr$stringPattern$escapeChar$not);
  2693.     }
  2694.     /**
  2695.      * NullComparisonExpression ::= (InputParameter | NullIfExpression | CoalesceExpression | AggregateExpression | FunctionDeclaration | IdentificationVariable | SingleValuedPathExpression | ResultVariable) "IS" ["NOT"] "NULL"
  2696.      *
  2697.      * @return AST\NullComparisonExpression
  2698.      */
  2699.     public function NullComparisonExpression()
  2700.     {
  2701.         switch (true) {
  2702.             case $this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER):
  2703.                 $this->match(Lexer::T_INPUT_PARAMETER);
  2704.                 assert($this->lexer->token !== null);
  2705.                 $expr = new AST\InputParameter($this->lexer->token->value);
  2706.                 break;
  2707.             case $this->lexer->isNextToken(Lexer::T_NULLIF):
  2708.                 $expr $this->NullIfExpression();
  2709.                 break;
  2710.             case $this->lexer->isNextToken(Lexer::T_COALESCE):
  2711.                 $expr $this->CoalesceExpression();
  2712.                 break;
  2713.             case $this->isFunction():
  2714.                 $expr $this->FunctionDeclaration();
  2715.                 break;
  2716.             default:
  2717.                 // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression
  2718.                 $glimpse $this->lexer->glimpse();
  2719.                 assert($glimpse !== null);
  2720.                 if ($glimpse->type === Lexer::T_DOT) {
  2721.                     $expr $this->SingleValuedPathExpression();
  2722.                     // Leave switch statement
  2723.                     break;
  2724.                 }
  2725.                 assert($this->lexer->lookahead !== null);
  2726.                 $lookaheadValue $this->lexer->lookahead->value;
  2727.                 // Validate existing component
  2728.                 if (! isset($this->queryComponents[$lookaheadValue])) {
  2729.                     $this->semanticalError('Cannot add having condition on undefined result variable.');
  2730.                 }
  2731.                 // Validate SingleValuedPathExpression (ie.: "product")
  2732.                 if (isset($this->queryComponents[$lookaheadValue]['metadata'])) {
  2733.                     $expr $this->SingleValuedPathExpression();
  2734.                     break;
  2735.                 }
  2736.                 // Validating ResultVariable
  2737.                 if (! isset($this->queryComponents[$lookaheadValue]['resultVariable'])) {
  2738.                     $this->semanticalError('Cannot add having condition on a non result variable.');
  2739.                 }
  2740.                 $expr $this->ResultVariable();
  2741.                 break;
  2742.         }
  2743.         $this->match(Lexer::T_IS);
  2744.         $not false;
  2745.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2746.             $this->match(Lexer::T_NOT);
  2747.             $not true;
  2748.         }
  2749.         $this->match(Lexer::T_NULL);
  2750.         return new AST\NullComparisonExpression($expr$not);
  2751.     }
  2752.     /**
  2753.      * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")"
  2754.      *
  2755.      * @return AST\ExistsExpression
  2756.      */
  2757.     public function ExistsExpression()
  2758.     {
  2759.         $not false;
  2760.         if ($this->lexer->isNextToken(Lexer::T_NOT)) {
  2761.             $this->match(Lexer::T_NOT);
  2762.             $not true;
  2763.         }
  2764.         $this->match(Lexer::T_EXISTS);
  2765.         $this->match(Lexer::T_OPEN_PARENTHESIS);
  2766.         $subselect $this->Subselect();
  2767.         $this->match(Lexer::T_CLOSE_PARENTHESIS);
  2768.         return new AST\ExistsExpression($subselect$not);
  2769.     }
  2770.     /**
  2771.      * ComparisonOperator ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!="
  2772.      *
  2773.      * @return string
  2774.      */
  2775.     public function ComparisonOperator()
  2776.     {
  2777.         assert($this->lexer->lookahead !== null);
  2778.         switch ($this->lexer->lookahead->value) {
  2779.             case '=':
  2780.                 $this->match(Lexer::T_EQUALS);
  2781.                 return '=';
  2782.             case '<':
  2783.                 $this->match(Lexer::T_LOWER_THAN);
  2784.                 $operator '<';
  2785.                 if ($this->lexer->isNextToken(Lexer::T_EQUALS)) {
  2786.                     $this->match(Lexer::T_EQUALS);
  2787.                     $operator .= '=';
  2788.                 } elseif ($this->lexer->isNextToken(Lexer::T_GREATER_THAN)) {
  2789.                     $this->match(Lexer::T_GREATER_THAN);
  2790.                     $operator .= '>';
  2791.                 }
  2792.                 return $operator;
  2793.             case '>':
  2794.                 $this->match(Lexer::T_GREATER_THAN);
  2795.                 $operator '>';
  2796.                 if ($this->lexer->isNextToken(Lexer::T_EQUALS)) {
  2797.                     $this->match(Lexer::T_EQUALS);
  2798.                     $operator .= '=';
  2799.                 }
  2800.                 return $operator;
  2801.             case '!':
  2802.                 $this->match(Lexer::T_NEGATE);
  2803.                 $this->match(Lexer::T_EQUALS);
  2804.                 return '<>';
  2805.             default:
  2806.                 $this->syntaxError('=, <, <=, <>, >, >=, !=');
  2807.         }
  2808.     }
  2809.     /**
  2810.      * FunctionDeclaration ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime
  2811.      *
  2812.      * @return Functions\FunctionNode
  2813.      */
  2814.     public function FunctionDeclaration()
  2815.     {
  2816.         assert($this->lexer->lookahead !== null);
  2817.         $token    $this->lexer->lookahead;
  2818.         $funcName strtolower($token->value);
  2819.         $customFunctionDeclaration $this->CustomFunctionDeclaration();
  2820.         // Check for custom functions functions first!
  2821.         switch (true) {
  2822.             case $customFunctionDeclaration !== null:
  2823.                 return $customFunctionDeclaration;
  2824.             case isset(self::$stringFunctions[$funcName]):
  2825.                 return $this->FunctionsReturningStrings();
  2826.             case isset(self::$numericFunctions[$funcName]):
  2827.                 return $this->FunctionsReturningNumerics();
  2828.             case isset(self::$datetimeFunctions[$funcName]):
  2829.                 return $this->FunctionsReturningDatetime();
  2830.             default:
  2831.                 $this->syntaxError('known function'$token);
  2832.         }
  2833.     }
  2834.     /**
  2835.      * Helper function for FunctionDeclaration grammar rule.
  2836.      */
  2837.     private function CustomFunctionDeclaration(): ?Functions\FunctionNode
  2838.     {
  2839.         assert($this->lexer->lookahead !== null);
  2840.         $token    $this->lexer->lookahead;
  2841.         $funcName strtolower($token->value);
  2842.         // Check for custom functions afterwards
  2843.         $config $this->em->getConfiguration();
  2844.         switch (true) {
  2845.             case $config->getCustomStringFunction($funcName) !== null:
  2846.                 return $this->CustomFunctionsReturningStrings();
  2847.             case $config->getCustomNumericFunction($funcName) !== null:
  2848.                 return $this->CustomFunctionsReturningNumerics();
  2849.             case $config->getCustomDatetimeFunction($funcName) !== null:
  2850.                 return $this->CustomFunctionsReturningDatetime();
  2851.             default:
  2852.                 return null;
  2853.         }
  2854.     }
  2855.     /**
  2856.      * FunctionsReturningNumerics ::=
  2857.      *      "LENGTH" "(" StringPrimary ")" |
  2858.      *      "LOCATE" "(" StringPrimary "," StringPrimary ["," SimpleArithmeticExpression]")" |
  2859.      *      "ABS" "(" SimpleArithmeticExpression ")" |
  2860.      *      "SQRT" "(" SimpleArithmeticExpression ")" |
  2861.      *      "MOD" "(" SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
  2862.      *      "SIZE" "(" CollectionValuedPathExpression ")" |
  2863.      *      "DATE_DIFF" "(" ArithmeticPrimary "," ArithmeticPrimary ")" |
  2864.      *      "BIT_AND" "(" ArithmeticPrimary "," ArithmeticPrimary ")" |
  2865.      *      "BIT_OR" "(" ArithmeticPrimary "," ArithmeticPrimary ")"
  2866.      *
  2867.      * @return Functions\FunctionNode
  2868.      */
  2869.     public function FunctionsReturningNumerics()
  2870.     {
  2871.         assert($this->lexer->lookahead !== null);
  2872.         $funcNameLower strtolower($this->lexer->lookahead->value);
  2873.         $funcClass     self::$numericFunctions[$funcNameLower];
  2874.         $function = new $funcClass($funcNameLower);
  2875.         $function->parse($this);
  2876.         return $function;
  2877.     }
  2878.     /** @return Functions\FunctionNode */
  2879.     public function CustomFunctionsReturningNumerics()
  2880.     {
  2881.         assert($this->lexer->lookahead !== null);
  2882.         // getCustomNumericFunction is case-insensitive
  2883.         $functionName  strtolower($this->lexer->lookahead->value);
  2884.         $functionClass $this->em->getConfiguration()->getCustomNumericFunction($functionName);
  2885.         assert($functionClass !== null);
  2886.         $function is_string($functionClass)
  2887.             ? new $functionClass($functionName)
  2888.             : $functionClass($functionName);
  2889.         $function->parse($this);
  2890.         return $function;
  2891.     }
  2892.     /**
  2893.      * FunctionsReturningDateTime ::=
  2894.      *     "CURRENT_DATE" |
  2895.      *     "CURRENT_TIME" |
  2896.      *     "CURRENT_TIMESTAMP" |
  2897.      *     "DATE_ADD" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")" |
  2898.      *     "DATE_SUB" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")"
  2899.      *
  2900.      * @return Functions\FunctionNode
  2901.      */
  2902.     public function FunctionsReturningDatetime()
  2903.     {
  2904.         assert($this->lexer->lookahead !== null);
  2905.         $funcNameLower strtolower($this->lexer->lookahead->value);
  2906.         $funcClass     self::$datetimeFunctions[$funcNameLower];
  2907.         $function = new $funcClass($funcNameLower);
  2908.         $function->parse($this);
  2909.         return $function;
  2910.     }
  2911.     /** @return Functions\FunctionNode */
  2912.     public function CustomFunctionsReturningDatetime()
  2913.     {
  2914.         assert($this->lexer->lookahead !== null);
  2915.         // getCustomDatetimeFunction is case-insensitive
  2916.         $functionName  $this->lexer->lookahead->value;
  2917.         $functionClass $this->em->getConfiguration()->getCustomDatetimeFunction($functionName);
  2918.         assert($functionClass !== null);
  2919.         $function is_string($functionClass)
  2920.             ? new $functionClass($functionName)
  2921.             : $functionClass($functionName);
  2922.         $function->parse($this);
  2923.         return $function;
  2924.     }
  2925.     /**
  2926.      * FunctionsReturningStrings ::=
  2927.      *   "CONCAT" "(" StringPrimary "," StringPrimary {"," StringPrimary}* ")" |
  2928.      *   "SUBSTRING" "(" StringPrimary "," SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
  2929.      *   "TRIM" "(" [["LEADING" | "TRAILING" | "BOTH"] [char] "FROM"] StringPrimary ")" |
  2930.      *   "LOWER" "(" StringPrimary ")" |
  2931.      *   "UPPER" "(" StringPrimary ")" |
  2932.      *   "IDENTITY" "(" SingleValuedAssociationPathExpression {"," string} ")"
  2933.      *
  2934.      * @return Functions\FunctionNode
  2935.      */
  2936.     public function FunctionsReturningStrings()
  2937.     {
  2938.         assert($this->lexer->lookahead !== null);
  2939.         $funcNameLower strtolower($this->lexer->lookahead->value);
  2940.         $funcClass     self::$stringFunctions[$funcNameLower];
  2941.         $function = new $funcClass($funcNameLower);
  2942.         $function->parse($this);
  2943.         return $function;
  2944.     }
  2945.     /** @return Functions\FunctionNode */
  2946.     public function CustomFunctionsReturningStrings()
  2947.     {
  2948.         assert($this->lexer->lookahead !== null);
  2949.         // getCustomStringFunction is case-insensitive
  2950.         $functionName  $this->lexer->lookahead->value;
  2951.         $functionClass $this->em->getConfiguration()->getCustomStringFunction($functionName);
  2952.         assert($functionClass !== null);
  2953.         $function is_string($functionClass)
  2954.             ? new $functionClass($functionName)
  2955.             : $functionClass($functionName);
  2956.         $function->parse($this);
  2957.         return $function;
  2958.     }
  2959.     private function getMetadataForDqlAlias(string $dqlAlias): ClassMetadata
  2960.     {
  2961.         if (! isset($this->queryComponents[$dqlAlias]['metadata'])) {
  2962.             throw new LogicException(sprintf('No metadata for DQL alias: %s'$dqlAlias));
  2963.         }
  2964.         return $this->queryComponents[$dqlAlias]['metadata'];
  2965.     }
  2966. }