123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621 |
- <?php
- /*
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * This software consists of voluntary contributions made by many individuals
- * and is licensed under the MIT license. For more information, see
- * <http://www.doctrine-project.org>.
- */
- namespace Doctrine\ORM\Query;
- use Doctrine\ORM\EntityManager;
- use Doctrine\ORM\Mapping\ClassMetadata;
- use Doctrine\ORM\Query;
- use Doctrine\ORM\Query\AST\AggregateExpression;
- use Doctrine\ORM\Query\AST\ArithmeticExpression;
- use Doctrine\ORM\Query\AST\ArithmeticFactor;
- use Doctrine\ORM\Query\AST\ArithmeticTerm;
- use Doctrine\ORM\Query\AST\BetweenExpression;
- use Doctrine\ORM\Query\AST\CoalesceExpression;
- use Doctrine\ORM\Query\AST\CollectionMemberExpression;
- use Doctrine\ORM\Query\AST\ComparisonExpression;
- use Doctrine\ORM\Query\AST\ConditionalPrimary;
- use Doctrine\ORM\Query\AST\DeleteClause;
- use Doctrine\ORM\Query\AST\DeleteStatement;
- use Doctrine\ORM\Query\AST\EmptyCollectionComparisonExpression;
- use Doctrine\ORM\Query\AST\ExistsExpression;
- use Doctrine\ORM\Query\AST\FromClause;
- use Doctrine\ORM\Query\AST\Functions;
- use Doctrine\ORM\Query\AST\Functions\FunctionNode;
- use Doctrine\ORM\Query\AST\GeneralCaseExpression;
- use Doctrine\ORM\Query\AST\GroupByClause;
- use Doctrine\ORM\Query\AST\HavingClause;
- use Doctrine\ORM\Query\AST\IdentificationVariableDeclaration;
- use Doctrine\ORM\Query\AST\IndexBy;
- use Doctrine\ORM\Query\AST\InExpression;
- use Doctrine\ORM\Query\AST\InputParameter;
- use Doctrine\ORM\Query\AST\InstanceOfExpression;
- use Doctrine\ORM\Query\AST\Join;
- use Doctrine\ORM\Query\AST\JoinAssociationPathExpression;
- use Doctrine\ORM\Query\AST\LikeExpression;
- use Doctrine\ORM\Query\AST\Literal;
- use Doctrine\ORM\Query\AST\NewObjectExpression;
- use Doctrine\ORM\Query\AST\Node;
- use Doctrine\ORM\Query\AST\NullComparisonExpression;
- use Doctrine\ORM\Query\AST\NullIfExpression;
- use Doctrine\ORM\Query\AST\OrderByClause;
- use Doctrine\ORM\Query\AST\OrderByItem;
- use Doctrine\ORM\Query\AST\PartialObjectExpression;
- use Doctrine\ORM\Query\AST\PathExpression;
- use Doctrine\ORM\Query\AST\QuantifiedExpression;
- use Doctrine\ORM\Query\AST\RangeVariableDeclaration;
- use Doctrine\ORM\Query\AST\SelectClause;
- use Doctrine\ORM\Query\AST\SelectExpression;
- use Doctrine\ORM\Query\AST\SelectStatement;
- use Doctrine\ORM\Query\AST\SimpleArithmeticExpression;
- use Doctrine\ORM\Query\AST\SimpleSelectClause;
- use Doctrine\ORM\Query\AST\SimpleSelectExpression;
- use Doctrine\ORM\Query\AST\SimpleWhenClause;
- use Doctrine\ORM\Query\AST\Subselect;
- use Doctrine\ORM\Query\AST\SubselectFromClause;
- use Doctrine\ORM\Query\AST\SubselectIdentificationVariableDeclaration;
- use Doctrine\ORM\Query\AST\UpdateClause;
- use Doctrine\ORM\Query\AST\UpdateItem;
- use Doctrine\ORM\Query\AST\UpdateStatement;
- use Doctrine\ORM\Query\AST\WhenClause;
- use Doctrine\ORM\Query\AST\WhereClause;
- use ReflectionClass;
- use function array_intersect;
- use function array_search;
- use function assert;
- use function call_user_func;
- use function class_exists;
- use function count;
- use function explode;
- use function implode;
- use function in_array;
- use function interface_exists;
- use function is_string;
- use function sprintf;
- use function strlen;
- use function strpos;
- use function strrpos;
- use function strtolower;
- use function substr;
- /**
- * An LL(*) recursive-descent parser for the context-free grammar of the Doctrine Query Language.
- * Parses a DQL query, reports any errors in it, and generates an AST.
- */
- class Parser
- {
- /**
- * READ-ONLY: Maps BUILT-IN string function names to AST class names.
- *
- * @psalm-var array<string, class-string<Functions\FunctionNode>>
- */
- private static $stringFunctions = [
- 'concat' => Functions\ConcatFunction::class,
- 'substring' => Functions\SubstringFunction::class,
- 'trim' => Functions\TrimFunction::class,
- 'lower' => Functions\LowerFunction::class,
- 'upper' => Functions\UpperFunction::class,
- 'identity' => Functions\IdentityFunction::class,
- ];
- /**
- * READ-ONLY: Maps BUILT-IN numeric function names to AST class names.
- *
- * @psalm-var array<string, class-string<Functions\FunctionNode>>
- */
- private static $numericFunctions = [
- 'length' => Functions\LengthFunction::class,
- 'locate' => Functions\LocateFunction::class,
- 'abs' => Functions\AbsFunction::class,
- 'sqrt' => Functions\SqrtFunction::class,
- 'mod' => Functions\ModFunction::class,
- 'size' => Functions\SizeFunction::class,
- 'date_diff' => Functions\DateDiffFunction::class,
- 'bit_and' => Functions\BitAndFunction::class,
- 'bit_or' => Functions\BitOrFunction::class,
- // Aggregate functions
- 'min' => Functions\MinFunction::class,
- 'max' => Functions\MaxFunction::class,
- 'avg' => Functions\AvgFunction::class,
- 'sum' => Functions\SumFunction::class,
- 'count' => Functions\CountFunction::class,
- ];
- /**
- * READ-ONLY: Maps BUILT-IN datetime function names to AST class names.
- *
- * @psalm-var array<string, class-string<Functions\FunctionNode>>
- */
- private static $datetimeFunctions = [
- 'current_date' => Functions\CurrentDateFunction::class,
- 'current_time' => Functions\CurrentTimeFunction::class,
- 'current_timestamp' => Functions\CurrentTimestampFunction::class,
- 'date_add' => Functions\DateAddFunction::class,
- 'date_sub' => Functions\DateSubFunction::class,
- ];
- /*
- * Expressions that were encountered during parsing of identifiers and expressions
- * and still need to be validated.
- */
- /** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
- private $deferredIdentificationVariables = [];
- /** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
- private $deferredPartialObjectExpressions = [];
- /** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
- private $deferredPathExpressions = [];
- /** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
- private $deferredResultVariables = [];
- /** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
- private $deferredNewObjectExpressions = [];
- /**
- * The lexer.
- *
- * @var Lexer
- */
- private $lexer;
- /**
- * The parser result.
- *
- * @var ParserResult
- */
- private $parserResult;
- /**
- * The EntityManager.
- *
- * @var EntityManager
- */
- private $em;
- /**
- * The Query to parse.
- *
- * @var Query
- */
- private $query;
- /**
- * Map of declared query components in the parsed query.
- *
- * @psalm-var array<string, array<string, mixed>>
- */
- private $queryComponents = [];
- /**
- * Keeps the nesting level of defined ResultVariables.
- *
- * @var int
- */
- private $nestingLevel = 0;
- /**
- * Any additional custom tree walkers that modify the AST.
- *
- * @psalm-var list<class-string<TreeWalker>>
- */
- private $customTreeWalkers = [];
- /**
- * The custom last tree walker, if any, that is responsible for producing the output.
- *
- * @var class-string<TreeWalker>
- */
- private $customOutputWalker;
- /** @psalm-var list<AST\SelectExpression> */
- private $identVariableExpressions = [];
- /**
- * Creates a new query parser object.
- *
- * @param Query $query The Query to parse.
- */
- public function __construct(Query $query)
- {
- $this->query = $query;
- $this->em = $query->getEntityManager();
- $this->lexer = new Lexer((string) $query->getDQL());
- $this->parserResult = new ParserResult();
- }
- /**
- * Sets a custom tree walker that produces output.
- * This tree walker will be run last over the AST, after any other walkers.
- *
- * @param string $className
- *
- * @return void
- */
- public function setCustomOutputTreeWalker($className)
- {
- $this->customOutputWalker = $className;
- }
- /**
- * Adds a custom tree walker for modifying the AST.
- *
- * @return void
- *
- * @psalm-param class-string $className
- */
- public function addCustomTreeWalker($className)
- {
- $this->customTreeWalkers[] = $className;
- }
- /**
- * Gets the lexer used by the parser.
- *
- * @return Lexer
- */
- public function getLexer()
- {
- return $this->lexer;
- }
- /**
- * Gets the ParserResult that is being filled with information during parsing.
- *
- * @return ParserResult
- */
- public function getParserResult()
- {
- return $this->parserResult;
- }
- /**
- * Gets the EntityManager used by the parser.
- *
- * @return EntityManager
- */
- public function getEntityManager()
- {
- return $this->em;
- }
- /**
- * Parses and builds AST for the given Query.
- *
- * @return SelectStatement|UpdateStatement|DeleteStatement
- */
- public function getAST()
- {
- // Parse & build AST
- $AST = $this->QueryLanguage();
- // Process any deferred validations of some nodes in the AST.
- // This also allows post-processing of the AST for modification purposes.
- $this->processDeferredIdentificationVariables();
- if ($this->deferredPartialObjectExpressions) {
- $this->processDeferredPartialObjectExpressions();
- }
- if ($this->deferredPathExpressions) {
- $this->processDeferredPathExpressions();
- }
- if ($this->deferredResultVariables) {
- $this->processDeferredResultVariables();
- }
- if ($this->deferredNewObjectExpressions) {
- $this->processDeferredNewObjectExpressions($AST);
- }
- $this->processRootEntityAliasSelected();
- // TODO: Is there a way to remove this? It may impact the mixed hydration resultset a lot!
- $this->fixIdentificationVariableOrder($AST);
- return $AST;
- }
- /**
- * Attempts to match the given token with the current lookahead token.
- *
- * If they match, updates the lookahead token; otherwise raises a syntax
- * error.
- *
- * @param int $token The token type.
- *
- * @return void
- *
- * @throws QueryException If the tokens don't match.
- */
- public function match($token)
- {
- $lookaheadType = $this->lexer->lookahead['type'] ?? null;
- // Short-circuit on first condition, usually types match
- if ($lookaheadType === $token) {
- $this->lexer->moveNext();
- return;
- }
- // If parameter is not identifier (1-99) must be exact match
- if ($token < Lexer::T_IDENTIFIER) {
- $this->syntaxError($this->lexer->getLiteral($token));
- }
- // If parameter is keyword (200+) must be exact match
- if ($token > Lexer::T_IDENTIFIER) {
- $this->syntaxError($this->lexer->getLiteral($token));
- }
- // If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+)
- if ($token === Lexer::T_IDENTIFIER && $lookaheadType < Lexer::T_IDENTIFIER) {
- $this->syntaxError($this->lexer->getLiteral($token));
- }
- $this->lexer->moveNext();
- }
- /**
- * Frees this parser, enabling it to be reused.
- *
- * @param bool $deep Whether to clean peek and reset errors.
- * @param int $position Position to reset.
- *
- * @return void
- */
- public function free($deep = false, $position = 0)
- {
- // WARNING! Use this method with care. It resets the scanner!
- $this->lexer->resetPosition($position);
- // Deep = true cleans peek and also any previously defined errors
- if ($deep) {
- $this->lexer->resetPeek();
- }
- $this->lexer->token = null;
- $this->lexer->lookahead = null;
- }
- /**
- * Parses a query string.
- *
- * @return ParserResult
- */
- public function parse()
- {
- $AST = $this->getAST();
- $customWalkers = $this->query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
- if ($customWalkers !== false) {
- $this->customTreeWalkers = $customWalkers;
- }
- $customOutputWalker = $this->query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER);
- if ($customOutputWalker !== false) {
- $this->customOutputWalker = $customOutputWalker;
- }
- // Run any custom tree walkers over the AST
- if ($this->customTreeWalkers) {
- $treeWalkerChain = new TreeWalkerChain($this->query, $this->parserResult, $this->queryComponents);
- foreach ($this->customTreeWalkers as $walker) {
- $treeWalkerChain->addTreeWalker($walker);
- }
- switch (true) {
- case $AST instanceof AST\UpdateStatement:
- $treeWalkerChain->walkUpdateStatement($AST);
- break;
- case $AST instanceof AST\DeleteStatement:
- $treeWalkerChain->walkDeleteStatement($AST);
- break;
- case $AST instanceof AST\SelectStatement:
- default:
- $treeWalkerChain->walkSelectStatement($AST);
- }
- $this->queryComponents = $treeWalkerChain->getQueryComponents();
- }
- $outputWalkerClass = $this->customOutputWalker ?: SqlWalker::class;
- $outputWalker = new $outputWalkerClass($this->query, $this->parserResult, $this->queryComponents);
- // Assign an SQL executor to the parser result
- $this->parserResult->setSqlExecutor($outputWalker->getExecutor($AST));
- return $this->parserResult;
- }
- /**
- * Fixes order of identification variables.
- *
- * They have to appear in the select clause in the same order as the
- * declarations (from ... x join ... y join ... z ...) appear in the query
- * as the hydration process relies on that order for proper operation.
- *
- * @param AST\SelectStatement|AST\DeleteStatement|AST\UpdateStatement $AST
- *
- * @return void
- */
- private function fixIdentificationVariableOrder($AST)
- {
- if (count($this->identVariableExpressions) <= 1) {
- return;
- }
- assert($AST instanceof AST\SelectStatement);
- foreach ($this->queryComponents as $dqlAlias => $qComp) {
- if (! isset($this->identVariableExpressions[$dqlAlias])) {
- continue;
- }
- $expr = $this->identVariableExpressions[$dqlAlias];
- $key = array_search($expr, $AST->selectClause->selectExpressions);
- unset($AST->selectClause->selectExpressions[$key]);
- $AST->selectClause->selectExpressions[] = $expr;
- }
- }
- /**
- * Generates a new syntax error.
- *
- * @param string $expected Expected string.
- *
- * @return void
- *
- * @throws QueryException
- *
- * @psalm-param array<string, mixed>|null $token Got token.
- */
- public function syntaxError($expected = '', $token = null)
- {
- if ($token === null) {
- $token = $this->lexer->lookahead;
- }
- $tokenPos = $token['position'] ?? '-1';
- $message = sprintf('line 0, col %d: Error: ', $tokenPos);
- $message .= $expected !== '' ? sprintf('Expected %s, got ', $expected) : 'Unexpected ';
- $message .= $this->lexer->lookahead === null ? 'end of string.' : sprintf("'%s'", $token['value']);
- throw QueryException::syntaxError($message, QueryException::dqlError($this->query->getDQL()));
- }
- /**
- * Generates a new semantical error.
- *
- * @param string $message Optional message.
- *
- * @return void
- *
- * @throws QueryException
- *
- * @psalm-param array<string, mixed>|null $token Optional token.
- */
- public function semanticalError($message = '', $token = null)
- {
- if ($token === null) {
- $token = $this->lexer->lookahead ?? ['position' => null];
- }
- // Minimum exposed chars ahead of token
- $distance = 12;
- // Find a position of a final word to display in error string
- $dql = $this->query->getDQL();
- $length = strlen($dql);
- $pos = $token['position'] + $distance;
- $pos = strpos($dql, ' ', $length > $pos ? $pos : $length);
- $length = $pos !== false ? $pos - $token['position'] : $distance;
- $tokenPos = isset($token['position']) && $token['position'] > 0 ? $token['position'] : '-1';
- $tokenStr = substr($dql, $token['position'], $length);
- // Building informative message
- $message = 'line 0, col ' . $tokenPos . " near '" . $tokenStr . "': Error: " . $message;
- throw QueryException::semanticalError($message, QueryException::dqlError($this->query->getDQL()));
- }
- /**
- * Peeks beyond the matched closing parenthesis and returns the first token after that one.
- *
- * @param bool $resetPeek Reset peek after finding the closing parenthesis.
- *
- * @psalm-return array<string, mixed>| null
- */
- private function peekBeyondClosingParenthesis(bool $resetPeek = true)
- {
- $token = $this->lexer->peek();
- $numUnmatched = 1;
- while ($numUnmatched > 0 && $token !== null) {
- switch ($token['type']) {
- case Lexer::T_OPEN_PARENTHESIS:
- ++$numUnmatched;
- break;
- case Lexer::T_CLOSE_PARENTHESIS:
- --$numUnmatched;
- break;
- default:
- // Do nothing
- }
- $token = $this->lexer->peek();
- }
- if ($resetPeek) {
- $this->lexer->resetPeek();
- }
- return $token;
- }
- /**
- * Checks if the given token indicates a mathematical operator.
- *
- * @psalm-param array<string, mixed> $token
- */
- private function isMathOperator($token): bool
- {
- return $token !== null && in_array($token['type'], [Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY]);
- }
- /**
- * Checks if the next-next (after lookahead) token starts a function.
- *
- * @return bool TRUE if the next-next tokens start a function, FALSE otherwise.
- */
- private function isFunction(): bool
- {
- $lookaheadType = $this->lexer->lookahead['type'];
- $peek = $this->lexer->peek();
- $this->lexer->resetPeek();
- return $lookaheadType >= Lexer::T_IDENTIFIER && $peek !== null && $peek['type'] === Lexer::T_OPEN_PARENTHESIS;
- }
- /**
- * Checks whether the given token type indicates an aggregate function.
- *
- * @return bool TRUE if the token type is an aggregate function, FALSE otherwise.
- *
- * @psalm-param Lexer::T_* $tokenType
- */
- private function isAggregateFunction(int $tokenType): bool
- {
- return in_array(
- $tokenType,
- [Lexer::T_AVG, Lexer::T_MIN, Lexer::T_MAX, Lexer::T_SUM, Lexer::T_COUNT]
- );
- }
- /**
- * Checks whether the current lookahead token of the lexer has the type T_ALL, T_ANY or T_SOME.
- */
- private function isNextAllAnySome(): bool
- {
- return in_array(
- $this->lexer->lookahead['type'],
- [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME]
- );
- }
- /**
- * Validates that the given <tt>IdentificationVariable</tt> is semantically correct.
- * It must exist in query components list.
- */
- private function processDeferredIdentificationVariables(): void
- {
- foreach ($this->deferredIdentificationVariables as $deferredItem) {
- $identVariable = $deferredItem['expression'];
- // Check if IdentificationVariable exists in queryComponents
- if (! isset($this->queryComponents[$identVariable])) {
- $this->semanticalError(
- sprintf("'%s' is not defined.", $identVariable),
- $deferredItem['token']
- );
- }
- $qComp = $this->queryComponents[$identVariable];
- // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
- if (! isset($qComp['metadata'])) {
- $this->semanticalError(
- sprintf("'%s' does not point to a Class.", $identVariable),
- $deferredItem['token']
- );
- }
- // Validate if identification variable nesting level is lower or equal than the current one
- if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
- $this->semanticalError(
- sprintf("'%s' is used outside the scope of its declaration.", $identVariable),
- $deferredItem['token']
- );
- }
- }
- }
- /**
- * Validates that the given <tt>NewObjectExpression</tt>.
- */
- private function processDeferredNewObjectExpressions(SelectStatement $AST): void
- {
- foreach ($this->deferredNewObjectExpressions as $deferredItem) {
- $expression = $deferredItem['expression'];
- $token = $deferredItem['token'];
- $className = $expression->className;
- $args = $expression->args;
- $fromClassName = $AST->fromClause->identificationVariableDeclarations[0]->rangeVariableDeclaration->abstractSchemaName ?? null;
- // If the namespace is not given then assumes the first FROM entity namespace
- if (strpos($className, '\\') === false && ! class_exists($className) && strpos($fromClassName, '\\') !== false) {
- $namespace = substr($fromClassName, 0, strrpos($fromClassName, '\\'));
- $fqcn = $namespace . '\\' . $className;
- if (class_exists($fqcn)) {
- $expression->className = $fqcn;
- $className = $fqcn;
- }
- }
- if (! class_exists($className)) {
- $this->semanticalError(sprintf('Class "%s" is not defined.', $className), $token);
- }
- $class = new ReflectionClass($className);
- if (! $class->isInstantiable()) {
- $this->semanticalError(sprintf('Class "%s" can not be instantiated.', $className), $token);
- }
- if ($class->getConstructor() === null) {
- $this->semanticalError(sprintf('Class "%s" has not a valid constructor.', $className), $token);
- }
- if ($class->getConstructor()->getNumberOfRequiredParameters() > count($args)) {
- $this->semanticalError(sprintf('Number of arguments does not match with "%s" constructor declaration.', $className), $token);
- }
- }
- }
- /**
- * Validates that the given <tt>PartialObjectExpression</tt> is semantically correct.
- * It must exist in query components list.
- */
- private function processDeferredPartialObjectExpressions(): void
- {
- foreach ($this->deferredPartialObjectExpressions as $deferredItem) {
- $expr = $deferredItem['expression'];
- $class = $this->queryComponents[$expr->identificationVariable]['metadata'];
- foreach ($expr->partialFieldSet as $field) {
- if (isset($class->fieldMappings[$field])) {
- continue;
- }
- if (
- isset($class->associationMappings[$field]) &&
- $class->associationMappings[$field]['isOwningSide'] &&
- $class->associationMappings[$field]['type'] & ClassMetadata::TO_ONE
- ) {
- continue;
- }
- $this->semanticalError(sprintf(
- "There is no mapped field named '%s' on class %s.",
- $field,
- $class->name
- ), $deferredItem['token']);
- }
- if (array_intersect($class->identifier, $expr->partialFieldSet) !== $class->identifier) {
- $this->semanticalError(
- 'The partial field selection of class ' . $class->name . ' must contain the identifier.',
- $deferredItem['token']
- );
- }
- }
- }
- /**
- * Validates that the given <tt>ResultVariable</tt> is semantically correct.
- * It must exist in query components list.
- */
- private function processDeferredResultVariables(): void
- {
- foreach ($this->deferredResultVariables as $deferredItem) {
- $resultVariable = $deferredItem['expression'];
- // Check if ResultVariable exists in queryComponents
- if (! isset($this->queryComponents[$resultVariable])) {
- $this->semanticalError(
- sprintf("'%s' is not defined.", $resultVariable),
- $deferredItem['token']
- );
- }
- $qComp = $this->queryComponents[$resultVariable];
- // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
- if (! isset($qComp['resultVariable'])) {
- $this->semanticalError(
- sprintf("'%s' does not point to a ResultVariable.", $resultVariable),
- $deferredItem['token']
- );
- }
- // Validate if identification variable nesting level is lower or equal than the current one
- if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
- $this->semanticalError(
- sprintf("'%s' is used outside the scope of its declaration.", $resultVariable),
- $deferredItem['token']
- );
- }
- }
- }
- /**
- * Validates that the given <tt>PathExpression</tt> is semantically correct for grammar rules:
- *
- * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
- * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
- * StateFieldPathExpression ::= IdentificationVariable "." StateField
- * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField
- * CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField
- */
- private function processDeferredPathExpressions(): void
- {
- foreach ($this->deferredPathExpressions as $deferredItem) {
- $pathExpression = $deferredItem['expression'];
- $qComp = $this->queryComponents[$pathExpression->identificationVariable];
- $class = $qComp['metadata'];
- $field = $pathExpression->field;
- if ($field === null) {
- $field = $pathExpression->field = $class->identifier[0];
- }
- // Check if field or association exists
- if (! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) {
- $this->semanticalError(
- 'Class ' . $class->name . ' has no field or association named ' . $field,
- $deferredItem['token']
- );
- }
- $fieldType = AST\PathExpression::TYPE_STATE_FIELD;
- if (isset($class->associationMappings[$field])) {
- $assoc = $class->associationMappings[$field];
- $fieldType = $assoc['type'] & ClassMetadata::TO_ONE
- ? AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION
- : AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION;
- }
- // Validate if PathExpression is one of the expected types
- $expectedType = $pathExpression->expectedType;
- if (! ($expectedType & $fieldType)) {
- // We need to recognize which was expected type(s)
- $expectedStringTypes = [];
- // Validate state field type
- if ($expectedType & AST\PathExpression::TYPE_STATE_FIELD) {
- $expectedStringTypes[] = 'StateFieldPathExpression';
- }
- // Validate single valued association (*-to-one)
- if ($expectedType & AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) {
- $expectedStringTypes[] = 'SingleValuedAssociationField';
- }
- // Validate single valued association (*-to-many)
- if ($expectedType & AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION) {
- $expectedStringTypes[] = 'CollectionValuedAssociationField';
- }
- // Build the error message
- $semanticalError = 'Invalid PathExpression. ';
- $semanticalError .= count($expectedStringTypes) === 1
- ? 'Must be a ' . $expectedStringTypes[0] . '.'
- : implode(' or ', $expectedStringTypes) . ' expected.';
- $this->semanticalError($semanticalError, $deferredItem['token']);
- }
- // We need to force the type in PathExpression
- $pathExpression->type = $fieldType;
- }
- }
- private function processRootEntityAliasSelected(): void
- {
- if (! count($this->identVariableExpressions)) {
- return;
- }
- foreach ($this->identVariableExpressions as $dqlAlias => $expr) {
- if (isset($this->queryComponents[$dqlAlias]) && $this->queryComponents[$dqlAlias]['parent'] === null) {
- return;
- }
- }
- $this->semanticalError('Cannot select entity through identification variables without choosing at least one root entity alias.');
- }
- /**
- * QueryLanguage ::= SelectStatement | UpdateStatement | DeleteStatement
- *
- * @return SelectStatement|UpdateStatement|DeleteStatement
- */
- public function QueryLanguage()
- {
- $statement = null;
- $this->lexer->moveNext();
- switch ($this->lexer->lookahead['type'] ?? null) {
- case Lexer::T_SELECT:
- $statement = $this->SelectStatement();
- break;
- case Lexer::T_UPDATE:
- $statement = $this->UpdateStatement();
- break;
- case Lexer::T_DELETE:
- $statement = $this->DeleteStatement();
- break;
- default:
- $this->syntaxError('SELECT, UPDATE or DELETE');
- break;
- }
- // Check for end of string
- if ($this->lexer->lookahead !== null) {
- $this->syntaxError('end of string');
- }
- return $statement;
- }
- /**
- * SelectStatement ::= SelectClause FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
- *
- * @return SelectStatement
- */
- public function SelectStatement()
- {
- $selectStatement = new AST\SelectStatement($this->SelectClause(), $this->FromClause());
- $selectStatement->whereClause = $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
- $selectStatement->groupByClause = $this->lexer->isNextToken(Lexer::T_GROUP) ? $this->GroupByClause() : null;
- $selectStatement->havingClause = $this->lexer->isNextToken(Lexer::T_HAVING) ? $this->HavingClause() : null;
- $selectStatement->orderByClause = $this->lexer->isNextToken(Lexer::T_ORDER) ? $this->OrderByClause() : null;
- return $selectStatement;
- }
- /**
- * UpdateStatement ::= UpdateClause [WhereClause]
- *
- * @return UpdateStatement
- */
- public function UpdateStatement()
- {
- $updateStatement = new AST\UpdateStatement($this->UpdateClause());
- $updateStatement->whereClause = $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
- return $updateStatement;
- }
- /**
- * DeleteStatement ::= DeleteClause [WhereClause]
- *
- * @return DeleteStatement
- */
- public function DeleteStatement()
- {
- $deleteStatement = new AST\DeleteStatement($this->DeleteClause());
- $deleteStatement->whereClause = $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
- return $deleteStatement;
- }
- /**
- * IdentificationVariable ::= identifier
- *
- * @return string
- */
- public function IdentificationVariable()
- {
- $this->match(Lexer::T_IDENTIFIER);
- $identVariable = $this->lexer->token['value'];
- $this->deferredIdentificationVariables[] = [
- 'expression' => $identVariable,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $this->lexer->token,
- ];
- return $identVariable;
- }
- /**
- * AliasIdentificationVariable = identifier
- *
- * @return string
- */
- public function AliasIdentificationVariable()
- {
- $this->match(Lexer::T_IDENTIFIER);
- $aliasIdentVariable = $this->lexer->token['value'];
- $exists = isset($this->queryComponents[$aliasIdentVariable]);
- if ($exists) {
- $this->semanticalError(
- sprintf("'%s' is already defined.", $aliasIdentVariable),
- $this->lexer->token
- );
- }
- return $aliasIdentVariable;
- }
- /**
- * AbstractSchemaName ::= fully_qualified_name | aliased_name | identifier
- *
- * @return string
- */
- public function AbstractSchemaName()
- {
- if ($this->lexer->isNextToken(Lexer::T_FULLY_QUALIFIED_NAME)) {
- $this->match(Lexer::T_FULLY_QUALIFIED_NAME);
- return $this->lexer->token['value'];
- }
- if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) {
- $this->match(Lexer::T_IDENTIFIER);
- return $this->lexer->token['value'];
- }
- $this->match(Lexer::T_ALIASED_NAME);
- [$namespaceAlias, $simpleClassName] = explode(':', $this->lexer->token['value']);
- return $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName;
- }
- /**
- * Validates an AbstractSchemaName, making sure the class exists.
- *
- * @param string $schemaName The name to validate.
- *
- * @throws QueryException if the name does not exist.
- */
- private function validateAbstractSchemaName($schemaName)
- {
- if (! (class_exists($schemaName, true) || interface_exists($schemaName, true))) {
- $this->semanticalError(
- sprintf("Class '%s' is not defined.", $schemaName),
- $this->lexer->token
- );
- }
- }
- /**
- * AliasResultVariable ::= identifier
- *
- * @return string
- */
- public function AliasResultVariable()
- {
- $this->match(Lexer::T_IDENTIFIER);
- $resultVariable = $this->lexer->token['value'];
- $exists = isset($this->queryComponents[$resultVariable]);
- if ($exists) {
- $this->semanticalError(
- sprintf("'%s' is already defined.", $resultVariable),
- $this->lexer->token
- );
- }
- return $resultVariable;
- }
- /**
- * ResultVariable ::= identifier
- *
- * @return string
- */
- public function ResultVariable()
- {
- $this->match(Lexer::T_IDENTIFIER);
- $resultVariable = $this->lexer->token['value'];
- // Defer ResultVariable validation
- $this->deferredResultVariables[] = [
- 'expression' => $resultVariable,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $this->lexer->token,
- ];
- return $resultVariable;
- }
- /**
- * JoinAssociationPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField)
- *
- * @return JoinAssociationPathExpression
- */
- public function JoinAssociationPathExpression()
- {
- $identVariable = $this->IdentificationVariable();
- if (! isset($this->queryComponents[$identVariable])) {
- $this->semanticalError(
- 'Identification Variable ' . $identVariable . ' used in join path expression but was not defined before.'
- );
- }
- $this->match(Lexer::T_DOT);
- $this->match(Lexer::T_IDENTIFIER);
- $field = $this->lexer->token['value'];
- // Validate association field
- $qComp = $this->queryComponents[$identVariable];
- $class = $qComp['metadata'];
- if (! $class->hasAssociation($field)) {
- $this->semanticalError('Class ' . $class->name . ' has no association named ' . $field);
- }
- return new AST\JoinAssociationPathExpression($identVariable, $field);
- }
- /**
- * Parses an arbitrary path expression and defers semantical validation
- * based on expected types.
- *
- * PathExpression ::= IdentificationVariable {"." identifier}*
- *
- * @param int $expectedTypes
- *
- * @return PathExpression
- */
- public function PathExpression($expectedTypes)
- {
- $identVariable = $this->IdentificationVariable();
- $field = null;
- if ($this->lexer->isNextToken(Lexer::T_DOT)) {
- $this->match(Lexer::T_DOT);
- $this->match(Lexer::T_IDENTIFIER);
- $field = $this->lexer->token['value'];
- while ($this->lexer->isNextToken(Lexer::T_DOT)) {
- $this->match(Lexer::T_DOT);
- $this->match(Lexer::T_IDENTIFIER);
- $field .= '.' . $this->lexer->token['value'];
- }
- }
- // Creating AST node
- $pathExpr = new AST\PathExpression($expectedTypes, $identVariable, $field);
- // Defer PathExpression validation if requested to be deferred
- $this->deferredPathExpressions[] = [
- 'expression' => $pathExpr,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $this->lexer->token,
- ];
- return $pathExpr;
- }
- /**
- * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
- *
- * @return PathExpression
- */
- public function AssociationPathExpression()
- {
- return $this->PathExpression(
- AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION |
- AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION
- );
- }
- /**
- * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
- *
- * @return PathExpression
- */
- public function SingleValuedPathExpression()
- {
- return $this->PathExpression(
- AST\PathExpression::TYPE_STATE_FIELD |
- AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION
- );
- }
- /**
- * StateFieldPathExpression ::= IdentificationVariable "." StateField
- *
- * @return PathExpression
- */
- public function StateFieldPathExpression()
- {
- return $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD);
- }
- /**
- * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField
- *
- * @return PathExpression
- */
- public function SingleValuedAssociationPathExpression()
- {
- return $this->PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION);
- }
- /**
- * CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField
- *
- * @return PathExpression
- */
- public function CollectionValuedPathExpression()
- {
- return $this->PathExpression(AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION);
- }
- /**
- * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression}
- *
- * @return SelectClause
- */
- public function SelectClause()
- {
- $isDistinct = false;
- $this->match(Lexer::T_SELECT);
- // Check for DISTINCT
- if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
- $this->match(Lexer::T_DISTINCT);
- $isDistinct = true;
- }
- // Process SelectExpressions (1..N)
- $selectExpressions = [];
- $selectExpressions[] = $this->SelectExpression();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $selectExpressions[] = $this->SelectExpression();
- }
- return new AST\SelectClause($selectExpressions, $isDistinct);
- }
- /**
- * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression
- *
- * @return SimpleSelectClause
- */
- public function SimpleSelectClause()
- {
- $isDistinct = false;
- $this->match(Lexer::T_SELECT);
- if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
- $this->match(Lexer::T_DISTINCT);
- $isDistinct = true;
- }
- return new AST\SimpleSelectClause($this->SimpleSelectExpression(), $isDistinct);
- }
- /**
- * UpdateClause ::= "UPDATE" AbstractSchemaName ["AS"] AliasIdentificationVariable "SET" UpdateItem {"," UpdateItem}*
- *
- * @return UpdateClause
- */
- public function UpdateClause()
- {
- $this->match(Lexer::T_UPDATE);
- $token = $this->lexer->lookahead;
- $abstractSchemaName = $this->AbstractSchemaName();
- $this->validateAbstractSchemaName($abstractSchemaName);
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- }
- $aliasIdentificationVariable = $this->AliasIdentificationVariable();
- $class = $this->em->getClassMetadata($abstractSchemaName);
- // Building queryComponent
- $queryComponent = [
- 'metadata' => $class,
- 'parent' => null,
- 'relation' => null,
- 'map' => null,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $token,
- ];
- $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;
- $this->match(Lexer::T_SET);
- $updateItems = [];
- $updateItems[] = $this->UpdateItem();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $updateItems[] = $this->UpdateItem();
- }
- $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems);
- $updateClause->aliasIdentificationVariable = $aliasIdentificationVariable;
- return $updateClause;
- }
- /**
- * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName ["AS"] AliasIdentificationVariable
- *
- * @return DeleteClause
- */
- public function DeleteClause()
- {
- $this->match(Lexer::T_DELETE);
- if ($this->lexer->isNextToken(Lexer::T_FROM)) {
- $this->match(Lexer::T_FROM);
- }
- $token = $this->lexer->lookahead;
- $abstractSchemaName = $this->AbstractSchemaName();
- $this->validateAbstractSchemaName($abstractSchemaName);
- $deleteClause = new AST\DeleteClause($abstractSchemaName);
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- }
- $aliasIdentificationVariable = $this->lexer->isNextToken(Lexer::T_IDENTIFIER)
- ? $this->AliasIdentificationVariable()
- : 'alias_should_have_been_set';
- $deleteClause->aliasIdentificationVariable = $aliasIdentificationVariable;
- $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName);
- // Building queryComponent
- $queryComponent = [
- 'metadata' => $class,
- 'parent' => null,
- 'relation' => null,
- 'map' => null,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $token,
- ];
- $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;
- return $deleteClause;
- }
- /**
- * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}*
- *
- * @return FromClause
- */
- public function FromClause()
- {
- $this->match(Lexer::T_FROM);
- $identificationVariableDeclarations = [];
- $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();
- }
- return new AST\FromClause($identificationVariableDeclarations);
- }
- /**
- * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}*
- *
- * @return SubselectFromClause
- */
- public function SubselectFromClause()
- {
- $this->match(Lexer::T_FROM);
- $identificationVariables = [];
- $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
- }
- return new AST\SubselectFromClause($identificationVariables);
- }
- /**
- * WhereClause ::= "WHERE" ConditionalExpression
- *
- * @return WhereClause
- */
- public function WhereClause()
- {
- $this->match(Lexer::T_WHERE);
- return new AST\WhereClause($this->ConditionalExpression());
- }
- /**
- * HavingClause ::= "HAVING" ConditionalExpression
- *
- * @return HavingClause
- */
- public function HavingClause()
- {
- $this->match(Lexer::T_HAVING);
- return new AST\HavingClause($this->ConditionalExpression());
- }
- /**
- * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}*
- *
- * @return GroupByClause
- */
- public function GroupByClause()
- {
- $this->match(Lexer::T_GROUP);
- $this->match(Lexer::T_BY);
- $groupByItems = [$this->GroupByItem()];
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $groupByItems[] = $this->GroupByItem();
- }
- return new AST\GroupByClause($groupByItems);
- }
- /**
- * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}*
- *
- * @return OrderByClause
- */
- public function OrderByClause()
- {
- $this->match(Lexer::T_ORDER);
- $this->match(Lexer::T_BY);
- $orderByItems = [];
- $orderByItems[] = $this->OrderByItem();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $orderByItems[] = $this->OrderByItem();
- }
- return new AST\OrderByClause($orderByItems);
- }
- /**
- * Subselect ::= SimpleSelectClause SubselectFromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
- *
- * @return Subselect
- */
- public function Subselect()
- {
- // Increase query nesting level
- $this->nestingLevel++;
- $subselect = new AST\Subselect($this->SimpleSelectClause(), $this->SubselectFromClause());
- $subselect->whereClause = $this->lexer->isNextToken(Lexer::T_WHERE) ? $this->WhereClause() : null;
- $subselect->groupByClause = $this->lexer->isNextToken(Lexer::T_GROUP) ? $this->GroupByClause() : null;
- $subselect->havingClause = $this->lexer->isNextToken(Lexer::T_HAVING) ? $this->HavingClause() : null;
- $subselect->orderByClause = $this->lexer->isNextToken(Lexer::T_ORDER) ? $this->OrderByClause() : null;
- // Decrease query nesting level
- $this->nestingLevel--;
- return $subselect;
- }
- /**
- * UpdateItem ::= SingleValuedPathExpression "=" NewValue
- *
- * @return UpdateItem
- */
- public function UpdateItem()
- {
- $pathExpr = $this->SingleValuedPathExpression();
- $this->match(Lexer::T_EQUALS);
- return new AST\UpdateItem($pathExpr, $this->NewValue());
- }
- /**
- * GroupByItem ::= IdentificationVariable | ResultVariable | SingleValuedPathExpression
- *
- * @return string|PathExpression
- */
- public function GroupByItem()
- {
- // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression
- $glimpse = $this->lexer->glimpse();
- if ($glimpse !== null && $glimpse['type'] === Lexer::T_DOT) {
- return $this->SingleValuedPathExpression();
- }
- // Still need to decide between IdentificationVariable or ResultVariable
- $lookaheadValue = $this->lexer->lookahead['value'];
- if (! isset($this->queryComponents[$lookaheadValue])) {
- $this->semanticalError('Cannot group by undefined identification or result variable.');
- }
- return isset($this->queryComponents[$lookaheadValue]['metadata'])
- ? $this->IdentificationVariable()
- : $this->ResultVariable();
- }
- /**
- * OrderByItem ::= (
- * SimpleArithmeticExpression | SingleValuedPathExpression | CaseExpression |
- * ScalarExpression | ResultVariable | FunctionDeclaration
- * ) ["ASC" | "DESC"]
- *
- * @return OrderByItem
- */
- public function OrderByItem()
- {
- $this->lexer->peek(); // lookahead => '.'
- $this->lexer->peek(); // lookahead => token after '.'
- $peek = $this->lexer->peek(); // lookahead => token after the token after the '.'
- $this->lexer->resetPeek();
- $glimpse = $this->lexer->glimpse();
- switch (true) {
- case $this->isMathOperator($peek):
- $expr = $this->SimpleArithmeticExpression();
- break;
- case $glimpse !== null && $glimpse['type'] === Lexer::T_DOT:
- $expr = $this->SingleValuedPathExpression();
- break;
- case $this->lexer->peek() && $this->isMathOperator($this->peekBeyondClosingParenthesis()):
- $expr = $this->ScalarExpression();
- break;
- case $this->lexer->lookahead['type'] === Lexer::T_CASE:
- $expr = $this->CaseExpression();
- break;
- case $this->isFunction():
- $expr = $this->FunctionDeclaration();
- break;
- default:
- $expr = $this->ResultVariable();
- break;
- }
- $type = 'ASC';
- $item = new AST\OrderByItem($expr);
- switch (true) {
- case $this->lexer->isNextToken(Lexer::T_DESC):
- $this->match(Lexer::T_DESC);
- $type = 'DESC';
- break;
- case $this->lexer->isNextToken(Lexer::T_ASC):
- $this->match(Lexer::T_ASC);
- break;
- default:
- // Do nothing
- }
- $item->type = $type;
- return $item;
- }
- /**
- * NewValue ::= SimpleArithmeticExpression | StringPrimary | DatetimePrimary | BooleanPrimary |
- * EnumPrimary | SimpleEntityExpression | "NULL"
- *
- * NOTE: Since it is not possible to correctly recognize individual types, here is the full
- * grammar that needs to be supported:
- *
- * NewValue ::= SimpleArithmeticExpression | "NULL"
- *
- * SimpleArithmeticExpression covers all *Primary grammar rules and also SimpleEntityExpression
- *
- * @return AST\ArithmeticExpression|AST\InputParameter|null
- */
- public function NewValue()
- {
- if ($this->lexer->isNextToken(Lexer::T_NULL)) {
- $this->match(Lexer::T_NULL);
- return null;
- }
- if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
- $this->match(Lexer::T_INPUT_PARAMETER);
- return new AST\InputParameter($this->lexer->token['value']);
- }
- return $this->ArithmeticExpression();
- }
- /**
- * IdentificationVariableDeclaration ::= RangeVariableDeclaration [IndexBy] {Join}*
- *
- * @return IdentificationVariableDeclaration
- */
- public function IdentificationVariableDeclaration()
- {
- $joins = [];
- $rangeVariableDeclaration = $this->RangeVariableDeclaration();
- $indexBy = $this->lexer->isNextToken(Lexer::T_INDEX)
- ? $this->IndexBy()
- : null;
- $rangeVariableDeclaration->isRoot = true;
- while (
- $this->lexer->isNextToken(Lexer::T_LEFT) ||
- $this->lexer->isNextToken(Lexer::T_INNER) ||
- $this->lexer->isNextToken(Lexer::T_JOIN)
- ) {
- $joins[] = $this->Join();
- }
- return new AST\IdentificationVariableDeclaration(
- $rangeVariableDeclaration,
- $indexBy,
- $joins
- );
- }
- /**
- * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration
- *
- * {Internal note: WARNING: Solution is harder than a bare implementation.
- * Desired EBNF support:
- *
- * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration | (AssociationPathExpression ["AS"] AliasIdentificationVariable)
- *
- * It demands that entire SQL generation to become programmatical. This is
- * needed because association based subselect requires "WHERE" conditional
- * expressions to be injected, but there is no scope to do that. Only scope
- * accessible is "FROM", prohibiting an easy implementation without larger
- * changes.}
- *
- * @return SubselectIdentificationVariableDeclaration|IdentificationVariableDeclaration
- */
- public function SubselectIdentificationVariableDeclaration()
- {
- /*
- NOT YET IMPLEMENTED!
- $glimpse = $this->lexer->glimpse();
- if ($glimpse['type'] == Lexer::T_DOT) {
- $associationPathExpression = $this->AssociationPathExpression();
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- }
- $aliasIdentificationVariable = $this->AliasIdentificationVariable();
- $identificationVariable = $associationPathExpression->identificationVariable;
- $field = $associationPathExpression->associationField;
- $class = $this->queryComponents[$identificationVariable]['metadata'];
- $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']);
- // Building queryComponent
- $joinQueryComponent = array(
- 'metadata' => $targetClass,
- 'parent' => $identificationVariable,
- 'relation' => $class->getAssociationMapping($field),
- 'map' => null,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $this->lexer->lookahead
- );
- $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;
- return new AST\SubselectIdentificationVariableDeclaration(
- $associationPathExpression, $aliasIdentificationVariable
- );
- }
- */
- return $this->IdentificationVariableDeclaration();
- }
- /**
- * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN"
- * (JoinAssociationDeclaration | RangeVariableDeclaration)
- * ["WITH" ConditionalExpression]
- *
- * @return Join
- */
- public function Join()
- {
- // Check Join type
- $joinType = AST\Join::JOIN_TYPE_INNER;
- switch (true) {
- case $this->lexer->isNextToken(Lexer::T_LEFT):
- $this->match(Lexer::T_LEFT);
- $joinType = AST\Join::JOIN_TYPE_LEFT;
- // Possible LEFT OUTER join
- if ($this->lexer->isNextToken(Lexer::T_OUTER)) {
- $this->match(Lexer::T_OUTER);
- $joinType = AST\Join::JOIN_TYPE_LEFTOUTER;
- }
- break;
- case $this->lexer->isNextToken(Lexer::T_INNER):
- $this->match(Lexer::T_INNER);
- break;
- default:
- // Do nothing
- }
- $this->match(Lexer::T_JOIN);
- $next = $this->lexer->glimpse();
- $joinDeclaration = $next['type'] === Lexer::T_DOT ? $this->JoinAssociationDeclaration() : $this->RangeVariableDeclaration();
- $adhocConditions = $this->lexer->isNextToken(Lexer::T_WITH);
- $join = new AST\Join($joinType, $joinDeclaration);
- // Describe non-root join declaration
- if ($joinDeclaration instanceof AST\RangeVariableDeclaration) {
- $joinDeclaration->isRoot = false;
- }
- // Check for ad-hoc Join conditions
- if ($adhocConditions) {
- $this->match(Lexer::T_WITH);
- $join->conditionalExpression = $this->ConditionalExpression();
- }
- return $join;
- }
- /**
- * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable
- *
- * @return RangeVariableDeclaration
- *
- * @throws QueryException
- */
- public function RangeVariableDeclaration()
- {
- if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS) && $this->lexer->glimpse()['type'] === Lexer::T_SELECT) {
- $this->semanticalError('Subquery is not supported here', $this->lexer->token);
- }
- $abstractSchemaName = $this->AbstractSchemaName();
- $this->validateAbstractSchemaName($abstractSchemaName);
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- }
- $token = $this->lexer->lookahead;
- $aliasIdentificationVariable = $this->AliasIdentificationVariable();
- $classMetadata = $this->em->getClassMetadata($abstractSchemaName);
- // Building queryComponent
- $queryComponent = [
- 'metadata' => $classMetadata,
- 'parent' => null,
- 'relation' => null,
- 'map' => null,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $token,
- ];
- $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;
- return new AST\RangeVariableDeclaration($abstractSchemaName, $aliasIdentificationVariable);
- }
- /**
- * JoinAssociationDeclaration ::= JoinAssociationPathExpression ["AS"] AliasIdentificationVariable [IndexBy]
- *
- * @return AST\JoinAssociationDeclaration
- */
- public function JoinAssociationDeclaration()
- {
- $joinAssociationPathExpression = $this->JoinAssociationPathExpression();
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- }
- $aliasIdentificationVariable = $this->AliasIdentificationVariable();
- $indexBy = $this->lexer->isNextToken(Lexer::T_INDEX) ? $this->IndexBy() : null;
- $identificationVariable = $joinAssociationPathExpression->identificationVariable;
- $field = $joinAssociationPathExpression->associationField;
- $class = $this->queryComponents[$identificationVariable]['metadata'];
- $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']);
- // Building queryComponent
- $joinQueryComponent = [
- 'metadata' => $targetClass,
- 'parent' => $joinAssociationPathExpression->identificationVariable,
- 'relation' => $class->getAssociationMapping($field),
- 'map' => null,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $this->lexer->lookahead,
- ];
- $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;
- return new AST\JoinAssociationDeclaration($joinAssociationPathExpression, $aliasIdentificationVariable, $indexBy);
- }
- /**
- * PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet
- * PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}"
- *
- * @return PartialObjectExpression
- */
- public function PartialObjectExpression()
- {
- $this->match(Lexer::T_PARTIAL);
- $partialFieldSet = [];
- $identificationVariable = $this->IdentificationVariable();
- $this->match(Lexer::T_DOT);
- $this->match(Lexer::T_OPEN_CURLY_BRACE);
- $this->match(Lexer::T_IDENTIFIER);
- $field = $this->lexer->token['value'];
- // First field in partial expression might be embeddable property
- while ($this->lexer->isNextToken(Lexer::T_DOT)) {
- $this->match(Lexer::T_DOT);
- $this->match(Lexer::T_IDENTIFIER);
- $field .= '.' . $this->lexer->token['value'];
- }
- $partialFieldSet[] = $field;
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $this->match(Lexer::T_IDENTIFIER);
- $field = $this->lexer->token['value'];
- while ($this->lexer->isNextToken(Lexer::T_DOT)) {
- $this->match(Lexer::T_DOT);
- $this->match(Lexer::T_IDENTIFIER);
- $field .= '.' . $this->lexer->token['value'];
- }
- $partialFieldSet[] = $field;
- }
- $this->match(Lexer::T_CLOSE_CURLY_BRACE);
- $partialObjectExpression = new AST\PartialObjectExpression($identificationVariable, $partialFieldSet);
- // Defer PartialObjectExpression validation
- $this->deferredPartialObjectExpressions[] = [
- 'expression' => $partialObjectExpression,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $this->lexer->token,
- ];
- return $partialObjectExpression;
- }
- /**
- * NewObjectExpression ::= "NEW" AbstractSchemaName "(" NewObjectArg {"," NewObjectArg}* ")"
- *
- * @return NewObjectExpression
- */
- public function NewObjectExpression()
- {
- $this->match(Lexer::T_NEW);
- $className = $this->AbstractSchemaName(); // note that this is not yet validated
- $token = $this->lexer->token;
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $args[] = $this->NewObjectArg();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $args[] = $this->NewObjectArg();
- }
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- $expression = new AST\NewObjectExpression($className, $args);
- // Defer NewObjectExpression validation
- $this->deferredNewObjectExpressions[] = [
- 'token' => $token,
- 'expression' => $expression,
- 'nestingLevel' => $this->nestingLevel,
- ];
- return $expression;
- }
- /**
- * NewObjectArg ::= ScalarExpression | "(" Subselect ")"
- *
- * @return mixed
- */
- public function NewObjectArg()
- {
- $token = $this->lexer->lookahead;
- $peek = $this->lexer->glimpse();
- if ($token['type'] === Lexer::T_OPEN_PARENTHESIS && $peek['type'] === Lexer::T_SELECT) {
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $expression = $this->Subselect();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $expression;
- }
- return $this->ScalarExpression();
- }
- /**
- * IndexBy ::= "INDEX" "BY" StateFieldPathExpression
- *
- * @return IndexBy
- */
- public function IndexBy()
- {
- $this->match(Lexer::T_INDEX);
- $this->match(Lexer::T_BY);
- $pathExpr = $this->StateFieldPathExpression();
- // Add the INDEX BY info to the query component
- $this->queryComponents[$pathExpr->identificationVariable]['map'] = $pathExpr->field;
- return new AST\IndexBy($pathExpr);
- }
- /**
- * ScalarExpression ::= SimpleArithmeticExpression | StringPrimary | DateTimePrimary |
- * StateFieldPathExpression | BooleanPrimary | CaseExpression |
- * InstanceOfExpression
- *
- * @return mixed One of the possible expressions or subexpressions.
- */
- public function ScalarExpression()
- {
- $lookahead = $this->lexer->lookahead['type'];
- $peek = $this->lexer->glimpse();
- switch (true) {
- case $lookahead === Lexer::T_INTEGER:
- case $lookahead === Lexer::T_FLOAT:
- // SimpleArithmeticExpression : (- u.value ) or ( + u.value ) or ( - 1 ) or ( + 1 )
- case $lookahead === Lexer::T_MINUS:
- case $lookahead === Lexer::T_PLUS:
- return $this->SimpleArithmeticExpression();
- case $lookahead === Lexer::T_STRING:
- return $this->StringPrimary();
- case $lookahead === Lexer::T_TRUE:
- case $lookahead === Lexer::T_FALSE:
- $this->match($lookahead);
- return new AST\Literal(AST\Literal::BOOLEAN, $this->lexer->token['value']);
- case $lookahead === Lexer::T_INPUT_PARAMETER:
- switch (true) {
- case $this->isMathOperator($peek):
- // :param + u.value
- return $this->SimpleArithmeticExpression();
- default:
- return $this->InputParameter();
- }
- case $lookahead === Lexer::T_CASE:
- case $lookahead === Lexer::T_COALESCE:
- case $lookahead === Lexer::T_NULLIF:
- // Since NULLIF and COALESCE can be identified as a function,
- // we need to check these before checking for FunctionDeclaration
- return $this->CaseExpression();
- case $lookahead === Lexer::T_OPEN_PARENTHESIS:
- return $this->SimpleArithmeticExpression();
- // this check must be done before checking for a filed path expression
- case $this->isFunction():
- $this->lexer->peek(); // "("
- switch (true) {
- case $this->isMathOperator($this->peekBeyondClosingParenthesis()):
- // SUM(u.id) + COUNT(u.id)
- return $this->SimpleArithmeticExpression();
- default:
- // IDENTITY(u)
- return $this->FunctionDeclaration();
- }
- break;
- // it is no function, so it must be a field path
- case $lookahead === Lexer::T_IDENTIFIER:
- $this->lexer->peek(); // lookahead => '.'
- $this->lexer->peek(); // lookahead => token after '.'
- $peek = $this->lexer->peek(); // lookahead => token after the token after the '.'
- $this->lexer->resetPeek();
- if ($this->isMathOperator($peek)) {
- return $this->SimpleArithmeticExpression();
- }
- return $this->StateFieldPathExpression();
- default:
- $this->syntaxError();
- }
- }
- /**
- * CaseExpression ::= GeneralCaseExpression | SimpleCaseExpression | CoalesceExpression | NullifExpression
- * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END"
- * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression
- * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END"
- * CaseOperand ::= StateFieldPathExpression | TypeDiscriminator
- * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression
- * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")"
- * NullifExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")"
- *
- * @return mixed One of the possible expressions or subexpressions.
- */
- public function CaseExpression()
- {
- $lookahead = $this->lexer->lookahead['type'];
- switch ($lookahead) {
- case Lexer::T_NULLIF:
- return $this->NullIfExpression();
- case Lexer::T_COALESCE:
- return $this->CoalesceExpression();
- case Lexer::T_CASE:
- $this->lexer->resetPeek();
- $peek = $this->lexer->peek();
- if ($peek['type'] === Lexer::T_WHEN) {
- return $this->GeneralCaseExpression();
- }
- return $this->SimpleCaseExpression();
- default:
- // Do nothing
- break;
- }
- $this->syntaxError();
- }
- /**
- * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")"
- *
- * @return CoalesceExpression
- */
- public function CoalesceExpression()
- {
- $this->match(Lexer::T_COALESCE);
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- // Process ScalarExpressions (1..N)
- $scalarExpressions = [];
- $scalarExpressions[] = $this->ScalarExpression();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $scalarExpressions[] = $this->ScalarExpression();
- }
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return new AST\CoalesceExpression($scalarExpressions);
- }
- /**
- * NullIfExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")"
- *
- * @return NullIfExpression
- */
- public function NullIfExpression()
- {
- $this->match(Lexer::T_NULLIF);
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $firstExpression = $this->ScalarExpression();
- $this->match(Lexer::T_COMMA);
- $secondExpression = $this->ScalarExpression();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return new AST\NullIfExpression($firstExpression, $secondExpression);
- }
- /**
- * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END"
- *
- * @return GeneralCaseExpression
- */
- public function GeneralCaseExpression()
- {
- $this->match(Lexer::T_CASE);
- // Process WhenClause (1..N)
- $whenClauses = [];
- do {
- $whenClauses[] = $this->WhenClause();
- } while ($this->lexer->isNextToken(Lexer::T_WHEN));
- $this->match(Lexer::T_ELSE);
- $scalarExpression = $this->ScalarExpression();
- $this->match(Lexer::T_END);
- return new AST\GeneralCaseExpression($whenClauses, $scalarExpression);
- }
- /**
- * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END"
- * CaseOperand ::= StateFieldPathExpression | TypeDiscriminator
- *
- * @return AST\SimpleCaseExpression
- */
- public function SimpleCaseExpression()
- {
- $this->match(Lexer::T_CASE);
- $caseOperand = $this->StateFieldPathExpression();
- // Process SimpleWhenClause (1..N)
- $simpleWhenClauses = [];
- do {
- $simpleWhenClauses[] = $this->SimpleWhenClause();
- } while ($this->lexer->isNextToken(Lexer::T_WHEN));
- $this->match(Lexer::T_ELSE);
- $scalarExpression = $this->ScalarExpression();
- $this->match(Lexer::T_END);
- return new AST\SimpleCaseExpression($caseOperand, $simpleWhenClauses, $scalarExpression);
- }
- /**
- * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression
- *
- * @return WhenClause
- */
- public function WhenClause()
- {
- $this->match(Lexer::T_WHEN);
- $conditionalExpression = $this->ConditionalExpression();
- $this->match(Lexer::T_THEN);
- return new AST\WhenClause($conditionalExpression, $this->ScalarExpression());
- }
- /**
- * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression
- *
- * @return SimpleWhenClause
- */
- public function SimpleWhenClause()
- {
- $this->match(Lexer::T_WHEN);
- $conditionalExpression = $this->ScalarExpression();
- $this->match(Lexer::T_THEN);
- return new AST\SimpleWhenClause($conditionalExpression, $this->ScalarExpression());
- }
- /**
- * SelectExpression ::= (
- * IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration |
- * PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression
- * ) [["AS"] ["HIDDEN"] AliasResultVariable]
- *
- * @return SelectExpression
- */
- public function SelectExpression()
- {
- $expression = null;
- $identVariable = null;
- $peek = $this->lexer->glimpse();
- $lookaheadType = $this->lexer->lookahead['type'];
- switch (true) {
- // ScalarExpression (u.name)
- case $lookaheadType === Lexer::T_IDENTIFIER && $peek['type'] === Lexer::T_DOT:
- $expression = $this->ScalarExpression();
- break;
- // IdentificationVariable (u)
- case $lookaheadType === Lexer::T_IDENTIFIER && $peek['type'] !== Lexer::T_OPEN_PARENTHESIS:
- $expression = $identVariable = $this->IdentificationVariable();
- break;
- // CaseExpression (CASE ... or NULLIF(...) or COALESCE(...))
- case $lookaheadType === Lexer::T_CASE:
- case $lookaheadType === Lexer::T_COALESCE:
- case $lookaheadType === Lexer::T_NULLIF:
- $expression = $this->CaseExpression();
- break;
- // DQL Function (SUM(u.value) or SUM(u.value) + 1)
- case $this->isFunction():
- $this->lexer->peek(); // "("
- switch (true) {
- case $this->isMathOperator($this->peekBeyondClosingParenthesis()):
- // SUM(u.id) + COUNT(u.id)
- $expression = $this->ScalarExpression();
- break;
- default:
- // IDENTITY(u)
- $expression = $this->FunctionDeclaration();
- break;
- }
- break;
- // PartialObjectExpression (PARTIAL u.{id, name})
- case $lookaheadType === Lexer::T_PARTIAL:
- $expression = $this->PartialObjectExpression();
- $identVariable = $expression->identificationVariable;
- break;
- // Subselect
- case $lookaheadType === Lexer::T_OPEN_PARENTHESIS && $peek['type'] === Lexer::T_SELECT:
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $expression = $this->Subselect();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- break;
- // Shortcut: ScalarExpression => SimpleArithmeticExpression
- case $lookaheadType === Lexer::T_OPEN_PARENTHESIS:
- case $lookaheadType === Lexer::T_INTEGER:
- case $lookaheadType === Lexer::T_STRING:
- case $lookaheadType === Lexer::T_FLOAT:
- // SimpleArithmeticExpression : (- u.value ) or ( + u.value )
- case $lookaheadType === Lexer::T_MINUS:
- case $lookaheadType === Lexer::T_PLUS:
- $expression = $this->SimpleArithmeticExpression();
- break;
- // NewObjectExpression (New ClassName(id, name))
- case $lookaheadType === Lexer::T_NEW:
- $expression = $this->NewObjectExpression();
- break;
- default:
- $this->syntaxError(
- 'IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression',
- $this->lexer->lookahead
- );
- }
- // [["AS"] ["HIDDEN"] AliasResultVariable]
- $mustHaveAliasResultVariable = false;
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- $mustHaveAliasResultVariable = true;
- }
- $hiddenAliasResultVariable = false;
- if ($this->lexer->isNextToken(Lexer::T_HIDDEN)) {
- $this->match(Lexer::T_HIDDEN);
- $hiddenAliasResultVariable = true;
- }
- $aliasResultVariable = null;
- if ($mustHaveAliasResultVariable || $this->lexer->isNextToken(Lexer::T_IDENTIFIER)) {
- $token = $this->lexer->lookahead;
- $aliasResultVariable = $this->AliasResultVariable();
- // Include AliasResultVariable in query components.
- $this->queryComponents[$aliasResultVariable] = [
- 'resultVariable' => $expression,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $token,
- ];
- }
- // AST
- $expr = new AST\SelectExpression($expression, $aliasResultVariable, $hiddenAliasResultVariable);
- if ($identVariable) {
- $this->identVariableExpressions[$identVariable] = $expr;
- }
- return $expr;
- }
- /**
- * SimpleSelectExpression ::= (
- * StateFieldPathExpression | IdentificationVariable | FunctionDeclaration |
- * AggregateExpression | "(" Subselect ")" | ScalarExpression
- * ) [["AS"] AliasResultVariable]
- *
- * @return SimpleSelectExpression
- */
- public function SimpleSelectExpression()
- {
- $peek = $this->lexer->glimpse();
- switch ($this->lexer->lookahead['type']) {
- case Lexer::T_IDENTIFIER:
- switch (true) {
- case $peek['type'] === Lexer::T_DOT:
- $expression = $this->StateFieldPathExpression();
- return new AST\SimpleSelectExpression($expression);
- case $peek['type'] !== Lexer::T_OPEN_PARENTHESIS:
- $expression = $this->IdentificationVariable();
- return new AST\SimpleSelectExpression($expression);
- case $this->isFunction():
- // SUM(u.id) + COUNT(u.id)
- if ($this->isMathOperator($this->peekBeyondClosingParenthesis())) {
- return new AST\SimpleSelectExpression($this->ScalarExpression());
- }
- // COUNT(u.id)
- if ($this->isAggregateFunction($this->lexer->lookahead['type'])) {
- return new AST\SimpleSelectExpression($this->AggregateExpression());
- }
- // IDENTITY(u)
- return new AST\SimpleSelectExpression($this->FunctionDeclaration());
- default:
- // Do nothing
- }
- break;
- case Lexer::T_OPEN_PARENTHESIS:
- if ($peek['type'] !== Lexer::T_SELECT) {
- // Shortcut: ScalarExpression => SimpleArithmeticExpression
- $expression = $this->SimpleArithmeticExpression();
- return new AST\SimpleSelectExpression($expression);
- }
- // Subselect
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $expression = $this->Subselect();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return new AST\SimpleSelectExpression($expression);
- default:
- // Do nothing
- }
- $this->lexer->peek();
- $expression = $this->ScalarExpression();
- $expr = new AST\SimpleSelectExpression($expression);
- if ($this->lexer->isNextToken(Lexer::T_AS)) {
- $this->match(Lexer::T_AS);
- }
- if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) {
- $token = $this->lexer->lookahead;
- $resultVariable = $this->AliasResultVariable();
- $expr->fieldIdentificationVariable = $resultVariable;
- // Include AliasResultVariable in query components.
- $this->queryComponents[$resultVariable] = [
- 'resultvariable' => $expr,
- 'nestingLevel' => $this->nestingLevel,
- 'token' => $token,
- ];
- }
- return $expr;
- }
- /**
- * ConditionalExpression ::= ConditionalTerm {"OR" ConditionalTerm}*
- *
- * @return AST\ConditionalExpression|AST\ConditionalFactor|AST\ConditionalPrimary|AST\ConditionalTerm
- */
- public function ConditionalExpression()
- {
- $conditionalTerms = [];
- $conditionalTerms[] = $this->ConditionalTerm();
- while ($this->lexer->isNextToken(Lexer::T_OR)) {
- $this->match(Lexer::T_OR);
- $conditionalTerms[] = $this->ConditionalTerm();
- }
- // Phase 1 AST optimization: Prevent AST\ConditionalExpression
- // if only one AST\ConditionalTerm is defined
- if (count($conditionalTerms) === 1) {
- return $conditionalTerms[0];
- }
- return new AST\ConditionalExpression($conditionalTerms);
- }
- /**
- * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}*
- *
- * @return AST\ConditionalFactor|AST\ConditionalPrimary|AST\ConditionalTerm
- */
- public function ConditionalTerm()
- {
- $conditionalFactors = [];
- $conditionalFactors[] = $this->ConditionalFactor();
- while ($this->lexer->isNextToken(Lexer::T_AND)) {
- $this->match(Lexer::T_AND);
- $conditionalFactors[] = $this->ConditionalFactor();
- }
- // Phase 1 AST optimization: Prevent AST\ConditionalTerm
- // if only one AST\ConditionalFactor is defined
- if (count($conditionalFactors) === 1) {
- return $conditionalFactors[0];
- }
- return new AST\ConditionalTerm($conditionalFactors);
- }
- /**
- * ConditionalFactor ::= ["NOT"] ConditionalPrimary
- *
- * @return AST\ConditionalFactor|AST\ConditionalPrimary
- */
- public function ConditionalFactor()
- {
- $not = false;
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $not = true;
- }
- $conditionalPrimary = $this->ConditionalPrimary();
- // Phase 1 AST optimization: Prevent AST\ConditionalFactor
- // if only one AST\ConditionalPrimary is defined
- if (! $not) {
- return $conditionalPrimary;
- }
- $conditionalFactor = new AST\ConditionalFactor($conditionalPrimary);
- $conditionalFactor->not = $not;
- return $conditionalFactor;
- }
- /**
- * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
- *
- * @return ConditionalPrimary
- */
- public function ConditionalPrimary()
- {
- $condPrimary = new AST\ConditionalPrimary();
- if (! $this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
- $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression();
- return $condPrimary;
- }
- // Peek beyond the matching closing parenthesis ')'
- $peek = $this->peekBeyondClosingParenthesis();
- if (
- $peek !== null && (
- in_array($peek['value'], ['=', '<', '<=', '<>', '>', '>=', '!=']) ||
- in_array($peek['type'], [Lexer::T_NOT, Lexer::T_BETWEEN, Lexer::T_LIKE, Lexer::T_IN, Lexer::T_IS, Lexer::T_EXISTS]) ||
- $this->isMathOperator($peek)
- )
- ) {
- $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression();
- return $condPrimary;
- }
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $condPrimary->conditionalExpression = $this->ConditionalExpression();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $condPrimary;
- }
- /**
- * SimpleConditionalExpression ::=
- * ComparisonExpression | BetweenExpression | LikeExpression |
- * InExpression | NullComparisonExpression | ExistsExpression |
- * EmptyCollectionComparisonExpression | CollectionMemberExpression |
- * InstanceOfExpression
- *
- * @return Node
- */
- public function SimpleConditionalExpression()
- {
- if ($this->lexer->isNextToken(Lexer::T_EXISTS)) {
- return $this->ExistsExpression();
- }
- $token = $this->lexer->lookahead;
- $peek = $this->lexer->glimpse();
- $lookahead = $token;
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $token = $this->lexer->glimpse();
- }
- if ($token['type'] === Lexer::T_IDENTIFIER || $token['type'] === Lexer::T_INPUT_PARAMETER || $this->isFunction()) {
- // Peek beyond the matching closing parenthesis.
- $beyond = $this->lexer->peek();
- switch ($peek['value']) {
- case '(':
- // Peeks beyond the matched closing parenthesis.
- $token = $this->peekBeyondClosingParenthesis(false);
- if ($token['type'] === Lexer::T_NOT) {
- $token = $this->lexer->peek();
- }
- if ($token['type'] === Lexer::T_IS) {
- $lookahead = $this->lexer->peek();
- }
- break;
- default:
- // Peek beyond the PathExpression or InputParameter.
- $token = $beyond;
- while ($token['value'] === '.') {
- $this->lexer->peek();
- $token = $this->lexer->peek();
- }
- // Also peek beyond a NOT if there is one.
- if ($token['type'] === Lexer::T_NOT) {
- $token = $this->lexer->peek();
- }
- // We need to go even further in case of IS (differentiate between NULL and EMPTY)
- $lookahead = $this->lexer->peek();
- }
- // Also peek beyond a NOT if there is one.
- if ($lookahead['type'] === Lexer::T_NOT) {
- $lookahead = $this->lexer->peek();
- }
- $this->lexer->resetPeek();
- }
- if ($token['type'] === Lexer::T_BETWEEN) {
- return $this->BetweenExpression();
- }
- if ($token['type'] === Lexer::T_LIKE) {
- return $this->LikeExpression();
- }
- if ($token['type'] === Lexer::T_IN) {
- return $this->InExpression();
- }
- if ($token['type'] === Lexer::T_INSTANCE) {
- return $this->InstanceOfExpression();
- }
- if ($token['type'] === Lexer::T_MEMBER) {
- return $this->CollectionMemberExpression();
- }
- if ($token['type'] === Lexer::T_IS && $lookahead['type'] === Lexer::T_NULL) {
- return $this->NullComparisonExpression();
- }
- if ($token['type'] === Lexer::T_IS && $lookahead['type'] === Lexer::T_EMPTY) {
- return $this->EmptyCollectionComparisonExpression();
- }
- return $this->ComparisonExpression();
- }
- /**
- * EmptyCollectionComparisonExpression ::= CollectionValuedPathExpression "IS" ["NOT"] "EMPTY"
- *
- * @return EmptyCollectionComparisonExpression
- */
- public function EmptyCollectionComparisonExpression()
- {
- $emptyCollectionCompExpr = new AST\EmptyCollectionComparisonExpression(
- $this->CollectionValuedPathExpression()
- );
- $this->match(Lexer::T_IS);
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $emptyCollectionCompExpr->not = true;
- }
- $this->match(Lexer::T_EMPTY);
- return $emptyCollectionCompExpr;
- }
- /**
- * CollectionMemberExpression ::= EntityExpression ["NOT"] "MEMBER" ["OF"] CollectionValuedPathExpression
- *
- * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
- * SimpleEntityExpression ::= IdentificationVariable | InputParameter
- *
- * @return CollectionMemberExpression
- */
- public function CollectionMemberExpression()
- {
- $not = false;
- $entityExpr = $this->EntityExpression();
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $not = true;
- }
- $this->match(Lexer::T_MEMBER);
- if ($this->lexer->isNextToken(Lexer::T_OF)) {
- $this->match(Lexer::T_OF);
- }
- $collMemberExpr = new AST\CollectionMemberExpression(
- $entityExpr,
- $this->CollectionValuedPathExpression()
- );
- $collMemberExpr->not = $not;
- return $collMemberExpr;
- }
- /**
- * Literal ::= string | char | integer | float | boolean
- *
- * @return Literal
- */
- public function Literal()
- {
- switch ($this->lexer->lookahead['type']) {
- case Lexer::T_STRING:
- $this->match(Lexer::T_STRING);
- return new AST\Literal(AST\Literal::STRING, $this->lexer->token['value']);
- case Lexer::T_INTEGER:
- case Lexer::T_FLOAT:
- $this->match(
- $this->lexer->isNextToken(Lexer::T_INTEGER) ? Lexer::T_INTEGER : Lexer::T_FLOAT
- );
- return new AST\Literal(AST\Literal::NUMERIC, $this->lexer->token['value']);
- case Lexer::T_TRUE:
- case Lexer::T_FALSE:
- $this->match(
- $this->lexer->isNextToken(Lexer::T_TRUE) ? Lexer::T_TRUE : Lexer::T_FALSE
- );
- return new AST\Literal(AST\Literal::BOOLEAN, $this->lexer->token['value']);
- default:
- $this->syntaxError('Literal');
- }
- }
- /**
- * InParameter ::= Literal | InputParameter
- *
- * @return AST\InputParameter|AST\Literal
- */
- public function InParameter()
- {
- if ($this->lexer->lookahead['type'] === Lexer::T_INPUT_PARAMETER) {
- return $this->InputParameter();
- }
- return $this->Literal();
- }
- /**
- * InputParameter ::= PositionalParameter | NamedParameter
- *
- * @return InputParameter
- */
- public function InputParameter()
- {
- $this->match(Lexer::T_INPUT_PARAMETER);
- return new AST\InputParameter($this->lexer->token['value']);
- }
- /**
- * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")"
- *
- * @return ArithmeticExpression
- */
- public function ArithmeticExpression()
- {
- $expr = new AST\ArithmeticExpression();
- if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
- $peek = $this->lexer->glimpse();
- if ($peek['type'] === Lexer::T_SELECT) {
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $expr->subselect = $this->Subselect();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $expr;
- }
- }
- $expr->simpleArithmeticExpression = $this->SimpleArithmeticExpression();
- return $expr;
- }
- /**
- * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}*
- *
- * @return SimpleArithmeticExpression
- */
- public function SimpleArithmeticExpression()
- {
- $terms = [];
- $terms[] = $this->ArithmeticTerm();
- while (($isPlus = $this->lexer->isNextToken(Lexer::T_PLUS)) || $this->lexer->isNextToken(Lexer::T_MINUS)) {
- $this->match($isPlus ? Lexer::T_PLUS : Lexer::T_MINUS);
- $terms[] = $this->lexer->token['value'];
- $terms[] = $this->ArithmeticTerm();
- }
- // Phase 1 AST optimization: Prevent AST\SimpleArithmeticExpression
- // if only one AST\ArithmeticTerm is defined
- if (count($terms) === 1) {
- return $terms[0];
- }
- return new AST\SimpleArithmeticExpression($terms);
- }
- /**
- * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}*
- *
- * @return ArithmeticTerm
- */
- public function ArithmeticTerm()
- {
- $factors = [];
- $factors[] = $this->ArithmeticFactor();
- while (($isMult = $this->lexer->isNextToken(Lexer::T_MULTIPLY)) || $this->lexer->isNextToken(Lexer::T_DIVIDE)) {
- $this->match($isMult ? Lexer::T_MULTIPLY : Lexer::T_DIVIDE);
- $factors[] = $this->lexer->token['value'];
- $factors[] = $this->ArithmeticFactor();
- }
- // Phase 1 AST optimization: Prevent AST\ArithmeticTerm
- // if only one AST\ArithmeticFactor is defined
- if (count($factors) === 1) {
- return $factors[0];
- }
- return new AST\ArithmeticTerm($factors);
- }
- /**
- * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary
- *
- * @return ArithmeticFactor
- */
- public function ArithmeticFactor()
- {
- $sign = null;
- $isPlus = $this->lexer->isNextToken(Lexer::T_PLUS);
- if ($isPlus || $this->lexer->isNextToken(Lexer::T_MINUS)) {
- $this->match($isPlus ? Lexer::T_PLUS : Lexer::T_MINUS);
- $sign = $isPlus;
- }
- $primary = $this->ArithmeticPrimary();
- // Phase 1 AST optimization: Prevent AST\ArithmeticFactor
- // if only one AST\ArithmeticPrimary is defined
- if ($sign === null) {
- return $primary;
- }
- return new AST\ArithmeticFactor($primary, $sign);
- }
- /**
- * ArithmeticPrimary ::= SingleValuedPathExpression | Literal | ParenthesisExpression
- * | FunctionsReturningNumerics | AggregateExpression | FunctionsReturningStrings
- * | FunctionsReturningDatetime | IdentificationVariable | ResultVariable
- * | InputParameter | CaseExpression
- *
- * @return Node|string
- */
- public function ArithmeticPrimary()
- {
- if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $expr = $this->SimpleArithmeticExpression();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return new AST\ParenthesisExpression($expr);
- }
- switch ($this->lexer->lookahead['type']) {
- case Lexer::T_COALESCE:
- case Lexer::T_NULLIF:
- case Lexer::T_CASE:
- return $this->CaseExpression();
- case Lexer::T_IDENTIFIER:
- $peek = $this->lexer->glimpse();
- if ($peek !== null && $peek['value'] === '(') {
- return $this->FunctionDeclaration();
- }
- if ($peek !== null && $peek['value'] === '.') {
- return $this->SingleValuedPathExpression();
- }
- if (isset($this->queryComponents[$this->lexer->lookahead['value']]['resultVariable'])) {
- return $this->ResultVariable();
- }
- return $this->StateFieldPathExpression();
- case Lexer::T_INPUT_PARAMETER:
- return $this->InputParameter();
- default:
- $peek = $this->lexer->glimpse();
- if ($peek !== null && $peek['value'] === '(') {
- return $this->FunctionDeclaration();
- }
- return $this->Literal();
- }
- }
- /**
- * StringExpression ::= StringPrimary | ResultVariable | "(" Subselect ")"
- *
- * @return Subselect|string
- */
- public function StringExpression()
- {
- $peek = $this->lexer->glimpse();
- // Subselect
- if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS) && $peek['type'] === Lexer::T_SELECT) {
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $expr = $this->Subselect();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $expr;
- }
- // ResultVariable (string)
- if (
- $this->lexer->isNextToken(Lexer::T_IDENTIFIER) &&
- isset($this->queryComponents[$this->lexer->lookahead['value']]['resultVariable'])
- ) {
- return $this->ResultVariable();
- }
- return $this->StringPrimary();
- }
- /**
- * StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression | CaseExpression
- *
- * @return Node
- */
- public function StringPrimary()
- {
- $lookaheadType = $this->lexer->lookahead['type'];
- switch ($lookaheadType) {
- case Lexer::T_IDENTIFIER:
- $peek = $this->lexer->glimpse();
- if ($peek['value'] === '.') {
- return $this->StateFieldPathExpression();
- }
- if ($peek['value'] === '(') {
- // do NOT directly go to FunctionsReturningString() because it doesn't check for custom functions.
- return $this->FunctionDeclaration();
- }
- $this->syntaxError("'.' or '('");
- break;
- case Lexer::T_STRING:
- $this->match(Lexer::T_STRING);
- return new AST\Literal(AST\Literal::STRING, $this->lexer->token['value']);
- case Lexer::T_INPUT_PARAMETER:
- return $this->InputParameter();
- case Lexer::T_CASE:
- case Lexer::T_COALESCE:
- case Lexer::T_NULLIF:
- return $this->CaseExpression();
- default:
- if ($this->isAggregateFunction($lookaheadType)) {
- return $this->AggregateExpression();
- }
- }
- $this->syntaxError(
- 'StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression'
- );
- }
- /**
- * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
- *
- * @return AST\InputParameter|PathExpression
- */
- public function EntityExpression()
- {
- $glimpse = $this->lexer->glimpse();
- if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER) && $glimpse['value'] === '.') {
- return $this->SingleValuedAssociationPathExpression();
- }
- return $this->SimpleEntityExpression();
- }
- /**
- * SimpleEntityExpression ::= IdentificationVariable | InputParameter
- *
- * @return AST\InputParameter|AST\PathExpression
- */
- public function SimpleEntityExpression()
- {
- if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
- return $this->InputParameter();
- }
- return $this->StateFieldPathExpression();
- }
- /**
- * AggregateExpression ::=
- * ("AVG" | "MAX" | "MIN" | "SUM" | "COUNT") "(" ["DISTINCT"] SimpleArithmeticExpression ")"
- *
- * @return AggregateExpression
- */
- public function AggregateExpression()
- {
- $lookaheadType = $this->lexer->lookahead['type'];
- $isDistinct = false;
- if (! in_array($lookaheadType, [Lexer::T_COUNT, Lexer::T_AVG, Lexer::T_MAX, Lexer::T_MIN, Lexer::T_SUM])) {
- $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT');
- }
- $this->match($lookaheadType);
- $functionName = $this->lexer->token['value'];
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
- $this->match(Lexer::T_DISTINCT);
- $isDistinct = true;
- }
- $pathExp = $this->SimpleArithmeticExpression();
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return new AST\AggregateExpression($functionName, $pathExp, $isDistinct);
- }
- /**
- * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")"
- *
- * @return QuantifiedExpression
- */
- public function QuantifiedExpression()
- {
- $lookaheadType = $this->lexer->lookahead['type'];
- $value = $this->lexer->lookahead['value'];
- if (! in_array($lookaheadType, [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME])) {
- $this->syntaxError('ALL, ANY or SOME');
- }
- $this->match($lookaheadType);
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $qExpr = new AST\QuantifiedExpression($this->Subselect());
- $qExpr->type = $value;
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $qExpr;
- }
- /**
- * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression
- *
- * @return BetweenExpression
- */
- public function BetweenExpression()
- {
- $not = false;
- $arithExpr1 = $this->ArithmeticExpression();
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $not = true;
- }
- $this->match(Lexer::T_BETWEEN);
- $arithExpr2 = $this->ArithmeticExpression();
- $this->match(Lexer::T_AND);
- $arithExpr3 = $this->ArithmeticExpression();
- $betweenExpr = new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3);
- $betweenExpr->not = $not;
- return $betweenExpr;
- }
- /**
- * ComparisonExpression ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression )
- *
- * @return ComparisonExpression
- */
- public function ComparisonExpression()
- {
- $this->lexer->glimpse();
- $leftExpr = $this->ArithmeticExpression();
- $operator = $this->ComparisonOperator();
- $rightExpr = $this->isNextAllAnySome()
- ? $this->QuantifiedExpression()
- : $this->ArithmeticExpression();
- return new AST\ComparisonExpression($leftExpr, $operator, $rightExpr);
- }
- /**
- * InExpression ::= SingleValuedPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")"
- *
- * @return InExpression
- */
- public function InExpression()
- {
- $inExpression = new AST\InExpression($this->ArithmeticExpression());
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $inExpression->not = true;
- }
- $this->match(Lexer::T_IN);
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
- $inExpression->subselect = $this->Subselect();
- } else {
- $literals = [];
- $literals[] = $this->InParameter();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $literals[] = $this->InParameter();
- }
- $inExpression->literals = $literals;
- }
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $inExpression;
- }
- /**
- * InstanceOfExpression ::= IdentificationVariable ["NOT"] "INSTANCE" ["OF"] (InstanceOfParameter | "(" InstanceOfParameter {"," InstanceOfParameter}* ")")
- *
- * @return InstanceOfExpression
- */
- public function InstanceOfExpression()
- {
- $instanceOfExpression = new AST\InstanceOfExpression($this->IdentificationVariable());
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $instanceOfExpression->not = true;
- }
- $this->match(Lexer::T_INSTANCE);
- $this->match(Lexer::T_OF);
- $exprValues = [];
- if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $exprValues[] = $this->InstanceOfParameter();
- while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
- $this->match(Lexer::T_COMMA);
- $exprValues[] = $this->InstanceOfParameter();
- }
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- $instanceOfExpression->value = $exprValues;
- return $instanceOfExpression;
- }
- $exprValues[] = $this->InstanceOfParameter();
- $instanceOfExpression->value = $exprValues;
- return $instanceOfExpression;
- }
- /**
- * InstanceOfParameter ::= AbstractSchemaName | InputParameter
- *
- * @return mixed
- */
- public function InstanceOfParameter()
- {
- if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
- $this->match(Lexer::T_INPUT_PARAMETER);
- return new AST\InputParameter($this->lexer->token['value']);
- }
- $abstractSchemaName = $this->AbstractSchemaName();
- $this->validateAbstractSchemaName($abstractSchemaName);
- return $abstractSchemaName;
- }
- /**
- * LikeExpression ::= StringExpression ["NOT"] "LIKE" StringPrimary ["ESCAPE" char]
- *
- * @return LikeExpression
- */
- public function LikeExpression()
- {
- $stringExpr = $this->StringExpression();
- $not = false;
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $not = true;
- }
- $this->match(Lexer::T_LIKE);
- if ($this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
- $this->match(Lexer::T_INPUT_PARAMETER);
- $stringPattern = new AST\InputParameter($this->lexer->token['value']);
- } else {
- $stringPattern = $this->StringPrimary();
- }
- $escapeChar = null;
- if ($this->lexer->lookahead !== null && $this->lexer->lookahead['type'] === Lexer::T_ESCAPE) {
- $this->match(Lexer::T_ESCAPE);
- $this->match(Lexer::T_STRING);
- $escapeChar = new AST\Literal(AST\Literal::STRING, $this->lexer->token['value']);
- }
- $likeExpr = new AST\LikeExpression($stringExpr, $stringPattern, $escapeChar);
- $likeExpr->not = $not;
- return $likeExpr;
- }
- /**
- * NullComparisonExpression ::= (InputParameter | NullIfExpression | CoalesceExpression | AggregateExpression | FunctionDeclaration | IdentificationVariable | SingleValuedPathExpression | ResultVariable) "IS" ["NOT"] "NULL"
- *
- * @return NullComparisonExpression
- */
- public function NullComparisonExpression()
- {
- switch (true) {
- case $this->lexer->isNextToken(Lexer::T_INPUT_PARAMETER):
- $this->match(Lexer::T_INPUT_PARAMETER);
- $expr = new AST\InputParameter($this->lexer->token['value']);
- break;
- case $this->lexer->isNextToken(Lexer::T_NULLIF):
- $expr = $this->NullIfExpression();
- break;
- case $this->lexer->isNextToken(Lexer::T_COALESCE):
- $expr = $this->CoalesceExpression();
- break;
- case $this->isFunction():
- $expr = $this->FunctionDeclaration();
- break;
- default:
- // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression
- $glimpse = $this->lexer->glimpse();
- if ($glimpse['type'] === Lexer::T_DOT) {
- $expr = $this->SingleValuedPathExpression();
- // Leave switch statement
- break;
- }
- $lookaheadValue = $this->lexer->lookahead['value'];
- // Validate existing component
- if (! isset($this->queryComponents[$lookaheadValue])) {
- $this->semanticalError('Cannot add having condition on undefined result variable.');
- }
- // Validate SingleValuedPathExpression (ie.: "product")
- if (isset($this->queryComponents[$lookaheadValue]['metadata'])) {
- $expr = $this->SingleValuedPathExpression();
- break;
- }
- // Validating ResultVariable
- if (! isset($this->queryComponents[$lookaheadValue]['resultVariable'])) {
- $this->semanticalError('Cannot add having condition on a non result variable.');
- }
- $expr = $this->ResultVariable();
- break;
- }
- $nullCompExpr = new AST\NullComparisonExpression($expr);
- $this->match(Lexer::T_IS);
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $nullCompExpr->not = true;
- }
- $this->match(Lexer::T_NULL);
- return $nullCompExpr;
- }
- /**
- * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")"
- *
- * @return ExistsExpression
- */
- public function ExistsExpression()
- {
- $not = false;
- if ($this->lexer->isNextToken(Lexer::T_NOT)) {
- $this->match(Lexer::T_NOT);
- $not = true;
- }
- $this->match(Lexer::T_EXISTS);
- $this->match(Lexer::T_OPEN_PARENTHESIS);
- $existsExpression = new AST\ExistsExpression($this->Subselect());
- $existsExpression->not = $not;
- $this->match(Lexer::T_CLOSE_PARENTHESIS);
- return $existsExpression;
- }
- /**
- * ComparisonOperator ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!="
- *
- * @return string
- */
- public function ComparisonOperator()
- {
- switch ($this->lexer->lookahead['value']) {
- case '=':
- $this->match(Lexer::T_EQUALS);
- return '=';
- case '<':
- $this->match(Lexer::T_LOWER_THAN);
- $operator = '<';
- if ($this->lexer->isNextToken(Lexer::T_EQUALS)) {
- $this->match(Lexer::T_EQUALS);
- $operator .= '=';
- } elseif ($this->lexer->isNextToken(Lexer::T_GREATER_THAN)) {
- $this->match(Lexer::T_GREATER_THAN);
- $operator .= '>';
- }
- return $operator;
- case '>':
- $this->match(Lexer::T_GREATER_THAN);
- $operator = '>';
- if ($this->lexer->isNextToken(Lexer::T_EQUALS)) {
- $this->match(Lexer::T_EQUALS);
- $operator .= '=';
- }
- return $operator;
- case '!':
- $this->match(Lexer::T_NEGATE);
- $this->match(Lexer::T_EQUALS);
- return '<>';
- default:
- $this->syntaxError('=, <, <=, <>, >, >=, !=');
- }
- }
- /**
- * FunctionDeclaration ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime
- *
- * @return FunctionNode
- */
- public function FunctionDeclaration()
- {
- $token = $this->lexer->lookahead;
- $funcName = strtolower($token['value']);
- $customFunctionDeclaration = $this->CustomFunctionDeclaration();
- // Check for custom functions functions first!
- switch (true) {
- case $customFunctionDeclaration !== null:
- return $customFunctionDeclaration;
- case isset(self::$stringFunctions[$funcName]):
- return $this->FunctionsReturningStrings();
- case isset(self::$numericFunctions[$funcName]):
- return $this->FunctionsReturningNumerics();
- case isset(self::$datetimeFunctions[$funcName]):
- return $this->FunctionsReturningDatetime();
- default:
- $this->syntaxError('known function', $token);
- }
- }
- /**
- * Helper function for FunctionDeclaration grammar rule.
- *
- * @return FunctionNode
- */
- private function CustomFunctionDeclaration()
- {
- $token = $this->lexer->lookahead;
- $funcName = strtolower($token['value']);
- // Check for custom functions afterwards
- $config = $this->em->getConfiguration();
- switch (true) {
- case $config->getCustomStringFunction($funcName) !== null:
- return $this->CustomFunctionsReturningStrings();
- case $config->getCustomNumericFunction($funcName) !== null:
- return $this->CustomFunctionsReturningNumerics();
- case $config->getCustomDatetimeFunction($funcName) !== null:
- return $this->CustomFunctionsReturningDatetime();
- default:
- return null;
- }
- }
- /**
- * FunctionsReturningNumerics ::=
- * "LENGTH" "(" StringPrimary ")" |
- * "LOCATE" "(" StringPrimary "," StringPrimary ["," SimpleArithmeticExpression]")" |
- * "ABS" "(" SimpleArithmeticExpression ")" |
- * "SQRT" "(" SimpleArithmeticExpression ")" |
- * "MOD" "(" SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
- * "SIZE" "(" CollectionValuedPathExpression ")" |
- * "DATE_DIFF" "(" ArithmeticPrimary "," ArithmeticPrimary ")" |
- * "BIT_AND" "(" ArithmeticPrimary "," ArithmeticPrimary ")" |
- * "BIT_OR" "(" ArithmeticPrimary "," ArithmeticPrimary ")"
- *
- * @return FunctionNode
- */
- public function FunctionsReturningNumerics()
- {
- $funcNameLower = strtolower($this->lexer->lookahead['value']);
- $funcClass = self::$numericFunctions[$funcNameLower];
- $function = new $funcClass($funcNameLower);
- $function->parse($this);
- return $function;
- }
- /**
- * @return FunctionNode
- */
- public function CustomFunctionsReturningNumerics()
- {
- // getCustomNumericFunction is case-insensitive
- $functionName = strtolower($this->lexer->lookahead['value']);
- $functionClass = $this->em->getConfiguration()->getCustomNumericFunction($functionName);
- $function = is_string($functionClass)
- ? new $functionClass($functionName)
- : call_user_func($functionClass, $functionName);
- $function->parse($this);
- return $function;
- }
- /**
- * FunctionsReturningDateTime ::=
- * "CURRENT_DATE" |
- * "CURRENT_TIME" |
- * "CURRENT_TIMESTAMP" |
- * "DATE_ADD" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")" |
- * "DATE_SUB" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")"
- *
- * @return FunctionNode
- */
- public function FunctionsReturningDatetime()
- {
- $funcNameLower = strtolower($this->lexer->lookahead['value']);
- $funcClass = self::$datetimeFunctions[$funcNameLower];
- $function = new $funcClass($funcNameLower);
- $function->parse($this);
- return $function;
- }
- /**
- * @return FunctionNode
- */
- public function CustomFunctionsReturningDatetime()
- {
- // getCustomDatetimeFunction is case-insensitive
- $functionName = $this->lexer->lookahead['value'];
- $functionClass = $this->em->getConfiguration()->getCustomDatetimeFunction($functionName);
- $function = is_string($functionClass)
- ? new $functionClass($functionName)
- : call_user_func($functionClass, $functionName);
- $function->parse($this);
- return $function;
- }
- /**
- * FunctionsReturningStrings ::=
- * "CONCAT" "(" StringPrimary "," StringPrimary {"," StringPrimary}* ")" |
- * "SUBSTRING" "(" StringPrimary "," SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
- * "TRIM" "(" [["LEADING" | "TRAILING" | "BOTH"] [char] "FROM"] StringPrimary ")" |
- * "LOWER" "(" StringPrimary ")" |
- * "UPPER" "(" StringPrimary ")" |
- * "IDENTITY" "(" SingleValuedAssociationPathExpression {"," string} ")"
- *
- * @return FunctionNode
- */
- public function FunctionsReturningStrings()
- {
- $funcNameLower = strtolower($this->lexer->lookahead['value']);
- $funcClass = self::$stringFunctions[$funcNameLower];
- $function = new $funcClass($funcNameLower);
- $function->parse($this);
- return $function;
- }
- /**
- * @return FunctionNode
- */
- public function CustomFunctionsReturningStrings()
- {
- // getCustomStringFunction is case-insensitive
- $functionName = $this->lexer->lookahead['value'];
- $functionClass = $this->em->getConfiguration()->getCustomStringFunction($functionName);
- $function = is_string($functionClass)
- ? new $functionClass($functionName)
- : call_user_func($functionClass, $functionName);
- $function->parse($this);
- return $function;
- }
- }
|