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

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