Parser.php 94KB

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