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

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