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

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