Parser.php 99 KB

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