api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.php 368KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984
  1. <?php
  2. /**
  3. * PHP-CRUD-API v2 License: MIT
  4. * Maurits van der Schee: maurits@vdschee.nl
  5. * https://github.com/mevdschee/php-crud-api
  6. *
  7. * Dependencies:
  8. * - vendor/psr/*: PHP-FIG
  9. * https://github.com/php-fig
  10. * - vendor/nyholm/*: Tobias Nyholm
  11. * https://github.com/Nyholm
  12. **/
  13. // file: vendor/psr/http-factory/src/RequestFactoryInterface.php
  14. namespace Psr\Http\Message {
  15. interface RequestFactoryInterface
  16. {
  17. /**
  18. * Create a new request.
  19. *
  20. * @param string $method The HTTP method associated with the request.
  21. * @param UriInterface|string $uri The URI associated with the request. If
  22. * the value is a string, the factory MUST create a UriInterface
  23. * instance based on it.
  24. *
  25. * @return RequestInterface
  26. */
  27. public function createRequest(string $method, $uri): RequestInterface;
  28. }
  29. }
  30. // file: vendor/psr/http-factory/src/ResponseFactoryInterface.php
  31. namespace Psr\Http\Message {
  32. interface ResponseFactoryInterface
  33. {
  34. /**
  35. * Create a new response.
  36. *
  37. * @param int $code HTTP status code; defaults to 200
  38. * @param string $reasonPhrase Reason phrase to associate with status code
  39. * in generated response; if none is provided implementations MAY use
  40. * the defaults as suggested in the HTTP specification.
  41. *
  42. * @return ResponseInterface
  43. */
  44. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface;
  45. }
  46. }
  47. // file: vendor/psr/http-factory/src/ServerRequestFactoryInterface.php
  48. namespace Psr\Http\Message {
  49. interface ServerRequestFactoryInterface
  50. {
  51. /**
  52. * Create a new server request.
  53. *
  54. * Note that server-params are taken precisely as given - no parsing/processing
  55. * of the given values is performed, and, in particular, no attempt is made to
  56. * determine the HTTP method or URI, which must be provided explicitly.
  57. *
  58. * @param string $method The HTTP method associated with the request.
  59. * @param UriInterface|string $uri The URI associated with the request. If
  60. * the value is a string, the factory MUST create a UriInterface
  61. * instance based on it.
  62. * @param array $serverParams Array of SAPI parameters with which to seed
  63. * the generated request instance.
  64. *
  65. * @return ServerRequestInterface
  66. */
  67. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface;
  68. }
  69. }
  70. // file: vendor/psr/http-factory/src/StreamFactoryInterface.php
  71. namespace Psr\Http\Message {
  72. interface StreamFactoryInterface
  73. {
  74. /**
  75. * Create a new stream from a string.
  76. *
  77. * The stream SHOULD be created with a temporary resource.
  78. *
  79. * @param string $content String content with which to populate the stream.
  80. *
  81. * @return StreamInterface
  82. */
  83. public function createStream(string $content = ''): StreamInterface;
  84. /**
  85. * Create a stream from an existing file.
  86. *
  87. * The file MUST be opened using the given mode, which may be any mode
  88. * supported by the `fopen` function.
  89. *
  90. * The `$filename` MAY be any string supported by `fopen()`.
  91. *
  92. * @param string $filename Filename or stream URI to use as basis of stream.
  93. * @param string $mode Mode with which to open the underlying filename/stream.
  94. *
  95. * @return StreamInterface
  96. * @throws \RuntimeException If the file cannot be opened.
  97. * @throws \InvalidArgumentException If the mode is invalid.
  98. */
  99. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface;
  100. /**
  101. * Create a new stream from an existing resource.
  102. *
  103. * The stream MUST be readable and may be writable.
  104. *
  105. * @param resource $resource PHP resource to use as basis of stream.
  106. *
  107. * @return StreamInterface
  108. */
  109. public function createStreamFromResource($resource): StreamInterface;
  110. }
  111. }
  112. // file: vendor/psr/http-factory/src/UploadedFileFactoryInterface.php
  113. namespace Psr\Http\Message {
  114. interface UploadedFileFactoryInterface
  115. {
  116. /**
  117. * Create a new uploaded file.
  118. *
  119. * If a size is not provided it will be determined by checking the size of
  120. * the file.
  121. *
  122. * @see http://php.net/manual/features.file-upload.post-method.php
  123. * @see http://php.net/manual/features.file-upload.errors.php
  124. *
  125. * @param StreamInterface $stream Underlying stream representing the
  126. * uploaded file content.
  127. * @param int $size in bytes
  128. * @param int $error PHP file upload error
  129. * @param string $clientFilename Filename as provided by the client, if any.
  130. * @param string $clientMediaType Media type as provided by the client, if any.
  131. *
  132. * @return UploadedFileInterface
  133. *
  134. * @throws \InvalidArgumentException If the file resource is not readable.
  135. */
  136. public function createUploadedFile(
  137. StreamInterface $stream,
  138. int $size = null,
  139. int $error = \UPLOAD_ERR_OK,
  140. string $clientFilename = null,
  141. string $clientMediaType = null
  142. ): UploadedFileInterface;
  143. }
  144. }
  145. // file: vendor/psr/http-factory/src/UriFactoryInterface.php
  146. namespace Psr\Http\Message {
  147. interface UriFactoryInterface
  148. {
  149. /**
  150. * Create a new URI.
  151. *
  152. * @param string $uri
  153. *
  154. * @return UriInterface
  155. *
  156. * @throws \InvalidArgumentException If the given URI cannot be parsed.
  157. */
  158. public function createUri(string $uri = ''): UriInterface;
  159. }
  160. }
  161. // file: vendor/psr/http-message/src/MessageInterface.php
  162. namespace Psr\Http\Message {
  163. /**
  164. * HTTP messages consist of requests from a client to a server and responses
  165. * from a server to a client. This interface defines the methods common to
  166. * each.
  167. *
  168. * Messages are considered immutable; all methods that might change state MUST
  169. * be implemented such that they retain the internal state of the current
  170. * message and return an instance that contains the changed state.
  171. *
  172. * @link http://www.ietf.org/rfc/rfc7230.txt
  173. * @link http://www.ietf.org/rfc/rfc7231.txt
  174. */
  175. interface MessageInterface
  176. {
  177. /**
  178. * Retrieves the HTTP protocol version as a string.
  179. *
  180. * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
  181. *
  182. * @return string HTTP protocol version.
  183. */
  184. public function getProtocolVersion();
  185. /**
  186. * Return an instance with the specified HTTP protocol version.
  187. *
  188. * The version string MUST contain only the HTTP version number (e.g.,
  189. * "1.1", "1.0").
  190. *
  191. * This method MUST be implemented in such a way as to retain the
  192. * immutability of the message, and MUST return an instance that has the
  193. * new protocol version.
  194. *
  195. * @param string $version HTTP protocol version
  196. * @return static
  197. */
  198. public function withProtocolVersion($version);
  199. /**
  200. * Retrieves all message header values.
  201. *
  202. * The keys represent the header name as it will be sent over the wire, and
  203. * each value is an array of strings associated with the header.
  204. *
  205. * // Represent the headers as a string
  206. * foreach ($message->getHeaders() as $name => $values) {
  207. * echo $name . ": " . implode(", ", $values);
  208. * }
  209. *
  210. * // Emit headers iteratively:
  211. * foreach ($message->getHeaders() as $name => $values) {
  212. * foreach ($values as $value) {
  213. * header(sprintf('%s: %s', $name, $value), false);
  214. * }
  215. * }
  216. *
  217. * While header names are not case-sensitive, getHeaders() will preserve the
  218. * exact case in which headers were originally specified.
  219. *
  220. * @return string[][] Returns an associative array of the message's headers. Each
  221. * key MUST be a header name, and each value MUST be an array of strings
  222. * for that header.
  223. */
  224. public function getHeaders();
  225. /**
  226. * Checks if a header exists by the given case-insensitive name.
  227. *
  228. * @param string $name Case-insensitive header field name.
  229. * @return bool Returns true if any header names match the given header
  230. * name using a case-insensitive string comparison. Returns false if
  231. * no matching header name is found in the message.
  232. */
  233. public function hasHeader($name);
  234. /**
  235. * Retrieves a message header value by the given case-insensitive name.
  236. *
  237. * This method returns an array of all the header values of the given
  238. * case-insensitive header name.
  239. *
  240. * If the header does not appear in the message, this method MUST return an
  241. * empty array.
  242. *
  243. * @param string $name Case-insensitive header field name.
  244. * @return string[] An array of string values as provided for the given
  245. * header. If the header does not appear in the message, this method MUST
  246. * return an empty array.
  247. */
  248. public function getHeader($name);
  249. /**
  250. * Retrieves a comma-separated string of the values for a single header.
  251. *
  252. * This method returns all of the header values of the given
  253. * case-insensitive header name as a string concatenated together using
  254. * a comma.
  255. *
  256. * NOTE: Not all header values may be appropriately represented using
  257. * comma concatenation. For such headers, use getHeader() instead
  258. * and supply your own delimiter when concatenating.
  259. *
  260. * If the header does not appear in the message, this method MUST return
  261. * an empty string.
  262. *
  263. * @param string $name Case-insensitive header field name.
  264. * @return string A string of values as provided for the given header
  265. * concatenated together using a comma. If the header does not appear in
  266. * the message, this method MUST return an empty string.
  267. */
  268. public function getHeaderLine($name);
  269. /**
  270. * Return an instance with the provided value replacing the specified header.
  271. *
  272. * While header names are case-insensitive, the casing of the header will
  273. * be preserved by this function, and returned from getHeaders().
  274. *
  275. * This method MUST be implemented in such a way as to retain the
  276. * immutability of the message, and MUST return an instance that has the
  277. * new and/or updated header and value.
  278. *
  279. * @param string $name Case-insensitive header field name.
  280. * @param string|string[] $value Header value(s).
  281. * @return static
  282. * @throws \InvalidArgumentException for invalid header names or values.
  283. */
  284. public function withHeader($name, $value);
  285. /**
  286. * Return an instance with the specified header appended with the given value.
  287. *
  288. * Existing values for the specified header will be maintained. The new
  289. * value(s) will be appended to the existing list. If the header did not
  290. * exist previously, it will be added.
  291. *
  292. * This method MUST be implemented in such a way as to retain the
  293. * immutability of the message, and MUST return an instance that has the
  294. * new header and/or value.
  295. *
  296. * @param string $name Case-insensitive header field name to add.
  297. * @param string|string[] $value Header value(s).
  298. * @return static
  299. * @throws \InvalidArgumentException for invalid header names or values.
  300. */
  301. public function withAddedHeader($name, $value);
  302. /**
  303. * Return an instance without the specified header.
  304. *
  305. * Header resolution MUST be done without case-sensitivity.
  306. *
  307. * This method MUST be implemented in such a way as to retain the
  308. * immutability of the message, and MUST return an instance that removes
  309. * the named header.
  310. *
  311. * @param string $name Case-insensitive header field name to remove.
  312. * @return static
  313. */
  314. public function withoutHeader($name);
  315. /**
  316. * Gets the body of the message.
  317. *
  318. * @return StreamInterface Returns the body as a stream.
  319. */
  320. public function getBody();
  321. /**
  322. * Return an instance with the specified message body.
  323. *
  324. * The body MUST be a StreamInterface object.
  325. *
  326. * This method MUST be implemented in such a way as to retain the
  327. * immutability of the message, and MUST return a new instance that has the
  328. * new body stream.
  329. *
  330. * @param StreamInterface $body Body.
  331. * @return static
  332. * @throws \InvalidArgumentException When the body is not valid.
  333. */
  334. public function withBody(StreamInterface $body);
  335. }
  336. }
  337. // file: vendor/psr/http-message/src/RequestInterface.php
  338. namespace Psr\Http\Message {
  339. /**
  340. * Representation of an outgoing, client-side request.
  341. *
  342. * Per the HTTP specification, this interface includes properties for
  343. * each of the following:
  344. *
  345. * - Protocol version
  346. * - HTTP method
  347. * - URI
  348. * - Headers
  349. * - Message body
  350. *
  351. * During construction, implementations MUST attempt to set the Host header from
  352. * a provided URI if no Host header is provided.
  353. *
  354. * Requests are considered immutable; all methods that might change state MUST
  355. * be implemented such that they retain the internal state of the current
  356. * message and return an instance that contains the changed state.
  357. */
  358. interface RequestInterface extends MessageInterface
  359. {
  360. /**
  361. * Retrieves the message's request target.
  362. *
  363. * Retrieves the message's request-target either as it will appear (for
  364. * clients), as it appeared at request (for servers), or as it was
  365. * specified for the instance (see withRequestTarget()).
  366. *
  367. * In most cases, this will be the origin-form of the composed URI,
  368. * unless a value was provided to the concrete implementation (see
  369. * withRequestTarget() below).
  370. *
  371. * If no URI is available, and no request-target has been specifically
  372. * provided, this method MUST return the string "/".
  373. *
  374. * @return string
  375. */
  376. public function getRequestTarget();
  377. /**
  378. * Return an instance with the specific request-target.
  379. *
  380. * If the request needs a non-origin-form request-target — e.g., for
  381. * specifying an absolute-form, authority-form, or asterisk-form —
  382. * this method may be used to create an instance with the specified
  383. * request-target, verbatim.
  384. *
  385. * This method MUST be implemented in such a way as to retain the
  386. * immutability of the message, and MUST return an instance that has the
  387. * changed request target.
  388. *
  389. * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various
  390. * request-target forms allowed in request messages)
  391. * @param mixed $requestTarget
  392. * @return static
  393. */
  394. public function withRequestTarget($requestTarget);
  395. /**
  396. * Retrieves the HTTP method of the request.
  397. *
  398. * @return string Returns the request method.
  399. */
  400. public function getMethod();
  401. /**
  402. * Return an instance with the provided HTTP method.
  403. *
  404. * While HTTP method names are typically all uppercase characters, HTTP
  405. * method names are case-sensitive and thus implementations SHOULD NOT
  406. * modify the given string.
  407. *
  408. * This method MUST be implemented in such a way as to retain the
  409. * immutability of the message, and MUST return an instance that has the
  410. * changed request method.
  411. *
  412. * @param string $method Case-sensitive method.
  413. * @return static
  414. * @throws \InvalidArgumentException for invalid HTTP methods.
  415. */
  416. public function withMethod($method);
  417. /**
  418. * Retrieves the URI instance.
  419. *
  420. * This method MUST return a UriInterface instance.
  421. *
  422. * @link http://tools.ietf.org/html/rfc3986#section-4.3
  423. * @return UriInterface Returns a UriInterface instance
  424. * representing the URI of the request.
  425. */
  426. public function getUri();
  427. /**
  428. * Returns an instance with the provided URI.
  429. *
  430. * This method MUST update the Host header of the returned request by
  431. * default if the URI contains a host component. If the URI does not
  432. * contain a host component, any pre-existing Host header MUST be carried
  433. * over to the returned request.
  434. *
  435. * You can opt-in to preserving the original state of the Host header by
  436. * setting `$preserveHost` to `true`. When `$preserveHost` is set to
  437. * `true`, this method interacts with the Host header in the following ways:
  438. *
  439. * - If the Host header is missing or empty, and the new URI contains
  440. * a host component, this method MUST update the Host header in the returned
  441. * request.
  442. * - If the Host header is missing or empty, and the new URI does not contain a
  443. * host component, this method MUST NOT update the Host header in the returned
  444. * request.
  445. * - If a Host header is present and non-empty, this method MUST NOT update
  446. * the Host header in the returned request.
  447. *
  448. * This method MUST be implemented in such a way as to retain the
  449. * immutability of the message, and MUST return an instance that has the
  450. * new UriInterface instance.
  451. *
  452. * @link http://tools.ietf.org/html/rfc3986#section-4.3
  453. * @param UriInterface $uri New request URI to use.
  454. * @param bool $preserveHost Preserve the original state of the Host header.
  455. * @return static
  456. */
  457. public function withUri(UriInterface $uri, $preserveHost = false);
  458. }
  459. }
  460. // file: vendor/psr/http-message/src/ResponseInterface.php
  461. namespace Psr\Http\Message {
  462. /**
  463. * Representation of an outgoing, server-side response.
  464. *
  465. * Per the HTTP specification, this interface includes properties for
  466. * each of the following:
  467. *
  468. * - Protocol version
  469. * - Status code and reason phrase
  470. * - Headers
  471. * - Message body
  472. *
  473. * Responses are considered immutable; all methods that might change state MUST
  474. * be implemented such that they retain the internal state of the current
  475. * message and return an instance that contains the changed state.
  476. */
  477. interface ResponseInterface extends MessageInterface
  478. {
  479. /**
  480. * Gets the response status code.
  481. *
  482. * The status code is a 3-digit integer result code of the server's attempt
  483. * to understand and satisfy the request.
  484. *
  485. * @return int Status code.
  486. */
  487. public function getStatusCode();
  488. /**
  489. * Return an instance with the specified status code and, optionally, reason phrase.
  490. *
  491. * If no reason phrase is specified, implementations MAY choose to default
  492. * to the RFC 7231 or IANA recommended reason phrase for the response's
  493. * status code.
  494. *
  495. * This method MUST be implemented in such a way as to retain the
  496. * immutability of the message, and MUST return an instance that has the
  497. * updated status and reason phrase.
  498. *
  499. * @link http://tools.ietf.org/html/rfc7231#section-6
  500. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  501. * @param int $code The 3-digit integer result code to set.
  502. * @param string $reasonPhrase The reason phrase to use with the
  503. * provided status code; if none is provided, implementations MAY
  504. * use the defaults as suggested in the HTTP specification.
  505. * @return static
  506. * @throws \InvalidArgumentException For invalid status code arguments.
  507. */
  508. public function withStatus($code, $reasonPhrase = '');
  509. /**
  510. * Gets the response reason phrase associated with the status code.
  511. *
  512. * Because a reason phrase is not a required element in a response
  513. * status line, the reason phrase value MAY be null. Implementations MAY
  514. * choose to return the default RFC 7231 recommended reason phrase (or those
  515. * listed in the IANA HTTP Status Code Registry) for the response's
  516. * status code.
  517. *
  518. * @link http://tools.ietf.org/html/rfc7231#section-6
  519. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  520. * @return string Reason phrase; must return an empty string if none present.
  521. */
  522. public function getReasonPhrase();
  523. }
  524. }
  525. // file: vendor/psr/http-message/src/ServerRequestInterface.php
  526. namespace Psr\Http\Message {
  527. /**
  528. * Representation of an incoming, server-side HTTP request.
  529. *
  530. * Per the HTTP specification, this interface includes properties for
  531. * each of the following:
  532. *
  533. * - Protocol version
  534. * - HTTP method
  535. * - URI
  536. * - Headers
  537. * - Message body
  538. *
  539. * Additionally, it encapsulates all data as it has arrived to the
  540. * application from the CGI and/or PHP environment, including:
  541. *
  542. * - The values represented in $_SERVER.
  543. * - Any cookies provided (generally via $_COOKIE)
  544. * - Query string arguments (generally via $_GET, or as parsed via parse_str())
  545. * - Upload files, if any (as represented by $_FILES)
  546. * - Deserialized body parameters (generally from $_POST)
  547. *
  548. * $_SERVER values MUST be treated as immutable, as they represent application
  549. * state at the time of request; as such, no methods are provided to allow
  550. * modification of those values. The other values provide such methods, as they
  551. * can be restored from $_SERVER or the request body, and may need treatment
  552. * during the application (e.g., body parameters may be deserialized based on
  553. * content type).
  554. *
  555. * Additionally, this interface recognizes the utility of introspecting a
  556. * request to derive and match additional parameters (e.g., via URI path
  557. * matching, decrypting cookie values, deserializing non-form-encoded body
  558. * content, matching authorization headers to users, etc). These parameters
  559. * are stored in an "attributes" property.
  560. *
  561. * Requests are considered immutable; all methods that might change state MUST
  562. * be implemented such that they retain the internal state of the current
  563. * message and return an instance that contains the changed state.
  564. */
  565. interface ServerRequestInterface extends RequestInterface
  566. {
  567. /**
  568. * Retrieve server parameters.
  569. *
  570. * Retrieves data related to the incoming request environment,
  571. * typically derived from PHP's $_SERVER superglobal. The data IS NOT
  572. * REQUIRED to originate from $_SERVER.
  573. *
  574. * @return array
  575. */
  576. public function getServerParams();
  577. /**
  578. * Retrieve cookies.
  579. *
  580. * Retrieves cookies sent by the client to the server.
  581. *
  582. * The data MUST be compatible with the structure of the $_COOKIE
  583. * superglobal.
  584. *
  585. * @return array
  586. */
  587. public function getCookieParams();
  588. /**
  589. * Return an instance with the specified cookies.
  590. *
  591. * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
  592. * be compatible with the structure of $_COOKIE. Typically, this data will
  593. * be injected at instantiation.
  594. *
  595. * This method MUST NOT update the related Cookie header of the request
  596. * instance, nor related values in the server params.
  597. *
  598. * This method MUST be implemented in such a way as to retain the
  599. * immutability of the message, and MUST return an instance that has the
  600. * updated cookie values.
  601. *
  602. * @param array $cookies Array of key/value pairs representing cookies.
  603. * @return static
  604. */
  605. public function withCookieParams(array $cookies);
  606. /**
  607. * Retrieve query string arguments.
  608. *
  609. * Retrieves the deserialized query string arguments, if any.
  610. *
  611. * Note: the query params might not be in sync with the URI or server
  612. * params. If you need to ensure you are only getting the original
  613. * values, you may need to parse the query string from `getUri()->getQuery()`
  614. * or from the `QUERY_STRING` server param.
  615. *
  616. * @return array
  617. */
  618. public function getQueryParams();
  619. /**
  620. * Return an instance with the specified query string arguments.
  621. *
  622. * These values SHOULD remain immutable over the course of the incoming
  623. * request. They MAY be injected during instantiation, such as from PHP's
  624. * $_GET superglobal, or MAY be derived from some other value such as the
  625. * URI. In cases where the arguments are parsed from the URI, the data
  626. * MUST be compatible with what PHP's parse_str() would return for
  627. * purposes of how duplicate query parameters are handled, and how nested
  628. * sets are handled.
  629. *
  630. * Setting query string arguments MUST NOT change the URI stored by the
  631. * request, nor the values in the server params.
  632. *
  633. * This method MUST be implemented in such a way as to retain the
  634. * immutability of the message, and MUST return an instance that has the
  635. * updated query string arguments.
  636. *
  637. * @param array $query Array of query string arguments, typically from
  638. * $_GET.
  639. * @return static
  640. */
  641. public function withQueryParams(array $query);
  642. /**
  643. * Retrieve normalized file upload data.
  644. *
  645. * This method returns upload metadata in a normalized tree, with each leaf
  646. * an instance of Psr\Http\Message\UploadedFileInterface.
  647. *
  648. * These values MAY be prepared from $_FILES or the message body during
  649. * instantiation, or MAY be injected via withUploadedFiles().
  650. *
  651. * @return array An array tree of UploadedFileInterface instances; an empty
  652. * array MUST be returned if no data is present.
  653. */
  654. public function getUploadedFiles();
  655. /**
  656. * Create a new instance with the specified uploaded files.
  657. *
  658. * This method MUST be implemented in such a way as to retain the
  659. * immutability of the message, and MUST return an instance that has the
  660. * updated body parameters.
  661. *
  662. * @param array $uploadedFiles An array tree of UploadedFileInterface instances.
  663. * @return static
  664. * @throws \InvalidArgumentException if an invalid structure is provided.
  665. */
  666. public function withUploadedFiles(array $uploadedFiles);
  667. /**
  668. * Retrieve any parameters provided in the request body.
  669. *
  670. * If the request Content-Type is either application/x-www-form-urlencoded
  671. * or multipart/form-data, and the request method is POST, this method MUST
  672. * return the contents of $_POST.
  673. *
  674. * Otherwise, this method may return any results of deserializing
  675. * the request body content; as parsing returns structured content, the
  676. * potential types MUST be arrays or objects only. A null value indicates
  677. * the absence of body content.
  678. *
  679. * @return null|array|object The deserialized body parameters, if any.
  680. * These will typically be an array or object.
  681. */
  682. public function getParsedBody();
  683. /**
  684. * Return an instance with the specified body parameters.
  685. *
  686. * These MAY be injected during instantiation.
  687. *
  688. * If the request Content-Type is either application/x-www-form-urlencoded
  689. * or multipart/form-data, and the request method is POST, use this method
  690. * ONLY to inject the contents of $_POST.
  691. *
  692. * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
  693. * deserializing the request body content. Deserialization/parsing returns
  694. * structured data, and, as such, this method ONLY accepts arrays or objects,
  695. * or a null value if nothing was available to parse.
  696. *
  697. * As an example, if content negotiation determines that the request data
  698. * is a JSON payload, this method could be used to create a request
  699. * instance with the deserialized parameters.
  700. *
  701. * This method MUST be implemented in such a way as to retain the
  702. * immutability of the message, and MUST return an instance that has the
  703. * updated body parameters.
  704. *
  705. * @param null|array|object $data The deserialized body data. This will
  706. * typically be in an array or object.
  707. * @return static
  708. * @throws \InvalidArgumentException if an unsupported argument type is
  709. * provided.
  710. */
  711. public function withParsedBody($data);
  712. /**
  713. * Retrieve attributes derived from the request.
  714. *
  715. * The request "attributes" may be used to allow injection of any
  716. * parameters derived from the request: e.g., the results of path
  717. * match operations; the results of decrypting cookies; the results of
  718. * deserializing non-form-encoded message bodies; etc. Attributes
  719. * will be application and request specific, and CAN be mutable.
  720. *
  721. * @return array Attributes derived from the request.
  722. */
  723. public function getAttributes();
  724. /**
  725. * Retrieve a single derived request attribute.
  726. *
  727. * Retrieves a single derived request attribute as described in
  728. * getAttributes(). If the attribute has not been previously set, returns
  729. * the default value as provided.
  730. *
  731. * This method obviates the need for a hasAttribute() method, as it allows
  732. * specifying a default value to return if the attribute is not found.
  733. *
  734. * @see getAttributes()
  735. * @param string $name The attribute name.
  736. * @param mixed $default Default value to return if the attribute does not exist.
  737. * @return mixed
  738. */
  739. public function getAttribute($name, $default = null);
  740. /**
  741. * Return an instance with the specified derived request attribute.
  742. *
  743. * This method allows setting a single derived request attribute as
  744. * described in getAttributes().
  745. *
  746. * This method MUST be implemented in such a way as to retain the
  747. * immutability of the message, and MUST return an instance that has the
  748. * updated attribute.
  749. *
  750. * @see getAttributes()
  751. * @param string $name The attribute name.
  752. * @param mixed $value The value of the attribute.
  753. * @return static
  754. */
  755. public function withAttribute($name, $value);
  756. /**
  757. * Return an instance that removes the specified derived request attribute.
  758. *
  759. * This method allows removing a single derived request attribute as
  760. * described in getAttributes().
  761. *
  762. * This method MUST be implemented in such a way as to retain the
  763. * immutability of the message, and MUST return an instance that removes
  764. * the attribute.
  765. *
  766. * @see getAttributes()
  767. * @param string $name The attribute name.
  768. * @return static
  769. */
  770. public function withoutAttribute($name);
  771. }
  772. }
  773. // file: vendor/psr/http-message/src/StreamInterface.php
  774. namespace Psr\Http\Message {
  775. /**
  776. * Describes a data stream.
  777. *
  778. * Typically, an instance will wrap a PHP stream; this interface provides
  779. * a wrapper around the most common operations, including serialization of
  780. * the entire stream to a string.
  781. */
  782. interface StreamInterface
  783. {
  784. /**
  785. * Reads all data from the stream into a string, from the beginning to end.
  786. *
  787. * This method MUST attempt to seek to the beginning of the stream before
  788. * reading data and read the stream until the end is reached.
  789. *
  790. * Warning: This could attempt to load a large amount of data into memory.
  791. *
  792. * This method MUST NOT raise an exception in order to conform with PHP's
  793. * string casting operations.
  794. *
  795. * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
  796. * @return string
  797. */
  798. public function __toString();
  799. /**
  800. * Closes the stream and any underlying resources.
  801. *
  802. * @return void
  803. */
  804. public function close();
  805. /**
  806. * Separates any underlying resources from the stream.
  807. *
  808. * After the stream has been detached, the stream is in an unusable state.
  809. *
  810. * @return resource|null Underlying PHP stream, if any
  811. */
  812. public function detach();
  813. /**
  814. * Get the size of the stream if known.
  815. *
  816. * @return int|null Returns the size in bytes if known, or null if unknown.
  817. */
  818. public function getSize();
  819. /**
  820. * Returns the current position of the file read/write pointer
  821. *
  822. * @return int Position of the file pointer
  823. * @throws \RuntimeException on error.
  824. */
  825. public function tell();
  826. /**
  827. * Returns true if the stream is at the end of the stream.
  828. *
  829. * @return bool
  830. */
  831. public function eof();
  832. /**
  833. * Returns whether or not the stream is seekable.
  834. *
  835. * @return bool
  836. */
  837. public function isSeekable();
  838. /**
  839. * Seek to a position in the stream.
  840. *
  841. * @link http://www.php.net/manual/en/function.fseek.php
  842. * @param int $offset Stream offset
  843. * @param int $whence Specifies how the cursor position will be calculated
  844. * based on the seek offset. Valid values are identical to the built-in
  845. * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
  846. * offset bytes SEEK_CUR: Set position to current location plus offset
  847. * SEEK_END: Set position to end-of-stream plus offset.
  848. * @throws \RuntimeException on failure.
  849. */
  850. public function seek($offset, $whence = SEEK_SET);
  851. /**
  852. * Seek to the beginning of the stream.
  853. *
  854. * If the stream is not seekable, this method will raise an exception;
  855. * otherwise, it will perform a seek(0).
  856. *
  857. * @see seek()
  858. * @link http://www.php.net/manual/en/function.fseek.php
  859. * @throws \RuntimeException on failure.
  860. */
  861. public function rewind();
  862. /**
  863. * Returns whether or not the stream is writable.
  864. *
  865. * @return bool
  866. */
  867. public function isWritable();
  868. /**
  869. * Write data to the stream.
  870. *
  871. * @param string $string The string that is to be written.
  872. * @return int Returns the number of bytes written to the stream.
  873. * @throws \RuntimeException on failure.
  874. */
  875. public function write($string);
  876. /**
  877. * Returns whether or not the stream is readable.
  878. *
  879. * @return bool
  880. */
  881. public function isReadable();
  882. /**
  883. * Read data from the stream.
  884. *
  885. * @param int $length Read up to $length bytes from the object and return
  886. * them. Fewer than $length bytes may be returned if underlying stream
  887. * call returns fewer bytes.
  888. * @return string Returns the data read from the stream, or an empty string
  889. * if no bytes are available.
  890. * @throws \RuntimeException if an error occurs.
  891. */
  892. public function read($length);
  893. /**
  894. * Returns the remaining contents in a string
  895. *
  896. * @return string
  897. * @throws \RuntimeException if unable to read or an error occurs while
  898. * reading.
  899. */
  900. public function getContents();
  901. /**
  902. * Get stream metadata as an associative array or retrieve a specific key.
  903. *
  904. * The keys returned are identical to the keys returned from PHP's
  905. * stream_get_meta_data() function.
  906. *
  907. * @link http://php.net/manual/en/function.stream-get-meta-data.php
  908. * @param string $key Specific metadata to retrieve.
  909. * @return array|mixed|null Returns an associative array if no key is
  910. * provided. Returns a specific key value if a key is provided and the
  911. * value is found, or null if the key is not found.
  912. */
  913. public function getMetadata($key = null);
  914. }
  915. }
  916. // file: vendor/psr/http-message/src/UploadedFileInterface.php
  917. namespace Psr\Http\Message {
  918. /**
  919. * Value object representing a file uploaded through an HTTP request.
  920. *
  921. * Instances of this interface are considered immutable; all methods that
  922. * might change state MUST be implemented such that they retain the internal
  923. * state of the current instance and return an instance that contains the
  924. * changed state.
  925. */
  926. interface UploadedFileInterface
  927. {
  928. /**
  929. * Retrieve a stream representing the uploaded file.
  930. *
  931. * This method MUST return a StreamInterface instance, representing the
  932. * uploaded file. The purpose of this method is to allow utilizing native PHP
  933. * stream functionality to manipulate the file upload, such as
  934. * stream_copy_to_stream() (though the result will need to be decorated in a
  935. * native PHP stream wrapper to work with such functions).
  936. *
  937. * If the moveTo() method has been called previously, this method MUST raise
  938. * an exception.
  939. *
  940. * @return StreamInterface Stream representation of the uploaded file.
  941. * @throws \RuntimeException in cases when no stream is available or can be
  942. * created.
  943. */
  944. public function getStream();
  945. /**
  946. * Move the uploaded file to a new location.
  947. *
  948. * Use this method as an alternative to move_uploaded_file(). This method is
  949. * guaranteed to work in both SAPI and non-SAPI environments.
  950. * Implementations must determine which environment they are in, and use the
  951. * appropriate method (move_uploaded_file(), rename(), or a stream
  952. * operation) to perform the operation.
  953. *
  954. * $targetPath may be an absolute path, or a relative path. If it is a
  955. * relative path, resolution should be the same as used by PHP's rename()
  956. * function.
  957. *
  958. * The original file or stream MUST be removed on completion.
  959. *
  960. * If this method is called more than once, any subsequent calls MUST raise
  961. * an exception.
  962. *
  963. * When used in an SAPI environment where $_FILES is populated, when writing
  964. * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
  965. * used to ensure permissions and upload status are verified correctly.
  966. *
  967. * If you wish to move to a stream, use getStream(), as SAPI operations
  968. * cannot guarantee writing to stream destinations.
  969. *
  970. * @see http://php.net/is_uploaded_file
  971. * @see http://php.net/move_uploaded_file
  972. * @param string $targetPath Path to which to move the uploaded file.
  973. * @throws \InvalidArgumentException if the $targetPath specified is invalid.
  974. * @throws \RuntimeException on any error during the move operation, or on
  975. * the second or subsequent call to the method.
  976. */
  977. public function moveTo($targetPath);
  978. /**
  979. * Retrieve the file size.
  980. *
  981. * Implementations SHOULD return the value stored in the "size" key of
  982. * the file in the $_FILES array if available, as PHP calculates this based
  983. * on the actual size transmitted.
  984. *
  985. * @return int|null The file size in bytes or null if unknown.
  986. */
  987. public function getSize();
  988. /**
  989. * Retrieve the error associated with the uploaded file.
  990. *
  991. * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
  992. *
  993. * If the file was uploaded successfully, this method MUST return
  994. * UPLOAD_ERR_OK.
  995. *
  996. * Implementations SHOULD return the value stored in the "error" key of
  997. * the file in the $_FILES array.
  998. *
  999. * @see http://php.net/manual/en/features.file-upload.errors.php
  1000. * @return int One of PHP's UPLOAD_ERR_XXX constants.
  1001. */
  1002. public function getError();
  1003. /**
  1004. * Retrieve the filename sent by the client.
  1005. *
  1006. * Do not trust the value returned by this method. A client could send
  1007. * a malicious filename with the intention to corrupt or hack your
  1008. * application.
  1009. *
  1010. * Implementations SHOULD return the value stored in the "name" key of
  1011. * the file in the $_FILES array.
  1012. *
  1013. * @return string|null The filename sent by the client or null if none
  1014. * was provided.
  1015. */
  1016. public function getClientFilename();
  1017. /**
  1018. * Retrieve the media type sent by the client.
  1019. *
  1020. * Do not trust the value returned by this method. A client could send
  1021. * a malicious media type with the intention to corrupt or hack your
  1022. * application.
  1023. *
  1024. * Implementations SHOULD return the value stored in the "type" key of
  1025. * the file in the $_FILES array.
  1026. *
  1027. * @return string|null The media type sent by the client or null if none
  1028. * was provided.
  1029. */
  1030. public function getClientMediaType();
  1031. }
  1032. }
  1033. // file: vendor/psr/http-message/src/UriInterface.php
  1034. namespace Psr\Http\Message {
  1035. /**
  1036. * Value object representing a URI.
  1037. *
  1038. * This interface is meant to represent URIs according to RFC 3986 and to
  1039. * provide methods for most common operations. Additional functionality for
  1040. * working with URIs can be provided on top of the interface or externally.
  1041. * Its primary use is for HTTP requests, but may also be used in other
  1042. * contexts.
  1043. *
  1044. * Instances of this interface are considered immutable; all methods that
  1045. * might change state MUST be implemented such that they retain the internal
  1046. * state of the current instance and return an instance that contains the
  1047. * changed state.
  1048. *
  1049. * Typically the Host header will be also be present in the request message.
  1050. * For server-side requests, the scheme will typically be discoverable in the
  1051. * server parameters.
  1052. *
  1053. * @link http://tools.ietf.org/html/rfc3986 (the URI specification)
  1054. */
  1055. interface UriInterface
  1056. {
  1057. /**
  1058. * Retrieve the scheme component of the URI.
  1059. *
  1060. * If no scheme is present, this method MUST return an empty string.
  1061. *
  1062. * The value returned MUST be normalized to lowercase, per RFC 3986
  1063. * Section 3.1.
  1064. *
  1065. * The trailing ":" character is not part of the scheme and MUST NOT be
  1066. * added.
  1067. *
  1068. * @see https://tools.ietf.org/html/rfc3986#section-3.1
  1069. * @return string The URI scheme.
  1070. */
  1071. public function getScheme();
  1072. /**
  1073. * Retrieve the authority component of the URI.
  1074. *
  1075. * If no authority information is present, this method MUST return an empty
  1076. * string.
  1077. *
  1078. * The authority syntax of the URI is:
  1079. *
  1080. * <pre>
  1081. * [user-info@]host[:port]
  1082. * </pre>
  1083. *
  1084. * If the port component is not set or is the standard port for the current
  1085. * scheme, it SHOULD NOT be included.
  1086. *
  1087. * @see https://tools.ietf.org/html/rfc3986#section-3.2
  1088. * @return string The URI authority, in "[user-info@]host[:port]" format.
  1089. */
  1090. public function getAuthority();
  1091. /**
  1092. * Retrieve the user information component of the URI.
  1093. *
  1094. * If no user information is present, this method MUST return an empty
  1095. * string.
  1096. *
  1097. * If a user is present in the URI, this will return that value;
  1098. * additionally, if the password is also present, it will be appended to the
  1099. * user value, with a colon (":") separating the values.
  1100. *
  1101. * The trailing "@" character is not part of the user information and MUST
  1102. * NOT be added.
  1103. *
  1104. * @return string The URI user information, in "username[:password]" format.
  1105. */
  1106. public function getUserInfo();
  1107. /**
  1108. * Retrieve the host component of the URI.
  1109. *
  1110. * If no host is present, this method MUST return an empty string.
  1111. *
  1112. * The value returned MUST be normalized to lowercase, per RFC 3986
  1113. * Section 3.2.2.
  1114. *
  1115. * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
  1116. * @return string The URI host.
  1117. */
  1118. public function getHost();
  1119. /**
  1120. * Retrieve the port component of the URI.
  1121. *
  1122. * If a port is present, and it is non-standard for the current scheme,
  1123. * this method MUST return it as an integer. If the port is the standard port
  1124. * used with the current scheme, this method SHOULD return null.
  1125. *
  1126. * If no port is present, and no scheme is present, this method MUST return
  1127. * a null value.
  1128. *
  1129. * If no port is present, but a scheme is present, this method MAY return
  1130. * the standard port for that scheme, but SHOULD return null.
  1131. *
  1132. * @return null|int The URI port.
  1133. */
  1134. public function getPort();
  1135. /**
  1136. * Retrieve the path component of the URI.
  1137. *
  1138. * The path can either be empty or absolute (starting with a slash) or
  1139. * rootless (not starting with a slash). Implementations MUST support all
  1140. * three syntaxes.
  1141. *
  1142. * Normally, the empty path "" and absolute path "/" are considered equal as
  1143. * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
  1144. * do this normalization because in contexts with a trimmed base path, e.g.
  1145. * the front controller, this difference becomes significant. It's the task
  1146. * of the user to handle both "" and "/".
  1147. *
  1148. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1149. * any characters. To determine what characters to encode, please refer to
  1150. * RFC 3986, Sections 2 and 3.3.
  1151. *
  1152. * As an example, if the value should include a slash ("/") not intended as
  1153. * delimiter between path segments, that value MUST be passed in encoded
  1154. * form (e.g., "%2F") to the instance.
  1155. *
  1156. * @see https://tools.ietf.org/html/rfc3986#section-2
  1157. * @see https://tools.ietf.org/html/rfc3986#section-3.3
  1158. * @return string The URI path.
  1159. */
  1160. public function getPath();
  1161. /**
  1162. * Retrieve the query string of the URI.
  1163. *
  1164. * If no query string is present, this method MUST return an empty string.
  1165. *
  1166. * The leading "?" character is not part of the query and MUST NOT be
  1167. * added.
  1168. *
  1169. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1170. * any characters. To determine what characters to encode, please refer to
  1171. * RFC 3986, Sections 2 and 3.4.
  1172. *
  1173. * As an example, if a value in a key/value pair of the query string should
  1174. * include an ampersand ("&") not intended as a delimiter between values,
  1175. * that value MUST be passed in encoded form (e.g., "%26") to the instance.
  1176. *
  1177. * @see https://tools.ietf.org/html/rfc3986#section-2
  1178. * @see https://tools.ietf.org/html/rfc3986#section-3.4
  1179. * @return string The URI query string.
  1180. */
  1181. public function getQuery();
  1182. /**
  1183. * Retrieve the fragment component of the URI.
  1184. *
  1185. * If no fragment is present, this method MUST return an empty string.
  1186. *
  1187. * The leading "#" character is not part of the fragment and MUST NOT be
  1188. * added.
  1189. *
  1190. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1191. * any characters. To determine what characters to encode, please refer to
  1192. * RFC 3986, Sections 2 and 3.5.
  1193. *
  1194. * @see https://tools.ietf.org/html/rfc3986#section-2
  1195. * @see https://tools.ietf.org/html/rfc3986#section-3.5
  1196. * @return string The URI fragment.
  1197. */
  1198. public function getFragment();
  1199. /**
  1200. * Return an instance with the specified scheme.
  1201. *
  1202. * This method MUST retain the state of the current instance, and return
  1203. * an instance that contains the specified scheme.
  1204. *
  1205. * Implementations MUST support the schemes "http" and "https" case
  1206. * insensitively, and MAY accommodate other schemes if required.
  1207. *
  1208. * An empty scheme is equivalent to removing the scheme.
  1209. *
  1210. * @param string $scheme The scheme to use with the new instance.
  1211. * @return static A new instance with the specified scheme.
  1212. * @throws \InvalidArgumentException for invalid or unsupported schemes.
  1213. */
  1214. public function withScheme($scheme);
  1215. /**
  1216. * Return an instance with the specified user information.
  1217. *
  1218. * This method MUST retain the state of the current instance, and return
  1219. * an instance that contains the specified user information.
  1220. *
  1221. * Password is optional, but the user information MUST include the
  1222. * user; an empty string for the user is equivalent to removing user
  1223. * information.
  1224. *
  1225. * @param string $user The user name to use for authority.
  1226. * @param null|string $password The password associated with $user.
  1227. * @return static A new instance with the specified user information.
  1228. */
  1229. public function withUserInfo($user, $password = null);
  1230. /**
  1231. * Return an instance with the specified host.
  1232. *
  1233. * This method MUST retain the state of the current instance, and return
  1234. * an instance that contains the specified host.
  1235. *
  1236. * An empty host value is equivalent to removing the host.
  1237. *
  1238. * @param string $host The hostname to use with the new instance.
  1239. * @return static A new instance with the specified host.
  1240. * @throws \InvalidArgumentException for invalid hostnames.
  1241. */
  1242. public function withHost($host);
  1243. /**
  1244. * Return an instance with the specified port.
  1245. *
  1246. * This method MUST retain the state of the current instance, and return
  1247. * an instance that contains the specified port.
  1248. *
  1249. * Implementations MUST raise an exception for ports outside the
  1250. * established TCP and UDP port ranges.
  1251. *
  1252. * A null value provided for the port is equivalent to removing the port
  1253. * information.
  1254. *
  1255. * @param null|int $port The port to use with the new instance; a null value
  1256. * removes the port information.
  1257. * @return static A new instance with the specified port.
  1258. * @throws \InvalidArgumentException for invalid ports.
  1259. */
  1260. public function withPort($port);
  1261. /**
  1262. * Return an instance with the specified path.
  1263. *
  1264. * This method MUST retain the state of the current instance, and return
  1265. * an instance that contains the specified path.
  1266. *
  1267. * The path can either be empty or absolute (starting with a slash) or
  1268. * rootless (not starting with a slash). Implementations MUST support all
  1269. * three syntaxes.
  1270. *
  1271. * If the path is intended to be domain-relative rather than path relative then
  1272. * it must begin with a slash ("/"). Paths not starting with a slash ("/")
  1273. * are assumed to be relative to some base path known to the application or
  1274. * consumer.
  1275. *
  1276. * Users can provide both encoded and decoded path characters.
  1277. * Implementations ensure the correct encoding as outlined in getPath().
  1278. *
  1279. * @param string $path The path to use with the new instance.
  1280. * @return static A new instance with the specified path.
  1281. * @throws \InvalidArgumentException for invalid paths.
  1282. */
  1283. public function withPath($path);
  1284. /**
  1285. * Return an instance with the specified query string.
  1286. *
  1287. * This method MUST retain the state of the current instance, and return
  1288. * an instance that contains the specified query string.
  1289. *
  1290. * Users can provide both encoded and decoded query characters.
  1291. * Implementations ensure the correct encoding as outlined in getQuery().
  1292. *
  1293. * An empty query string value is equivalent to removing the query string.
  1294. *
  1295. * @param string $query The query string to use with the new instance.
  1296. * @return static A new instance with the specified query string.
  1297. * @throws \InvalidArgumentException for invalid query strings.
  1298. */
  1299. public function withQuery($query);
  1300. /**
  1301. * Return an instance with the specified URI fragment.
  1302. *
  1303. * This method MUST retain the state of the current instance, and return
  1304. * an instance that contains the specified URI fragment.
  1305. *
  1306. * Users can provide both encoded and decoded fragment characters.
  1307. * Implementations ensure the correct encoding as outlined in getFragment().
  1308. *
  1309. * An empty fragment value is equivalent to removing the fragment.
  1310. *
  1311. * @param string $fragment The fragment to use with the new instance.
  1312. * @return static A new instance with the specified fragment.
  1313. */
  1314. public function withFragment($fragment);
  1315. /**
  1316. * Return the string representation as a URI reference.
  1317. *
  1318. * Depending on which components of the URI are present, the resulting
  1319. * string is either a full URI or relative reference according to RFC 3986,
  1320. * Section 4.1. The method concatenates the various components of the URI,
  1321. * using the appropriate delimiters:
  1322. *
  1323. * - If a scheme is present, it MUST be suffixed by ":".
  1324. * - If an authority is present, it MUST be prefixed by "//".
  1325. * - The path can be concatenated without delimiters. But there are two
  1326. * cases where the path has to be adjusted to make the URI reference
  1327. * valid as PHP does not allow to throw an exception in __toString():
  1328. * - If the path is rootless and an authority is present, the path MUST
  1329. * be prefixed by "/".
  1330. * - If the path is starting with more than one "/" and no authority is
  1331. * present, the starting slashes MUST be reduced to one.
  1332. * - If a query is present, it MUST be prefixed by "?".
  1333. * - If a fragment is present, it MUST be prefixed by "#".
  1334. *
  1335. * @see http://tools.ietf.org/html/rfc3986#section-4.1
  1336. * @return string
  1337. */
  1338. public function __toString();
  1339. }
  1340. }
  1341. // file: vendor/psr/http-server-handler/src/RequestHandlerInterface.php
  1342. namespace Psr\Http\Server {
  1343. use Psr\Http\Message\ResponseInterface;
  1344. use Psr\Http\Message\ServerRequestInterface;
  1345. /**
  1346. * Handles a server request and produces a response.
  1347. *
  1348. * An HTTP request handler process an HTTP request in order to produce an
  1349. * HTTP response.
  1350. */
  1351. interface RequestHandlerInterface
  1352. {
  1353. /**
  1354. * Handles a request and produces a response.
  1355. *
  1356. * May call other collaborating code to generate the response.
  1357. */
  1358. public function handle(ServerRequestInterface $request): ResponseInterface;
  1359. }
  1360. }
  1361. // file: vendor/psr/http-server-middleware/src/MiddlewareInterface.php
  1362. namespace Psr\Http\Server {
  1363. use Psr\Http\Message\ResponseInterface;
  1364. use Psr\Http\Message\ServerRequestInterface;
  1365. /**
  1366. * Participant in processing a server request and response.
  1367. *
  1368. * An HTTP middleware component participates in processing an HTTP message:
  1369. * by acting on the request, generating the response, or forwarding the
  1370. * request to a subsequent middleware and possibly acting on its response.
  1371. */
  1372. interface MiddlewareInterface
  1373. {
  1374. /**
  1375. * Process an incoming server request.
  1376. *
  1377. * Processes an incoming server request in order to produce a response.
  1378. * If unable to produce the response itself, it may delegate to the provided
  1379. * request handler to do so.
  1380. */
  1381. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
  1382. }
  1383. }
  1384. // file: vendor/nyholm/psr7/src/Factory/Psr17Factory.php
  1385. namespace Nyholm\Psr7\Factory {
  1386. use Nyholm\Psr7\{Request, Response, ServerRequest, Stream, UploadedFile, Uri};
  1387. use Psr\Http\Message\{RequestFactoryInterface, RequestInterface, ResponseFactoryInterface, ResponseInterface, ServerRequestFactoryInterface, ServerRequestInterface, StreamFactoryInterface, StreamInterface, UploadedFileFactoryInterface, UploadedFileInterface, UriFactoryInterface, UriInterface};
  1388. /**
  1389. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1390. * @author Martijn van der Ven <martijn@vanderven.se>
  1391. */
  1392. final class Psr17Factory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
  1393. {
  1394. public function createRequest(string $method, $uri): RequestInterface
  1395. {
  1396. return new Request($method, $uri);
  1397. }
  1398. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface
  1399. {
  1400. return new Response($code, [], null, '1.1', $reasonPhrase);
  1401. }
  1402. public function createStream(string $content = ''): StreamInterface
  1403. {
  1404. return Stream::create($content);
  1405. }
  1406. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
  1407. {
  1408. $resource = @\fopen($filename, $mode);
  1409. if (false === $resource) {
  1410. if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'])) {
  1411. throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.');
  1412. }
  1413. throw new \RuntimeException('The file ' . $filename . ' cannot be opened.');
  1414. }
  1415. return Stream::create($resource);
  1416. }
  1417. public function createStreamFromResource($resource): StreamInterface
  1418. {
  1419. return Stream::create($resource);
  1420. }
  1421. public function createUploadedFile(StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null): UploadedFileInterface
  1422. {
  1423. if (null === $size) {
  1424. $size = $stream->getSize();
  1425. }
  1426. return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);
  1427. }
  1428. public function createUri(string $uri = ''): UriInterface
  1429. {
  1430. return new Uri($uri);
  1431. }
  1432. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  1433. {
  1434. return new ServerRequest($method, $uri, [], null, '1.1', $serverParams);
  1435. }
  1436. }
  1437. }
  1438. // file: vendor/nyholm/psr7/src/MessageTrait.php
  1439. namespace Nyholm\Psr7 {
  1440. use Psr\Http\Message\StreamInterface;
  1441. /**
  1442. * Trait implementing functionality common to requests and responses.
  1443. *
  1444. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1445. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1446. * @author Martijn van der Ven <martijn@vanderven.se>
  1447. *
  1448. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1449. */
  1450. trait MessageTrait
  1451. {
  1452. /** @var array Map of all registered headers, as original name => array of values */
  1453. private $headers = [];
  1454. /** @var array Map of lowercase header name => original name at registration */
  1455. private $headerNames = [];
  1456. /** @var string */
  1457. private $protocol = '1.1';
  1458. /** @var StreamInterface|null */
  1459. private $stream;
  1460. public function getProtocolVersion(): string
  1461. {
  1462. return $this->protocol;
  1463. }
  1464. public function withProtocolVersion($version): self
  1465. {
  1466. if ($this->protocol === $version) {
  1467. return $this;
  1468. }
  1469. $new = clone $this;
  1470. $new->protocol = $version;
  1471. return $new;
  1472. }
  1473. public function getHeaders(): array
  1474. {
  1475. return $this->headers;
  1476. }
  1477. public function hasHeader($header): bool
  1478. {
  1479. return isset($this->headerNames[\strtolower($header)]);
  1480. }
  1481. public function getHeader($header): array
  1482. {
  1483. $header = \strtolower($header);
  1484. if (!isset($this->headerNames[$header])) {
  1485. return [];
  1486. }
  1487. $header = $this->headerNames[$header];
  1488. return $this->headers[$header];
  1489. }
  1490. public function getHeaderLine($header): string
  1491. {
  1492. return \implode(', ', $this->getHeader($header));
  1493. }
  1494. public function withHeader($header, $value): self
  1495. {
  1496. $value = $this->validateAndTrimHeader($header, $value);
  1497. $normalized = \strtolower($header);
  1498. $new = clone $this;
  1499. if (isset($new->headerNames[$normalized])) {
  1500. unset($new->headers[$new->headerNames[$normalized]]);
  1501. }
  1502. $new->headerNames[$normalized] = $header;
  1503. $new->headers[$header] = $value;
  1504. return $new;
  1505. }
  1506. public function withAddedHeader($header, $value): self
  1507. {
  1508. if (!\is_string($header) || '' === $header) {
  1509. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1510. }
  1511. $new = clone $this;
  1512. $new->setHeaders([$header => $value]);
  1513. return $new;
  1514. }
  1515. public function withoutHeader($header): self
  1516. {
  1517. $normalized = \strtolower($header);
  1518. if (!isset($this->headerNames[$normalized])) {
  1519. return $this;
  1520. }
  1521. $header = $this->headerNames[$normalized];
  1522. $new = clone $this;
  1523. unset($new->headers[$header], $new->headerNames[$normalized]);
  1524. return $new;
  1525. }
  1526. public function getBody(): StreamInterface
  1527. {
  1528. if (null === $this->stream) {
  1529. $this->stream = Stream::create('');
  1530. }
  1531. return $this->stream;
  1532. }
  1533. public function withBody(StreamInterface $body): self
  1534. {
  1535. if ($body === $this->stream) {
  1536. return $this;
  1537. }
  1538. $new = clone $this;
  1539. $new->stream = $body;
  1540. return $new;
  1541. }
  1542. private function setHeaders(array $headers) /*:void*/
  1543. {
  1544. foreach ($headers as $header => $value) {
  1545. $value = $this->validateAndTrimHeader($header, $value);
  1546. $normalized = \strtolower($header);
  1547. if (isset($this->headerNames[$normalized])) {
  1548. $header = $this->headerNames[$normalized];
  1549. $this->headers[$header] = \array_merge($this->headers[$header], $value);
  1550. } else {
  1551. $this->headerNames[$normalized] = $header;
  1552. $this->headers[$header] = $value;
  1553. }
  1554. }
  1555. }
  1556. /**
  1557. * Make sure the header complies with RFC 7230.
  1558. *
  1559. * Header names must be a non-empty string consisting of token characters.
  1560. *
  1561. * Header values must be strings consisting of visible characters with all optional
  1562. * leading and trailing whitespace stripped. This method will always strip such
  1563. * optional whitespace. Note that the method does not allow folding whitespace within
  1564. * the values as this was deprecated for almost all instances by the RFC.
  1565. *
  1566. * header-field = field-name ":" OWS field-value OWS
  1567. * field-name = 1*( "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^"
  1568. * / "_" / "`" / "|" / "~" / %x30-39 / ( %x41-5A / %x61-7A ) )
  1569. * OWS = *( SP / HTAB )
  1570. * field-value = *( ( %x21-7E / %x80-FF ) [ 1*( SP / HTAB ) ( %x21-7E / %x80-FF ) ] )
  1571. *
  1572. * @see https://tools.ietf.org/html/rfc7230#section-3.2.4
  1573. */
  1574. private function validateAndTrimHeader($header, $values): array
  1575. {
  1576. if (!\is_string($header) || 1 !== \preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@", $header)) {
  1577. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1578. }
  1579. if (!\is_array($values)) {
  1580. // This is simple, just one value.
  1581. if ((!\is_numeric($values) && !\is_string($values)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $values)) {
  1582. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1583. }
  1584. return [\trim((string) $values, " \t")];
  1585. }
  1586. if (empty($values)) {
  1587. throw new \InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
  1588. }
  1589. // Assert Non empty array
  1590. $returnValues = [];
  1591. foreach ($values as $v) {
  1592. if ((!\is_numeric($v) && !\is_string($v)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $v)) {
  1593. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1594. }
  1595. $returnValues[] = \trim((string) $v, " \t");
  1596. }
  1597. return $returnValues;
  1598. }
  1599. }
  1600. }
  1601. // file: vendor/nyholm/psr7/src/Request.php
  1602. namespace Nyholm\Psr7 {
  1603. use Psr\Http\Message\{RequestInterface, StreamInterface, UriInterface};
  1604. /**
  1605. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1606. * @author Martijn van der Ven <martijn@vanderven.se>
  1607. */
  1608. final class Request implements RequestInterface
  1609. {
  1610. use MessageTrait;
  1611. use RequestTrait;
  1612. /**
  1613. * @param string $method HTTP method
  1614. * @param string|UriInterface $uri URI
  1615. * @param array $headers Request headers
  1616. * @param string|resource|StreamInterface|null $body Request body
  1617. * @param string $version Protocol version
  1618. */
  1619. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
  1620. {
  1621. if (!($uri instanceof UriInterface)) {
  1622. $uri = new Uri($uri);
  1623. }
  1624. $this->method = $method;
  1625. $this->uri = $uri;
  1626. $this->setHeaders($headers);
  1627. $this->protocol = $version;
  1628. if (!$this->hasHeader('Host')) {
  1629. $this->updateHostFromUri();
  1630. }
  1631. // If we got no body, defer initialization of the stream until Request::getBody()
  1632. if ('' !== $body && null !== $body) {
  1633. $this->stream = Stream::create($body);
  1634. }
  1635. }
  1636. }
  1637. }
  1638. // file: vendor/nyholm/psr7/src/RequestTrait.php
  1639. namespace Nyholm\Psr7 {
  1640. use Psr\Http\Message\UriInterface;
  1641. /**
  1642. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1643. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1644. * @author Martijn van der Ven <martijn@vanderven.se>
  1645. *
  1646. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1647. */
  1648. trait RequestTrait
  1649. {
  1650. /** @var string */
  1651. private $method;
  1652. /** @var string|null */
  1653. private $requestTarget;
  1654. /** @var UriInterface|null */
  1655. private $uri;
  1656. public function getRequestTarget(): string
  1657. {
  1658. if (null !== $this->requestTarget) {
  1659. return $this->requestTarget;
  1660. }
  1661. if ('' === $target = $this->uri->getPath()) {
  1662. $target = '/';
  1663. }
  1664. if ('' !== $this->uri->getQuery()) {
  1665. $target .= '?' . $this->uri->getQuery();
  1666. }
  1667. return $target;
  1668. }
  1669. public function withRequestTarget($requestTarget): self
  1670. {
  1671. if (\preg_match('#\s#', $requestTarget)) {
  1672. throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
  1673. }
  1674. $new = clone $this;
  1675. $new->requestTarget = $requestTarget;
  1676. return $new;
  1677. }
  1678. public function getMethod(): string
  1679. {
  1680. return $this->method;
  1681. }
  1682. public function withMethod($method): self
  1683. {
  1684. if (!\is_string($method)) {
  1685. throw new \InvalidArgumentException('Method must be a string');
  1686. }
  1687. $new = clone $this;
  1688. $new->method = $method;
  1689. return $new;
  1690. }
  1691. public function getUri(): UriInterface
  1692. {
  1693. return $this->uri;
  1694. }
  1695. public function withUri(UriInterface $uri, $preserveHost = false): self
  1696. {
  1697. if ($uri === $this->uri) {
  1698. return $this;
  1699. }
  1700. $new = clone $this;
  1701. $new->uri = $uri;
  1702. if (!$preserveHost || !$this->hasHeader('Host')) {
  1703. $new->updateHostFromUri();
  1704. }
  1705. return $new;
  1706. }
  1707. private function updateHostFromUri() /*:void*/
  1708. {
  1709. if ('' === $host = $this->uri->getHost()) {
  1710. return;
  1711. }
  1712. if (null !== ($port = $this->uri->getPort())) {
  1713. $host .= ':' . $port;
  1714. }
  1715. if (isset($this->headerNames['host'])) {
  1716. $header = $this->headerNames['host'];
  1717. } else {
  1718. $this->headerNames['host'] = $header = 'Host';
  1719. }
  1720. // Ensure Host is the first header.
  1721. // See: http://tools.ietf.org/html/rfc7230#section-5.4
  1722. $this->headers = [$header => [$host]] + $this->headers;
  1723. }
  1724. }
  1725. }
  1726. // file: vendor/nyholm/psr7/src/Response.php
  1727. namespace Nyholm\Psr7 {
  1728. use Psr\Http\Message\{ResponseInterface, StreamInterface};
  1729. /**
  1730. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1731. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1732. * @author Martijn van der Ven <martijn@vanderven.se>
  1733. */
  1734. final class Response implements ResponseInterface
  1735. {
  1736. use MessageTrait;
  1737. /** @var array Map of standard HTTP status code/reason phrases */
  1738. /*private*/ const PHRASES = [
  1739. 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing',
  1740. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported',
  1741. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect',
  1742. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons',
  1743. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 511 => 'Network Authentication Required',
  1744. ];
  1745. /** @var string */
  1746. private $reasonPhrase = '';
  1747. /** @var int */
  1748. private $statusCode;
  1749. /**
  1750. * @param int $status Status code
  1751. * @param array $headers Response headers
  1752. * @param string|resource|StreamInterface|null $body Response body
  1753. * @param string $version Protocol version
  1754. * @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
  1755. */
  1756. public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
  1757. {
  1758. // If we got no body, defer initialization of the stream until Response::getBody()
  1759. if ('' !== $body && null !== $body) {
  1760. $this->stream = Stream::create($body);
  1761. }
  1762. $this->statusCode = $status;
  1763. $this->setHeaders($headers);
  1764. if (null === $reason && isset(self::PHRASES[$this->statusCode])) {
  1765. $this->reasonPhrase = self::PHRASES[$status];
  1766. } else {
  1767. $this->reasonPhrase = $reason;
  1768. }
  1769. $this->protocol = $version;
  1770. }
  1771. public function getStatusCode(): int
  1772. {
  1773. return $this->statusCode;
  1774. }
  1775. public function getReasonPhrase(): string
  1776. {
  1777. return $this->reasonPhrase;
  1778. }
  1779. public function withStatus($code, $reasonPhrase = ''): self
  1780. {
  1781. if (!\is_int($code) && !\is_string($code)) {
  1782. throw new \InvalidArgumentException('Status code has to be an integer');
  1783. }
  1784. $code = (int) $code;
  1785. if ($code < 100 || $code > 599) {
  1786. throw new \InvalidArgumentException('Status code has to be an integer between 100 and 599');
  1787. }
  1788. $new = clone $this;
  1789. $new->statusCode = $code;
  1790. if ((null === $reasonPhrase || '' === $reasonPhrase) && isset(self::PHRASES[$new->statusCode])) {
  1791. $reasonPhrase = self::PHRASES[$new->statusCode];
  1792. }
  1793. $new->reasonPhrase = $reasonPhrase;
  1794. return $new;
  1795. }
  1796. }
  1797. }
  1798. // file: vendor/nyholm/psr7/src/ServerRequest.php
  1799. namespace Nyholm\Psr7 {
  1800. use Psr\Http\Message\{ServerRequestInterface, StreamInterface, UploadedFileInterface, UriInterface};
  1801. /**
  1802. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1803. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1804. * @author Martijn van der Ven <martijn@vanderven.se>
  1805. */
  1806. final class ServerRequest implements ServerRequestInterface
  1807. {
  1808. use MessageTrait;
  1809. use RequestTrait;
  1810. /** @var array */
  1811. private $attributes = [];
  1812. /** @var array */
  1813. private $cookieParams = [];
  1814. /** @var array|object|null */
  1815. private $parsedBody;
  1816. /** @var array */
  1817. private $queryParams = [];
  1818. /** @var array */
  1819. private $serverParams;
  1820. /** @var UploadedFileInterface[] */
  1821. private $uploadedFiles = [];
  1822. /**
  1823. * @param string $method HTTP method
  1824. * @param string|UriInterface $uri URI
  1825. * @param array $headers Request headers
  1826. * @param string|resource|StreamInterface|null $body Request body
  1827. * @param string $version Protocol version
  1828. * @param array $serverParams Typically the $_SERVER superglobal
  1829. */
  1830. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
  1831. {
  1832. $this->serverParams = $serverParams;
  1833. if (!($uri instanceof UriInterface)) {
  1834. $uri = new Uri($uri);
  1835. }
  1836. $this->method = $method;
  1837. $this->uri = $uri;
  1838. $this->setHeaders($headers);
  1839. $this->protocol = $version;
  1840. if (!$this->hasHeader('Host')) {
  1841. $this->updateHostFromUri();
  1842. }
  1843. // If we got no body, defer initialization of the stream until ServerRequest::getBody()
  1844. if ('' !== $body && null !== $body) {
  1845. $this->stream = Stream::create($body);
  1846. }
  1847. }
  1848. public function getServerParams(): array
  1849. {
  1850. return $this->serverParams;
  1851. }
  1852. public function getUploadedFiles(): array
  1853. {
  1854. return $this->uploadedFiles;
  1855. }
  1856. public function withUploadedFiles(array $uploadedFiles)
  1857. {
  1858. $new = clone $this;
  1859. $new->uploadedFiles = $uploadedFiles;
  1860. return $new;
  1861. }
  1862. public function getCookieParams(): array
  1863. {
  1864. return $this->cookieParams;
  1865. }
  1866. public function withCookieParams(array $cookies)
  1867. {
  1868. $new = clone $this;
  1869. $new->cookieParams = $cookies;
  1870. return $new;
  1871. }
  1872. public function getQueryParams(): array
  1873. {
  1874. return $this->queryParams;
  1875. }
  1876. public function withQueryParams(array $query)
  1877. {
  1878. $new = clone $this;
  1879. $new->queryParams = $query;
  1880. return $new;
  1881. }
  1882. public function getParsedBody()
  1883. {
  1884. return $this->parsedBody;
  1885. }
  1886. public function withParsedBody($data)
  1887. {
  1888. if (!\is_array($data) && !\is_object($data) && null !== $data) {
  1889. throw new \InvalidArgumentException('First parameter to withParsedBody MUST be object, array or null');
  1890. }
  1891. $new = clone $this;
  1892. $new->parsedBody = $data;
  1893. return $new;
  1894. }
  1895. public function getAttributes(): array
  1896. {
  1897. return $this->attributes;
  1898. }
  1899. public function getAttribute($attribute, $default = null)
  1900. {
  1901. if (false === \array_key_exists($attribute, $this->attributes)) {
  1902. return $default;
  1903. }
  1904. return $this->attributes[$attribute];
  1905. }
  1906. public function withAttribute($attribute, $value): self
  1907. {
  1908. $new = clone $this;
  1909. $new->attributes[$attribute] = $value;
  1910. return $new;
  1911. }
  1912. public function withoutAttribute($attribute): self
  1913. {
  1914. if (false === \array_key_exists($attribute, $this->attributes)) {
  1915. return $this;
  1916. }
  1917. $new = clone $this;
  1918. unset($new->attributes[$attribute]);
  1919. return $new;
  1920. }
  1921. }
  1922. }
  1923. // file: vendor/nyholm/psr7/src/Stream.php
  1924. namespace Nyholm\Psr7 {
  1925. use Psr\Http\Message\StreamInterface;
  1926. /**
  1927. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1928. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1929. * @author Martijn van der Ven <martijn@vanderven.se>
  1930. */
  1931. final class Stream implements StreamInterface
  1932. {
  1933. /** @var resource|null A resource reference */
  1934. private $stream;
  1935. /** @var bool */
  1936. private $seekable;
  1937. /** @var bool */
  1938. private $readable;
  1939. /** @var bool */
  1940. private $writable;
  1941. /** @var array|mixed|void|null */
  1942. private $uri;
  1943. /** @var int|null */
  1944. private $size;
  1945. /** @var array Hash of readable and writable stream types */
  1946. /*private*/ const READ_WRITE_HASH = [
  1947. 'read' => [
  1948. 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
  1949. 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
  1950. 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
  1951. 'x+t' => true, 'c+t' => true, 'a+' => true,
  1952. ],
  1953. 'write' => [
  1954. 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
  1955. 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
  1956. 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
  1957. 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
  1958. ],
  1959. ];
  1960. private function __construct()
  1961. {
  1962. }
  1963. /**
  1964. * Creates a new PSR-7 stream.
  1965. *
  1966. * @param string|resource|StreamInterface $body
  1967. *
  1968. * @return StreamInterface
  1969. *
  1970. * @throws \InvalidArgumentException
  1971. */
  1972. public static function create($body = ''): StreamInterface
  1973. {
  1974. if ($body instanceof StreamInterface) {
  1975. return $body;
  1976. }
  1977. if (\is_string($body)) {
  1978. $resource = \fopen('php://temp', 'rw+');
  1979. \fwrite($resource, $body);
  1980. $body = $resource;
  1981. }
  1982. if (\is_resource($body)) {
  1983. $new = new self();
  1984. $new->stream = $body;
  1985. $meta = \stream_get_meta_data($new->stream);
  1986. $new->seekable = $meta['seekable'];
  1987. $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]);
  1988. $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]);
  1989. $new->uri = $new->getMetadata('uri');
  1990. return $new;
  1991. }
  1992. throw new \InvalidArgumentException('First argument to Stream::create() must be a string, resource or StreamInterface.');
  1993. }
  1994. /**
  1995. * Closes the stream when the destructed.
  1996. */
  1997. public function __destruct()
  1998. {
  1999. $this->close();
  2000. }
  2001. public function __toString(): string
  2002. {
  2003. try {
  2004. if ($this->isSeekable()) {
  2005. $this->seek(0);
  2006. }
  2007. return $this->getContents();
  2008. } catch (\Exception $e) {
  2009. return '';
  2010. }
  2011. }
  2012. public function close() /*:void*/
  2013. {
  2014. if (isset($this->stream)) {
  2015. if (\is_resource($this->stream)) {
  2016. \fclose($this->stream);
  2017. }
  2018. $this->detach();
  2019. }
  2020. }
  2021. public function detach()
  2022. {
  2023. if (!isset($this->stream)) {
  2024. return null;
  2025. }
  2026. $result = $this->stream;
  2027. unset($this->stream);
  2028. $this->size = $this->uri = null;
  2029. $this->readable = $this->writable = $this->seekable = false;
  2030. return $result;
  2031. }
  2032. public function getSize() /*:?int*/
  2033. {
  2034. if (null !== $this->size) {
  2035. return $this->size;
  2036. }
  2037. if (!isset($this->stream)) {
  2038. return null;
  2039. }
  2040. // Clear the stat cache if the stream has a URI
  2041. if ($this->uri) {
  2042. \clearstatcache(true, $this->uri);
  2043. }
  2044. $stats = \fstat($this->stream);
  2045. if (isset($stats['size'])) {
  2046. $this->size = $stats['size'];
  2047. return $this->size;
  2048. }
  2049. return null;
  2050. }
  2051. public function tell(): int
  2052. {
  2053. if (false === $result = \ftell($this->stream)) {
  2054. throw new \RuntimeException('Unable to determine stream position');
  2055. }
  2056. return $result;
  2057. }
  2058. public function eof(): bool
  2059. {
  2060. return !$this->stream || \feof($this->stream);
  2061. }
  2062. public function isSeekable(): bool
  2063. {
  2064. return $this->seekable;
  2065. }
  2066. public function seek($offset, $whence = \SEEK_SET) /*:void*/
  2067. {
  2068. if (!$this->seekable) {
  2069. throw new \RuntimeException('Stream is not seekable');
  2070. }
  2071. if (-1 === \fseek($this->stream, $offset, $whence)) {
  2072. throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, true));
  2073. }
  2074. }
  2075. public function rewind() /*:void*/
  2076. {
  2077. $this->seek(0);
  2078. }
  2079. public function isWritable(): bool
  2080. {
  2081. return $this->writable;
  2082. }
  2083. public function write($string): int
  2084. {
  2085. if (!$this->writable) {
  2086. throw new \RuntimeException('Cannot write to a non-writable stream');
  2087. }
  2088. // We can't know the size after writing anything
  2089. $this->size = null;
  2090. if (false === $result = \fwrite($this->stream, $string)) {
  2091. throw new \RuntimeException('Unable to write to stream');
  2092. }
  2093. return $result;
  2094. }
  2095. public function isReadable(): bool
  2096. {
  2097. return $this->readable;
  2098. }
  2099. public function read($length): string
  2100. {
  2101. if (!$this->readable) {
  2102. throw new \RuntimeException('Cannot read from non-readable stream');
  2103. }
  2104. return \fread($this->stream, $length);
  2105. }
  2106. public function getContents(): string
  2107. {
  2108. if (!isset($this->stream)) {
  2109. throw new \RuntimeException('Unable to read stream contents');
  2110. }
  2111. if (false === $contents = \stream_get_contents($this->stream)) {
  2112. throw new \RuntimeException('Unable to read stream contents');
  2113. }
  2114. return $contents;
  2115. }
  2116. public function getMetadata($key = null)
  2117. {
  2118. if (!isset($this->stream)) {
  2119. return $key ? null : [];
  2120. }
  2121. $meta = \stream_get_meta_data($this->stream);
  2122. if (null === $key) {
  2123. return $meta;
  2124. }
  2125. return $meta[$key] ?? null;
  2126. }
  2127. }
  2128. }
  2129. // file: vendor/nyholm/psr7/src/UploadedFile.php
  2130. namespace Nyholm\Psr7 {
  2131. use Psr\Http\Message\{StreamInterface, UploadedFileInterface};
  2132. /**
  2133. * @author Michael Dowling and contributors to guzzlehttp/psr7
  2134. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2135. * @author Martijn van der Ven <martijn@vanderven.se>
  2136. */
  2137. final class UploadedFile implements UploadedFileInterface
  2138. {
  2139. /** @var array */
  2140. /*private*/ const ERRORS = [
  2141. \UPLOAD_ERR_OK => 1,
  2142. \UPLOAD_ERR_INI_SIZE => 1,
  2143. \UPLOAD_ERR_FORM_SIZE => 1,
  2144. \UPLOAD_ERR_PARTIAL => 1,
  2145. \UPLOAD_ERR_NO_FILE => 1,
  2146. \UPLOAD_ERR_NO_TMP_DIR => 1,
  2147. \UPLOAD_ERR_CANT_WRITE => 1,
  2148. \UPLOAD_ERR_EXTENSION => 1,
  2149. ];
  2150. /** @var string */
  2151. private $clientFilename;
  2152. /** @var string */
  2153. private $clientMediaType;
  2154. /** @var int */
  2155. private $error;
  2156. /** @var string|null */
  2157. private $file;
  2158. /** @var bool */
  2159. private $moved = false;
  2160. /** @var int */
  2161. private $size;
  2162. /** @var StreamInterface|null */
  2163. private $stream;
  2164. /**
  2165. * @param StreamInterface|string|resource $streamOrFile
  2166. * @param int $size
  2167. * @param int $errorStatus
  2168. * @param string|null $clientFilename
  2169. * @param string|null $clientMediaType
  2170. */
  2171. public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
  2172. {
  2173. if (false === \is_int($errorStatus) || !isset(self::ERRORS[$errorStatus])) {
  2174. throw new \InvalidArgumentException('Upload file error status must be an integer value and one of the "UPLOAD_ERR_*" constants.');
  2175. }
  2176. if (false === \is_int($size)) {
  2177. throw new \InvalidArgumentException('Upload file size must be an integer');
  2178. }
  2179. if (null !== $clientFilename && !\is_string($clientFilename)) {
  2180. throw new \InvalidArgumentException('Upload file client filename must be a string or null');
  2181. }
  2182. if (null !== $clientMediaType && !\is_string($clientMediaType)) {
  2183. throw new \InvalidArgumentException('Upload file client media type must be a string or null');
  2184. }
  2185. $this->error = $errorStatus;
  2186. $this->size = $size;
  2187. $this->clientFilename = $clientFilename;
  2188. $this->clientMediaType = $clientMediaType;
  2189. if (\UPLOAD_ERR_OK === $this->error) {
  2190. // Depending on the value set file or stream variable.
  2191. if (\is_string($streamOrFile)) {
  2192. $this->file = $streamOrFile;
  2193. } elseif (\is_resource($streamOrFile)) {
  2194. $this->stream = Stream::create($streamOrFile);
  2195. } elseif ($streamOrFile instanceof StreamInterface) {
  2196. $this->stream = $streamOrFile;
  2197. } else {
  2198. throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile');
  2199. }
  2200. }
  2201. }
  2202. /**
  2203. * @throws \RuntimeException if is moved or not ok
  2204. */
  2205. private function validateActive() /*:void*/
  2206. {
  2207. if (\UPLOAD_ERR_OK !== $this->error) {
  2208. throw new \RuntimeException('Cannot retrieve stream due to upload error');
  2209. }
  2210. if ($this->moved) {
  2211. throw new \RuntimeException('Cannot retrieve stream after it has already been moved');
  2212. }
  2213. }
  2214. public function getStream(): StreamInterface
  2215. {
  2216. $this->validateActive();
  2217. if ($this->stream instanceof StreamInterface) {
  2218. return $this->stream;
  2219. }
  2220. $resource = \fopen($this->file, 'r');
  2221. return Stream::create($resource);
  2222. }
  2223. public function moveTo($targetPath) /*:void*/
  2224. {
  2225. $this->validateActive();
  2226. if (!\is_string($targetPath) || '' === $targetPath) {
  2227. throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
  2228. }
  2229. if (null !== $this->file) {
  2230. $this->moved = 'cli' === \PHP_SAPI ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath);
  2231. } else {
  2232. $stream = $this->getStream();
  2233. if ($stream->isSeekable()) {
  2234. $stream->rewind();
  2235. }
  2236. // Copy the contents of a stream into another stream until end-of-file.
  2237. $dest = Stream::create(\fopen($targetPath, 'w'));
  2238. while (!$stream->eof()) {
  2239. if (!$dest->write($stream->read(1048576))) {
  2240. break;
  2241. }
  2242. }
  2243. $this->moved = true;
  2244. }
  2245. if (false === $this->moved) {
  2246. throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath));
  2247. }
  2248. }
  2249. public function getSize(): int
  2250. {
  2251. return $this->size;
  2252. }
  2253. public function getError(): int
  2254. {
  2255. return $this->error;
  2256. }
  2257. public function getClientFilename() /*:?string*/
  2258. {
  2259. return $this->clientFilename;
  2260. }
  2261. public function getClientMediaType() /*:?string*/
  2262. {
  2263. return $this->clientMediaType;
  2264. }
  2265. }
  2266. }
  2267. // file: vendor/nyholm/psr7/src/Uri.php
  2268. namespace Nyholm\Psr7 {
  2269. use Psr\Http\Message\UriInterface;
  2270. /**
  2271. * PSR-7 URI implementation.
  2272. *
  2273. * @author Michael Dowling
  2274. * @author Tobias Schultze
  2275. * @author Matthew Weier O'Phinney
  2276. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2277. * @author Martijn van der Ven <martijn@vanderven.se>
  2278. */
  2279. final class Uri implements UriInterface
  2280. {
  2281. /*private*/ const SCHEMES = ['http' => 80, 'https' => 443];
  2282. /*private*/ const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  2283. /*private*/ const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  2284. /** @var string Uri scheme. */
  2285. private $scheme = '';
  2286. /** @var string Uri user info. */
  2287. private $userInfo = '';
  2288. /** @var string Uri host. */
  2289. private $host = '';
  2290. /** @var int|null Uri port. */
  2291. private $port;
  2292. /** @var string Uri path. */
  2293. private $path = '';
  2294. /** @var string Uri query string. */
  2295. private $query = '';
  2296. /** @var string Uri fragment. */
  2297. private $fragment = '';
  2298. public function __construct(string $uri = '')
  2299. {
  2300. if ('' !== $uri) {
  2301. if (false === $parts = \parse_url($uri)) {
  2302. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  2303. }
  2304. // Apply parse_url parts to a URI.
  2305. $this->scheme = isset($parts['scheme']) ? \strtolower($parts['scheme']) : '';
  2306. $this->userInfo = $parts['user'] ?? '';
  2307. $this->host = isset($parts['host']) ? \strtolower($parts['host']) : '';
  2308. $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
  2309. $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
  2310. $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : '';
  2311. $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : '';
  2312. if (isset($parts['pass'])) {
  2313. $this->userInfo .= ':' . $parts['pass'];
  2314. }
  2315. }
  2316. }
  2317. public function __toString(): string
  2318. {
  2319. return self::createUriString($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment);
  2320. }
  2321. public function getScheme(): string
  2322. {
  2323. return $this->scheme;
  2324. }
  2325. public function getAuthority(): string
  2326. {
  2327. if ('' === $this->host) {
  2328. return '';
  2329. }
  2330. $authority = $this->host;
  2331. if ('' !== $this->userInfo) {
  2332. $authority = $this->userInfo . '@' . $authority;
  2333. }
  2334. if (null !== $this->port) {
  2335. $authority .= ':' . $this->port;
  2336. }
  2337. return $authority;
  2338. }
  2339. public function getUserInfo(): string
  2340. {
  2341. return $this->userInfo;
  2342. }
  2343. public function getHost(): string
  2344. {
  2345. return $this->host;
  2346. }
  2347. public function getPort() /*:?int*/
  2348. {
  2349. return $this->port;
  2350. }
  2351. public function getPath(): string
  2352. {
  2353. return $this->path;
  2354. }
  2355. public function getQuery(): string
  2356. {
  2357. return $this->query;
  2358. }
  2359. public function getFragment(): string
  2360. {
  2361. return $this->fragment;
  2362. }
  2363. public function withScheme($scheme): self
  2364. {
  2365. if (!\is_string($scheme)) {
  2366. throw new \InvalidArgumentException('Scheme must be a string');
  2367. }
  2368. if ($this->scheme === $scheme = \strtolower($scheme)) {
  2369. return $this;
  2370. }
  2371. $new = clone $this;
  2372. $new->scheme = $scheme;
  2373. $new->port = $new->filterPort($new->port);
  2374. return $new;
  2375. }
  2376. public function withUserInfo($user, $password = null): self
  2377. {
  2378. $info = $user;
  2379. if (null !== $password && '' !== $password) {
  2380. $info .= ':' . $password;
  2381. }
  2382. if ($this->userInfo === $info) {
  2383. return $this;
  2384. }
  2385. $new = clone $this;
  2386. $new->userInfo = $info;
  2387. return $new;
  2388. }
  2389. public function withHost($host): self
  2390. {
  2391. if (!\is_string($host)) {
  2392. throw new \InvalidArgumentException('Host must be a string');
  2393. }
  2394. if ($this->host === $host = \strtolower($host)) {
  2395. return $this;
  2396. }
  2397. $new = clone $this;
  2398. $new->host = $host;
  2399. return $new;
  2400. }
  2401. public function withPort($port): self
  2402. {
  2403. if ($this->port === $port = $this->filterPort($port)) {
  2404. return $this;
  2405. }
  2406. $new = clone $this;
  2407. $new->port = $port;
  2408. return $new;
  2409. }
  2410. public function withPath($path): self
  2411. {
  2412. if ($this->path === $path = $this->filterPath($path)) {
  2413. return $this;
  2414. }
  2415. $new = clone $this;
  2416. $new->path = $path;
  2417. return $new;
  2418. }
  2419. public function withQuery($query): self
  2420. {
  2421. if ($this->query === $query = $this->filterQueryAndFragment($query)) {
  2422. return $this;
  2423. }
  2424. $new = clone $this;
  2425. $new->query = $query;
  2426. return $new;
  2427. }
  2428. public function withFragment($fragment): self
  2429. {
  2430. if ($this->fragment === $fragment = $this->filterQueryAndFragment($fragment)) {
  2431. return $this;
  2432. }
  2433. $new = clone $this;
  2434. $new->fragment = $fragment;
  2435. return $new;
  2436. }
  2437. /**
  2438. * Create a URI string from its various parts.
  2439. */
  2440. private static function createUriString(string $scheme, string $authority, string $path, string $query, string $fragment): string
  2441. {
  2442. $uri = '';
  2443. if ('' !== $scheme) {
  2444. $uri .= $scheme . ':';
  2445. }
  2446. if ('' !== $authority) {
  2447. $uri .= '//' . $authority;
  2448. }
  2449. if ('' !== $path) {
  2450. if ('/' !== $path[0]) {
  2451. if ('' !== $authority) {
  2452. // If the path is rootless and an authority is present, the path MUST be prefixed by "/"
  2453. $path = '/' . $path;
  2454. }
  2455. } elseif (isset($path[1]) && '/' === $path[1]) {
  2456. if ('' === $authority) {
  2457. // If the path is starting with more than one "/" and no authority is present, the
  2458. // starting slashes MUST be reduced to one.
  2459. $path = '/' . \ltrim($path, '/');
  2460. }
  2461. }
  2462. $uri .= $path;
  2463. }
  2464. if ('' !== $query) {
  2465. $uri .= '?' . $query;
  2466. }
  2467. if ('' !== $fragment) {
  2468. $uri .= '#' . $fragment;
  2469. }
  2470. return $uri;
  2471. }
  2472. /**
  2473. * Is a given port non-standard for the current scheme?
  2474. */
  2475. private static function isNonStandardPort(string $scheme, int $port): bool
  2476. {
  2477. return !isset(self::SCHEMES[$scheme]) || $port !== self::SCHEMES[$scheme];
  2478. }
  2479. private function filterPort($port) /*:?int*/
  2480. {
  2481. if (null === $port) {
  2482. return null;
  2483. }
  2484. $port = (int) $port;
  2485. if (1 > $port || 0xffff < $port) {
  2486. throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 1 and 65535', $port));
  2487. }
  2488. return self::isNonStandardPort($this->scheme, $port) ? $port : null;
  2489. }
  2490. private function filterPath($path): string
  2491. {
  2492. if (!\is_string($path)) {
  2493. throw new \InvalidArgumentException('Path must be a string');
  2494. }
  2495. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $path);
  2496. }
  2497. private function filterQueryAndFragment($str): string
  2498. {
  2499. if (!\is_string($str)) {
  2500. throw new \InvalidArgumentException('Query and fragment must be a string');
  2501. }
  2502. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $str);
  2503. }
  2504. private static function rawurlencodeMatchZero(array $match): string
  2505. {
  2506. return \rawurlencode($match[0]);
  2507. }
  2508. }
  2509. }
  2510. // file: vendor/nyholm/psr7-server/src/ServerRequestCreator.php
  2511. namespace Nyholm\Psr7Server {
  2512. use Psr\Http\Message\ServerRequestFactoryInterface;
  2513. use Psr\Http\Message\ServerRequestInterface;
  2514. use Psr\Http\Message\StreamFactoryInterface;
  2515. use Psr\Http\Message\StreamInterface;
  2516. use Psr\Http\Message\UploadedFileFactoryInterface;
  2517. use Psr\Http\Message\UploadedFileInterface;
  2518. use Psr\Http\Message\UriFactoryInterface;
  2519. use Psr\Http\Message\UriInterface;
  2520. /**
  2521. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2522. * @author Martijn van der Ven <martijn@vanderven.se>
  2523. */
  2524. final class ServerRequestCreator implements ServerRequestCreatorInterface
  2525. {
  2526. private $serverRequestFactory;
  2527. private $uriFactory;
  2528. private $uploadedFileFactory;
  2529. private $streamFactory;
  2530. public function __construct(
  2531. ServerRequestFactoryInterface $serverRequestFactory,
  2532. UriFactoryInterface $uriFactory,
  2533. UploadedFileFactoryInterface $uploadedFileFactory,
  2534. StreamFactoryInterface $streamFactory
  2535. ) {
  2536. $this->serverRequestFactory = $serverRequestFactory;
  2537. $this->uriFactory = $uriFactory;
  2538. $this->uploadedFileFactory = $uploadedFileFactory;
  2539. $this->streamFactory = $streamFactory;
  2540. }
  2541. /**
  2542. * {@inheritdoc}
  2543. */
  2544. public function fromGlobals(): ServerRequestInterface
  2545. {
  2546. $server = $_SERVER;
  2547. if (false === isset($server['REQUEST_METHOD'])) {
  2548. $server['REQUEST_METHOD'] = 'GET';
  2549. }
  2550. $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
  2551. return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $_POST, $_FILES, fopen('php://input', 'r') ?: null);
  2552. }
  2553. /**
  2554. * {@inheritdoc}
  2555. */
  2556. public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
  2557. {
  2558. $method = $this->getMethodFromEnv($server);
  2559. $uri = $this->getUriFromEnvWithHTTP($server);
  2560. $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
  2561. $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
  2562. foreach ($headers as $name => $value) {
  2563. $serverRequest = $serverRequest->withAddedHeader($name, $value);
  2564. }
  2565. $serverRequest = $serverRequest
  2566. ->withProtocolVersion($protocol)
  2567. ->withCookieParams($cookie)
  2568. ->withQueryParams($get)
  2569. ->withParsedBody($post)
  2570. ->withUploadedFiles($this->normalizeFiles($files));
  2571. if (null === $body) {
  2572. return $serverRequest;
  2573. }
  2574. if (\is_resource($body)) {
  2575. $body = $this->streamFactory->createStreamFromResource($body);
  2576. } elseif (\is_string($body)) {
  2577. $body = $this->streamFactory->createStream($body);
  2578. } elseif (!$body instanceof StreamInterface) {
  2579. throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
  2580. }
  2581. return $serverRequest->withBody($body);
  2582. }
  2583. /**
  2584. * Implementation from Zend\Diactoros\marshalHeadersFromSapi().
  2585. */
  2586. public static function getHeadersFromServer(array $server): array
  2587. {
  2588. $headers = [];
  2589. foreach ($server as $key => $value) {
  2590. // Apache prefixes environment variables with REDIRECT_
  2591. // if they are added by rewrite rules
  2592. if (0 === \strpos($key, 'REDIRECT_')) {
  2593. $key = \substr($key, 9);
  2594. // We will not overwrite existing variables with the
  2595. // prefixed versions, though
  2596. if (\array_key_exists($key, $server)) {
  2597. continue;
  2598. }
  2599. }
  2600. if ($value && 0 === \strpos($key, 'HTTP_')) {
  2601. $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
  2602. $headers[$name] = $value;
  2603. continue;
  2604. }
  2605. if ($value && 0 === \strpos($key, 'CONTENT_')) {
  2606. $name = 'content-'.\strtolower(\substr($key, 8));
  2607. $headers[$name] = $value;
  2608. continue;
  2609. }
  2610. }
  2611. return $headers;
  2612. }
  2613. private function getMethodFromEnv(array $environment): string
  2614. {
  2615. if (false === isset($environment['REQUEST_METHOD'])) {
  2616. throw new \InvalidArgumentException('Cannot determine HTTP method');
  2617. }
  2618. return $environment['REQUEST_METHOD'];
  2619. }
  2620. private function getUriFromEnvWithHTTP(array $environment): UriInterface
  2621. {
  2622. $uri = $this->createUriFromArray($environment);
  2623. if (empty($uri->getScheme())) {
  2624. $uri = $uri->withScheme('http');
  2625. }
  2626. return $uri;
  2627. }
  2628. /**
  2629. * Return an UploadedFile instance array.
  2630. *
  2631. * @param array $files A array which respect $_FILES structure
  2632. *
  2633. * @return UploadedFileInterface[]
  2634. *
  2635. * @throws \InvalidArgumentException for unrecognized values
  2636. */
  2637. private function normalizeFiles(array $files): array
  2638. {
  2639. $normalized = [];
  2640. foreach ($files as $key => $value) {
  2641. if ($value instanceof UploadedFileInterface) {
  2642. $normalized[$key] = $value;
  2643. } elseif (\is_array($value) && isset($value['tmp_name'])) {
  2644. $normalized[$key] = $this->createUploadedFileFromSpec($value);
  2645. } elseif (\is_array($value)) {
  2646. $normalized[$key] = $this->normalizeFiles($value);
  2647. } else {
  2648. throw new \InvalidArgumentException('Invalid value in files specification');
  2649. }
  2650. }
  2651. return $normalized;
  2652. }
  2653. /**
  2654. * Create and return an UploadedFile instance from a $_FILES specification.
  2655. *
  2656. * If the specification represents an array of values, this method will
  2657. * delegate to normalizeNestedFileSpec() and return that return value.
  2658. *
  2659. * @param array $value $_FILES struct
  2660. *
  2661. * @return array|UploadedFileInterface
  2662. */
  2663. private function createUploadedFileFromSpec(array $value)
  2664. {
  2665. if (\is_array($value['tmp_name'])) {
  2666. return $this->normalizeNestedFileSpec($value);
  2667. }
  2668. try {
  2669. $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
  2670. } catch (\RuntimeException $e) {
  2671. $stream = $this->streamFactory->createStream();
  2672. }
  2673. return $this->uploadedFileFactory->createUploadedFile(
  2674. $stream,
  2675. (int) $value['size'],
  2676. (int) $value['error'],
  2677. $value['name'],
  2678. $value['type']
  2679. );
  2680. }
  2681. /**
  2682. * Normalize an array of file specifications.
  2683. *
  2684. * Loops through all nested files and returns a normalized array of
  2685. * UploadedFileInterface instances.
  2686. *
  2687. * @param array $files
  2688. *
  2689. * @return UploadedFileInterface[]
  2690. */
  2691. private function normalizeNestedFileSpec(array $files = []): array
  2692. {
  2693. $normalizedFiles = [];
  2694. foreach (\array_keys($files['tmp_name']) as $key) {
  2695. $spec = [
  2696. 'tmp_name' => $files['tmp_name'][$key],
  2697. 'size' => $files['size'][$key],
  2698. 'error' => $files['error'][$key],
  2699. 'name' => $files['name'][$key],
  2700. 'type' => $files['type'][$key],
  2701. ];
  2702. $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
  2703. }
  2704. return $normalizedFiles;
  2705. }
  2706. /**
  2707. * Create a new uri from server variable.
  2708. *
  2709. * @param array $server typically $_SERVER or similar structure
  2710. */
  2711. private function createUriFromArray(array $server): UriInterface
  2712. {
  2713. $uri = $this->uriFactory->createUri('');
  2714. if (isset($server['REQUEST_SCHEME'])) {
  2715. $uri = $uri->withScheme($server['REQUEST_SCHEME']);
  2716. } elseif (isset($server['HTTPS'])) {
  2717. $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
  2718. }
  2719. if (isset($server['HTTP_HOST'])) {
  2720. $uri = $uri->withHost($server['HTTP_HOST']);
  2721. } elseif (isset($server['SERVER_NAME'])) {
  2722. $uri = $uri->withHost($server['SERVER_NAME']);
  2723. }
  2724. if (isset($server['SERVER_PORT'])) {
  2725. $uri = $uri->withPort($server['SERVER_PORT']);
  2726. }
  2727. if (isset($server['REQUEST_URI'])) {
  2728. $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
  2729. }
  2730. if (isset($server['QUERY_STRING'])) {
  2731. $uri = $uri->withQuery($server['QUERY_STRING']);
  2732. }
  2733. return $uri;
  2734. }
  2735. }
  2736. }
  2737. // file: vendor/nyholm/psr7-server/src/ServerRequestCreatorInterface.php
  2738. namespace Nyholm\Psr7Server {
  2739. use Psr\Http\Message\ServerRequestInterface;
  2740. use Psr\Http\Message\StreamInterface;
  2741. /**
  2742. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2743. * @author Martijn van der Ven <martijn@vanderven.se>
  2744. */
  2745. interface ServerRequestCreatorInterface
  2746. {
  2747. /**
  2748. * Create a new server request from the current environment variables.
  2749. * Defaults to a GET request to minimise the risk of an \InvalidArgumentException.
  2750. * Includes the current request headers as supplied by the server through `getallheaders()`.
  2751. * If `getallheaders()` is unavailable on the current server it will fallback to its own `getHeadersFromServer()` method.
  2752. * Defaults to php://input for the request body.
  2753. *
  2754. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2755. */
  2756. public function fromGlobals(): ServerRequestInterface;
  2757. /**
  2758. * Create a new server request from a set of arrays.
  2759. *
  2760. * @param array $server typically $_SERVER or similar structure
  2761. * @param array $headers typically the output of getallheaders() or similar structure
  2762. * @param array $cookie typically $_COOKIE or similar structure
  2763. * @param array $get typically $_GET or similar structure
  2764. * @param array $post typically $_POST or similar structure
  2765. * @param array $files typically $_FILES or similar structure
  2766. * @param StreamInterface|resource|string|null $body Typically stdIn
  2767. *
  2768. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2769. */
  2770. public function fromArrays(
  2771. array $server,
  2772. array $headers = [],
  2773. array $cookie = [],
  2774. array $get = [],
  2775. array $post = [],
  2776. array $files = [],
  2777. $body = null
  2778. ): ServerRequestInterface;
  2779. /**
  2780. * Get parsed headers from ($_SERVER) array.
  2781. *
  2782. * @param array $server typically $_SERVER or similar structure
  2783. *
  2784. * @return array
  2785. */
  2786. public static function getHeadersFromServer(array $server): array;
  2787. }
  2788. }
  2789. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  2790. namespace Tqdev\PhpCrudApi\Cache {
  2791. interface Cache
  2792. {
  2793. public function set(string $key, string $value, int $ttl = 0): bool;
  2794. public function get(string $key): string;
  2795. public function clear(): bool;
  2796. }
  2797. }
  2798. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  2799. namespace Tqdev\PhpCrudApi\Cache {
  2800. class CacheFactory
  2801. {
  2802. public static function create(string $type, string $prefix, string $config): Cache
  2803. {
  2804. switch ($type) {
  2805. case 'TempFile':
  2806. $cache = new TempFileCache($prefix, $config);
  2807. break;
  2808. case 'Redis':
  2809. $cache = new RedisCache($prefix, $config);
  2810. break;
  2811. case 'Memcache':
  2812. $cache = new MemcacheCache($prefix, $config);
  2813. break;
  2814. case 'Memcached':
  2815. $cache = new MemcachedCache($prefix, $config);
  2816. break;
  2817. default:
  2818. $cache = new NoCache();
  2819. }
  2820. return $cache;
  2821. }
  2822. }
  2823. }
  2824. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  2825. namespace Tqdev\PhpCrudApi\Cache {
  2826. class MemcacheCache implements Cache
  2827. {
  2828. protected $prefix;
  2829. protected $memcache;
  2830. public function __construct(string $prefix, string $config)
  2831. {
  2832. $this->prefix = $prefix;
  2833. if ($config == '') {
  2834. $address = 'localhost';
  2835. $port = 11211;
  2836. } elseif (strpos($config, ':') === false) {
  2837. $address = $config;
  2838. $port = 11211;
  2839. } else {
  2840. list($address, $port) = explode(':', $config);
  2841. }
  2842. $this->memcache = $this->create();
  2843. $this->memcache->addServer($address, $port);
  2844. }
  2845. protected function create() /*: \Memcache*/
  2846. {
  2847. return new \Memcache();
  2848. }
  2849. public function set(string $key, string $value, int $ttl = 0): bool
  2850. {
  2851. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  2852. }
  2853. public function get(string $key): string
  2854. {
  2855. return $this->memcache->get($this->prefix . $key) ?: '';
  2856. }
  2857. public function clear(): bool
  2858. {
  2859. return $this->memcache->flush();
  2860. }
  2861. }
  2862. }
  2863. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  2864. namespace Tqdev\PhpCrudApi\Cache {
  2865. class MemcachedCache extends MemcacheCache
  2866. {
  2867. protected function create() /*: \Memcached*/
  2868. {
  2869. return new \Memcached();
  2870. }
  2871. public function set(string $key, string $value, int $ttl = 0): bool
  2872. {
  2873. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  2874. }
  2875. }
  2876. }
  2877. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  2878. namespace Tqdev\PhpCrudApi\Cache {
  2879. class NoCache implements Cache
  2880. {
  2881. public function __construct()
  2882. {
  2883. }
  2884. public function set(string $key, string $value, int $ttl = 0): bool
  2885. {
  2886. return true;
  2887. }
  2888. public function get(string $key): string
  2889. {
  2890. return '';
  2891. }
  2892. public function clear(): bool
  2893. {
  2894. return true;
  2895. }
  2896. }
  2897. }
  2898. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  2899. namespace Tqdev\PhpCrudApi\Cache {
  2900. class RedisCache implements Cache
  2901. {
  2902. protected $prefix;
  2903. protected $redis;
  2904. public function __construct(string $prefix, string $config)
  2905. {
  2906. $this->prefix = $prefix;
  2907. if ($config == '') {
  2908. $config = '127.0.0.1';
  2909. }
  2910. $params = explode(':', $config, 6);
  2911. if (isset($params[3])) {
  2912. $params[3] = null;
  2913. }
  2914. $this->redis = new \Redis();
  2915. call_user_func_array(array($this->redis, 'pconnect'), $params);
  2916. }
  2917. public function set(string $key, string $value, int $ttl = 0): bool
  2918. {
  2919. return $this->redis->set($this->prefix . $key, $value, $ttl);
  2920. }
  2921. public function get(string $key): string
  2922. {
  2923. return $this->redis->get($this->prefix . $key) ?: '';
  2924. }
  2925. public function clear(): bool
  2926. {
  2927. return $this->redis->flushDb();
  2928. }
  2929. }
  2930. }
  2931. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  2932. namespace Tqdev\PhpCrudApi\Cache {
  2933. class TempFileCache implements Cache
  2934. {
  2935. const SUFFIX = 'cache';
  2936. private $path;
  2937. private $segments;
  2938. public function __construct(string $prefix, string $config)
  2939. {
  2940. $this->segments = [];
  2941. $s = DIRECTORY_SEPARATOR;
  2942. $ps = PATH_SEPARATOR;
  2943. if ($config == '') {
  2944. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  2945. } elseif (strpos($config, $ps) === false) {
  2946. $this->path = $config;
  2947. } else {
  2948. list($path, $segments) = explode($ps, $config);
  2949. $this->path = $path;
  2950. $this->segments = explode(',', $segments);
  2951. }
  2952. if (file_exists($this->path) && is_dir($this->path)) {
  2953. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  2954. }
  2955. }
  2956. private function getFileName(string $key): string
  2957. {
  2958. $s = DIRECTORY_SEPARATOR;
  2959. $md5 = md5($key);
  2960. $filename = rtrim($this->path, $s) . $s;
  2961. $i = 0;
  2962. foreach ($this->segments as $segment) {
  2963. $filename .= substr($md5, $i, $segment) . $s;
  2964. $i += $segment;
  2965. }
  2966. $filename .= substr($md5, $i);
  2967. return $filename;
  2968. }
  2969. public function set(string $key, string $value, int $ttl = 0): bool
  2970. {
  2971. $filename = $this->getFileName($key);
  2972. $dirname = dirname($filename);
  2973. if (!file_exists($dirname)) {
  2974. if (!mkdir($dirname, 0755, true)) {
  2975. return false;
  2976. }
  2977. }
  2978. $string = $ttl . '|' . $value;
  2979. return $this->filePutContents($filename, $string) !== false;
  2980. }
  2981. private function filePutContents($filename, $string)
  2982. {
  2983. return file_put_contents($filename, $string, LOCK_EX);
  2984. }
  2985. private function fileGetContents($filename)
  2986. {
  2987. $file = fopen($filename, 'rb');
  2988. if ($file === false) {
  2989. return false;
  2990. }
  2991. $lock = flock($file, LOCK_SH);
  2992. if (!$lock) {
  2993. fclose($file);
  2994. return false;
  2995. }
  2996. $string = '';
  2997. while (!feof($file)) {
  2998. $string .= fread($file, 8192);
  2999. }
  3000. flock($file, LOCK_UN);
  3001. fclose($file);
  3002. return $string;
  3003. }
  3004. private function getString($filename): string
  3005. {
  3006. $data = $this->fileGetContents($filename);
  3007. if ($data === false) {
  3008. return '';
  3009. }
  3010. list($ttl, $string) = explode('|', $data, 2);
  3011. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  3012. return '';
  3013. }
  3014. return $string;
  3015. }
  3016. public function get(string $key): string
  3017. {
  3018. $filename = $this->getFileName($key);
  3019. if (!file_exists($filename)) {
  3020. return '';
  3021. }
  3022. $string = $this->getString($filename);
  3023. if ($string == null) {
  3024. return '';
  3025. }
  3026. return $string;
  3027. }
  3028. private function clean(string $path, array $segments, int $len, bool $all) /*: void*/
  3029. {
  3030. $entries = scandir($path);
  3031. foreach ($entries as $entry) {
  3032. if ($entry === '.' || $entry === '..') {
  3033. continue;
  3034. }
  3035. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  3036. if (count($segments) == 0) {
  3037. if (strlen($entry) != $len) {
  3038. continue;
  3039. }
  3040. if (is_file($filename)) {
  3041. if ($all || $this->getString($filename) == null) {
  3042. unlink($filename);
  3043. }
  3044. }
  3045. } else {
  3046. if (strlen($entry) != $segments[0]) {
  3047. continue;
  3048. }
  3049. if (is_dir($filename)) {
  3050. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  3051. rmdir($filename);
  3052. }
  3053. }
  3054. }
  3055. }
  3056. public function clear(): bool
  3057. {
  3058. if (!file_exists($this->path) || !is_dir($this->path)) {
  3059. return false;
  3060. }
  3061. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  3062. return true;
  3063. }
  3064. }
  3065. }
  3066. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  3067. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3068. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3069. class ReflectedColumn implements \JsonSerializable
  3070. {
  3071. const DEFAULT_LENGTH = 255;
  3072. const DEFAULT_PRECISION = 19;
  3073. const DEFAULT_SCALE = 4;
  3074. private $name;
  3075. private $type;
  3076. private $length;
  3077. private $precision;
  3078. private $scale;
  3079. private $nullable;
  3080. private $pk;
  3081. private $fk;
  3082. public function __construct(string $name, string $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, string $fk)
  3083. {
  3084. $this->name = $name;
  3085. $this->type = $type;
  3086. $this->length = $length;
  3087. $this->precision = $precision;
  3088. $this->scale = $scale;
  3089. $this->nullable = $nullable;
  3090. $this->pk = $pk;
  3091. $this->fk = $fk;
  3092. $this->sanitize();
  3093. }
  3094. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  3095. {
  3096. $name = $columnResult['COLUMN_NAME'];
  3097. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  3098. $type = $reflection->toJdbcType($columnResult['DATA_TYPE'], $length);
  3099. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  3100. $scale = (int) $columnResult['NUMERIC_SCALE'];
  3101. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  3102. $pk = false;
  3103. $fk = '';
  3104. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3105. }
  3106. public static function fromJson( /* object */$json): ReflectedColumn
  3107. {
  3108. $name = $json->name;
  3109. $type = $json->type;
  3110. $length = isset($json->length) ? $json->length : 0;
  3111. $precision = isset($json->precision) ? $json->precision : 0;
  3112. $scale = isset($json->scale) ? $json->scale : 0;
  3113. $nullable = isset($json->nullable) ? $json->nullable : false;
  3114. $pk = isset($json->pk) ? $json->pk : false;
  3115. $fk = isset($json->fk) ? $json->fk : '';
  3116. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3117. }
  3118. private function sanitize()
  3119. {
  3120. $this->length = $this->hasLength() ? $this->getLength() : 0;
  3121. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  3122. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  3123. }
  3124. public function getName(): string
  3125. {
  3126. return $this->name;
  3127. }
  3128. public function getNullable(): bool
  3129. {
  3130. return $this->nullable;
  3131. }
  3132. public function getType(): string
  3133. {
  3134. return $this->type;
  3135. }
  3136. public function getLength(): int
  3137. {
  3138. return $this->length ?: self::DEFAULT_LENGTH;
  3139. }
  3140. public function getPrecision(): int
  3141. {
  3142. return $this->precision ?: self::DEFAULT_PRECISION;
  3143. }
  3144. public function getScale(): int
  3145. {
  3146. return $this->scale ?: self::DEFAULT_SCALE;
  3147. }
  3148. public function hasLength(): bool
  3149. {
  3150. return in_array($this->type, ['varchar', 'varbinary']);
  3151. }
  3152. public function hasPrecision(): bool
  3153. {
  3154. return $this->type == 'decimal';
  3155. }
  3156. public function hasScale(): bool
  3157. {
  3158. return $this->type == 'decimal';
  3159. }
  3160. public function isBinary(): bool
  3161. {
  3162. return in_array($this->type, ['blob', 'varbinary']);
  3163. }
  3164. public function isBoolean(): bool
  3165. {
  3166. return $this->type == 'boolean';
  3167. }
  3168. public function isGeometry(): bool
  3169. {
  3170. return $this->type == 'geometry';
  3171. }
  3172. public function isInteger(): bool
  3173. {
  3174. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  3175. }
  3176. public function setPk($value) /*: void*/
  3177. {
  3178. $this->pk = $value;
  3179. }
  3180. public function getPk(): bool
  3181. {
  3182. return $this->pk;
  3183. }
  3184. public function setFk($value) /*: void*/
  3185. {
  3186. $this->fk = $value;
  3187. }
  3188. public function getFk(): string
  3189. {
  3190. return $this->fk;
  3191. }
  3192. public function serialize()
  3193. {
  3194. return [
  3195. 'name' => $this->name,
  3196. 'type' => $this->type,
  3197. 'length' => $this->length,
  3198. 'precision' => $this->precision,
  3199. 'scale' => $this->scale,
  3200. 'nullable' => $this->nullable,
  3201. 'pk' => $this->pk,
  3202. 'fk' => $this->fk,
  3203. ];
  3204. }
  3205. public function jsonSerialize()
  3206. {
  3207. return array_filter($this->serialize());
  3208. }
  3209. }
  3210. }
  3211. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  3212. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3213. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3214. class ReflectedDatabase implements \JsonSerializable
  3215. {
  3216. private $tableTypes;
  3217. public function __construct(array $tableTypes)
  3218. {
  3219. $this->tableTypes = $tableTypes;
  3220. }
  3221. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  3222. {
  3223. $tableTypes = [];
  3224. foreach ($reflection->getTables() as $table) {
  3225. $tableName = $table['TABLE_NAME'];
  3226. $tableType = $table['TABLE_TYPE'];
  3227. if (in_array($tableName, $reflection->getIgnoredTables())) {
  3228. continue;
  3229. }
  3230. $tableTypes[$tableName] = $tableType;
  3231. }
  3232. return new ReflectedDatabase($tableTypes);
  3233. }
  3234. public static function fromJson( /* object */$json): ReflectedDatabase
  3235. {
  3236. $tableTypes = (array) $json->tables;
  3237. return new ReflectedDatabase($tableTypes);
  3238. }
  3239. public function hasTable(string $tableName): bool
  3240. {
  3241. return isset($this->tableTypes[$tableName]);
  3242. }
  3243. public function getType(string $tableName): string
  3244. {
  3245. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  3246. }
  3247. public function getTableNames(): array
  3248. {
  3249. return array_keys($this->tableTypes);
  3250. }
  3251. public function removeTable(string $tableName): bool
  3252. {
  3253. if (!isset($this->tableTypes[$tableName])) {
  3254. return false;
  3255. }
  3256. unset($this->tableTypes[$tableName]);
  3257. return true;
  3258. }
  3259. public function serialize()
  3260. {
  3261. return [
  3262. 'tables' => $this->tableTypes,
  3263. ];
  3264. }
  3265. public function jsonSerialize()
  3266. {
  3267. return $this->serialize();
  3268. }
  3269. }
  3270. }
  3271. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  3272. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3273. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3274. class ReflectedTable implements \JsonSerializable
  3275. {
  3276. private $name;
  3277. private $type;
  3278. private $columns;
  3279. private $pk;
  3280. private $fks;
  3281. public function __construct(string $name, string $type, array $columns)
  3282. {
  3283. $this->name = $name;
  3284. $this->type = $type;
  3285. // set columns
  3286. $this->columns = [];
  3287. foreach ($columns as $column) {
  3288. $columnName = $column->getName();
  3289. $this->columns[$columnName] = $column;
  3290. }
  3291. // set primary key
  3292. $this->pk = null;
  3293. foreach ($columns as $column) {
  3294. if ($column->getPk() == true) {
  3295. $this->pk = $column;
  3296. }
  3297. }
  3298. // set foreign keys
  3299. $this->fks = [];
  3300. foreach ($columns as $column) {
  3301. $columnName = $column->getName();
  3302. $referencedTableName = $column->getFk();
  3303. if ($referencedTableName != '') {
  3304. $this->fks[$columnName] = $referencedTableName;
  3305. }
  3306. }
  3307. }
  3308. public static function fromReflection(GenericReflection $reflection, string $name, string $type): ReflectedTable
  3309. {
  3310. // set columns
  3311. $columns = [];
  3312. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  3313. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  3314. $columns[$column->getName()] = $column;
  3315. }
  3316. // set primary key
  3317. $columnNames = $reflection->getTablePrimaryKeys($name);
  3318. if (count($columnNames) == 1) {
  3319. $columnName = $columnNames[0];
  3320. if (isset($columns[$columnName])) {
  3321. $pk = $columns[$columnName];
  3322. $pk->setPk(true);
  3323. }
  3324. }
  3325. // set foreign keys
  3326. $fks = $reflection->getTableForeignKeys($name);
  3327. foreach ($fks as $columnName => $table) {
  3328. $columns[$columnName]->setFk($table);
  3329. }
  3330. return new ReflectedTable($name, $type, array_values($columns));
  3331. }
  3332. public static function fromJson( /* object */$json): ReflectedTable
  3333. {
  3334. $name = $json->name;
  3335. $type = $json->type;
  3336. $columns = [];
  3337. if (isset($json->columns) && is_array($json->columns)) {
  3338. foreach ($json->columns as $column) {
  3339. $columns[] = ReflectedColumn::fromJson($column);
  3340. }
  3341. }
  3342. return new ReflectedTable($name, $type, $columns);
  3343. }
  3344. public function hasColumn(string $columnName): bool
  3345. {
  3346. return isset($this->columns[$columnName]);
  3347. }
  3348. public function hasPk(): bool
  3349. {
  3350. return $this->pk != null;
  3351. }
  3352. public function getPk() /*: ?ReflectedColumn */
  3353. {
  3354. return $this->pk;
  3355. }
  3356. public function getName(): string
  3357. {
  3358. return $this->name;
  3359. }
  3360. public function getType(): string
  3361. {
  3362. return $this->type;
  3363. }
  3364. public function getColumnNames(): array
  3365. {
  3366. return array_keys($this->columns);
  3367. }
  3368. public function getColumn($columnName): ReflectedColumn
  3369. {
  3370. return $this->columns[$columnName];
  3371. }
  3372. public function getFksTo(string $tableName): array
  3373. {
  3374. $columns = array();
  3375. foreach ($this->fks as $columnName => $referencedTableName) {
  3376. if ($tableName == $referencedTableName) {
  3377. $columns[] = $this->columns[$columnName];
  3378. }
  3379. }
  3380. return $columns;
  3381. }
  3382. public function removeColumn(string $columnName): bool
  3383. {
  3384. if (!isset($this->columns[$columnName])) {
  3385. return false;
  3386. }
  3387. unset($this->columns[$columnName]);
  3388. return true;
  3389. }
  3390. public function serialize()
  3391. {
  3392. return [
  3393. 'name' => $this->name,
  3394. 'type' => $this->type,
  3395. 'columns' => array_values($this->columns),
  3396. ];
  3397. }
  3398. public function jsonSerialize()
  3399. {
  3400. return $this->serialize();
  3401. }
  3402. }
  3403. }
  3404. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  3405. namespace Tqdev\PhpCrudApi\Column {
  3406. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  3407. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3408. use Tqdev\PhpCrudApi\Database\GenericDB;
  3409. class DefinitionService
  3410. {
  3411. private $db;
  3412. private $reflection;
  3413. public function __construct(GenericDB $db, ReflectionService $reflection)
  3414. {
  3415. $this->db = $db;
  3416. $this->reflection = $reflection;
  3417. }
  3418. public function updateTable(string $tableName, /* object */ $changes): bool
  3419. {
  3420. $table = $this->reflection->getTable($tableName);
  3421. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  3422. if ($table->getName() != $newTable->getName()) {
  3423. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  3424. return false;
  3425. }
  3426. }
  3427. return true;
  3428. }
  3429. public function updateColumn(string $tableName, string $columnName, /* object */ $changes): bool
  3430. {
  3431. $table = $this->reflection->getTable($tableName);
  3432. $column = $table->getColumn($columnName);
  3433. // remove constraints on other column
  3434. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3435. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  3436. $oldColumn = $table->getPk();
  3437. if ($oldColumn->getName() != $columnName) {
  3438. $oldColumn->setPk(false);
  3439. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  3440. return false;
  3441. }
  3442. }
  3443. }
  3444. // remove constraints
  3445. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  3446. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  3447. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  3448. return false;
  3449. }
  3450. }
  3451. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  3452. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  3453. return false;
  3454. }
  3455. }
  3456. // name and type
  3457. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3458. $newColumn->setPk(false);
  3459. $newColumn->setFk('');
  3460. if ($newColumn->getName() != $column->getName()) {
  3461. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  3462. return false;
  3463. }
  3464. }
  3465. if ($newColumn->getType() != $column->getType() ||
  3466. $newColumn->getLength() != $column->getLength() ||
  3467. $newColumn->getPrecision() != $column->getPrecision() ||
  3468. $newColumn->getScale() != $column->getScale()
  3469. ) {
  3470. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  3471. return false;
  3472. }
  3473. }
  3474. if ($newColumn->getNullable() != $column->getNullable()) {
  3475. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  3476. return false;
  3477. }
  3478. }
  3479. // add constraints
  3480. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3481. if ($newColumn->getFk()) {
  3482. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3483. return false;
  3484. }
  3485. }
  3486. if ($newColumn->getPk()) {
  3487. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3488. return false;
  3489. }
  3490. }
  3491. return true;
  3492. }
  3493. public function addTable( /* object */$definition)
  3494. {
  3495. $newTable = ReflectedTable::fromJson($definition);
  3496. if (!$this->db->definition()->addTable($newTable)) {
  3497. return false;
  3498. }
  3499. return true;
  3500. }
  3501. public function addColumn(string $tableName, /* object */ $definition)
  3502. {
  3503. $newColumn = ReflectedColumn::fromJson($definition);
  3504. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  3505. return false;
  3506. }
  3507. if ($newColumn->getFk()) {
  3508. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  3509. return false;
  3510. }
  3511. }
  3512. if ($newColumn->getPk()) {
  3513. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  3514. return false;
  3515. }
  3516. }
  3517. return true;
  3518. }
  3519. public function removeTable(string $tableName)
  3520. {
  3521. if (!$this->db->definition()->removeTable($tableName)) {
  3522. return false;
  3523. }
  3524. return true;
  3525. }
  3526. public function removeColumn(string $tableName, string $columnName)
  3527. {
  3528. $table = $this->reflection->getTable($tableName);
  3529. $newColumn = $table->getColumn($columnName);
  3530. if ($newColumn->getPk()) {
  3531. $newColumn->setPk(false);
  3532. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3533. return false;
  3534. }
  3535. }
  3536. if ($newColumn->getFk()) {
  3537. $newColumn->setFk("");
  3538. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  3539. return false;
  3540. }
  3541. }
  3542. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  3543. return false;
  3544. }
  3545. return true;
  3546. }
  3547. }
  3548. }
  3549. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  3550. namespace Tqdev\PhpCrudApi\Column {
  3551. use Tqdev\PhpCrudApi\Cache\Cache;
  3552. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedDatabase;
  3553. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3554. use Tqdev\PhpCrudApi\Database\GenericDB;
  3555. class ReflectionService
  3556. {
  3557. private $db;
  3558. private $cache;
  3559. private $ttl;
  3560. private $database;
  3561. private $tables;
  3562. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  3563. {
  3564. $this->db = $db;
  3565. $this->cache = $cache;
  3566. $this->ttl = $ttl;
  3567. $this->database = $this->loadDatabase(true);
  3568. $this->tables = [];
  3569. }
  3570. private function loadDatabase(bool $useCache): ReflectedDatabase
  3571. {
  3572. $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
  3573. if ($data != '') {
  3574. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  3575. } else {
  3576. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  3577. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  3578. $this->cache->set('ReflectedDatabase', $data, $this->ttl);
  3579. }
  3580. return $database;
  3581. }
  3582. private function loadTable(string $tableName, bool $useCache): ReflectedTable
  3583. {
  3584. $data = $useCache ? $this->cache->get("ReflectedTable($tableName)") : '';
  3585. if ($data != '') {
  3586. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  3587. } else {
  3588. $tableType = $this->database->getType($tableName);
  3589. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  3590. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  3591. $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
  3592. }
  3593. return $table;
  3594. }
  3595. public function refreshTables()
  3596. {
  3597. $this->database = $this->loadDatabase(false);
  3598. }
  3599. public function refreshTable(string $tableName)
  3600. {
  3601. $this->tables[$tableName] = $this->loadTable($tableName, false);
  3602. }
  3603. public function hasTable(string $tableName): bool
  3604. {
  3605. return $this->database->hasTable($tableName);
  3606. }
  3607. public function getType(string $tableName): string
  3608. {
  3609. return $this->database->getType($tableName);
  3610. }
  3611. public function getTable(string $tableName): ReflectedTable
  3612. {
  3613. if (!isset($this->tables[$tableName])) {
  3614. $this->tables[$tableName] = $this->loadTable($tableName, true);
  3615. }
  3616. return $this->tables[$tableName];
  3617. }
  3618. public function getTableNames(): array
  3619. {
  3620. return $this->database->getTableNames();
  3621. }
  3622. public function getDatabaseName(): string
  3623. {
  3624. return $this->database->getName();
  3625. }
  3626. public function removeTable(string $tableName): bool
  3627. {
  3628. unset($this->tables[$tableName]);
  3629. return $this->database->removeTable($tableName);
  3630. }
  3631. }
  3632. }
  3633. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  3634. namespace Tqdev\PhpCrudApi\Controller {
  3635. use Psr\Http\Message\ResponseInterface;
  3636. use Psr\Http\Message\ServerRequestInterface;
  3637. use Tqdev\PhpCrudApi\Cache\Cache;
  3638. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3639. class CacheController
  3640. {
  3641. private $cache;
  3642. private $responder;
  3643. public function __construct(Router $router, Responder $responder, Cache $cache)
  3644. {
  3645. $router->register('GET', '/cache/clear', array($this, 'clear'));
  3646. $this->cache = $cache;
  3647. $this->responder = $responder;
  3648. }
  3649. public function clear(ServerRequestInterface $request): ResponseInterface
  3650. {
  3651. return $this->responder->success($this->cache->clear());
  3652. }
  3653. }
  3654. }
  3655. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  3656. namespace Tqdev\PhpCrudApi\Controller {
  3657. use Psr\Http\Message\ResponseInterface;
  3658. use Psr\Http\Message\ServerRequestInterface;
  3659. use Tqdev\PhpCrudApi\Column\DefinitionService;
  3660. use Tqdev\PhpCrudApi\Column\ReflectionService;
  3661. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3662. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3663. use Tqdev\PhpCrudApi\RequestUtils;
  3664. class ColumnController
  3665. {
  3666. private $responder;
  3667. private $reflection;
  3668. private $definition;
  3669. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  3670. {
  3671. $router->register('GET', '/columns', array($this, 'getDatabase'));
  3672. $router->register('GET', '/columns/*', array($this, 'getTable'));
  3673. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  3674. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  3675. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  3676. $router->register('POST', '/columns', array($this, 'addTable'));
  3677. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  3678. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  3679. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  3680. $this->responder = $responder;
  3681. $this->reflection = $reflection;
  3682. $this->definition = $definition;
  3683. }
  3684. public function getDatabase(ServerRequestInterface $request): ResponseInterface
  3685. {
  3686. $tables = [];
  3687. foreach ($this->reflection->getTableNames() as $table) {
  3688. $tables[] = $this->reflection->getTable($table);
  3689. }
  3690. $database = ['tables' => $tables];
  3691. return $this->responder->success($database);
  3692. }
  3693. public function getTable(ServerRequestInterface $request): ResponseInterface
  3694. {
  3695. $tableName = RequestUtils::getPathSegment($request, 2);
  3696. if (!$this->reflection->hasTable($tableName)) {
  3697. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3698. }
  3699. $table = $this->reflection->getTable($tableName);
  3700. return $this->responder->success($table);
  3701. }
  3702. public function getColumn(ServerRequestInterface $request): ResponseInterface
  3703. {
  3704. $tableName = RequestUtils::getPathSegment($request, 2);
  3705. $columnName = RequestUtils::getPathSegment($request, 3);
  3706. if (!$this->reflection->hasTable($tableName)) {
  3707. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3708. }
  3709. $table = $this->reflection->getTable($tableName);
  3710. if (!$table->hasColumn($columnName)) {
  3711. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3712. }
  3713. $column = $table->getColumn($columnName);
  3714. return $this->responder->success($column);
  3715. }
  3716. public function updateTable(ServerRequestInterface $request): ResponseInterface
  3717. {
  3718. $tableName = RequestUtils::getPathSegment($request, 2);
  3719. if (!$this->reflection->hasTable($tableName)) {
  3720. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3721. }
  3722. $success = $this->definition->updateTable($tableName, $request->getParsedBody());
  3723. if ($success) {
  3724. $this->reflection->refreshTables();
  3725. }
  3726. return $this->responder->success($success);
  3727. }
  3728. public function updateColumn(ServerRequestInterface $request): ResponseInterface
  3729. {
  3730. $tableName = RequestUtils::getPathSegment($request, 2);
  3731. $columnName = RequestUtils::getPathSegment($request, 3);
  3732. if (!$this->reflection->hasTable($tableName)) {
  3733. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3734. }
  3735. $table = $this->reflection->getTable($tableName);
  3736. if (!$table->hasColumn($columnName)) {
  3737. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3738. }
  3739. $success = $this->definition->updateColumn($tableName, $columnName, $request->getParsedBody());
  3740. if ($success) {
  3741. $this->reflection->refreshTable($tableName);
  3742. }
  3743. return $this->responder->success($success);
  3744. }
  3745. public function addTable(ServerRequestInterface $request): ResponseInterface
  3746. {
  3747. $tableName = $request->getParsedBody()->name;
  3748. if ($this->reflection->hasTable($tableName)) {
  3749. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  3750. }
  3751. $success = $this->definition->addTable($request->getParsedBody());
  3752. if ($success) {
  3753. $this->reflection->refreshTables();
  3754. }
  3755. return $this->responder->success($success);
  3756. }
  3757. public function addColumn(ServerRequestInterface $request): ResponseInterface
  3758. {
  3759. $tableName = RequestUtils::getPathSegment($request, 2);
  3760. if (!$this->reflection->hasTable($tableName)) {
  3761. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3762. }
  3763. $columnName = $request->getParsedBody()->name;
  3764. $table = $this->reflection->getTable($tableName);
  3765. if ($table->hasColumn($columnName)) {
  3766. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  3767. }
  3768. $success = $this->definition->addColumn($tableName, $request->getParsedBody());
  3769. if ($success) {
  3770. $this->reflection->refreshTable($tableName);
  3771. }
  3772. return $this->responder->success($success);
  3773. }
  3774. public function removeTable(ServerRequestInterface $request): ResponseInterface
  3775. {
  3776. $tableName = RequestUtils::getPathSegment($request, 2);
  3777. if (!$this->reflection->hasTable($tableName)) {
  3778. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3779. }
  3780. $success = $this->definition->removeTable($tableName);
  3781. if ($success) {
  3782. $this->reflection->refreshTables();
  3783. }
  3784. return $this->responder->success($success);
  3785. }
  3786. public function removeColumn(ServerRequestInterface $request): ResponseInterface
  3787. {
  3788. $tableName = RequestUtils::getPathSegment($request, 2);
  3789. $columnName = RequestUtils::getPathSegment($request, 3);
  3790. if (!$this->reflection->hasTable($tableName)) {
  3791. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3792. }
  3793. $table = $this->reflection->getTable($tableName);
  3794. if (!$table->hasColumn($columnName)) {
  3795. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3796. }
  3797. $success = $this->definition->removeColumn($tableName, $columnName);
  3798. if ($success) {
  3799. $this->reflection->refreshTable($tableName);
  3800. }
  3801. return $this->responder->success($success);
  3802. }
  3803. }
  3804. }
  3805. // file: src/Tqdev/PhpCrudApi/Controller/GeoJsonController.php
  3806. namespace Tqdev\PhpCrudApi\Controller {
  3807. use Psr\Http\Message\ResponseInterface;
  3808. use Psr\Http\Message\ServerRequestInterface;
  3809. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  3810. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3811. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3812. use Tqdev\PhpCrudApi\RequestUtils;
  3813. class GeoJsonController
  3814. {
  3815. private $service;
  3816. private $responder;
  3817. private $geoJsonConverter;
  3818. public function __construct(Router $router, Responder $responder, GeoJsonService $service)
  3819. {
  3820. $router->register('GET', '/geojson/*', array($this, '_list'));
  3821. $router->register('GET', '/geojson/*/*', array($this, 'read'));
  3822. $this->service = $service;
  3823. $this->responder = $responder;
  3824. }
  3825. public function _list(ServerRequestInterface $request): ResponseInterface
  3826. {
  3827. $table = RequestUtils::getPathSegment($request, 2);
  3828. $params = RequestUtils::getParams($request);
  3829. if (!$this->service->hasTable($table)) {
  3830. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3831. }
  3832. return $this->responder->success($this->service->_list($table, $params));
  3833. }
  3834. public function read(ServerRequestInterface $request): ResponseInterface
  3835. {
  3836. $table = RequestUtils::getPathSegment($request, 2);
  3837. if (!$this->service->hasTable($table)) {
  3838. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3839. }
  3840. if ($this->service->getType($table) != 'table') {
  3841. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3842. }
  3843. $id = RequestUtils::getPathSegment($request, 3);
  3844. $params = RequestUtils::getParams($request);
  3845. if (strpos($id, ',') !== false) {
  3846. $ids = explode(',', $id);
  3847. $result = (object) array('type' => 'FeatureCollection', 'features' => array());
  3848. for ($i = 0; $i < count($ids); $i++) {
  3849. array_push($result->features, $this->service->read($table, $ids[$i], $params));
  3850. }
  3851. return $this->responder->success($result);
  3852. } else {
  3853. $response = $this->service->read($table, $id, $params);
  3854. if ($response === null) {
  3855. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  3856. }
  3857. return $this->responder->success($response);
  3858. }
  3859. }
  3860. }
  3861. }
  3862. // file: src/Tqdev/PhpCrudApi/Controller/JsonResponder.php
  3863. namespace Tqdev\PhpCrudApi\Controller {
  3864. use Psr\Http\Message\ResponseInterface;
  3865. use Tqdev\PhpCrudApi\Record\Document\ErrorDocument;
  3866. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3867. use Tqdev\PhpCrudApi\ResponseFactory;
  3868. class JsonResponder implements Responder
  3869. {
  3870. public function error(int $error, string $argument, $details = null): ResponseInterface
  3871. {
  3872. $errorCode = new ErrorCode($error);
  3873. $status = $errorCode->getStatus();
  3874. $document = new ErrorDocument($errorCode, $argument, $details);
  3875. return ResponseFactory::fromObject($status, $document);
  3876. }
  3877. public function success($result): ResponseInterface
  3878. {
  3879. return ResponseFactory::fromObject(ResponseFactory::OK, $result);
  3880. }
  3881. }
  3882. }
  3883. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  3884. namespace Tqdev\PhpCrudApi\Controller {
  3885. use Psr\Http\Message\ResponseInterface;
  3886. use Psr\Http\Message\ServerRequestInterface;
  3887. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3888. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  3889. class OpenApiController
  3890. {
  3891. private $openApi;
  3892. private $responder;
  3893. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  3894. {
  3895. $router->register('GET', '/openapi', array($this, 'openapi'));
  3896. $this->openApi = $openApi;
  3897. $this->responder = $responder;
  3898. }
  3899. public function openapi(ServerRequestInterface $request): ResponseInterface
  3900. {
  3901. return $this->responder->success($this->openApi->get());
  3902. }
  3903. }
  3904. }
  3905. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  3906. namespace Tqdev\PhpCrudApi\Controller {
  3907. use Psr\Http\Message\ResponseInterface;
  3908. use Psr\Http\Message\ServerRequestInterface;
  3909. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3910. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3911. use Tqdev\PhpCrudApi\Record\RecordService;
  3912. use Tqdev\PhpCrudApi\RequestUtils;
  3913. class RecordController
  3914. {
  3915. private $service;
  3916. private $responder;
  3917. public function __construct(Router $router, Responder $responder, RecordService $service)
  3918. {
  3919. $router->register('GET', '/records/*', array($this, '_list'));
  3920. $router->register('POST', '/records/*', array($this, 'create'));
  3921. $router->register('GET', '/records/*/*', array($this, 'read'));
  3922. $router->register('PUT', '/records/*/*', array($this, 'update'));
  3923. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  3924. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  3925. $this->service = $service;
  3926. $this->responder = $responder;
  3927. }
  3928. public function _list(ServerRequestInterface $request): ResponseInterface
  3929. {
  3930. $table = RequestUtils::getPathSegment($request, 2);
  3931. $params = RequestUtils::getParams($request);
  3932. if (!$this->service->hasTable($table)) {
  3933. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3934. }
  3935. return $this->responder->success($this->service->_list($table, $params));
  3936. }
  3937. public function read(ServerRequestInterface $request): ResponseInterface
  3938. {
  3939. $table = RequestUtils::getPathSegment($request, 2);
  3940. if (!$this->service->hasTable($table)) {
  3941. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3942. }
  3943. if ($this->service->getType($table) != 'table') {
  3944. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3945. }
  3946. $id = RequestUtils::getPathSegment($request, 3);
  3947. $params = RequestUtils::getParams($request);
  3948. if (strpos($id, ',') !== false) {
  3949. $ids = explode(',', $id);
  3950. $result = [];
  3951. for ($i = 0; $i < count($ids); $i++) {
  3952. array_push($result, $this->service->read($table, $ids[$i], $params));
  3953. }
  3954. return $this->responder->success($result);
  3955. } else {
  3956. $response = $this->service->read($table, $id, $params);
  3957. if ($response === null) {
  3958. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  3959. }
  3960. return $this->responder->success($response);
  3961. }
  3962. }
  3963. public function create(ServerRequestInterface $request): ResponseInterface
  3964. {
  3965. $table = RequestUtils::getPathSegment($request, 2);
  3966. if (!$this->service->hasTable($table)) {
  3967. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3968. }
  3969. if ($this->service->getType($table) != 'table') {
  3970. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3971. }
  3972. $record = $request->getParsedBody();
  3973. if ($record === null) {
  3974. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  3975. }
  3976. $params = RequestUtils::getParams($request);
  3977. if (is_array($record)) {
  3978. $result = array();
  3979. foreach ($record as $r) {
  3980. $result[] = $this->service->create($table, $r, $params);
  3981. }
  3982. return $this->responder->success($result);
  3983. } else {
  3984. return $this->responder->success($this->service->create($table, $record, $params));
  3985. }
  3986. }
  3987. public function update(ServerRequestInterface $request): ResponseInterface
  3988. {
  3989. $table = RequestUtils::getPathSegment($request, 2);
  3990. if (!$this->service->hasTable($table)) {
  3991. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3992. }
  3993. if ($this->service->getType($table) != 'table') {
  3994. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3995. }
  3996. $id = RequestUtils::getPathSegment($request, 3);
  3997. $params = RequestUtils::getParams($request);
  3998. $record = $request->getParsedBody();
  3999. if ($record === null) {
  4000. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4001. }
  4002. $ids = explode(',', $id);
  4003. if (is_array($record)) {
  4004. if (count($ids) != count($record)) {
  4005. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4006. }
  4007. $result = array();
  4008. for ($i = 0; $i < count($ids); $i++) {
  4009. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  4010. }
  4011. return $this->responder->success($result);
  4012. } else {
  4013. if (count($ids) != 1) {
  4014. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4015. }
  4016. return $this->responder->success($this->service->update($table, $id, $record, $params));
  4017. }
  4018. }
  4019. public function delete(ServerRequestInterface $request): ResponseInterface
  4020. {
  4021. $table = RequestUtils::getPathSegment($request, 2);
  4022. if (!$this->service->hasTable($table)) {
  4023. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4024. }
  4025. if ($this->service->getType($table) != 'table') {
  4026. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4027. }
  4028. $id = RequestUtils::getPathSegment($request, 3);
  4029. $params = RequestUtils::getParams($request);
  4030. $ids = explode(',', $id);
  4031. if (count($ids) > 1) {
  4032. $result = array();
  4033. for ($i = 0; $i < count($ids); $i++) {
  4034. $result[] = $this->service->delete($table, $ids[$i], $params);
  4035. }
  4036. return $this->responder->success($result);
  4037. } else {
  4038. return $this->responder->success($this->service->delete($table, $id, $params));
  4039. }
  4040. }
  4041. public function increment(ServerRequestInterface $request): ResponseInterface
  4042. {
  4043. $table = RequestUtils::getPathSegment($request, 2);
  4044. if (!$this->service->hasTable($table)) {
  4045. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4046. }
  4047. if ($this->service->getType($table) != 'table') {
  4048. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4049. }
  4050. $id = RequestUtils::getPathSegment($request, 3);
  4051. $record = $request->getParsedBody();
  4052. if ($record === null) {
  4053. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4054. }
  4055. $params = RequestUtils::getParams($request);
  4056. $ids = explode(',', $id);
  4057. if (is_array($record)) {
  4058. if (count($ids) != count($record)) {
  4059. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4060. }
  4061. $result = array();
  4062. for ($i = 0; $i < count($ids); $i++) {
  4063. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  4064. }
  4065. return $this->responder->success($result);
  4066. } else {
  4067. if (count($ids) != 1) {
  4068. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4069. }
  4070. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  4071. }
  4072. }
  4073. }
  4074. }
  4075. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  4076. namespace Tqdev\PhpCrudApi\Controller {
  4077. use Psr\Http\Message\ResponseInterface;
  4078. interface Responder
  4079. {
  4080. public function error(int $error, string $argument, $details = null): ResponseInterface;
  4081. public function success($result): ResponseInterface;
  4082. }
  4083. }
  4084. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  4085. namespace Tqdev\PhpCrudApi\Database {
  4086. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4087. class ColumnConverter
  4088. {
  4089. private $driver;
  4090. public function __construct(string $driver)
  4091. {
  4092. $this->driver = $driver;
  4093. }
  4094. public function convertColumnValue(ReflectedColumn $column): string
  4095. {
  4096. if ($column->isBinary()) {
  4097. switch ($this->driver) {
  4098. case 'mysql':
  4099. return "FROM_BASE64(?)";
  4100. case 'pgsql':
  4101. return "decode(?, 'base64')";
  4102. case 'sqlsrv':
  4103. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  4104. }
  4105. }
  4106. if ($column->isGeometry()) {
  4107. switch ($this->driver) {
  4108. case 'mysql':
  4109. case 'pgsql':
  4110. return "ST_GeomFromText(?)";
  4111. case 'sqlsrv':
  4112. return "geometry::STGeomFromText(?,0)";
  4113. }
  4114. }
  4115. return '?';
  4116. }
  4117. public function convertColumnName(ReflectedColumn $column, $value): string
  4118. {
  4119. if ($column->isBinary()) {
  4120. switch ($this->driver) {
  4121. case 'mysql':
  4122. return "TO_BASE64($value) as $value";
  4123. case 'pgsql':
  4124. return "encode($value::bytea, 'base64') as $value";
  4125. case 'sqlsrv':
  4126. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  4127. }
  4128. }
  4129. if ($column->isGeometry()) {
  4130. switch ($this->driver) {
  4131. case 'mysql':
  4132. case 'pgsql':
  4133. return "ST_AsText($value) as $value";
  4134. case 'sqlsrv':
  4135. return "REPLACE($value.STAsText(),' (','(') as $value";
  4136. }
  4137. }
  4138. return $value;
  4139. }
  4140. }
  4141. }
  4142. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  4143. namespace Tqdev\PhpCrudApi\Database {
  4144. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4145. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4146. class ColumnsBuilder
  4147. {
  4148. private $driver;
  4149. private $converter;
  4150. public function __construct(string $driver)
  4151. {
  4152. $this->driver = $driver;
  4153. $this->converter = new ColumnConverter($driver);
  4154. }
  4155. public function getOffsetLimit(int $offset, int $limit): string
  4156. {
  4157. if ($limit < 0 || $offset < 0) {
  4158. return '';
  4159. }
  4160. switch ($this->driver) {
  4161. case 'mysql':return " LIMIT $offset, $limit";
  4162. case 'pgsql':return " LIMIT $limit OFFSET $offset";
  4163. case 'sqlsrv':return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  4164. }
  4165. }
  4166. private function quoteColumnName(ReflectedColumn $column): string
  4167. {
  4168. return '"' . $column->getName() . '"';
  4169. }
  4170. public function getOrderBy(ReflectedTable $table, array $columnOrdering): string
  4171. {
  4172. if (count($columnOrdering) == 0) {
  4173. return '';
  4174. }
  4175. $results = array();
  4176. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  4177. $column = $table->getColumn($columnName);
  4178. $quotedColumnName = $this->quoteColumnName($column);
  4179. $results[] = $quotedColumnName . ' ' . $ordering;
  4180. }
  4181. return ' ORDER BY ' . implode(',', $results);
  4182. }
  4183. public function getSelect(ReflectedTable $table, array $columnNames): string
  4184. {
  4185. $results = array();
  4186. foreach ($columnNames as $columnName) {
  4187. $column = $table->getColumn($columnName);
  4188. $quotedColumnName = $this->quoteColumnName($column);
  4189. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  4190. $results[] = $quotedColumnName;
  4191. }
  4192. return implode(',', $results);
  4193. }
  4194. public function getInsert(ReflectedTable $table, array $columnValues): string
  4195. {
  4196. $columns = array();
  4197. $values = array();
  4198. foreach ($columnValues as $columnName => $columnValue) {
  4199. $column = $table->getColumn($columnName);
  4200. $quotedColumnName = $this->quoteColumnName($column);
  4201. $columns[] = $quotedColumnName;
  4202. $columnValue = $this->converter->convertColumnValue($column);
  4203. $values[] = $columnValue;
  4204. }
  4205. $columnsSql = '(' . implode(',', $columns) . ')';
  4206. $valuesSql = '(' . implode(',', $values) . ')';
  4207. $outputColumn = $this->quoteColumnName($table->getPk());
  4208. switch ($this->driver) {
  4209. case 'mysql':return "$columnsSql VALUES $valuesSql";
  4210. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  4211. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  4212. }
  4213. }
  4214. public function getUpdate(ReflectedTable $table, array $columnValues): string
  4215. {
  4216. $results = array();
  4217. foreach ($columnValues as $columnName => $columnValue) {
  4218. $column = $table->getColumn($columnName);
  4219. $quotedColumnName = $this->quoteColumnName($column);
  4220. $columnValue = $this->converter->convertColumnValue($column);
  4221. $results[] = $quotedColumnName . '=' . $columnValue;
  4222. }
  4223. return implode(',', $results);
  4224. }
  4225. public function getIncrement(ReflectedTable $table, array $columnValues): string
  4226. {
  4227. $results = array();
  4228. foreach ($columnValues as $columnName => $columnValue) {
  4229. if (!is_numeric($columnValue)) {
  4230. continue;
  4231. }
  4232. $column = $table->getColumn($columnName);
  4233. $quotedColumnName = $this->quoteColumnName($column);
  4234. $columnValue = $this->converter->convertColumnValue($column);
  4235. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  4236. }
  4237. return implode(',', $results);
  4238. }
  4239. }
  4240. }
  4241. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  4242. namespace Tqdev\PhpCrudApi\Database {
  4243. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4244. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  4245. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4246. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4247. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  4248. use Tqdev\PhpCrudApi\Record\Condition\NotCondition;
  4249. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  4250. use Tqdev\PhpCrudApi\Record\Condition\SpatialCondition;
  4251. class ConditionsBuilder
  4252. {
  4253. private $driver;
  4254. public function __construct(string $driver)
  4255. {
  4256. $this->driver = $driver;
  4257. }
  4258. private function getConditionSql(Condition $condition, array &$arguments): string
  4259. {
  4260. if ($condition instanceof AndCondition) {
  4261. return $this->getAndConditionSql($condition, $arguments);
  4262. }
  4263. if ($condition instanceof OrCondition) {
  4264. return $this->getOrConditionSql($condition, $arguments);
  4265. }
  4266. if ($condition instanceof NotCondition) {
  4267. return $this->getNotConditionSql($condition, $arguments);
  4268. }
  4269. if ($condition instanceof SpatialCondition) {
  4270. return $this->getSpatialConditionSql($condition, $arguments);
  4271. }
  4272. if ($condition instanceof ColumnCondition) {
  4273. return $this->getColumnConditionSql($condition, $arguments);
  4274. }
  4275. throw new \Exception('Unknown Condition: ' . get_class($condition));
  4276. }
  4277. private function getAndConditionSql(AndCondition $and, array &$arguments): string
  4278. {
  4279. $parts = [];
  4280. foreach ($and->getConditions() as $condition) {
  4281. $parts[] = $this->getConditionSql($condition, $arguments);
  4282. }
  4283. return '(' . implode(' AND ', $parts) . ')';
  4284. }
  4285. private function getOrConditionSql(OrCondition $or, array &$arguments): string
  4286. {
  4287. $parts = [];
  4288. foreach ($or->getConditions() as $condition) {
  4289. $parts[] = $this->getConditionSql($condition, $arguments);
  4290. }
  4291. return '(' . implode(' OR ', $parts) . ')';
  4292. }
  4293. private function getNotConditionSql(NotCondition $not, array &$arguments): string
  4294. {
  4295. $condition = $not->getCondition();
  4296. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  4297. }
  4298. private function quoteColumnName(ReflectedColumn $column): string
  4299. {
  4300. return '"' . $column->getName() . '"';
  4301. }
  4302. private function escapeLikeValue(string $value): string
  4303. {
  4304. return addcslashes($value, '%_');
  4305. }
  4306. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): string
  4307. {
  4308. $column = $this->quoteColumnName($condition->getColumn());
  4309. $operator = $condition->getOperator();
  4310. $value = $condition->getValue();
  4311. switch ($operator) {
  4312. case 'cs':
  4313. $sql = "$column LIKE ?";
  4314. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  4315. break;
  4316. case 'sw':
  4317. $sql = "$column LIKE ?";
  4318. $arguments[] = $this->escapeLikeValue($value) . '%';
  4319. break;
  4320. case 'ew':
  4321. $sql = "$column LIKE ?";
  4322. $arguments[] = '%' . $this->escapeLikeValue($value);
  4323. break;
  4324. case 'eq':
  4325. $sql = "$column = ?";
  4326. $arguments[] = $value;
  4327. break;
  4328. case 'lt':
  4329. $sql = "$column < ?";
  4330. $arguments[] = $value;
  4331. break;
  4332. case 'le':
  4333. $sql = "$column <= ?";
  4334. $arguments[] = $value;
  4335. break;
  4336. case 'ge':
  4337. $sql = "$column >= ?";
  4338. $arguments[] = $value;
  4339. break;
  4340. case 'gt':
  4341. $sql = "$column > ?";
  4342. $arguments[] = $value;
  4343. break;
  4344. case 'bt':
  4345. $parts = explode(',', $value, 2);
  4346. $count = count($parts);
  4347. if ($count == 2) {
  4348. $sql = "($column >= ? AND $column <= ?)";
  4349. $arguments[] = $parts[0];
  4350. $arguments[] = $parts[1];
  4351. } else {
  4352. $sql = "FALSE";
  4353. }
  4354. break;
  4355. case 'in':
  4356. $parts = explode(',', $value);
  4357. $count = count($parts);
  4358. if ($count > 0) {
  4359. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  4360. $sql = "$column IN ($qmarks)";
  4361. for ($i = 0; $i < $count; $i++) {
  4362. $arguments[] = $parts[$i];
  4363. }
  4364. } else {
  4365. $sql = "FALSE";
  4366. }
  4367. break;
  4368. case 'is':
  4369. $sql = "$column IS NULL";
  4370. break;
  4371. }
  4372. return $sql;
  4373. }
  4374. private function getSpatialFunctionName(string $operator): string
  4375. {
  4376. switch ($operator) {
  4377. case 'co':return 'ST_Contains';
  4378. case 'cr':return 'ST_Crosses';
  4379. case 'di':return 'ST_Disjoint';
  4380. case 'eq':return 'ST_Equals';
  4381. case 'in':return 'ST_Intersects';
  4382. case 'ov':return 'ST_Overlaps';
  4383. case 'to':return 'ST_Touches';
  4384. case 'wi':return 'ST_Within';
  4385. case 'ic':return 'ST_IsClosed';
  4386. case 'is':return 'ST_IsSimple';
  4387. case 'iv':return 'ST_IsValid';
  4388. }
  4389. }
  4390. private function hasSpatialArgument(string $operator): bool
  4391. {
  4392. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  4393. }
  4394. private function getSpatialFunctionCall(string $functionName, string $column, bool $hasArgument): string
  4395. {
  4396. switch ($this->driver) {
  4397. case 'mysql':
  4398. case 'pgsql':
  4399. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  4400. return "$functionName($column, $argument)=TRUE";
  4401. case 'sqlsrv':
  4402. $functionName = str_replace('ST_', 'ST', $functionName);
  4403. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  4404. return "$column.$functionName($argument)=1";
  4405. }
  4406. }
  4407. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): string
  4408. {
  4409. $column = $this->quoteColumnName($condition->getColumn());
  4410. $operator = $condition->getOperator();
  4411. $value = $condition->getValue();
  4412. $functionName = $this->getSpatialFunctionName($operator);
  4413. $hasArgument = $this->hasSpatialArgument($operator);
  4414. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  4415. if ($hasArgument) {
  4416. $arguments[] = $value;
  4417. }
  4418. return $sql;
  4419. }
  4420. public function getWhereClause(Condition $condition, array &$arguments): string
  4421. {
  4422. if ($condition instanceof NoCondition) {
  4423. return '';
  4424. }
  4425. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  4426. }
  4427. }
  4428. }
  4429. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  4430. namespace Tqdev\PhpCrudApi\Database {
  4431. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4432. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4433. class DataConverter
  4434. {
  4435. private $driver;
  4436. public function __construct(string $driver)
  4437. {
  4438. $this->driver = $driver;
  4439. }
  4440. private function convertRecordValue($conversion, $value)
  4441. {
  4442. switch ($conversion) {
  4443. case 'boolean':
  4444. return $value ? true : false;
  4445. case 'integer':
  4446. return (int) $value;
  4447. }
  4448. return $value;
  4449. }
  4450. private function getRecordValueConversion(ReflectedColumn $column): string
  4451. {
  4452. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  4453. return 'boolean';
  4454. }
  4455. if ($this->driver == 'sqlsrv' && $column->getType() == 'bigint') {
  4456. return 'integer';
  4457. }
  4458. return 'none';
  4459. }
  4460. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  4461. {
  4462. foreach ($columnNames as $columnName) {
  4463. $column = $table->getColumn($columnName);
  4464. $conversion = $this->getRecordValueConversion($column);
  4465. if ($conversion != 'none') {
  4466. foreach ($records as $i => $record) {
  4467. $value = $records[$i][$columnName];
  4468. if ($value === null) {
  4469. continue;
  4470. }
  4471. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  4472. }
  4473. }
  4474. }
  4475. }
  4476. private function convertInputValue($conversion, $value)
  4477. {
  4478. switch ($conversion) {
  4479. case 'base64url_to_base64':
  4480. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  4481. }
  4482. return $value;
  4483. }
  4484. private function getInputValueConversion(ReflectedColumn $column): string
  4485. {
  4486. if ($column->isBinary()) {
  4487. return 'base64url_to_base64';
  4488. }
  4489. return 'none';
  4490. }
  4491. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  4492. {
  4493. $columnNames = array_keys($columnValues);
  4494. foreach ($columnNames as $columnName) {
  4495. $column = $table->getColumn($columnName);
  4496. $conversion = $this->getInputValueConversion($column);
  4497. if ($conversion != 'none') {
  4498. $value = $columnValues[$columnName];
  4499. if ($value !== null) {
  4500. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  4501. }
  4502. }
  4503. }
  4504. }
  4505. }
  4506. }
  4507. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  4508. namespace Tqdev\PhpCrudApi\Database {
  4509. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4510. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  4511. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4512. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4513. class GenericDB
  4514. {
  4515. private $driver;
  4516. private $database;
  4517. private $pdo;
  4518. private $reflection;
  4519. private $definition;
  4520. private $conditions;
  4521. private $columns;
  4522. private $converter;
  4523. private function getDsn(string $address, int $port, string $database): string
  4524. {
  4525. switch ($this->driver) {
  4526. case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  4527. case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  4528. case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
  4529. }
  4530. }
  4531. private function getCommands(): array
  4532. {
  4533. switch ($this->driver) {
  4534. case 'mysql':return [
  4535. 'SET SESSION sql_warnings=1;',
  4536. 'SET NAMES utf8mb4;',
  4537. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  4538. ];
  4539. case 'pgsql':return [
  4540. "SET NAMES 'UTF8';",
  4541. ];
  4542. case 'sqlsrv':return [
  4543. ];
  4544. }
  4545. }
  4546. private function getOptions(): array
  4547. {
  4548. $options = array(
  4549. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  4550. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  4551. );
  4552. switch ($this->driver) {
  4553. case 'mysql':return $options + [
  4554. \PDO::ATTR_EMULATE_PREPARES => false,
  4555. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  4556. \PDO::ATTR_PERSISTENT => true,
  4557. ];
  4558. case 'pgsql':return $options + [
  4559. \PDO::ATTR_EMULATE_PREPARES => false,
  4560. \PDO::ATTR_PERSISTENT => true,
  4561. ];
  4562. case 'sqlsrv':return $options + [
  4563. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  4564. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  4565. ];
  4566. }
  4567. }
  4568. public function __construct(string $driver, string $address, int $port, string $database, string $username, string $password)
  4569. {
  4570. $this->driver = $driver;
  4571. $this->database = $database;
  4572. $dsn = $this->getDsn($address, $port, $database);
  4573. $options = $this->getOptions();
  4574. $this->pdo = new \PDO($dsn, $username, $password, $options);
  4575. $commands = $this->getCommands();
  4576. foreach ($commands as $command) {
  4577. $this->pdo->query($command);
  4578. }
  4579. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  4580. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  4581. $this->conditions = new ConditionsBuilder($driver);
  4582. $this->columns = new ColumnsBuilder($driver);
  4583. $this->converter = new DataConverter($driver);
  4584. }
  4585. public function pdo(): \PDO
  4586. {
  4587. return $this->pdo;
  4588. }
  4589. public function reflection(): GenericReflection
  4590. {
  4591. return $this->reflection;
  4592. }
  4593. public function definition(): GenericDefinition
  4594. {
  4595. return $this->definition;
  4596. }
  4597. private function addMiddlewareConditions(string $tableName, Condition $condition): Condition
  4598. {
  4599. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  4600. if ($condition1) {
  4601. $condition = $condition->_and($condition1);
  4602. }
  4603. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  4604. if ($condition2) {
  4605. $condition = $condition->_and($condition2);
  4606. }
  4607. return $condition;
  4608. }
  4609. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  4610. {
  4611. $this->converter->convertColumnValues($table, $columnValues);
  4612. $insertColumns = $this->columns->getInsert($table, $columnValues);
  4613. $tableName = $table->getName();
  4614. $pkName = $table->getPk()->getName();
  4615. $parameters = array_values($columnValues);
  4616. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  4617. $stmt = $this->query($sql, $parameters);
  4618. // return primary key value if specified in the input
  4619. if (isset($columnValues[$pkName])) {
  4620. return $columnValues[$pkName];
  4621. }
  4622. // work around missing "returning" or "output" in mysql
  4623. switch ($this->driver) {
  4624. case 'mysql':
  4625. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  4626. break;
  4627. }
  4628. $pkValue = $stmt->fetchColumn(0);
  4629. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  4630. return (int) $pkValue;
  4631. }
  4632. return $pkValue;
  4633. }
  4634. public function selectSingle(ReflectedTable $table, array $columnNames, string $id) /*: ?array*/
  4635. {
  4636. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4637. $tableName = $table->getName();
  4638. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4639. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4640. $parameters = array();
  4641. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4642. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4643. $stmt = $this->query($sql, $parameters);
  4644. $record = $stmt->fetch() ?: null;
  4645. if ($record === null) {
  4646. return null;
  4647. }
  4648. $records = array($record);
  4649. $this->converter->convertRecords($table, $columnNames, $records);
  4650. return $records[0];
  4651. }
  4652. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  4653. {
  4654. if (count($ids) == 0) {
  4655. return [];
  4656. }
  4657. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4658. $tableName = $table->getName();
  4659. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  4660. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4661. $parameters = array();
  4662. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4663. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4664. $stmt = $this->query($sql, $parameters);
  4665. $records = $stmt->fetchAll();
  4666. $this->converter->convertRecords($table, $columnNames, $records);
  4667. return $records;
  4668. }
  4669. public function selectCount(ReflectedTable $table, Condition $condition): int
  4670. {
  4671. $tableName = $table->getName();
  4672. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4673. $parameters = array();
  4674. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4675. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  4676. $stmt = $this->query($sql, $parameters);
  4677. return $stmt->fetchColumn(0);
  4678. }
  4679. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  4680. {
  4681. if ($limit == 0) {
  4682. return array();
  4683. }
  4684. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4685. $tableName = $table->getName();
  4686. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4687. $parameters = array();
  4688. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4689. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  4690. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  4691. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  4692. $stmt = $this->query($sql, $parameters);
  4693. $records = $stmt->fetchAll();
  4694. $this->converter->convertRecords($table, $columnNames, $records);
  4695. return $records;
  4696. }
  4697. public function updateSingle(ReflectedTable $table, array $columnValues, string $id)
  4698. {
  4699. if (count($columnValues) == 0) {
  4700. return 0;
  4701. }
  4702. $this->converter->convertColumnValues($table, $columnValues);
  4703. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  4704. $tableName = $table->getName();
  4705. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4706. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4707. $parameters = array_values($columnValues);
  4708. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4709. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4710. $stmt = $this->query($sql, $parameters);
  4711. return $stmt->rowCount();
  4712. }
  4713. public function deleteSingle(ReflectedTable $table, string $id)
  4714. {
  4715. $tableName = $table->getName();
  4716. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4717. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4718. $parameters = array();
  4719. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4720. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  4721. $stmt = $this->query($sql, $parameters);
  4722. return $stmt->rowCount();
  4723. }
  4724. public function incrementSingle(ReflectedTable $table, array $columnValues, string $id)
  4725. {
  4726. if (count($columnValues) == 0) {
  4727. return 0;
  4728. }
  4729. $this->converter->convertColumnValues($table, $columnValues);
  4730. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  4731. $tableName = $table->getName();
  4732. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4733. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4734. $parameters = array_values($columnValues);
  4735. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4736. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4737. $stmt = $this->query($sql, $parameters);
  4738. return $stmt->rowCount();
  4739. }
  4740. private function query(string $sql, array $parameters): \PDOStatement
  4741. {
  4742. $stmt = $this->pdo->prepare($sql);
  4743. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  4744. $stmt->execute($parameters);
  4745. return $stmt;
  4746. }
  4747. }
  4748. }
  4749. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  4750. namespace Tqdev\PhpCrudApi\Database {
  4751. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4752. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4753. class GenericDefinition
  4754. {
  4755. private $pdo;
  4756. private $driver;
  4757. private $database;
  4758. private $typeConverter;
  4759. private $reflection;
  4760. public function __construct(\PDO $pdo, string $driver, string $database)
  4761. {
  4762. $this->pdo = $pdo;
  4763. $this->driver = $driver;
  4764. $this->database = $database;
  4765. $this->typeConverter = new TypeConverter($driver);
  4766. $this->reflection = new GenericReflection($pdo, $driver, $database);
  4767. }
  4768. private function quote(string $identifier): string
  4769. {
  4770. return '"' . str_replace('"', '', $identifier) . '"';
  4771. }
  4772. public function getColumnType(ReflectedColumn $column, bool $update): string
  4773. {
  4774. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  4775. return 'serial';
  4776. }
  4777. $type = $this->typeConverter->fromJdbc($column->getType());
  4778. if ($column->hasPrecision() && $column->hasScale()) {
  4779. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  4780. } else if ($column->hasPrecision()) {
  4781. $size = '(' . $column->getPrecision() . ')';
  4782. } else if ($column->hasLength()) {
  4783. $size = '(' . $column->getLength() . ')';
  4784. } else {
  4785. $size = '';
  4786. }
  4787. $null = $this->getColumnNullType($column, $update);
  4788. $auto = $this->getColumnAutoIncrement($column, $update);
  4789. return $type . $size . $null . $auto;
  4790. }
  4791. private function getPrimaryKey(string $tableName): string
  4792. {
  4793. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  4794. if (count($pks) == 1) {
  4795. return $pks[0];
  4796. }
  4797. return "";
  4798. }
  4799. private function canAutoIncrement(ReflectedColumn $column): bool
  4800. {
  4801. return in_array($column->getType(), ['integer', 'bigint']);
  4802. }
  4803. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): string
  4804. {
  4805. if (!$this->canAutoIncrement($column)) {
  4806. return '';
  4807. }
  4808. switch ($this->driver) {
  4809. case 'mysql':
  4810. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  4811. case 'pgsql':
  4812. case 'sqlsrv':
  4813. return '';
  4814. }
  4815. }
  4816. private function getColumnNullType(ReflectedColumn $column, bool $update): string
  4817. {
  4818. if ($this->driver == 'pgsql' && $update) {
  4819. return '';
  4820. }
  4821. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  4822. }
  4823. private function getTableRenameSQL(string $tableName, string $newTableName): string
  4824. {
  4825. $p1 = $this->quote($tableName);
  4826. $p2 = $this->quote($newTableName);
  4827. switch ($this->driver) {
  4828. case 'mysql':
  4829. return "RENAME TABLE $p1 TO $p2";
  4830. case 'pgsql':
  4831. return "ALTER TABLE $p1 RENAME TO $p2";
  4832. case 'sqlsrv':
  4833. return "EXEC sp_rename $p1, $p2";
  4834. }
  4835. }
  4836. private function getColumnRenameSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4837. {
  4838. $p1 = $this->quote($tableName);
  4839. $p2 = $this->quote($columnName);
  4840. $p3 = $this->quote($newColumn->getName());
  4841. switch ($this->driver) {
  4842. case 'mysql':
  4843. $p4 = $this->getColumnType($newColumn, true);
  4844. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4845. case 'pgsql':
  4846. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  4847. case 'sqlsrv':
  4848. $p4 = $this->quote($tableName . '.' . $columnName);
  4849. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  4850. }
  4851. }
  4852. private function getColumnRetypeSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4853. {
  4854. $p1 = $this->quote($tableName);
  4855. $p2 = $this->quote($columnName);
  4856. $p3 = $this->quote($newColumn->getName());
  4857. $p4 = $this->getColumnType($newColumn, true);
  4858. switch ($this->driver) {
  4859. case 'mysql':
  4860. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4861. case 'pgsql':
  4862. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  4863. case 'sqlsrv':
  4864. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  4865. }
  4866. }
  4867. private function getSetColumnNullableSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4868. {
  4869. $p1 = $this->quote($tableName);
  4870. $p2 = $this->quote($columnName);
  4871. $p3 = $this->quote($newColumn->getName());
  4872. $p4 = $this->getColumnType($newColumn, true);
  4873. switch ($this->driver) {
  4874. case 'mysql':
  4875. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4876. case 'pgsql':
  4877. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  4878. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  4879. case 'sqlsrv':
  4880. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  4881. }
  4882. }
  4883. private function getSetColumnPkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4884. {
  4885. $p1 = $this->quote($tableName);
  4886. $p2 = $this->quote($columnName);
  4887. $p3 = $this->quote($tableName . '_pkey');
  4888. switch ($this->driver) {
  4889. case 'mysql':
  4890. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  4891. return "ALTER TABLE $p1 $p4";
  4892. case 'pgsql':
  4893. case 'sqlsrv':
  4894. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  4895. return "ALTER TABLE $p1 $p4";
  4896. }
  4897. }
  4898. private function getSetColumnPkSequenceSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4899. {
  4900. $p1 = $this->quote($tableName);
  4901. $p2 = $this->quote($columnName);
  4902. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  4903. switch ($this->driver) {
  4904. case 'mysql':
  4905. return "select 1";
  4906. case 'pgsql':
  4907. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  4908. case 'sqlsrv':
  4909. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  4910. }
  4911. }
  4912. private function getSetColumnPkSequenceStartSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4913. {
  4914. $p1 = $this->quote($tableName);
  4915. $p2 = $this->quote($columnName);
  4916. switch ($this->driver) {
  4917. case 'mysql':
  4918. return "select 1";
  4919. case 'pgsql':
  4920. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  4921. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  4922. case 'sqlsrv':
  4923. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  4924. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  4925. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  4926. }
  4927. }
  4928. private function getSetColumnPkDefaultSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4929. {
  4930. $p1 = $this->quote($tableName);
  4931. $p2 = $this->quote($columnName);
  4932. switch ($this->driver) {
  4933. case 'mysql':
  4934. $p3 = $this->quote($newColumn->getName());
  4935. $p4 = $this->getColumnType($newColumn, true);
  4936. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4937. case 'pgsql':
  4938. if ($newColumn->getPk()) {
  4939. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  4940. $p4 = "SET DEFAULT nextval($p3)";
  4941. } else {
  4942. $p4 = 'DROP DEFAULT';
  4943. }
  4944. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  4945. case 'sqlsrv':
  4946. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  4947. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  4948. if ($newColumn->getPk()) {
  4949. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  4950. } else {
  4951. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  4952. }
  4953. }
  4954. }
  4955. private function getAddColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4956. {
  4957. $p1 = $this->quote($tableName);
  4958. $p2 = $this->quote($columnName);
  4959. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  4960. $p4 = $this->quote($newColumn->getFk());
  4961. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  4962. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  4963. }
  4964. private function getRemoveColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4965. {
  4966. $p1 = $this->quote($tableName);
  4967. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  4968. switch ($this->driver) {
  4969. case 'mysql':
  4970. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  4971. case 'pgsql':
  4972. case 'sqlsrv':
  4973. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  4974. }
  4975. }
  4976. private function getAddTableSQL(ReflectedTable $newTable): string
  4977. {
  4978. $tableName = $newTable->getName();
  4979. $p1 = $this->quote($tableName);
  4980. $fields = [];
  4981. $constraints = [];
  4982. foreach ($newTable->getColumnNames() as $columnName) {
  4983. $pkColumn = $this->getPrimaryKey($tableName);
  4984. $newColumn = $newTable->getColumn($columnName);
  4985. $f1 = $this->quote($columnName);
  4986. $f2 = $this->getColumnType($newColumn, false);
  4987. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  4988. $f4 = $this->quote($newColumn->getFk());
  4989. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  4990. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  4991. $fields[] = "$f1 $f2";
  4992. if ($newColumn->getPk()) {
  4993. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  4994. }
  4995. if ($newColumn->getFk()) {
  4996. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  4997. }
  4998. }
  4999. $p2 = implode(',', array_merge($fields, $constraints));
  5000. return "CREATE TABLE $p1 ($p2);";
  5001. }
  5002. private function getAddColumnSQL(string $tableName, ReflectedColumn $newColumn): string
  5003. {
  5004. $p1 = $this->quote($tableName);
  5005. $p2 = $this->quote($newColumn->getName());
  5006. $p3 = $this->getColumnType($newColumn, false);
  5007. switch ($this->driver) {
  5008. case 'mysql':
  5009. case 'pgsql':
  5010. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  5011. case 'sqlsrv':
  5012. return "ALTER TABLE $p1 ADD $p2 $p3";
  5013. }
  5014. }
  5015. private function getRemoveTableSQL(string $tableName): string
  5016. {
  5017. $p1 = $this->quote($tableName);
  5018. switch ($this->driver) {
  5019. case 'mysql':
  5020. case 'pgsql':
  5021. return "DROP TABLE $p1 CASCADE;";
  5022. case 'sqlsrv':
  5023. return "DROP TABLE $p1;";
  5024. }
  5025. }
  5026. private function getRemoveColumnSQL(string $tableName, string $columnName): string
  5027. {
  5028. $p1 = $this->quote($tableName);
  5029. $p2 = $this->quote($columnName);
  5030. switch ($this->driver) {
  5031. case 'mysql':
  5032. case 'pgsql':
  5033. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  5034. case 'sqlsrv':
  5035. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  5036. }
  5037. }
  5038. public function renameTable(string $tableName, string $newTableName)
  5039. {
  5040. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  5041. return $this->query($sql);
  5042. }
  5043. public function renameColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5044. {
  5045. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  5046. return $this->query($sql);
  5047. }
  5048. public function retypeColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5049. {
  5050. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  5051. return $this->query($sql);
  5052. }
  5053. public function setColumnNullable(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5054. {
  5055. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  5056. return $this->query($sql);
  5057. }
  5058. public function addColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5059. {
  5060. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5061. $this->query($sql);
  5062. if ($this->canAutoIncrement($newColumn)) {
  5063. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5064. $this->query($sql);
  5065. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  5066. $this->query($sql);
  5067. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5068. $this->query($sql);
  5069. }
  5070. return true;
  5071. }
  5072. public function removeColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5073. {
  5074. if ($this->canAutoIncrement($newColumn)) {
  5075. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5076. $this->query($sql);
  5077. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5078. $this->query($sql);
  5079. }
  5080. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5081. $this->query($sql);
  5082. return true;
  5083. }
  5084. public function addColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5085. {
  5086. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5087. return $this->query($sql);
  5088. }
  5089. public function removeColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5090. {
  5091. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5092. return $this->query($sql);
  5093. }
  5094. public function addTable(ReflectedTable $newTable)
  5095. {
  5096. $sql = $this->getAddTableSQL($newTable);
  5097. return $this->query($sql);
  5098. }
  5099. public function addColumn(string $tableName, ReflectedColumn $newColumn)
  5100. {
  5101. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  5102. return $this->query($sql);
  5103. }
  5104. public function removeTable(string $tableName)
  5105. {
  5106. $sql = $this->getRemoveTableSQL($tableName);
  5107. return $this->query($sql);
  5108. }
  5109. public function removeColumn(string $tableName, string $columnName)
  5110. {
  5111. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  5112. return $this->query($sql);
  5113. }
  5114. private function query(string $sql): bool
  5115. {
  5116. $stmt = $this->pdo->prepare($sql);
  5117. //echo "- $sql -- []\n";
  5118. return $stmt->execute();
  5119. }
  5120. }
  5121. }
  5122. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  5123. namespace Tqdev\PhpCrudApi\Database {
  5124. class GenericReflection
  5125. {
  5126. private $pdo;
  5127. private $driver;
  5128. private $database;
  5129. private $typeConverter;
  5130. public function __construct(\PDO $pdo, string $driver, string $database)
  5131. {
  5132. $this->pdo = $pdo;
  5133. $this->driver = $driver;
  5134. $this->database = $database;
  5135. $this->typeConverter = new TypeConverter($driver);
  5136. }
  5137. public function getIgnoredTables(): array
  5138. {
  5139. switch ($this->driver) {
  5140. case 'mysql':return [];
  5141. case 'pgsql':return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  5142. case 'sqlsrv':return [];
  5143. }
  5144. }
  5145. private function getTablesSQL(): string
  5146. {
  5147. switch ($this->driver) {
  5148. case 'mysql':return 'SELECT "TABLE_NAME", "TABLE_TYPE" FROM "INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" IN (\'BASE TABLE\' , \'VIEW\') AND "TABLE_SCHEMA" = ? ORDER BY BINARY "TABLE_NAME"';
  5149. case 'pgsql':return 'SELECT c.relname as "TABLE_NAME", c.relkind as "TABLE_TYPE" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN (\'r\', \'v\') AND n.nspname <> \'pg_catalog\' AND n.nspname <> \'information_schema\' AND n.nspname !~ \'^pg_toast\' AND pg_catalog.pg_table_is_visible(c.oid) AND \'\' <> ? ORDER BY "TABLE_NAME";';
  5150. case 'sqlsrv':return 'SELECT o.name as "TABLE_NAME", o.xtype as "TABLE_TYPE" FROM sysobjects o WHERE o.xtype IN (\'U\', \'V\') ORDER BY "TABLE_NAME"';
  5151. }
  5152. }
  5153. private function getTableColumnsSQL(): string
  5154. {
  5155. switch ($this->driver) {
  5156. case 'mysql':return 'SELECT "COLUMN_NAME", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5157. case 'pgsql':return 'SELECT a.attname AS "COLUMN_NAME", case when a.attnotnull then \'NO\' else \'YES\' end as "IS_NULLABLE", pg_catalog.format_type(a.atttypid, -1) as "DATA_TYPE", case when a.atttypmod < 0 then NULL else a.atttypmod-4 end as "CHARACTER_MAXIMUM_LENGTH", case when a.atttypid != 1700 then NULL else ((a.atttypmod - 4) >> 16) & 65535 end as "NUMERIC_PRECISION", case when a.atttypid != 1700 then NULL else (a.atttypmod - 4) & 65535 end as "NUMERIC_SCALE" FROM pg_attribute a JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND a.attnum > 0 AND NOT a.attisdropped;';
  5158. case 'sqlsrv':return 'SELECT c.name AS "COLUMN_NAME", c.is_nullable AS "IS_NULLABLE", t.Name AS "DATA_TYPE", (c.max_length/2) AS "CHARACTER_MAXIMUM_LENGTH", c.precision AS "NUMERIC_PRECISION", c.scale AS "NUMERIC_SCALE" FROM sys.columns c INNER JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE c.object_id = OBJECT_ID(?) AND \'\' <> ?';
  5159. }
  5160. }
  5161. private function getTablePrimaryKeysSQL(): string
  5162. {
  5163. switch ($this->driver) {
  5164. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5165. case 'pgsql':return 'SELECT a.attname AS "COLUMN_NAME" FROM pg_attribute a JOIN pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum) JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND c.contype = \'p\'';
  5166. case 'sqlsrv':return 'SELECT c.NAME as "COLUMN_NAME" FROM sys.key_constraints kc inner join sys.objects t on t.object_id = kc.parent_object_id INNER JOIN sys.index_columns ic ON kc.parent_object_id = ic.object_id and kc.unique_index_id = ic.index_id INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE kc.type = \'PK\' and t.object_id = OBJECT_ID(?) and \'\' <> ?';
  5167. }
  5168. }
  5169. private function getTableForeignKeysSQL(): string
  5170. {
  5171. switch ($this->driver) {
  5172. case 'mysql':return 'SELECT "COLUMN_NAME", "REFERENCED_TABLE_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "REFERENCED_TABLE_NAME" IS NOT NULL AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5173. case 'pgsql':return 'SELECT a.attname AS "COLUMN_NAME", c.confrelid::regclass::text AS "REFERENCED_TABLE_NAME" FROM pg_attribute a JOIN pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum) JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND c.contype = \'f\'';
  5174. case 'sqlsrv':return 'SELECT COL_NAME(fc.parent_object_id, fc.parent_column_id) AS "COLUMN_NAME", OBJECT_NAME (f.referenced_object_id) AS "REFERENCED_TABLE_NAME" FROM sys.foreign_keys AS f INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id WHERE f.parent_object_id = OBJECT_ID(?) and \'\' <> ?';
  5175. }
  5176. }
  5177. public function getDatabaseName(): string
  5178. {
  5179. return $this->database;
  5180. }
  5181. public function getTables(): array
  5182. {
  5183. $sql = $this->getTablesSQL();
  5184. $results = $this->query($sql, [$this->database]);
  5185. foreach ($results as &$result) {
  5186. switch ($this->driver) {
  5187. case 'mysql':
  5188. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  5189. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  5190. break;
  5191. case 'pgsql':
  5192. $map = ['r' => 'table', 'v' => 'view'];
  5193. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  5194. break;
  5195. case 'sqlsrv':
  5196. $map = ['U' => 'table', 'V' => 'view'];
  5197. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  5198. break;
  5199. }
  5200. }
  5201. return $results;
  5202. }
  5203. public function getTableColumns(string $tableName, string $type): array
  5204. {
  5205. $sql = $this->getTableColumnsSQL();
  5206. $results = $this->query($sql, [$tableName, $this->database]);
  5207. if ($type == 'view') {
  5208. foreach ($results as &$result) {
  5209. $result['IS_NULLABLE'] = false;
  5210. }
  5211. }
  5212. return $results;
  5213. }
  5214. public function getTablePrimaryKeys(string $tableName): array
  5215. {
  5216. $sql = $this->getTablePrimaryKeysSQL();
  5217. $results = $this->query($sql, [$tableName, $this->database]);
  5218. $primaryKeys = [];
  5219. foreach ($results as $result) {
  5220. $primaryKeys[] = $result['COLUMN_NAME'];
  5221. }
  5222. return $primaryKeys;
  5223. }
  5224. public function getTableForeignKeys(string $tableName): array
  5225. {
  5226. $sql = $this->getTableForeignKeysSQL();
  5227. $results = $this->query($sql, [$tableName, $this->database]);
  5228. $foreignKeys = [];
  5229. foreach ($results as $result) {
  5230. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  5231. }
  5232. return $foreignKeys;
  5233. }
  5234. public function toJdbcType(string $type, int $size): string
  5235. {
  5236. return $this->typeConverter->toJdbc($type, $size);
  5237. }
  5238. private function query(string $sql, array $parameters): array
  5239. {
  5240. $stmt = $this->pdo->prepare($sql);
  5241. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  5242. $stmt->execute($parameters);
  5243. return $stmt->fetchAll();
  5244. }
  5245. }
  5246. }
  5247. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  5248. namespace Tqdev\PhpCrudApi\Database {
  5249. class TypeConverter
  5250. {
  5251. private $driver;
  5252. public function __construct(string $driver)
  5253. {
  5254. $this->driver = $driver;
  5255. }
  5256. private $fromJdbc = [
  5257. 'mysql' => [
  5258. 'clob' => 'longtext',
  5259. 'boolean' => 'bit',
  5260. 'blob' => 'longblob',
  5261. 'timestamp' => 'datetime',
  5262. ],
  5263. 'pgsql' => [
  5264. 'clob' => 'text',
  5265. 'blob' => 'bytea',
  5266. ],
  5267. 'sqlsrv' => [
  5268. 'boolean' => 'bit',
  5269. 'varchar' => 'nvarchar',
  5270. 'clob' => 'ntext',
  5271. 'blob' => 'image',
  5272. ],
  5273. ];
  5274. private $toJdbc = [
  5275. 'simplified' => [
  5276. 'char' => 'varchar',
  5277. 'longvarchar' => 'clob',
  5278. 'nchar' => 'varchar',
  5279. 'nvarchar' => 'varchar',
  5280. 'longnvarchar' => 'clob',
  5281. 'binary' => 'varbinary',
  5282. 'longvarbinary' => 'blob',
  5283. 'tinyint' => 'integer',
  5284. 'smallint' => 'integer',
  5285. 'real' => 'float',
  5286. 'numeric' => 'decimal',
  5287. 'time_with_timezone' => 'time',
  5288. 'timestamp_with_timezone' => 'timestamp',
  5289. ],
  5290. 'mysql' => [
  5291. 'bit' => 'boolean',
  5292. 'tinyblob' => 'blob',
  5293. 'mediumblob' => 'blob',
  5294. 'longblob' => 'blob',
  5295. 'tinytext' => 'clob',
  5296. 'mediumtext' => 'clob',
  5297. 'longtext' => 'clob',
  5298. 'text' => 'clob',
  5299. 'mediumint' => 'integer',
  5300. 'int' => 'integer',
  5301. 'polygon' => 'geometry',
  5302. 'point' => 'geometry',
  5303. 'datetime' => 'timestamp',
  5304. 'year' => 'integer',
  5305. 'enum' => 'varchar',
  5306. 'json' => 'clob',
  5307. ],
  5308. 'pgsql' => [
  5309. 'bigserial' => 'bigint',
  5310. 'bit varying' => 'bit',
  5311. 'box' => 'geometry',
  5312. 'bytea' => 'blob',
  5313. 'bpchar' => 'char',
  5314. 'character varying' => 'varchar',
  5315. 'character' => 'char',
  5316. 'cidr' => 'varchar',
  5317. 'circle' => 'geometry',
  5318. 'double precision' => 'double',
  5319. 'inet' => 'integer',
  5320. //'interval [ fields ]'
  5321. 'json' => 'clob',
  5322. 'jsonb' => 'clob',
  5323. 'line' => 'geometry',
  5324. 'lseg' => 'geometry',
  5325. 'macaddr' => 'varchar',
  5326. 'money' => 'decimal',
  5327. 'path' => 'geometry',
  5328. 'point' => 'geometry',
  5329. 'polygon' => 'geometry',
  5330. 'real' => 'float',
  5331. 'serial' => 'integer',
  5332. 'text' => 'clob',
  5333. 'time without time zone' => 'time',
  5334. 'time with time zone' => 'time_with_timezone',
  5335. 'timestamp without time zone' => 'timestamp',
  5336. 'timestamp with time zone' => 'timestamp_with_timezone',
  5337. //'tsquery'=
  5338. //'tsvector'
  5339. //'txid_snapshot'
  5340. 'uuid' => 'char',
  5341. 'xml' => 'clob',
  5342. ],
  5343. // source: https://docs.microsoft.com/en-us/sql/connect/jdbc/using-basic-data-types?view=sql-server-2017
  5344. 'sqlsrv' => [
  5345. 'varbinary(0)' => 'blob',
  5346. 'bit' => 'boolean',
  5347. 'datetime' => 'timestamp',
  5348. 'datetime2' => 'timestamp',
  5349. 'float' => 'double',
  5350. 'image' => 'blob',
  5351. 'int' => 'integer',
  5352. 'money' => 'decimal',
  5353. 'ntext' => 'clob',
  5354. 'smalldatetime' => 'timestamp',
  5355. 'smallmoney' => 'decimal',
  5356. 'text' => 'clob',
  5357. 'timestamp' => 'binary',
  5358. 'udt' => 'varbinary',
  5359. 'uniqueidentifier' => 'char',
  5360. 'xml' => 'clob',
  5361. ],
  5362. ];
  5363. // source: https://docs.oracle.com/javase/9/docs/api/java/sql/Types.html
  5364. private $valid = [
  5365. //'array' => true,
  5366. 'bigint' => true,
  5367. 'binary' => true,
  5368. 'bit' => true,
  5369. 'blob' => true,
  5370. 'boolean' => true,
  5371. 'char' => true,
  5372. 'clob' => true,
  5373. //'datalink' => true,
  5374. 'date' => true,
  5375. 'decimal' => true,
  5376. 'distinct' => true,
  5377. 'double' => true,
  5378. 'float' => true,
  5379. 'integer' => true,
  5380. //'java_object' => true,
  5381. 'longnvarchar' => true,
  5382. 'longvarbinary' => true,
  5383. 'longvarchar' => true,
  5384. 'nchar' => true,
  5385. 'nclob' => true,
  5386. //'null' => true,
  5387. 'numeric' => true,
  5388. 'nvarchar' => true,
  5389. //'other' => true,
  5390. 'real' => true,
  5391. //'ref' => true,
  5392. //'ref_cursor' => true,
  5393. //'rowid' => true,
  5394. 'smallint' => true,
  5395. //'sqlxml' => true,
  5396. //'struct' => true,
  5397. 'time' => true,
  5398. 'time_with_timezone' => true,
  5399. 'timestamp' => true,
  5400. 'timestamp_with_timezone' => true,
  5401. 'tinyint' => true,
  5402. 'varbinary' => true,
  5403. 'varchar' => true,
  5404. // extra:
  5405. 'geometry' => true,
  5406. ];
  5407. public function toJdbc(string $type, int $size): string
  5408. {
  5409. $jdbcType = strtolower($type);
  5410. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  5411. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  5412. }
  5413. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  5414. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  5415. }
  5416. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  5417. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  5418. }
  5419. if (!isset($this->valid[$jdbcType])) {
  5420. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  5421. }
  5422. return $jdbcType;
  5423. }
  5424. public function fromJdbc(string $type): string
  5425. {
  5426. $jdbcType = strtolower($type);
  5427. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  5428. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  5429. }
  5430. return $jdbcType;
  5431. }
  5432. }
  5433. }
  5434. // file: src/Tqdev/PhpCrudApi/GeoJson/Feature.php
  5435. namespace Tqdev\PhpCrudApi\GeoJson {
  5436. class Feature implements \JsonSerializable
  5437. {
  5438. private $id;
  5439. private $properties;
  5440. private $geometry;
  5441. public function __construct($id, array $properties, /*?Geometry*/ $geometry)
  5442. {
  5443. $this->id = $id;
  5444. $this->properties = $properties;
  5445. $this->geometry = $geometry;
  5446. }
  5447. public function serialize()
  5448. {
  5449. return [
  5450. 'type' => 'Feature',
  5451. 'id' => $this->id,
  5452. 'properties' => $this->properties,
  5453. 'geometry' => $this->geometry,
  5454. ];
  5455. }
  5456. public function jsonSerialize()
  5457. {
  5458. return $this->serialize();
  5459. }
  5460. }
  5461. }
  5462. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  5463. namespace Tqdev\PhpCrudApi\GeoJson {
  5464. class FeatureCollection implements \JsonSerializable
  5465. {
  5466. private $features;
  5467. private $results;
  5468. public function __construct(array $features, int $results)
  5469. {
  5470. $this->features = $features;
  5471. $this->results = $results;
  5472. }
  5473. public function serialize()
  5474. {
  5475. return [
  5476. 'type' => 'FeatureCollection',
  5477. 'features' => $this->features,
  5478. 'results' => $this->results,
  5479. ];
  5480. }
  5481. public function jsonSerialize()
  5482. {
  5483. return array_filter($this->serialize(), function ($v) {
  5484. return $v !== 0;
  5485. });
  5486. }
  5487. }
  5488. }
  5489. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  5490. namespace Tqdev\PhpCrudApi\GeoJson {
  5491. use Tqdev\PhpCrudApi\Column\ReflectionService;
  5492. use Tqdev\PhpCrudApi\GeoJson\FeatureCollection;
  5493. use Tqdev\PhpCrudApi\Record\RecordService;
  5494. class GeoJsonService
  5495. {
  5496. private $reflection;
  5497. private $records;
  5498. public function __construct(ReflectionService $reflection, RecordService $records)
  5499. {
  5500. $this->reflection = $reflection;
  5501. $this->records = $records;
  5502. }
  5503. public function hasTable(string $table): bool
  5504. {
  5505. return $this->reflection->hasTable($table);
  5506. }
  5507. public function getType(string $table): string
  5508. {
  5509. return $this->reflection->getType($table);
  5510. }
  5511. private function getGeometryColumnName(string $tableName, array &$params): string
  5512. {
  5513. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  5514. $table = $this->reflection->getTable($tableName);
  5515. $geometryColumnName = '';
  5516. foreach ($table->getColumnNames() as $columnName) {
  5517. if ($geometryParam && $geometryParam != $columnName) {
  5518. continue;
  5519. }
  5520. $column = $table->getColumn($columnName);
  5521. if ($column->isGeometry()) {
  5522. $geometryColumnName = $columnName;
  5523. break;
  5524. }
  5525. }
  5526. if ($geometryColumnName) {
  5527. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  5528. }
  5529. return $geometryColumnName;
  5530. }
  5531. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  5532. {
  5533. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  5534. if ($boundingBox) {
  5535. $c = explode(',', $boundingBox);
  5536. if (!isset($params['filter'])) {
  5537. $params['filter'] = array();
  5538. }
  5539. $params['filter'][] = "$geometryColumnName,sin,POLYGON(($c[0] $c[1],$c[2] $c[1],$c[2] $c[3],$c[0] $c[3],$c[0] $c[1]))";
  5540. }
  5541. $tile = isset($params['tile']) ? $params['tile'][0] : '';
  5542. if ($tile) {
  5543. $zxy = explode(',', $tile);
  5544. if (count($zxy) == 3) {
  5545. list($z, $x, $y) = $zxy;
  5546. $c = array();
  5547. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x, $y));
  5548. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x + 1, $y + 1));
  5549. $params['filter'][] = "$geometryColumnName,sin,POLYGON(($c[0] $c[1],$c[2] $c[1],$c[2] $c[3],$c[0] $c[3],$c[0] $c[1]))";
  5550. }
  5551. }
  5552. }
  5553. private function convertTileToLatLonOfUpperLeftCorner($z, $x, $y): array
  5554. {
  5555. $n = pow(2, $z);
  5556. $lon = $x / $n * 360.0 - 180.0;
  5557. $lat = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n))));
  5558. return [$lon, $lat];
  5559. }
  5560. private function convertRecordToFeature( /*object*/$record, string $primaryKeyColumnName, string $geometryColumnName)
  5561. {
  5562. $id = null;
  5563. if ($primaryKeyColumnName) {
  5564. $id = $record[$primaryKeyColumnName];
  5565. }
  5566. $geometry = null;
  5567. if (isset($record[$geometryColumnName])) {
  5568. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  5569. }
  5570. $properties = array_diff_key($record, [$primaryKeyColumnName => true, $geometryColumnName => true]);
  5571. return new Feature($id, $properties, $geometry);
  5572. }
  5573. private function getPrimaryKeyColumnName(string $tableName, array &$params): string
  5574. {
  5575. $primaryKeyColumn = $this->reflection->getTable($tableName)->getPk();
  5576. if (!$primaryKeyColumn) {
  5577. return '';
  5578. }
  5579. $primaryKeyColumnName = $primaryKeyColumn->getName();
  5580. $params['mandatory'][] = $tableName . "." . $primaryKeyColumnName;
  5581. return $primaryKeyColumnName;
  5582. }
  5583. public function _list(string $tableName, array $params): FeatureCollection
  5584. {
  5585. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5586. $this->setBoudingBoxFilter($geometryColumnName, $params);
  5587. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5588. $records = $this->records->_list($tableName, $params);
  5589. $features = array();
  5590. foreach ($records->getRecords() as $record) {
  5591. $features[] = $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5592. }
  5593. return new FeatureCollection($features, $records->getResults());
  5594. }
  5595. public function read(string $tableName, string $id, array $params): Feature
  5596. {
  5597. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5598. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5599. $record = $this->records->read($tableName, $id, $params);
  5600. return $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5601. }
  5602. }
  5603. }
  5604. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  5605. namespace Tqdev\PhpCrudApi\GeoJson {
  5606. class Geometry implements \JsonSerializable
  5607. {
  5608. private $type;
  5609. private $geometry;
  5610. public static $types = [
  5611. "Point",
  5612. "MultiPoint",
  5613. "LineString",
  5614. "MultiLineString",
  5615. "Polygon",
  5616. "MultiPolygon",
  5617. //"GeometryCollection",
  5618. ];
  5619. public function __construct(string $type, array $coordinates)
  5620. {
  5621. $this->type = $type;
  5622. $this->coordinates = $coordinates;
  5623. }
  5624. public static function fromWkt(string $wkt): Geometry
  5625. {
  5626. $bracket = strpos($wkt, '(');
  5627. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  5628. $supported = false;
  5629. foreach (Geometry::$types as $typeName) {
  5630. if (strtoupper($typeName) == $type) {
  5631. $type = $typeName;
  5632. $supported = true;
  5633. }
  5634. }
  5635. if (!$supported) {
  5636. throw new \Exception('Geometry type not supported: ' . $type);
  5637. }
  5638. $coordinates = substr($wkt, $bracket);
  5639. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  5640. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  5641. }
  5642. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  5643. $json = $coordinates;
  5644. $coordinates = json_decode($coordinates);
  5645. if (!$coordinates) {
  5646. throw new \Exception('Could not decode WKT: ' . $wkt);
  5647. }
  5648. return new Geometry($type, $coordinates);
  5649. }
  5650. public function serialize()
  5651. {
  5652. return [
  5653. 'type' => $this->type,
  5654. 'coordinates' => $this->coordinates,
  5655. ];
  5656. }
  5657. public function jsonSerialize()
  5658. {
  5659. return $this->serialize();
  5660. }
  5661. }
  5662. }
  5663. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  5664. namespace Tqdev\PhpCrudApi\Middleware\Base {
  5665. use Psr\Http\Server\MiddlewareInterface;
  5666. use Tqdev\PhpCrudApi\Controller\Responder;
  5667. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  5668. abstract class Middleware implements MiddlewareInterface
  5669. {
  5670. protected $next;
  5671. protected $responder;
  5672. private $properties;
  5673. public function __construct(Router $router, Responder $responder, array $properties)
  5674. {
  5675. $router->load($this);
  5676. $this->responder = $responder;
  5677. $this->properties = $properties;
  5678. }
  5679. protected function getArrayProperty(string $key, string $default): array
  5680. {
  5681. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  5682. }
  5683. protected function getProperty(string $key, $default)
  5684. {
  5685. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  5686. }
  5687. }
  5688. }
  5689. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  5690. namespace Tqdev\PhpCrudApi\Middleware\Communication {
  5691. class VariableStore
  5692. {
  5693. static $values = array();
  5694. public static function get(string $key)
  5695. {
  5696. if (isset(self::$values[$key])) {
  5697. return self::$values[$key];
  5698. }
  5699. return null;
  5700. }
  5701. public static function set(string $key, /* object */ $value)
  5702. {
  5703. self::$values[$key] = $value;
  5704. }
  5705. }
  5706. }
  5707. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  5708. namespace Tqdev\PhpCrudApi\Middleware\Router {
  5709. use Psr\Http\Message\ResponseInterface;
  5710. use Psr\Http\Message\ServerRequestInterface;
  5711. use Psr\Http\Server\RequestHandlerInterface;
  5712. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5713. interface Router extends RequestHandlerInterface
  5714. {
  5715. public function register(string $method, string $path, array $handler);
  5716. public function load(Middleware $middleware);
  5717. public function route(ServerRequestInterface $request): ResponseInterface;
  5718. }
  5719. }
  5720. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  5721. namespace Tqdev\PhpCrudApi\Middleware\Router {
  5722. use Psr\Http\Message\ResponseInterface;
  5723. use Psr\Http\Message\ServerRequestInterface;
  5724. use Tqdev\PhpCrudApi\Cache\Cache;
  5725. use Tqdev\PhpCrudApi\Controller\Responder;
  5726. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5727. use Tqdev\PhpCrudApi\Record\ErrorCode;
  5728. use Tqdev\PhpCrudApi\Record\PathTree;
  5729. use Tqdev\PhpCrudApi\RequestUtils;
  5730. use Tqdev\PhpCrudApi\ResponseUtils;
  5731. class SimpleRouter implements Router
  5732. {
  5733. private $basePath;
  5734. private $responder;
  5735. private $cache;
  5736. private $ttl;
  5737. private $debug;
  5738. private $registration;
  5739. private $routes;
  5740. private $routeHandlers;
  5741. private $middlewares;
  5742. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  5743. {
  5744. $this->basePath = $this->detectBasePath($basePath);
  5745. $this->responder = $responder;
  5746. $this->cache = $cache;
  5747. $this->ttl = $ttl;
  5748. $this->debug = $debug;
  5749. $this->registration = true;
  5750. $this->routes = $this->loadPathTree();
  5751. $this->routeHandlers = [];
  5752. $this->middlewares = array();
  5753. }
  5754. private function detectBasePath(string $basePath): string
  5755. {
  5756. if ($basePath) {
  5757. return $basePath;
  5758. }
  5759. if (isset($_SERVER['REQUEST_URI'])) {
  5760. $fullPath = urldecode(explode('?', $_SERVER['REQUEST_URI'])[0]);
  5761. if (isset($_SERVER['PATH_INFO'])) {
  5762. $path = $_SERVER['PATH_INFO'];
  5763. if (substr($fullPath, -1 * strlen($path)) == $path) {
  5764. return substr($fullPath, 0, -1 * strlen($path));
  5765. }
  5766. }
  5767. return $fullPath;
  5768. }
  5769. return '/';
  5770. }
  5771. private function loadPathTree(): PathTree
  5772. {
  5773. $data = $this->cache->get('PathTree');
  5774. if ($data != '') {
  5775. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  5776. $this->registration = false;
  5777. } else {
  5778. $tree = new PathTree();
  5779. }
  5780. return $tree;
  5781. }
  5782. public function register(string $method, string $path, array $handler)
  5783. {
  5784. $routeNumber = count($this->routeHandlers);
  5785. $this->routeHandlers[$routeNumber] = $handler;
  5786. if ($this->registration) {
  5787. $path = trim($path, '/');
  5788. $parts = array();
  5789. if ($path) {
  5790. $parts = explode('/', $path);
  5791. }
  5792. array_unshift($parts, $method);
  5793. $this->routes->put($parts, $routeNumber);
  5794. }
  5795. }
  5796. public function load(Middleware $middleware) /*: void*/
  5797. {
  5798. array_push($this->middlewares, $middleware);
  5799. }
  5800. public function route(ServerRequestInterface $request): ResponseInterface
  5801. {
  5802. if ($this->registration) {
  5803. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  5804. $this->cache->set('PathTree', $data, $this->ttl);
  5805. }
  5806. return $this->handle($request);
  5807. }
  5808. private function getRouteNumbers(ServerRequestInterface $request): array
  5809. {
  5810. $method = strtoupper($request->getMethod());
  5811. $path = array();
  5812. $segment = $method;
  5813. for ($i = 1; $segment; $i++) {
  5814. array_push($path, $segment);
  5815. $segment = RequestUtils::getPathSegment($request, $i);
  5816. }
  5817. return $this->routes->match($path);
  5818. }
  5819. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  5820. {
  5821. $path = $request->getUri()->getPath();
  5822. $basePath = rtrim($this->basePath, '/');
  5823. if (substr($path, 0, strlen($basePath)) == $basePath) {
  5824. $path = substr($path, strlen($basePath));
  5825. $request = $request->withUri($request->getUri()->withPath($path));
  5826. }
  5827. return $request;
  5828. }
  5829. public function getBasePath(): string
  5830. {
  5831. return $this->basePath;
  5832. }
  5833. public function handle(ServerRequestInterface $request): ResponseInterface
  5834. {
  5835. $request = $this->removeBasePath($request);
  5836. if (count($this->middlewares)) {
  5837. $handler = array_pop($this->middlewares);
  5838. return $handler->process($request, $this);
  5839. }
  5840. $routeNumbers = $this->getRouteNumbers($request);
  5841. if (count($routeNumbers) == 0) {
  5842. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  5843. }
  5844. try {
  5845. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  5846. } catch (\PDOException $e) {
  5847. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  5848. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  5849. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  5850. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  5851. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  5852. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  5853. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  5854. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  5855. } else {
  5856. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  5857. }
  5858. if ($this->debug) {
  5859. $response = ResponseUtils::addExceptionHeaders($response, $e);
  5860. }
  5861. }
  5862. return $response;
  5863. }
  5864. }
  5865. }
  5866. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  5867. namespace Tqdev\PhpCrudApi\Middleware {
  5868. use Psr\Http\Message\ResponseInterface;
  5869. use Psr\Http\Message\ServerRequestInterface;
  5870. use Psr\Http\Server\RequestHandlerInterface;
  5871. use Tqdev\PhpCrudApi\Controller\Responder;
  5872. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5873. use Tqdev\PhpCrudApi\Record\ErrorCode;
  5874. use Tqdev\PhpCrudApi\RequestUtils;
  5875. class AjaxOnlyMiddleware extends Middleware
  5876. {
  5877. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  5878. {
  5879. $method = $request->getMethod();
  5880. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  5881. if (!in_array($method, $excludeMethods)) {
  5882. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  5883. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  5884. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  5885. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  5886. }
  5887. }
  5888. return $next->handle($request);
  5889. }
  5890. }
  5891. }
  5892. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  5893. namespace Tqdev\PhpCrudApi\Middleware {
  5894. use Psr\Http\Message\ResponseInterface;
  5895. use Psr\Http\Message\ServerRequestInterface;
  5896. use Psr\Http\Server\RequestHandlerInterface;
  5897. use Tqdev\PhpCrudApi\Column\ReflectionService;
  5898. use Tqdev\PhpCrudApi\Controller\Responder;
  5899. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5900. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  5901. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  5902. use Tqdev\PhpCrudApi\Record\FilterInfo;
  5903. use Tqdev\PhpCrudApi\RequestUtils;
  5904. class AuthorizationMiddleware extends Middleware
  5905. {
  5906. private $reflection;
  5907. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  5908. {
  5909. parent::__construct($router, $responder, $properties);
  5910. $this->reflection = $reflection;
  5911. }
  5912. private function handleColumns(string $operation, string $tableName) /*: void*/
  5913. {
  5914. $columnHandler = $this->getProperty('columnHandler', '');
  5915. if ($columnHandler) {
  5916. $table = $this->reflection->getTable($tableName);
  5917. foreach ($table->getColumnNames() as $columnName) {
  5918. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  5919. if (!$allowed) {
  5920. $table->removeColumn($columnName);
  5921. }
  5922. }
  5923. }
  5924. }
  5925. private function handleTable(string $operation, string $tableName) /*: void*/
  5926. {
  5927. if (!$this->reflection->hasTable($tableName)) {
  5928. return;
  5929. }
  5930. $allowed = true;
  5931. $tableHandler = $this->getProperty('tableHandler', '');
  5932. if ($tableHandler) {
  5933. $allowed = call_user_func($tableHandler, $operation, $tableName);
  5934. }
  5935. if (!$allowed) {
  5936. $this->reflection->removeTable($tableName);
  5937. } else {
  5938. $this->handleColumns($operation, $tableName);
  5939. }
  5940. }
  5941. private function handleRecords(string $operation, string $tableName) /*: void*/
  5942. {
  5943. if (!$this->reflection->hasTable($tableName)) {
  5944. return;
  5945. }
  5946. $recordHandler = $this->getProperty('recordHandler', '');
  5947. if ($recordHandler) {
  5948. $query = call_user_func($recordHandler, $operation, $tableName);
  5949. $filters = new FilterInfo();
  5950. $table = $this->reflection->getTable($tableName);
  5951. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  5952. parse_str($query, $params);
  5953. $condition = $filters->getCombinedConditions($table, $params);
  5954. VariableStore::set("authorization.conditions.$tableName", $condition);
  5955. }
  5956. }
  5957. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  5958. {
  5959. $path = RequestUtils::getPathSegment($request, 1);
  5960. $operation = RequestUtils::getOperation($request);
  5961. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  5962. foreach ($tableNames as $tableName) {
  5963. $this->handleTable($operation, $tableName);
  5964. if ($path == 'records') {
  5965. $this->handleRecords($operation, $tableName);
  5966. }
  5967. }
  5968. if ($path == 'openapi') {
  5969. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  5970. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  5971. }
  5972. return $next->handle($request);
  5973. }
  5974. }
  5975. }
  5976. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  5977. namespace Tqdev\PhpCrudApi\Middleware {
  5978. use Psr\Http\Message\ResponseInterface;
  5979. use Psr\Http\Message\ServerRequestInterface;
  5980. use Psr\Http\Server\RequestHandlerInterface;
  5981. use Tqdev\PhpCrudApi\Controller\Responder;
  5982. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5983. use Tqdev\PhpCrudApi\Record\ErrorCode;
  5984. use Tqdev\PhpCrudApi\RequestUtils;
  5985. class BasicAuthMiddleware extends Middleware
  5986. {
  5987. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  5988. {
  5989. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  5990. if ($hash && password_verify($password, $hash)) {
  5991. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  5992. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  5993. }
  5994. return true;
  5995. }
  5996. return false;
  5997. }
  5998. private function getValidUsername(string $username, string $password, string $passwordFile): string
  5999. {
  6000. $passwords = $this->readPasswords($passwordFile);
  6001. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  6002. $this->writePasswords($passwordFile, $passwords);
  6003. return $valid ? $username : '';
  6004. }
  6005. private function readPasswords(string $passwordFile): array
  6006. {
  6007. $passwords = [];
  6008. $passwordLines = file($passwordFile);
  6009. foreach ($passwordLines as $passwordLine) {
  6010. if (strpos($passwordLine, ':') !== false) {
  6011. list($username, $hash) = explode(':', trim($passwordLine), 2);
  6012. if (strlen($hash) > 0 && $hash[0] != '$') {
  6013. $hash = password_hash($hash, PASSWORD_DEFAULT);
  6014. }
  6015. $passwords[$username] = $hash;
  6016. }
  6017. }
  6018. return $passwords;
  6019. }
  6020. private function writePasswords(string $passwordFile, array $passwords): bool
  6021. {
  6022. $success = false;
  6023. $passwordFileContents = '';
  6024. foreach ($passwords as $username => $hash) {
  6025. $passwordFileContents .= "$username:$hash\n";
  6026. }
  6027. if (file_get_contents($passwordFile) != $passwordFileContents) {
  6028. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  6029. }
  6030. return $success;
  6031. }
  6032. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  6033. {
  6034. if (isset($_SERVER['PHP_AUTH_USER'])) {
  6035. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  6036. }
  6037. $header = RequestUtils::getHeader($request, 'Authorization');
  6038. $parts = explode(' ', trim($header), 2);
  6039. if (count($parts) != 2) {
  6040. return '';
  6041. }
  6042. if ($parts[0] != 'Basic') {
  6043. return '';
  6044. }
  6045. return base64_decode(strtr($parts[1], '-_', '+/'));
  6046. }
  6047. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6048. {
  6049. if (session_status() == PHP_SESSION_NONE) {
  6050. if (!headers_sent()) {
  6051. session_start();
  6052. }
  6053. }
  6054. $credentials = $this->getAuthorizationCredentials($request);
  6055. if ($credentials) {
  6056. list($username, $password) = array('', '');
  6057. if (strpos($credentials, ':') !== false) {
  6058. list($username, $password) = explode(':', $credentials, 2);
  6059. }
  6060. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  6061. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  6062. $_SESSION['username'] = $validUser;
  6063. if (!$validUser) {
  6064. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6065. }
  6066. if (!headers_sent()) {
  6067. session_regenerate_id();
  6068. }
  6069. }
  6070. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  6071. $authenticationMode = $this->getProperty('mode', 'required');
  6072. if ($authenticationMode == 'required') {
  6073. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6074. $realm = $this->getProperty('realm', 'Username and password required');
  6075. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  6076. return $response;
  6077. }
  6078. }
  6079. return $next->handle($request);
  6080. }
  6081. }
  6082. }
  6083. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  6084. namespace Tqdev\PhpCrudApi\Middleware {
  6085. use Psr\Http\Message\ResponseInterface;
  6086. use Psr\Http\Message\ServerRequestInterface;
  6087. use Psr\Http\Server\RequestHandlerInterface;
  6088. use Tqdev\PhpCrudApi\Controller\Responder;
  6089. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6090. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6091. use Tqdev\PhpCrudApi\ResponseFactory;
  6092. class CorsMiddleware extends Middleware
  6093. {
  6094. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  6095. {
  6096. $found = false;
  6097. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  6098. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  6099. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  6100. if (preg_match($regex, $origin)) {
  6101. $found = true;
  6102. break;
  6103. }
  6104. }
  6105. return $found;
  6106. }
  6107. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6108. {
  6109. $method = $request->getMethod();
  6110. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  6111. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  6112. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  6113. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  6114. } elseif ($method == 'OPTIONS') {
  6115. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  6116. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  6117. if ($allowHeaders) {
  6118. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  6119. }
  6120. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  6121. if ($allowMethods) {
  6122. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  6123. }
  6124. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6125. if ($allowCredentials) {
  6126. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6127. }
  6128. $maxAge = $this->getProperty('maxAge', '1728000');
  6129. if ($maxAge) {
  6130. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  6131. }
  6132. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  6133. if ($exposeHeaders) {
  6134. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  6135. }
  6136. } else {
  6137. $response = $next->handle($request);
  6138. }
  6139. if ($origin) {
  6140. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6141. if ($allowCredentials) {
  6142. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6143. }
  6144. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  6145. }
  6146. return $response;
  6147. }
  6148. }
  6149. }
  6150. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  6151. namespace Tqdev\PhpCrudApi\Middleware {
  6152. use Psr\Http\Message\ResponseInterface;
  6153. use Psr\Http\Message\ServerRequestInterface;
  6154. use Psr\Http\Server\RequestHandlerInterface;
  6155. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6156. use Tqdev\PhpCrudApi\Controller\Responder;
  6157. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6158. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6159. use Tqdev\PhpCrudApi\RequestUtils;
  6160. class CustomizationMiddleware extends Middleware
  6161. {
  6162. private $reflection;
  6163. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6164. {
  6165. parent::__construct($router, $responder, $properties);
  6166. $this->reflection = $reflection;
  6167. }
  6168. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6169. {
  6170. $operation = RequestUtils::getOperation($request);
  6171. $tableName = RequestUtils::getPathSegment($request, 2);
  6172. $beforeHandler = $this->getProperty('beforeHandler', '');
  6173. $environment = (object) array();
  6174. if ($beforeHandler !== '') {
  6175. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  6176. $request = $result ?: $request;
  6177. }
  6178. $response = $next->handle($request);
  6179. $afterHandler = $this->getProperty('afterHandler', '');
  6180. if ($afterHandler !== '') {
  6181. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  6182. $response = $result ?: $response;
  6183. }
  6184. return $response;
  6185. }
  6186. }
  6187. }
  6188. // file: src/Tqdev/PhpCrudApi/Middleware/DbAuthMiddleware.php
  6189. namespace Tqdev\PhpCrudApi\Middleware {
  6190. use Psr\Http\Message\ResponseInterface;
  6191. use Psr\Http\Message\ServerRequestInterface;
  6192. use Psr\Http\Server\RequestHandlerInterface;
  6193. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6194. use Tqdev\PhpCrudApi\Controller\Responder;
  6195. use Tqdev\PhpCrudApi\Database\GenericDB;
  6196. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6197. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6198. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  6199. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6200. use Tqdev\PhpCrudApi\Record\OrderingInfo;
  6201. use Tqdev\PhpCrudApi\RequestUtils;
  6202. class DbAuthMiddleware extends Middleware
  6203. {
  6204. private $reflection;
  6205. private $db;
  6206. private $ordering;
  6207. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  6208. {
  6209. parent::__construct($router, $responder, $properties);
  6210. $this->reflection = $reflection;
  6211. $this->db = $db;
  6212. $this->ordering = new OrderingInfo();
  6213. }
  6214. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6215. {
  6216. if (session_status() == PHP_SESSION_NONE) {
  6217. if (!headers_sent()) {
  6218. session_start();
  6219. }
  6220. }
  6221. $path = RequestUtils::getPathSegment($request, 1);
  6222. $method = $request->getMethod();
  6223. if ($method == 'POST' && $path == 'login') {
  6224. $body = $request->getParsedBody();
  6225. $username = isset($body->username) ? $body->username : '';
  6226. $password = isset($body->password) ? $body->password : '';
  6227. $tableName = $this->getProperty('usersTable', 'users');
  6228. $table = $this->reflection->getTable($tableName);
  6229. $usernameColumnName = $this->getProperty('usernameColumn', 'username');
  6230. $usernameColumn = $table->getColumn($usernameColumnName);
  6231. $passwordColumnName = $this->getProperty('passwordColumn', 'password');
  6232. $passwordColumn = $table->getColumn($passwordColumnName);
  6233. $condition = new ColumnCondition($usernameColumn, 'eq', $username);
  6234. $returnedColumns = $this->getProperty('returnedColumns', '');
  6235. if (!$returnedColumns) {
  6236. $columnNames = $table->getColumnNames();
  6237. } else {
  6238. $columnNames = array_map('trim', explode(',', $returnedColumns));
  6239. $columnNames[] = $passwordColumnName;
  6240. }
  6241. $columnOrdering = $this->ordering->getDefaultColumnOrdering($table);
  6242. $users = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, 0, 1);
  6243. foreach ($users as $user) {
  6244. if (password_verify($password, $user[$passwordColumnName]) == 1) {
  6245. if (!headers_sent()) {
  6246. session_regenerate_id(true);
  6247. }
  6248. unset($user[$passwordColumnName]);
  6249. $_SESSION['user'] = $user;
  6250. return $this->responder->success($user);
  6251. }
  6252. }
  6253. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6254. }
  6255. if ($method == 'POST' && $path == 'logout') {
  6256. if (isset($_SESSION['user'])) {
  6257. $user = $_SESSION['user'];
  6258. unset($_SESSION['user']);
  6259. if (session_status() != PHP_SESSION_NONE) {
  6260. session_destroy();
  6261. }
  6262. return $this->responder->success($user);
  6263. }
  6264. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6265. }
  6266. if (!isset($_SESSION['user']) || !$_SESSION['user']) {
  6267. $authenticationMode = $this->getProperty('mode', 'required');
  6268. if ($authenticationMode == 'required') {
  6269. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6270. }
  6271. }
  6272. return $next->handle($request);
  6273. }
  6274. }
  6275. }
  6276. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  6277. namespace Tqdev\PhpCrudApi\Middleware {
  6278. use Psr\Http\Message\ResponseInterface;
  6279. use Psr\Http\Message\ServerRequestInterface;
  6280. use Psr\Http\Server\RequestHandlerInterface;
  6281. use Tqdev\PhpCrudApi\Controller\Responder;
  6282. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6283. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6284. class FirewallMiddleware extends Middleware
  6285. {
  6286. private function ipMatch(string $ip, string $cidr): bool
  6287. {
  6288. if (strpos($cidr, '/') !== false) {
  6289. list($subnet, $mask) = explode('/', trim($cidr));
  6290. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  6291. return true;
  6292. }
  6293. } else {
  6294. if (ip2long($ip) == ip2long($cidr)) {
  6295. return true;
  6296. }
  6297. }
  6298. return false;
  6299. }
  6300. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  6301. {
  6302. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  6303. if ($this->ipMatch($ipAddress, $allowedIp)) {
  6304. return true;
  6305. }
  6306. }
  6307. return false;
  6308. }
  6309. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6310. {
  6311. $reverseProxy = $this->getProperty('reverseProxy', '');
  6312. if ($reverseProxy) {
  6313. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  6314. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  6315. $ipAddress = $_SERVER['REMOTE_ADDR'];
  6316. } else {
  6317. $ipAddress = '127.0.0.1';
  6318. }
  6319. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  6320. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  6321. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  6322. } else {
  6323. $response = $next->handle($request);
  6324. }
  6325. return $response;
  6326. }
  6327. }
  6328. }
  6329. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  6330. namespace Tqdev\PhpCrudApi\Middleware {
  6331. use Psr\Http\Message\ResponseInterface;
  6332. use Psr\Http\Message\ServerRequestInterface;
  6333. use Psr\Http\Server\RequestHandlerInterface;
  6334. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6335. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6336. use Tqdev\PhpCrudApi\Controller\Responder;
  6337. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6338. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6339. use Tqdev\PhpCrudApi\RequestUtils;
  6340. class IpAddressMiddleware extends Middleware
  6341. {
  6342. private $reflection;
  6343. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6344. {
  6345. parent::__construct($router, $responder, $properties);
  6346. $this->reflection = $reflection;
  6347. }
  6348. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  6349. {
  6350. $context = (array) $record;
  6351. $columnNames = $this->getProperty('columns', '');
  6352. if ($columnNames) {
  6353. foreach (explode(',', $columnNames) as $columnName) {
  6354. if ($table->hasColumn($columnName)) {
  6355. if ($operation == 'create') {
  6356. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  6357. } else {
  6358. unset($context[$columnName]);
  6359. }
  6360. }
  6361. }
  6362. }
  6363. return (object) $context;
  6364. }
  6365. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6366. {
  6367. $operation = RequestUtils::getOperation($request);
  6368. if (in_array($operation, ['create', 'update', 'increment'])) {
  6369. $tableNames = $this->getProperty('tables', '');
  6370. $tableName = RequestUtils::getPathSegment($request, 2);
  6371. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  6372. if ($this->reflection->hasTable($tableName)) {
  6373. $record = $request->getParsedBody();
  6374. if ($record !== null) {
  6375. $table = $this->reflection->getTable($tableName);
  6376. if (is_array($record)) {
  6377. foreach ($record as &$r) {
  6378. $r = $this->callHandler($r, $operation, $table);
  6379. }
  6380. } else {
  6381. $record = $this->callHandler($record, $operation, $table);
  6382. }
  6383. $request = $request->withParsedBody($record);
  6384. }
  6385. }
  6386. }
  6387. }
  6388. return $next->handle($request);
  6389. }
  6390. }
  6391. }
  6392. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  6393. namespace Tqdev\PhpCrudApi\Middleware {
  6394. use Psr\Http\Message\ResponseInterface;
  6395. use Psr\Http\Message\ServerRequestInterface;
  6396. use Psr\Http\Server\RequestHandlerInterface;
  6397. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6398. use Tqdev\PhpCrudApi\Controller\Responder;
  6399. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6400. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6401. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6402. use Tqdev\PhpCrudApi\RequestUtils;
  6403. class JoinLimitsMiddleware extends Middleware
  6404. {
  6405. private $reflection;
  6406. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6407. {
  6408. parent::__construct($router, $responder, $properties);
  6409. $this->reflection = $reflection;
  6410. }
  6411. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6412. {
  6413. $operation = RequestUtils::getOperation($request);
  6414. $params = RequestUtils::getParams($request);
  6415. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  6416. $maxDepth = (int) $this->getProperty('depth', '3');
  6417. $maxTables = (int) $this->getProperty('tables', '10');
  6418. $maxRecords = (int) $this->getProperty('records', '1000');
  6419. $tableCount = 0;
  6420. $joinPaths = array();
  6421. for ($i = 0; $i < count($params['join']); $i++) {
  6422. $joinPath = array();
  6423. $tables = explode(',', $params['join'][$i]);
  6424. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  6425. array_push($joinPath, $tables[$depth]);
  6426. $tableCount += 1;
  6427. if ($tableCount == $maxTables) {
  6428. break;
  6429. }
  6430. }
  6431. array_push($joinPaths, implode(',', $joinPath));
  6432. if ($tableCount == $maxTables) {
  6433. break;
  6434. }
  6435. }
  6436. $params['join'] = $joinPaths;
  6437. $request = RequestUtils::setParams($request, $params);
  6438. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  6439. }
  6440. return $next->handle($request);
  6441. }
  6442. }
  6443. }
  6444. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  6445. namespace Tqdev\PhpCrudApi\Middleware {
  6446. use Psr\Http\Message\ResponseInterface;
  6447. use Psr\Http\Message\ServerRequestInterface;
  6448. use Psr\Http\Server\RequestHandlerInterface;
  6449. use Tqdev\PhpCrudApi\Controller\Responder;
  6450. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6451. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6452. use Tqdev\PhpCrudApi\RequestUtils;
  6453. class JwtAuthMiddleware extends Middleware
  6454. {
  6455. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, string $secret, array $requirements): array
  6456. {
  6457. $algorithms = array(
  6458. 'HS256' => 'sha256',
  6459. 'HS384' => 'sha384',
  6460. 'HS512' => 'sha512',
  6461. 'RS256' => 'sha256',
  6462. 'RS384' => 'sha384',
  6463. 'RS512' => 'sha512',
  6464. );
  6465. $token = explode('.', $token);
  6466. if (count($token) < 3) {
  6467. return array();
  6468. }
  6469. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  6470. if (!$secret) {
  6471. return array();
  6472. }
  6473. if ($header['typ'] != 'JWT') {
  6474. return array();
  6475. }
  6476. $algorithm = $header['alg'];
  6477. if (!isset($algorithms[$algorithm])) {
  6478. return array();
  6479. }
  6480. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  6481. return array();
  6482. }
  6483. $hmac = $algorithms[$algorithm];
  6484. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  6485. $data = "$token[0].$token[1]";
  6486. switch ($algorithm[0]) {
  6487. case 'H':
  6488. $hash = hash_hmac($hmac, $data, $secret, true);
  6489. if (function_exists('hash_equals')) {
  6490. $equals = hash_equals($signature, $hash);
  6491. } else {
  6492. $equals = $signature == $hash;
  6493. }
  6494. if (!$equals) {
  6495. return array();
  6496. }
  6497. break;
  6498. case 'R':
  6499. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  6500. if (!$equals) {
  6501. return array();
  6502. }
  6503. break;
  6504. }
  6505. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  6506. if (!$claims) {
  6507. return array();
  6508. }
  6509. foreach ($requirements as $field => $values) {
  6510. if (!empty($values)) {
  6511. if ($field != 'alg') {
  6512. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  6513. return array();
  6514. }
  6515. }
  6516. }
  6517. }
  6518. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  6519. return array();
  6520. }
  6521. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  6522. return array();
  6523. }
  6524. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  6525. return array();
  6526. }
  6527. if (isset($claims['iat']) && !isset($claims['exp'])) {
  6528. if ($time - $leeway > $claims['iat'] + $ttl) {
  6529. return array();
  6530. }
  6531. }
  6532. return $claims;
  6533. }
  6534. private function getClaims(string $token): array
  6535. {
  6536. $time = (int) $this->getProperty('time', time());
  6537. $leeway = (int) $this->getProperty('leeway', '5');
  6538. $ttl = (int) $this->getProperty('ttl', '30');
  6539. $secret = $this->getProperty('secret', '');
  6540. $requirements = array(
  6541. 'alg' => $this->getArrayProperty('algorithms', ''),
  6542. 'aud' => $this->getArrayProperty('audiences', ''),
  6543. 'iss' => $this->getArrayProperty('issuers', ''),
  6544. );
  6545. if (!$secret) {
  6546. return array();
  6547. }
  6548. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  6549. }
  6550. private function getAuthorizationToken(ServerRequestInterface $request): string
  6551. {
  6552. $headerName = $this->getProperty('header', 'X-Authorization');
  6553. $headerValue = RequestUtils::getHeader($request, $headerName);
  6554. $parts = explode(' ', trim($headerValue), 2);
  6555. if (count($parts) != 2) {
  6556. return '';
  6557. }
  6558. if ($parts[0] != 'Bearer') {
  6559. return '';
  6560. }
  6561. return $parts[1];
  6562. }
  6563. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6564. {
  6565. if (session_status() == PHP_SESSION_NONE) {
  6566. if (!headers_sent()) {
  6567. session_start();
  6568. }
  6569. }
  6570. $token = $this->getAuthorizationToken($request);
  6571. if ($token) {
  6572. $claims = $this->getClaims($token);
  6573. $_SESSION['claims'] = $claims;
  6574. if (empty($claims)) {
  6575. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  6576. }
  6577. if (!headers_sent()) {
  6578. session_regenerate_id();
  6579. }
  6580. }
  6581. if (empty($_SESSION['claims'])) {
  6582. $authenticationMode = $this->getProperty('mode', 'required');
  6583. if ($authenticationMode == 'required') {
  6584. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6585. }
  6586. }
  6587. return $next->handle($request);
  6588. }
  6589. }
  6590. }
  6591. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  6592. namespace Tqdev\PhpCrudApi\Middleware {
  6593. use Psr\Http\Message\ResponseInterface;
  6594. use Psr\Http\Message\ServerRequestInterface;
  6595. use Psr\Http\Server\RequestHandlerInterface;
  6596. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6597. use Tqdev\PhpCrudApi\Controller\Responder;
  6598. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6599. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6600. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6601. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  6602. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  6603. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  6604. use Tqdev\PhpCrudApi\RequestUtils;
  6605. class MultiTenancyMiddleware extends Middleware
  6606. {
  6607. private $reflection;
  6608. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6609. {
  6610. parent::__construct($router, $responder, $properties);
  6611. $this->reflection = $reflection;
  6612. }
  6613. private function getCondition(string $tableName, array $pairs): Condition
  6614. {
  6615. $condition = new NoCondition();
  6616. $table = $this->reflection->getTable($tableName);
  6617. foreach ($pairs as $k => $v) {
  6618. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  6619. }
  6620. return $condition;
  6621. }
  6622. private function getPairs($handler, string $operation, string $tableName): array
  6623. {
  6624. $result = array();
  6625. $pairs = call_user_func($handler, $operation, $tableName);
  6626. $table = $this->reflection->getTable($tableName);
  6627. foreach ($pairs as $k => $v) {
  6628. if ($table->hasColumn($k)) {
  6629. $result[$k] = $v;
  6630. }
  6631. }
  6632. return $result;
  6633. }
  6634. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  6635. {
  6636. $record = $request->getParsedBody();
  6637. if ($record === null) {
  6638. return $request;
  6639. }
  6640. $multi = is_array($record);
  6641. $records = $multi ? $record : [$record];
  6642. foreach ($records as &$record) {
  6643. foreach ($pairs as $column => $value) {
  6644. if ($operation == 'create') {
  6645. $record->$column = $value;
  6646. } else {
  6647. if (isset($record->$column)) {
  6648. unset($record->$column);
  6649. }
  6650. }
  6651. }
  6652. }
  6653. return $request->withParsedBody($multi ? $records : $records[0]);
  6654. }
  6655. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6656. {
  6657. $handler = $this->getProperty('handler', '');
  6658. if ($handler !== '') {
  6659. $path = RequestUtils::getPathSegment($request, 1);
  6660. if ($path == 'records') {
  6661. $operation = RequestUtils::getOperation($request);
  6662. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  6663. foreach ($tableNames as $i => $tableName) {
  6664. if (!$this->reflection->hasTable($tableName)) {
  6665. continue;
  6666. }
  6667. $pairs = $this->getPairs($handler, $operation, $tableName);
  6668. if ($i == 0) {
  6669. if (in_array($operation, ['create', 'update', 'increment'])) {
  6670. $request = $this->handleRecord($request, $operation, $pairs);
  6671. }
  6672. }
  6673. $condition = $this->getCondition($tableName, $pairs);
  6674. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  6675. }
  6676. }
  6677. }
  6678. return $next->handle($request);
  6679. }
  6680. }
  6681. }
  6682. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  6683. namespace Tqdev\PhpCrudApi\Middleware {
  6684. use Psr\Http\Message\ResponseInterface;
  6685. use Psr\Http\Message\ServerRequestInterface;
  6686. use Psr\Http\Server\RequestHandlerInterface;
  6687. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6688. use Tqdev\PhpCrudApi\Controller\Responder;
  6689. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6690. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6691. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6692. use Tqdev\PhpCrudApi\RequestUtils;
  6693. class PageLimitsMiddleware extends Middleware
  6694. {
  6695. private $reflection;
  6696. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6697. {
  6698. parent::__construct($router, $responder, $properties);
  6699. $this->reflection = $reflection;
  6700. }
  6701. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6702. {
  6703. $operation = RequestUtils::getOperation($request);
  6704. if ($operation == 'list') {
  6705. $params = RequestUtils::getParams($request);
  6706. $maxPage = (int) $this->getProperty('pages', '100');
  6707. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  6708. if (strpos($params['page'][0], ',') === false) {
  6709. $page = $params['page'][0];
  6710. } else {
  6711. list($page, $size) = explode(',', $params['page'][0], 2);
  6712. }
  6713. if ($page > $maxPage) {
  6714. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  6715. }
  6716. }
  6717. $maxSize = (int) $this->getProperty('records', '1000');
  6718. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  6719. $params['size'] = array($maxSize);
  6720. } else {
  6721. $params['size'] = array(min($params['size'][0], $maxSize));
  6722. }
  6723. $request = RequestUtils::setParams($request, $params);
  6724. }
  6725. return $next->handle($request);
  6726. }
  6727. }
  6728. }
  6729. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  6730. namespace Tqdev\PhpCrudApi\Middleware {
  6731. use Psr\Http\Message\ResponseInterface;
  6732. use Psr\Http\Message\ServerRequestInterface;
  6733. use Psr\Http\Server\RequestHandlerInterface;
  6734. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6735. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6736. use Tqdev\PhpCrudApi\Controller\Responder;
  6737. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6738. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6739. use Tqdev\PhpCrudApi\RequestUtils;
  6740. class SanitationMiddleware extends Middleware
  6741. {
  6742. private $reflection;
  6743. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6744. {
  6745. parent::__construct($router, $responder, $properties);
  6746. $this->reflection = $reflection;
  6747. }
  6748. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  6749. {
  6750. $context = (array) $record;
  6751. $tableName = $table->getName();
  6752. foreach ($context as $columnName => &$value) {
  6753. if ($table->hasColumn($columnName)) {
  6754. $column = $table->getColumn($columnName);
  6755. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  6756. }
  6757. }
  6758. return (object) $context;
  6759. }
  6760. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6761. {
  6762. $operation = RequestUtils::getOperation($request);
  6763. if (in_array($operation, ['create', 'update', 'increment'])) {
  6764. $tableName = RequestUtils::getPathSegment($request, 2);
  6765. if ($this->reflection->hasTable($tableName)) {
  6766. $record = $request->getParsedBody();
  6767. if ($record !== null) {
  6768. $handler = $this->getProperty('handler', '');
  6769. if ($handler !== '') {
  6770. $table = $this->reflection->getTable($tableName);
  6771. if (is_array($record)) {
  6772. foreach ($record as &$r) {
  6773. $r = $this->callHandler($handler, $r, $operation, $table);
  6774. }
  6775. } else {
  6776. $record = $this->callHandler($handler, $record, $operation, $table);
  6777. }
  6778. $request = $request->withParsedBody($record);
  6779. }
  6780. }
  6781. }
  6782. }
  6783. return $next->handle($request);
  6784. }
  6785. }
  6786. }
  6787. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  6788. namespace Tqdev\PhpCrudApi\Middleware {
  6789. use Psr\Http\Message\ResponseInterface;
  6790. use Psr\Http\Message\ServerRequestInterface;
  6791. use Psr\Http\Server\RequestHandlerInterface;
  6792. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6793. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6794. use Tqdev\PhpCrudApi\Controller\Responder;
  6795. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6796. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6797. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6798. use Tqdev\PhpCrudApi\RequestUtils;
  6799. class ValidationMiddleware extends Middleware
  6800. {
  6801. private $reflection;
  6802. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6803. {
  6804. parent::__construct($router, $responder, $properties);
  6805. $this->reflection = $reflection;
  6806. }
  6807. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  6808. {
  6809. $context = (array) $record;
  6810. $details = array();
  6811. $tableName = $table->getName();
  6812. foreach ($context as $columnName => $value) {
  6813. if ($table->hasColumn($columnName)) {
  6814. $column = $table->getColumn($columnName);
  6815. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  6816. if ($valid !== true && $valid !== '') {
  6817. $details[$columnName] = $valid;
  6818. }
  6819. }
  6820. }
  6821. if (count($details) > 0) {
  6822. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  6823. }
  6824. return null;
  6825. }
  6826. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6827. {
  6828. $operation = RequestUtils::getOperation($request);
  6829. if (in_array($operation, ['create', 'update', 'increment'])) {
  6830. $tableName = RequestUtils::getPathSegment($request, 2);
  6831. if ($this->reflection->hasTable($tableName)) {
  6832. $record = $request->getParsedBody();
  6833. if ($record !== null) {
  6834. $handler = $this->getProperty('handler', '');
  6835. if ($handler !== '') {
  6836. $table = $this->reflection->getTable($tableName);
  6837. if (is_array($record)) {
  6838. foreach ($record as $r) {
  6839. $response = $this->callHandler($handler, $r, $operation, $table);
  6840. if ($response !== null) {
  6841. return $response;
  6842. }
  6843. }
  6844. } else {
  6845. $response = $this->callHandler($handler, $record, $operation, $table);
  6846. if ($response !== null) {
  6847. return $response;
  6848. }
  6849. }
  6850. }
  6851. }
  6852. }
  6853. }
  6854. return $next->handle($request);
  6855. }
  6856. }
  6857. }
  6858. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  6859. namespace Tqdev\PhpCrudApi\Middleware {
  6860. use Psr\Http\Message\ResponseInterface;
  6861. use Psr\Http\Message\ServerRequestInterface;
  6862. use Psr\Http\Server\RequestHandlerInterface;
  6863. use Tqdev\PhpCrudApi\Controller\Responder;
  6864. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6865. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6866. class XsrfMiddleware extends Middleware
  6867. {
  6868. private function getToken(): string
  6869. {
  6870. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  6871. if (isset($_COOKIE[$cookieName])) {
  6872. $token = $_COOKIE[$cookieName];
  6873. } else {
  6874. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  6875. $token = bin2hex(random_bytes(8));
  6876. if (!headers_sent()) {
  6877. setcookie($cookieName, $token, 0, '', '', $secure);
  6878. }
  6879. }
  6880. return $token;
  6881. }
  6882. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6883. {
  6884. $token = $this->getToken();
  6885. $method = $request->getMethod();
  6886. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  6887. if (!in_array($method, $excludeMethods)) {
  6888. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  6889. if ($token != $request->getHeader($headerName)) {
  6890. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  6891. }
  6892. }
  6893. return $next->handle($request);
  6894. }
  6895. }
  6896. }
  6897. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  6898. namespace Tqdev\PhpCrudApi\OpenApi {
  6899. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6900. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6901. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  6902. class OpenApiBuilder
  6903. {
  6904. private $openapi;
  6905. private $reflection;
  6906. private $operations = [
  6907. 'list' => 'get',
  6908. 'create' => 'post',
  6909. 'read' => 'get',
  6910. 'update' => 'put',
  6911. 'delete' => 'delete',
  6912. 'increment' => 'patch',
  6913. ];
  6914. private $types = [
  6915. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  6916. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  6917. 'varchar' => ['type' => 'string'],
  6918. 'clob' => ['type' => 'string'],
  6919. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  6920. 'blob' => ['type' => 'string', 'format' => 'byte'],
  6921. 'decimal' => ['type' => 'string'],
  6922. 'float' => ['type' => 'number', 'format' => 'float'],
  6923. 'double' => ['type' => 'number', 'format' => 'double'],
  6924. 'date' => ['type' => 'string', 'format' => 'date'],
  6925. 'time' => ['type' => 'string', 'format' => 'date-time'],
  6926. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  6927. 'geometry' => ['type' => 'string'],
  6928. 'boolean' => ['type' => 'boolean'],
  6929. ];
  6930. public function __construct(ReflectionService $reflection, $base)
  6931. {
  6932. $this->reflection = $reflection;
  6933. $this->openapi = new OpenApiDefinition($base);
  6934. }
  6935. private function getServerUrl(): string
  6936. {
  6937. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  6938. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  6939. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  6940. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  6941. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  6942. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  6943. }
  6944. private function getAllTableReferences(): array
  6945. {
  6946. $tableReferences = array();
  6947. foreach ($this->reflection->getTableNames() as $tableName) {
  6948. $table = $this->reflection->getTable($tableName);
  6949. foreach ($table->getColumnNames() as $columnName) {
  6950. $column = $table->getColumn($columnName);
  6951. $referencedTableName = $column->getFk();
  6952. if ($referencedTableName) {
  6953. if (!isset($tableReferences[$referencedTableName])) {
  6954. $tableReferences[$referencedTableName] = array();
  6955. }
  6956. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  6957. }
  6958. }
  6959. }
  6960. return $tableReferences;
  6961. }
  6962. public function build(): OpenApiDefinition
  6963. {
  6964. $this->openapi->set("openapi", "3.0.0");
  6965. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  6966. $this->openapi->set("servers|0|url", $this->getServerUrl());
  6967. }
  6968. $tableNames = $this->reflection->getTableNames();
  6969. foreach ($tableNames as $tableName) {
  6970. $this->setPath($tableName);
  6971. }
  6972. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  6973. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  6974. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  6975. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  6976. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  6977. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  6978. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  6979. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  6980. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  6981. $tableReferences = $this->getAllTableReferences();
  6982. foreach ($tableNames as $tableName) {
  6983. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  6984. $this->setComponentSchema($tableName, $references);
  6985. $this->setComponentResponse($tableName);
  6986. $this->setComponentRequestBody($tableName);
  6987. }
  6988. $this->setComponentParameters();
  6989. foreach ($tableNames as $index => $tableName) {
  6990. $this->setTag($index, $tableName);
  6991. }
  6992. return $this->openapi;
  6993. }
  6994. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  6995. {
  6996. $tableHandler = VariableStore::get('authorization.tableHandler');
  6997. if (!$tableHandler) {
  6998. return true;
  6999. }
  7000. return (bool) call_user_func($tableHandler, $operation, $tableName);
  7001. }
  7002. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  7003. {
  7004. $columnHandler = VariableStore::get('authorization.columnHandler');
  7005. if (!$columnHandler) {
  7006. return true;
  7007. }
  7008. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  7009. }
  7010. private function setPath(string $tableName) /*: void*/
  7011. {
  7012. $table = $this->reflection->getTable($tableName);
  7013. $type = $table->getType();
  7014. $pk = $table->getPk();
  7015. $pkName = $pk ? $pk->getName() : '';
  7016. foreach ($this->operations as $operation => $method) {
  7017. if (!$pkName && $operation != 'list') {
  7018. continue;
  7019. }
  7020. if ($type != 'table' && $operation != 'list') {
  7021. continue;
  7022. }
  7023. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7024. continue;
  7025. }
  7026. $parameters = [];
  7027. if (in_array($operation, ['list', 'create'])) {
  7028. $path = sprintf('/records/%s', $tableName);
  7029. if ($operation == 'list') {
  7030. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  7031. }
  7032. } else {
  7033. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  7034. if ($operation == 'read') {
  7035. $parameters = ['pk', 'include', 'exclude', 'join'];
  7036. } else {
  7037. $parameters = ['pk'];
  7038. }
  7039. }
  7040. foreach ($parameters as $p => $parameter) {
  7041. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  7042. }
  7043. if (in_array($operation, ['create', 'update', 'increment'])) {
  7044. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  7045. }
  7046. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  7047. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  7048. switch ($operation) {
  7049. case 'list':
  7050. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  7051. break;
  7052. case 'create':
  7053. if ($pk->getType() == 'integer') {
  7054. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  7055. } else {
  7056. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  7057. }
  7058. break;
  7059. case 'read':
  7060. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  7061. break;
  7062. case 'update':
  7063. case 'delete':
  7064. case 'increment':
  7065. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  7066. break;
  7067. }
  7068. }
  7069. }
  7070. private function setComponentSchema(string $tableName, array $references) /*: void*/
  7071. {
  7072. $table = $this->reflection->getTable($tableName);
  7073. $type = $table->getType();
  7074. $pk = $table->getPk();
  7075. $pkName = $pk ? $pk->getName() : '';
  7076. foreach ($this->operations as $operation => $method) {
  7077. if (!$pkName && $operation != 'list') {
  7078. continue;
  7079. }
  7080. if ($type != 'table' && $operation != 'list') {
  7081. continue;
  7082. }
  7083. if ($operation == 'delete') {
  7084. continue;
  7085. }
  7086. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7087. continue;
  7088. }
  7089. if ($operation == 'list') {
  7090. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  7091. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  7092. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  7093. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  7094. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  7095. } else {
  7096. $prefix = "components|schemas|$operation-$tableName";
  7097. }
  7098. $this->openapi->set("$prefix|type", "object");
  7099. foreach ($table->getColumnNames() as $columnName) {
  7100. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  7101. continue;
  7102. }
  7103. $column = $table->getColumn($columnName);
  7104. $properties = $this->types[$column->getType()];
  7105. foreach ($properties as $key => $value) {
  7106. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  7107. }
  7108. if ($column->getPk()) {
  7109. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  7110. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  7111. }
  7112. $fk = $column->getFk();
  7113. if ($fk) {
  7114. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  7115. }
  7116. }
  7117. }
  7118. }
  7119. private function setComponentResponse(string $tableName) /*: void*/
  7120. {
  7121. $table = $this->reflection->getTable($tableName);
  7122. $type = $table->getType();
  7123. $pk = $table->getPk();
  7124. $pkName = $pk ? $pk->getName() : '';
  7125. foreach (['list', 'read'] as $operation) {
  7126. if (!$pkName && $operation != 'list') {
  7127. continue;
  7128. }
  7129. if ($type != 'table' && $operation != 'list') {
  7130. continue;
  7131. }
  7132. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7133. continue;
  7134. }
  7135. if ($operation == 'list') {
  7136. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  7137. } else {
  7138. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  7139. }
  7140. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  7141. }
  7142. }
  7143. private function setComponentRequestBody(string $tableName) /*: void*/
  7144. {
  7145. $table = $this->reflection->getTable($tableName);
  7146. $type = $table->getType();
  7147. $pk = $table->getPk();
  7148. $pkName = $pk ? $pk->getName() : '';
  7149. if ($pkName && $type == 'table') {
  7150. foreach (['create', 'update', 'increment'] as $operation) {
  7151. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7152. continue;
  7153. }
  7154. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  7155. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  7156. }
  7157. }
  7158. }
  7159. private function setComponentParameters() /*: void*/
  7160. {
  7161. $this->openapi->set("components|parameters|pk|name", "id");
  7162. $this->openapi->set("components|parameters|pk|in", "path");
  7163. $this->openapi->set("components|parameters|pk|schema|type", "string");
  7164. $this->openapi->set("components|parameters|pk|description", "primary key value");
  7165. $this->openapi->set("components|parameters|pk|required", true);
  7166. $this->openapi->set("components|parameters|filter|name", "filter");
  7167. $this->openapi->set("components|parameters|filter|in", "query");
  7168. $this->openapi->set("components|parameters|filter|schema|type", "array");
  7169. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  7170. $this->openapi->set("components|parameters|filter|description", "Filters to be applied. Each filter consists of a column, an operator and a value (comma separated). Example: id,eq,1");
  7171. $this->openapi->set("components|parameters|filter|required", false);
  7172. $this->openapi->set("components|parameters|include|name", "include");
  7173. $this->openapi->set("components|parameters|include|in", "query");
  7174. $this->openapi->set("components|parameters|include|schema|type", "string");
  7175. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  7176. $this->openapi->set("components|parameters|include|required", false);
  7177. $this->openapi->set("components|parameters|exclude|name", "exclude");
  7178. $this->openapi->set("components|parameters|exclude|in", "query");
  7179. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  7180. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  7181. $this->openapi->set("components|parameters|exclude|required", false);
  7182. $this->openapi->set("components|parameters|order|name", "order");
  7183. $this->openapi->set("components|parameters|order|in", "query");
  7184. $this->openapi->set("components|parameters|order|schema|type", "array");
  7185. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  7186. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  7187. $this->openapi->set("components|parameters|order|required", false);
  7188. $this->openapi->set("components|parameters|size|name", "size");
  7189. $this->openapi->set("components|parameters|size|in", "query");
  7190. $this->openapi->set("components|parameters|size|schema|type", "string");
  7191. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  7192. $this->openapi->set("components|parameters|size|required", false);
  7193. $this->openapi->set("components|parameters|page|name", "page");
  7194. $this->openapi->set("components|parameters|page|in", "query");
  7195. $this->openapi->set("components|parameters|page|schema|type", "string");
  7196. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  7197. $this->openapi->set("components|parameters|page|required", false);
  7198. $this->openapi->set("components|parameters|join|name", "join");
  7199. $this->openapi->set("components|parameters|join|in", "query");
  7200. $this->openapi->set("components|parameters|join|schema|type", "array");
  7201. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  7202. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  7203. $this->openapi->set("components|parameters|join|required", false);
  7204. }
  7205. private function setTag(int $index, string $tableName) /*: void*/
  7206. {
  7207. $this->openapi->set("tags|$index|name", "$tableName");
  7208. $this->openapi->set("tags|$index|description", "$tableName operations");
  7209. }
  7210. }
  7211. }
  7212. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  7213. namespace Tqdev\PhpCrudApi\OpenApi {
  7214. class OpenApiDefinition implements \JsonSerializable
  7215. {
  7216. private $root;
  7217. public function __construct($base)
  7218. {
  7219. $this->root = $base;
  7220. }
  7221. public function set(string $path, $value) /*: void*/
  7222. {
  7223. $parts = explode('|', trim($path, '|'));
  7224. $current = &$this->root;
  7225. while (count($parts) > 0) {
  7226. $part = array_shift($parts);
  7227. if (!isset($current[$part])) {
  7228. $current[$part] = [];
  7229. }
  7230. $current = &$current[$part];
  7231. }
  7232. $current = $value;
  7233. }
  7234. public function has(string $path): bool
  7235. {
  7236. $parts = explode('|', trim($path, '|'));
  7237. $current = &$this->root;
  7238. while (count($parts) > 0) {
  7239. $part = array_shift($parts);
  7240. if (!isset($current[$part])) {
  7241. return false;
  7242. }
  7243. $current = &$current[$part];
  7244. }
  7245. return true;
  7246. }
  7247. public function jsonSerialize()
  7248. {
  7249. return $this->root;
  7250. }
  7251. }
  7252. }
  7253. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  7254. namespace Tqdev\PhpCrudApi\OpenApi {
  7255. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7256. use Tqdev\PhpCrudApi\OpenApi\OpenApiBuilder;
  7257. class OpenApiService
  7258. {
  7259. private $builder;
  7260. public function __construct(ReflectionService $reflection, array $base)
  7261. {
  7262. $this->builder = new OpenApiBuilder($reflection, $base);
  7263. }
  7264. public function get(): OpenApiDefinition
  7265. {
  7266. return $this->builder->build();
  7267. }
  7268. }
  7269. }
  7270. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  7271. namespace Tqdev\PhpCrudApi\Record\Condition {
  7272. class AndCondition extends Condition
  7273. {
  7274. private $conditions;
  7275. public function __construct(Condition $condition1, Condition $condition2)
  7276. {
  7277. $this->conditions = [$condition1, $condition2];
  7278. }
  7279. public function _and(Condition $condition): Condition
  7280. {
  7281. if ($condition instanceof NoCondition) {
  7282. return $this;
  7283. }
  7284. $this->conditions[] = $condition;
  7285. return $this;
  7286. }
  7287. public function getConditions(): array
  7288. {
  7289. return $this->conditions;
  7290. }
  7291. public static function fromArray(array $conditions): Condition
  7292. {
  7293. $condition = new NoCondition();
  7294. foreach ($conditions as $c) {
  7295. $condition = $condition->_and($c);
  7296. }
  7297. return $condition;
  7298. }
  7299. }
  7300. }
  7301. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  7302. namespace Tqdev\PhpCrudApi\Record\Condition {
  7303. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  7304. class ColumnCondition extends Condition
  7305. {
  7306. private $column;
  7307. private $operator;
  7308. private $value;
  7309. public function __construct(ReflectedColumn $column, string $operator, string $value)
  7310. {
  7311. $this->column = $column;
  7312. $this->operator = $operator;
  7313. $this->value = $value;
  7314. }
  7315. public function getColumn(): ReflectedColumn
  7316. {
  7317. return $this->column;
  7318. }
  7319. public function getOperator(): string
  7320. {
  7321. return $this->operator;
  7322. }
  7323. public function getValue(): string
  7324. {
  7325. return $this->value;
  7326. }
  7327. }
  7328. }
  7329. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  7330. namespace Tqdev\PhpCrudApi\Record\Condition {
  7331. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7332. abstract class Condition
  7333. {
  7334. public function _and(Condition $condition): Condition
  7335. {
  7336. if ($condition instanceof NoCondition) {
  7337. return $this;
  7338. }
  7339. return new AndCondition($this, $condition);
  7340. }
  7341. public function _or(Condition $condition): Condition
  7342. {
  7343. if ($condition instanceof NoCondition) {
  7344. return $this;
  7345. }
  7346. return new OrCondition($this, $condition);
  7347. }
  7348. public function _not(): Condition
  7349. {
  7350. return new NotCondition($this);
  7351. }
  7352. public static function fromString(ReflectedTable $table, string $value): Condition
  7353. {
  7354. $condition = new NoCondition();
  7355. $parts = explode(',', $value, 3);
  7356. if (count($parts) < 2) {
  7357. return $condition;
  7358. }
  7359. if (count($parts) < 3) {
  7360. $parts[2] = '';
  7361. }
  7362. $field = $table->getColumn($parts[0]);
  7363. $command = $parts[1];
  7364. $negate = false;
  7365. $spatial = false;
  7366. if (strlen($command) > 2) {
  7367. if (substr($command, 0, 1) == 'n') {
  7368. $negate = true;
  7369. $command = substr($command, 1);
  7370. }
  7371. if (substr($command, 0, 1) == 's') {
  7372. $spatial = true;
  7373. $command = substr($command, 1);
  7374. }
  7375. }
  7376. if ($spatial) {
  7377. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  7378. $condition = new SpatialCondition($field, $command, $parts[2]);
  7379. }
  7380. } else {
  7381. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  7382. $condition = new ColumnCondition($field, $command, $parts[2]);
  7383. }
  7384. }
  7385. if ($negate) {
  7386. $condition = $condition->_not();
  7387. }
  7388. return $condition;
  7389. }
  7390. }
  7391. }
  7392. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  7393. namespace Tqdev\PhpCrudApi\Record\Condition {
  7394. class NoCondition extends Condition
  7395. {
  7396. public function _and(Condition $condition): Condition
  7397. {
  7398. return $condition;
  7399. }
  7400. public function _or(Condition $condition): Condition
  7401. {
  7402. return $condition;
  7403. }
  7404. public function _not(): Condition
  7405. {
  7406. return $this;
  7407. }
  7408. }
  7409. }
  7410. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  7411. namespace Tqdev\PhpCrudApi\Record\Condition {
  7412. class NotCondition extends Condition
  7413. {
  7414. private $condition;
  7415. public function __construct(Condition $condition)
  7416. {
  7417. $this->condition = $condition;
  7418. }
  7419. public function getCondition(): Condition
  7420. {
  7421. return $this->condition;
  7422. }
  7423. }
  7424. }
  7425. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  7426. namespace Tqdev\PhpCrudApi\Record\Condition {
  7427. class OrCondition extends Condition
  7428. {
  7429. private $conditions;
  7430. public function __construct(Condition $condition1, Condition $condition2)
  7431. {
  7432. $this->conditions = [$condition1, $condition2];
  7433. }
  7434. public function _or(Condition $condition): Condition
  7435. {
  7436. if ($condition instanceof NoCondition) {
  7437. return $this;
  7438. }
  7439. $this->conditions[] = $condition;
  7440. return $this;
  7441. }
  7442. public function getConditions(): array
  7443. {
  7444. return $this->conditions;
  7445. }
  7446. public static function fromArray(array $conditions): Condition
  7447. {
  7448. $condition = new NoCondition();
  7449. foreach ($conditions as $c) {
  7450. $condition = $condition->_or($c);
  7451. }
  7452. return $condition;
  7453. }
  7454. }
  7455. }
  7456. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  7457. namespace Tqdev\PhpCrudApi\Record\Condition {
  7458. class SpatialCondition extends ColumnCondition
  7459. {
  7460. }
  7461. }
  7462. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  7463. namespace Tqdev\PhpCrudApi\Record\Document {
  7464. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7465. class ErrorDocument implements \JsonSerializable
  7466. {
  7467. public $code;
  7468. public $message;
  7469. public $details;
  7470. public function __construct(ErrorCode $errorCode, string $argument, $details)
  7471. {
  7472. $this->code = $errorCode->getCode();
  7473. $this->message = $errorCode->getMessage($argument);
  7474. $this->details = $details;
  7475. }
  7476. public function getCode(): int
  7477. {
  7478. return $this->code;
  7479. }
  7480. public function getMessage(): string
  7481. {
  7482. return $this->message;
  7483. }
  7484. public function serialize()
  7485. {
  7486. return [
  7487. 'code' => $this->code,
  7488. 'message' => $this->message,
  7489. 'details' => $this->details,
  7490. ];
  7491. }
  7492. public function jsonSerialize()
  7493. {
  7494. return array_filter($this->serialize());
  7495. }
  7496. }
  7497. }
  7498. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  7499. namespace Tqdev\PhpCrudApi\Record\Document {
  7500. class ListDocument implements \JsonSerializable
  7501. {
  7502. private $records;
  7503. private $results;
  7504. public function __construct(array $records, int $results)
  7505. {
  7506. $this->records = $records;
  7507. $this->results = $results;
  7508. }
  7509. public function getRecords(): array
  7510. {
  7511. return $this->records;
  7512. }
  7513. public function getResults(): int
  7514. {
  7515. return $this->results;
  7516. }
  7517. public function serialize()
  7518. {
  7519. return [
  7520. 'records' => $this->records,
  7521. 'results' => $this->results,
  7522. ];
  7523. }
  7524. public function jsonSerialize()
  7525. {
  7526. return array_filter($this->serialize(), function ($v) {
  7527. return $v !== 0;
  7528. });
  7529. }
  7530. }
  7531. }
  7532. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  7533. namespace Tqdev\PhpCrudApi\Record {
  7534. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7535. class ColumnIncluder
  7536. {
  7537. private function isMandatory(string $tableName, string $columnName, array $params): bool
  7538. {
  7539. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  7540. }
  7541. private function select(string $tableName, bool $primaryTable, array $params, string $paramName,
  7542. array $columnNames, bool $include): array{
  7543. if (!isset($params[$paramName])) {
  7544. return $columnNames;
  7545. }
  7546. $columns = array();
  7547. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  7548. $columns[$columnName] = true;
  7549. }
  7550. $result = array();
  7551. foreach ($columnNames as $columnName) {
  7552. $match = isset($columns['*.*']);
  7553. if (!$match) {
  7554. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  7555. }
  7556. if ($primaryTable && !$match) {
  7557. $match = isset($columns['*']) || isset($columns[$columnName]);
  7558. }
  7559. if ($match) {
  7560. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  7561. $result[] = $columnName;
  7562. }
  7563. } else {
  7564. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  7565. $result[] = $columnName;
  7566. }
  7567. }
  7568. }
  7569. return $result;
  7570. }
  7571. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  7572. {
  7573. $tableName = $table->getName();
  7574. $results = $table->getColumnNames();
  7575. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  7576. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  7577. return $results;
  7578. }
  7579. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  7580. {
  7581. $results = array();
  7582. $columnNames = $this->getNames($table, $primaryTable, $params);
  7583. foreach ($columnNames as $columnName) {
  7584. if (property_exists($record, $columnName)) {
  7585. $results[$columnName] = $record->$columnName;
  7586. }
  7587. }
  7588. return $results;
  7589. }
  7590. }
  7591. }
  7592. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  7593. namespace Tqdev\PhpCrudApi\Record {
  7594. use Tqdev\PhpCrudApi\ResponseFactory;
  7595. class ErrorCode
  7596. {
  7597. private $code;
  7598. private $message;
  7599. private $status;
  7600. const ERROR_NOT_FOUND = 9999;
  7601. const ROUTE_NOT_FOUND = 1000;
  7602. const TABLE_NOT_FOUND = 1001;
  7603. const ARGUMENT_COUNT_MISMATCH = 1002;
  7604. const RECORD_NOT_FOUND = 1003;
  7605. const ORIGIN_FORBIDDEN = 1004;
  7606. const COLUMN_NOT_FOUND = 1005;
  7607. const TABLE_ALREADY_EXISTS = 1006;
  7608. const COLUMN_ALREADY_EXISTS = 1007;
  7609. const HTTP_MESSAGE_NOT_READABLE = 1008;
  7610. const DUPLICATE_KEY_EXCEPTION = 1009;
  7611. const DATA_INTEGRITY_VIOLATION = 1010;
  7612. const AUTHENTICATION_REQUIRED = 1011;
  7613. const AUTHENTICATION_FAILED = 1012;
  7614. const INPUT_VALIDATION_FAILED = 1013;
  7615. const OPERATION_FORBIDDEN = 1014;
  7616. const OPERATION_NOT_SUPPORTED = 1015;
  7617. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  7618. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  7619. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  7620. const PAGINATION_FORBIDDEN = 1019;
  7621. private $values = [
  7622. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  7623. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  7624. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  7625. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  7626. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  7627. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  7628. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  7629. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  7630. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  7631. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  7632. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  7633. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  7634. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  7635. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  7636. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  7637. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  7638. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  7639. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  7640. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  7641. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  7642. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  7643. ];
  7644. public function __construct(int $code)
  7645. {
  7646. if (!isset($this->values[$code])) {
  7647. $code = 9999;
  7648. }
  7649. $this->code = $code;
  7650. $this->message = $this->values[$code][0];
  7651. $this->status = $this->values[$code][1];
  7652. }
  7653. public function getCode(): int
  7654. {
  7655. return $this->code;
  7656. }
  7657. public function getMessage(string $argument): string
  7658. {
  7659. return sprintf($this->message, $argument);
  7660. }
  7661. public function getStatus(): int
  7662. {
  7663. return $this->status;
  7664. }
  7665. }
  7666. }
  7667. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  7668. namespace Tqdev\PhpCrudApi\Record {
  7669. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7670. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  7671. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  7672. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  7673. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  7674. class FilterInfo
  7675. {
  7676. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  7677. {
  7678. $key = 'filter' . implode('', $path);
  7679. if (isset($params[$key])) {
  7680. foreach ($params[$key] as $filter) {
  7681. $condition = Condition::fromString($table, $filter);
  7682. if (($condition instanceof NoCondition) == false) {
  7683. $conditions->put($path, $condition);
  7684. }
  7685. }
  7686. }
  7687. }
  7688. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  7689. {
  7690. $conditions = new PathTree();
  7691. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  7692. for ($n = ord('0'); $n <= ord('9'); $n++) {
  7693. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  7694. for ($l = ord('a'); $l <= ord('f'); $l++) {
  7695. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  7696. }
  7697. }
  7698. return $conditions;
  7699. }
  7700. private function combinePathTreeOfConditions(PathTree $tree): Condition
  7701. {
  7702. $andConditions = $tree->getValues();
  7703. $and = AndCondition::fromArray($andConditions);
  7704. $orConditions = [];
  7705. foreach ($tree->getKeys() as $p) {
  7706. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  7707. }
  7708. $or = OrCondition::fromArray($orConditions);
  7709. return $and->_and($or);
  7710. }
  7711. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  7712. {
  7713. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  7714. }
  7715. }
  7716. }
  7717. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  7718. namespace Tqdev\PhpCrudApi\Record {
  7719. class HabtmValues
  7720. {
  7721. public $pkValues;
  7722. public $fkValues;
  7723. public function __construct(array $pkValues, array $fkValues)
  7724. {
  7725. $this->pkValues = $pkValues;
  7726. $this->fkValues = $fkValues;
  7727. }
  7728. }
  7729. }
  7730. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  7731. namespace Tqdev\PhpCrudApi\Record {
  7732. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7733. class OrderingInfo
  7734. {
  7735. public function getColumnOrdering(ReflectedTable $table, array $params): array
  7736. {
  7737. $fields = array();
  7738. if (isset($params['order'])) {
  7739. foreach ($params['order'] as $order) {
  7740. $parts = explode(',', $order, 3);
  7741. $columnName = $parts[0];
  7742. if (!$table->hasColumn($columnName)) {
  7743. continue;
  7744. }
  7745. $ascending = 'ASC';
  7746. if (count($parts) > 1) {
  7747. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  7748. $ascending = 'DESC';
  7749. }
  7750. }
  7751. $fields[] = [$columnName, $ascending];
  7752. }
  7753. }
  7754. if (count($fields) == 0) {
  7755. return $this->getDefaultColumnOrdering($table);
  7756. }
  7757. return $fields;
  7758. }
  7759. public function getDefaultColumnOrdering(ReflectedTable $table): array
  7760. {
  7761. $fields = array();
  7762. $pk = $table->getPk();
  7763. if ($pk) {
  7764. $fields[] = [$pk->getName(), 'ASC'];
  7765. } else {
  7766. foreach ($table->getColumnNames() as $columnName) {
  7767. $fields[] = [$columnName, 'ASC'];
  7768. }
  7769. }
  7770. return $fields;
  7771. }
  7772. }
  7773. }
  7774. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  7775. namespace Tqdev\PhpCrudApi\Record {
  7776. class PaginationInfo
  7777. {
  7778. public $DEFAULT_PAGE_SIZE = 20;
  7779. public function hasPage(array $params): bool
  7780. {
  7781. return isset($params['page']);
  7782. }
  7783. public function getPageOffset(array $params): int
  7784. {
  7785. $offset = 0;
  7786. $pageSize = $this->getPageSize($params);
  7787. if (isset($params['page'])) {
  7788. foreach ($params['page'] as $page) {
  7789. $parts = explode(',', $page, 2);
  7790. $page = intval($parts[0]) - 1;
  7791. $offset = $page * $pageSize;
  7792. }
  7793. }
  7794. return $offset;
  7795. }
  7796. private function getPageSize(array $params): int
  7797. {
  7798. $pageSize = $this->DEFAULT_PAGE_SIZE;
  7799. if (isset($params['page'])) {
  7800. foreach ($params['page'] as $page) {
  7801. $parts = explode(',', $page, 2);
  7802. if (count($parts) > 1) {
  7803. $pageSize = intval($parts[1]);
  7804. }
  7805. }
  7806. }
  7807. return $pageSize;
  7808. }
  7809. public function getResultSize(array $params): int
  7810. {
  7811. $numberOfRows = -1;
  7812. if (isset($params['size'])) {
  7813. foreach ($params['size'] as $size) {
  7814. $numberOfRows = intval($size);
  7815. }
  7816. }
  7817. return $numberOfRows;
  7818. }
  7819. public function getPageLimit(array $params): int
  7820. {
  7821. $pageLimit = -1;
  7822. if ($this->hasPage($params)) {
  7823. $pageLimit = $this->getPageSize($params);
  7824. }
  7825. $resultSize = $this->getResultSize($params);
  7826. if ($resultSize >= 0) {
  7827. if ($pageLimit >= 0) {
  7828. $pageLimit = min($pageLimit, $resultSize);
  7829. } else {
  7830. $pageLimit = $resultSize;
  7831. }
  7832. }
  7833. return $pageLimit;
  7834. }
  7835. }
  7836. }
  7837. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  7838. namespace Tqdev\PhpCrudApi\Record {
  7839. class PathTree implements \JsonSerializable
  7840. {
  7841. const WILDCARD = '*';
  7842. private $tree;
  7843. public function __construct( /* object */&$tree = null)
  7844. {
  7845. if (!$tree) {
  7846. $tree = $this->newTree();
  7847. }
  7848. $this->tree = &$tree;
  7849. }
  7850. public function newTree()
  7851. {
  7852. return (object) ['values' => [], 'branches' => (object) []];
  7853. }
  7854. public function getKeys(): array
  7855. {
  7856. $branches = (array) $this->tree->branches;
  7857. return array_keys($branches);
  7858. }
  7859. public function getValues(): array
  7860. {
  7861. return $this->tree->values;
  7862. }
  7863. public function get(string $key): PathTree
  7864. {
  7865. if (!isset($this->tree->branches->$key)) {
  7866. return null;
  7867. }
  7868. return new PathTree($this->tree->branches->$key);
  7869. }
  7870. public function put(array $path, $value)
  7871. {
  7872. $tree = &$this->tree;
  7873. foreach ($path as $key) {
  7874. if (!isset($tree->branches->$key)) {
  7875. $tree->branches->$key = $this->newTree();
  7876. }
  7877. $tree = &$tree->branches->$key;
  7878. }
  7879. $tree->values[] = $value;
  7880. }
  7881. public function match(array $path): array
  7882. {
  7883. $star = self::WILDCARD;
  7884. $tree = &$this->tree;
  7885. foreach ($path as $key) {
  7886. if (isset($tree->branches->$key)) {
  7887. $tree = &$tree->branches->$key;
  7888. } else if (isset($tree->branches->$star)) {
  7889. $tree = &$tree->branches->$star;
  7890. } else {
  7891. return [];
  7892. }
  7893. }
  7894. return $tree->values;
  7895. }
  7896. public static function fromJson( /* object */$tree): PathTree
  7897. {
  7898. return new PathTree($tree);
  7899. }
  7900. public function jsonSerialize()
  7901. {
  7902. return $this->tree;
  7903. }
  7904. }
  7905. }
  7906. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  7907. namespace Tqdev\PhpCrudApi\Record {
  7908. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7909. use Tqdev\PhpCrudApi\Database\GenericDB;
  7910. use Tqdev\PhpCrudApi\Record\Document\ListDocument;
  7911. class RecordService
  7912. {
  7913. private $db;
  7914. private $reflection;
  7915. private $columns;
  7916. private $joiner;
  7917. private $filters;
  7918. private $ordering;
  7919. private $pagination;
  7920. public function __construct(GenericDB $db, ReflectionService $reflection)
  7921. {
  7922. $this->db = $db;
  7923. $this->reflection = $reflection;
  7924. $this->columns = new ColumnIncluder();
  7925. $this->joiner = new RelationJoiner($reflection, $this->columns);
  7926. $this->filters = new FilterInfo();
  7927. $this->ordering = new OrderingInfo();
  7928. $this->pagination = new PaginationInfo();
  7929. }
  7930. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  7931. {
  7932. $keyset = array_keys((array) $record);
  7933. foreach ($keyset as $key) {
  7934. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  7935. unset($record->$key);
  7936. }
  7937. }
  7938. if ($id != '') {
  7939. $pk = $this->reflection->getTable($tableName)->getPk();
  7940. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  7941. $field = $this->reflection->getTable($tableName)->getColumn($key);
  7942. if ($field->getName() == $pk->getName()) {
  7943. unset($record->$key);
  7944. }
  7945. }
  7946. }
  7947. }
  7948. public function hasTable(string $table): bool
  7949. {
  7950. return $this->reflection->hasTable($table);
  7951. }
  7952. public function getType(string $table): string
  7953. {
  7954. return $this->reflection->getType($table);
  7955. }
  7956. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  7957. {
  7958. $this->sanitizeRecord($tableName, $record, '');
  7959. $table = $this->reflection->getTable($tableName);
  7960. $columnValues = $this->columns->getValues($table, true, $record, $params);
  7961. return $this->db->createSingle($table, $columnValues);
  7962. }
  7963. public function read(string $tableName, string $id, array $params) /*: ?object*/
  7964. {
  7965. $table = $this->reflection->getTable($tableName);
  7966. $this->joiner->addMandatoryColumns($table, $params);
  7967. $columnNames = $this->columns->getNames($table, true, $params);
  7968. $record = $this->db->selectSingle($table, $columnNames, $id);
  7969. if ($record == null) {
  7970. return null;
  7971. }
  7972. $records = array($record);
  7973. $this->joiner->addJoins($table, $records, $params, $this->db);
  7974. return $records[0];
  7975. }
  7976. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  7977. {
  7978. $this->sanitizeRecord($tableName, $record, $id);
  7979. $table = $this->reflection->getTable($tableName);
  7980. $columnValues = $this->columns->getValues($table, true, $record, $params);
  7981. return $this->db->updateSingle($table, $columnValues, $id);
  7982. }
  7983. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  7984. {
  7985. $table = $this->reflection->getTable($tableName);
  7986. return $this->db->deleteSingle($table, $id);
  7987. }
  7988. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  7989. {
  7990. $this->sanitizeRecord($tableName, $record, $id);
  7991. $table = $this->reflection->getTable($tableName);
  7992. $columnValues = $this->columns->getValues($table, true, $record, $params);
  7993. return $this->db->incrementSingle($table, $columnValues, $id);
  7994. }
  7995. public function _list(string $tableName, array $params): ListDocument
  7996. {
  7997. $table = $this->reflection->getTable($tableName);
  7998. $this->joiner->addMandatoryColumns($table, $params);
  7999. $columnNames = $this->columns->getNames($table, true, $params);
  8000. $condition = $this->filters->getCombinedConditions($table, $params);
  8001. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  8002. if (!$this->pagination->hasPage($params)) {
  8003. $offset = 0;
  8004. $limit = $this->pagination->getPageLimit($params);
  8005. $count = 0;
  8006. } else {
  8007. $offset = $this->pagination->getPageOffset($params);
  8008. $limit = $this->pagination->getPageLimit($params);
  8009. $count = $this->db->selectCount($table, $condition);
  8010. }
  8011. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  8012. $this->joiner->addJoins($table, $records, $params, $this->db);
  8013. return new ListDocument($records, $count);
  8014. }
  8015. }
  8016. }
  8017. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  8018. namespace Tqdev\PhpCrudApi\Record {
  8019. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8020. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8021. use Tqdev\PhpCrudApi\Database\GenericDB;
  8022. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  8023. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  8024. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  8025. class RelationJoiner
  8026. {
  8027. private $reflection;
  8028. private $ordering;
  8029. private $columns;
  8030. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  8031. {
  8032. $this->reflection = $reflection;
  8033. $this->ordering = new OrderingInfo();
  8034. $this->columns = $columns;
  8035. }
  8036. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  8037. {
  8038. if (!isset($params['join']) || !isset($params['include'])) {
  8039. return;
  8040. }
  8041. $params['mandatory'] = array();
  8042. foreach ($params['join'] as $tableNames) {
  8043. $t1 = $table;
  8044. foreach (explode(',', $tableNames) as $tableName) {
  8045. if (!$this->reflection->hasTable($tableName)) {
  8046. continue;
  8047. }
  8048. $t2 = $this->reflection->getTable($tableName);
  8049. $fks1 = $t1->getFksTo($t2->getName());
  8050. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  8051. if ($t3 != null || count($fks1) > 0) {
  8052. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  8053. }
  8054. foreach ($fks1 as $fk) {
  8055. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  8056. }
  8057. $fks2 = $t2->getFksTo($t1->getName());
  8058. if ($t3 != null || count($fks2) > 0) {
  8059. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  8060. }
  8061. foreach ($fks2 as $fk) {
  8062. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  8063. }
  8064. $t1 = $t2;
  8065. }
  8066. }
  8067. }
  8068. private function getJoinsAsPathTree(array $params): PathTree
  8069. {
  8070. $joins = new PathTree();
  8071. if (isset($params['join'])) {
  8072. foreach ($params['join'] as $tableNames) {
  8073. $path = array();
  8074. foreach (explode(',', $tableNames) as $tableName) {
  8075. $t = $this->reflection->getTable($tableName);
  8076. if ($t != null) {
  8077. $path[] = $t->getName();
  8078. }
  8079. }
  8080. $joins->put($path, true);
  8081. }
  8082. }
  8083. return $joins;
  8084. }
  8085. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  8086. {
  8087. $joins = $this->getJoinsAsPathTree($params);
  8088. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  8089. }
  8090. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  8091. {
  8092. foreach ($this->reflection->getTableNames() as $tableName) {
  8093. $t3 = $this->reflection->getTable($tableName);
  8094. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  8095. return $t3;
  8096. }
  8097. }
  8098. return null;
  8099. }
  8100. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  8101. {
  8102. foreach ($joins->getKeys() as $t2Name) {
  8103. $t2 = $this->reflection->getTable($t2Name);
  8104. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  8105. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  8106. if (!$belongsTo && !$hasMany) {
  8107. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  8108. } else {
  8109. $t3 = null;
  8110. }
  8111. $hasAndBelongsToMany = ($t3 != null);
  8112. $newRecords = array();
  8113. $fkValues = null;
  8114. $pkValues = null;
  8115. $habtmValues = null;
  8116. if ($belongsTo) {
  8117. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  8118. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  8119. }
  8120. if ($hasMany) {
  8121. $pkValues = $this->getPkEmptyValues($t1, $records);
  8122. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  8123. }
  8124. if ($hasAndBelongsToMany) {
  8125. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  8126. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  8127. }
  8128. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  8129. if ($fkValues != null) {
  8130. $this->fillFkValues($t2, $newRecords, $fkValues);
  8131. $this->setFkValues($t1, $t2, $records, $fkValues);
  8132. }
  8133. if ($pkValues != null) {
  8134. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  8135. $this->setPkValues($t1, $t2, $records, $pkValues);
  8136. }
  8137. if ($habtmValues != null) {
  8138. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  8139. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  8140. }
  8141. }
  8142. }
  8143. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  8144. {
  8145. $fkValues = array();
  8146. $fks = $t1->getFksTo($t2->getName());
  8147. foreach ($fks as $fk) {
  8148. $fkName = $fk->getName();
  8149. foreach ($records as $record) {
  8150. if (isset($record[$fkName])) {
  8151. $fkValue = $record[$fkName];
  8152. $fkValues[$fkValue] = null;
  8153. }
  8154. }
  8155. }
  8156. return $fkValues;
  8157. }
  8158. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  8159. {
  8160. $columnNames = $this->columns->getNames($t2, false, $params);
  8161. $fkIds = array_keys($fkValues);
  8162. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  8163. $records[] = $record;
  8164. }
  8165. }
  8166. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  8167. {
  8168. $pkName = $t2->getPk()->getName();
  8169. foreach ($fkRecords as $fkRecord) {
  8170. $pkValue = $fkRecord[$pkName];
  8171. $fkValues[$pkValue] = $fkRecord;
  8172. }
  8173. }
  8174. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  8175. {
  8176. $fks = $t1->getFksTo($t2->getName());
  8177. foreach ($fks as $fk) {
  8178. $fkName = $fk->getName();
  8179. foreach ($records as $i => $record) {
  8180. if (isset($record[$fkName])) {
  8181. $key = $record[$fkName];
  8182. $records[$i][$fkName] = $fkValues[$key];
  8183. }
  8184. }
  8185. }
  8186. }
  8187. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  8188. {
  8189. $pkValues = array();
  8190. $pkName = $t1->getPk()->getName();
  8191. foreach ($records as $record) {
  8192. $key = $record[$pkName];
  8193. $pkValues[$key] = array();
  8194. }
  8195. return $pkValues;
  8196. }
  8197. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  8198. {
  8199. $fks = $t2->getFksTo($t1->getName());
  8200. $columnNames = $this->columns->getNames($t2, false, $params);
  8201. $pkValueKeys = implode(',', array_keys($pkValues));
  8202. $conditions = array();
  8203. foreach ($fks as $fk) {
  8204. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  8205. }
  8206. $condition = OrCondition::fromArray($conditions);
  8207. $columnOrdering = array();
  8208. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  8209. if ($limit != -1) {
  8210. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  8211. }
  8212. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  8213. $records[] = $record;
  8214. }
  8215. }
  8216. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  8217. {
  8218. $fks = $t2->getFksTo($t1->getName());
  8219. foreach ($fks as $fk) {
  8220. $fkName = $fk->getName();
  8221. foreach ($pkRecords as $pkRecord) {
  8222. $key = $pkRecord[$fkName];
  8223. if (isset($pkValues[$key])) {
  8224. $pkValues[$key][] = $pkRecord;
  8225. }
  8226. }
  8227. }
  8228. }
  8229. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  8230. {
  8231. $pkName = $t1->getPk()->getName();
  8232. $t2Name = $t2->getName();
  8233. foreach ($records as $i => $record) {
  8234. $key = $record[$pkName];
  8235. $records[$i][$t2Name] = $pkValues[$key];
  8236. }
  8237. }
  8238. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  8239. {
  8240. $pkValues = $this->getPkEmptyValues($t1, $records);
  8241. $fkValues = array();
  8242. $fk1 = $t3->getFksTo($t1->getName())[0];
  8243. $fk2 = $t3->getFksTo($t2->getName())[0];
  8244. $fk1Name = $fk1->getName();
  8245. $fk2Name = $fk2->getName();
  8246. $columnNames = array($fk1Name, $fk2Name);
  8247. $pkIds = implode(',', array_keys($pkValues));
  8248. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  8249. $columnOrdering = array();
  8250. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  8251. if ($limit != -1) {
  8252. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  8253. }
  8254. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  8255. foreach ($records as $record) {
  8256. $val1 = $record[$fk1Name];
  8257. $val2 = $record[$fk2Name];
  8258. $pkValues[$val1][] = $val2;
  8259. $fkValues[$val2] = null;
  8260. }
  8261. return new HabtmValues($pkValues, $fkValues);
  8262. }
  8263. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  8264. {
  8265. $pkName = $t1->getPk()->getName();
  8266. $t2Name = $t2->getName();
  8267. foreach ($records as $i => $record) {
  8268. $key = $record[$pkName];
  8269. $val = array();
  8270. $fks = $habtmValues->pkValues[$key];
  8271. foreach ($fks as $fk) {
  8272. $val[] = $habtmValues->fkValues[$fk];
  8273. }
  8274. $records[$i][$t2Name] = $val;
  8275. }
  8276. }
  8277. }
  8278. }
  8279. // file: src/Tqdev/PhpCrudApi/Api.php
  8280. namespace Tqdev\PhpCrudApi {
  8281. use Psr\Http\Message\ResponseInterface;
  8282. use Psr\Http\Message\ServerRequestInterface;
  8283. use Psr\Http\Server\RequestHandlerInterface;
  8284. use Tqdev\PhpCrudApi\Cache\CacheFactory;
  8285. use Tqdev\PhpCrudApi\Column\DefinitionService;
  8286. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8287. use Tqdev\PhpCrudApi\Controller\CacheController;
  8288. use Tqdev\PhpCrudApi\Controller\ColumnController;
  8289. use Tqdev\PhpCrudApi\Controller\GeoJsonController;
  8290. use Tqdev\PhpCrudApi\Controller\JsonResponder;
  8291. use Tqdev\PhpCrudApi\Controller\OpenApiController;
  8292. use Tqdev\PhpCrudApi\Controller\RecordController;
  8293. use Tqdev\PhpCrudApi\Database\GenericDB;
  8294. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  8295. use Tqdev\PhpCrudApi\Middleware\AuthorizationMiddleware;
  8296. use Tqdev\PhpCrudApi\Middleware\BasicAuthMiddleware;
  8297. use Tqdev\PhpCrudApi\Middleware\CorsMiddleware;
  8298. use Tqdev\PhpCrudApi\Middleware\CustomizationMiddleware;
  8299. use Tqdev\PhpCrudApi\Middleware\DbAuthMiddleware;
  8300. use Tqdev\PhpCrudApi\Middleware\FirewallMiddleware;
  8301. use Tqdev\PhpCrudApi\Middleware\IpAddressMiddleware;
  8302. use Tqdev\PhpCrudApi\Middleware\JoinLimitsMiddleware;
  8303. use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware;
  8304. use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware;
  8305. use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware;
  8306. use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter;
  8307. use Tqdev\PhpCrudApi\Middleware\SanitationMiddleware;
  8308. use Tqdev\PhpCrudApi\Middleware\ValidationMiddleware;
  8309. use Tqdev\PhpCrudApi\Middleware\XsrfMiddleware;
  8310. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  8311. use Tqdev\PhpCrudApi\Record\ErrorCode;
  8312. use Tqdev\PhpCrudApi\Record\RecordService;
  8313. use Tqdev\PhpCrudApi\ResponseUtils;
  8314. class Api implements RequestHandlerInterface
  8315. {
  8316. private $router;
  8317. private $responder;
  8318. private $debug;
  8319. public function __construct(Config $config)
  8320. {
  8321. $db = new GenericDB(
  8322. $config->getDriver(),
  8323. $config->getAddress(),
  8324. $config->getPort(),
  8325. $config->getDatabase(),
  8326. $config->getUsername(),
  8327. $config->getPassword()
  8328. );
  8329. $prefix = sprintf('phpcrudapi-%s-%s-%s-', $config->getDriver(), $config->getDatabase(), substr(md5(__FILE__), 0, 8));
  8330. $cache = CacheFactory::create($config->getCacheType(), $prefix, $config->getCachePath());
  8331. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  8332. $responder = new JsonResponder();
  8333. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  8334. foreach ($config->getMiddlewares() as $middleware => $properties) {
  8335. switch ($middleware) {
  8336. case 'cors':
  8337. new CorsMiddleware($router, $responder, $properties);
  8338. break;
  8339. case 'firewall':
  8340. new FirewallMiddleware($router, $responder, $properties);
  8341. break;
  8342. case 'basicAuth':
  8343. new BasicAuthMiddleware($router, $responder, $properties);
  8344. break;
  8345. case 'jwtAuth':
  8346. new JwtAuthMiddleware($router, $responder, $properties);
  8347. break;
  8348. case 'dbAuth':
  8349. new DbAuthMiddleware($router, $responder, $properties, $reflection, $db);
  8350. break;
  8351. case 'validation':
  8352. new ValidationMiddleware($router, $responder, $properties, $reflection);
  8353. break;
  8354. case 'ipAddress':
  8355. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  8356. break;
  8357. case 'sanitation':
  8358. new SanitationMiddleware($router, $responder, $properties, $reflection);
  8359. break;
  8360. case 'multiTenancy':
  8361. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  8362. break;
  8363. case 'authorization':
  8364. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  8365. break;
  8366. case 'xsrf':
  8367. new XsrfMiddleware($router, $responder, $properties);
  8368. break;
  8369. case 'pageLimits':
  8370. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  8371. break;
  8372. case 'joinLimits':
  8373. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  8374. break;
  8375. case 'customization':
  8376. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  8377. break;
  8378. }
  8379. }
  8380. foreach ($config->getControllers() as $controller) {
  8381. switch ($controller) {
  8382. case 'records':
  8383. $records = new RecordService($db, $reflection);
  8384. new RecordController($router, $responder, $records);
  8385. break;
  8386. case 'columns':
  8387. $definition = new DefinitionService($db, $reflection);
  8388. new ColumnController($router, $responder, $reflection, $definition);
  8389. break;
  8390. case 'cache':
  8391. new CacheController($router, $responder, $cache);
  8392. break;
  8393. case 'openapi':
  8394. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  8395. new OpenApiController($router, $responder, $openApi);
  8396. break;
  8397. case 'geojson':
  8398. $records = new RecordService($db, $reflection);
  8399. $geoJson = new GeoJsonService($reflection, $records);
  8400. new GeoJsonController($router, $responder, $geoJson);
  8401. break;
  8402. }
  8403. }
  8404. $this->router = $router;
  8405. $this->responder = $responder;
  8406. $this->debug = $config->getDebug();
  8407. }
  8408. private function parseBody(string $body) /*: ?object*/
  8409. {
  8410. $first = substr($body, 0, 1);
  8411. if ($first == '[' || $first == '{') {
  8412. $object = json_decode($body);
  8413. $causeCode = json_last_error();
  8414. if ($causeCode !== JSON_ERROR_NONE) {
  8415. $object = null;
  8416. }
  8417. } else {
  8418. parse_str($body, $input);
  8419. foreach ($input as $key => $value) {
  8420. if (substr($key, -9) == '__is_null') {
  8421. $input[substr($key, 0, -9)] = null;
  8422. unset($input[$key]);
  8423. }
  8424. }
  8425. $object = (object) $input;
  8426. }
  8427. return $object;
  8428. }
  8429. private function addParsedBody(ServerRequestInterface $request): ServerRequestInterface
  8430. {
  8431. $body = $request->getBody();
  8432. if ($body->isReadable() && $body->isSeekable()) {
  8433. $contents = $body->getContents();
  8434. $body->rewind();
  8435. if ($contents) {
  8436. $parsedBody = $this->parseBody($contents);
  8437. $request = $request->withParsedBody($parsedBody);
  8438. }
  8439. }
  8440. return $request;
  8441. }
  8442. public function handle(ServerRequestInterface $request): ResponseInterface
  8443. {
  8444. $response = null;
  8445. try {
  8446. $response = $this->router->route($this->addParsedBody($request));
  8447. } catch (\Throwable $e) {
  8448. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  8449. if ($this->debug) {
  8450. $response = ResponseUtils::addExceptionHeaders($response, $e);
  8451. }
  8452. }
  8453. return $response;
  8454. }
  8455. }
  8456. }
  8457. // file: src/Tqdev/PhpCrudApi/Config.php
  8458. namespace Tqdev\PhpCrudApi {
  8459. class Config
  8460. {
  8461. private $values = [
  8462. 'driver' => null,
  8463. 'address' => 'localhost',
  8464. 'port' => null,
  8465. 'username' => null,
  8466. 'password' => null,
  8467. 'database' => null,
  8468. 'middlewares' => 'cors',
  8469. 'controllers' => 'records,geojson,openapi',
  8470. 'cacheType' => 'TempFile',
  8471. 'cachePath' => '',
  8472. 'cacheTime' => 10,
  8473. 'debug' => false,
  8474. 'basePath' => '',
  8475. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  8476. ];
  8477. private function getDefaultDriver(array $values): string
  8478. {
  8479. if (isset($values['driver'])) {
  8480. return $values['driver'];
  8481. }
  8482. return 'mysql';
  8483. }
  8484. private function getDefaultPort(string $driver): int
  8485. {
  8486. switch ($driver) {
  8487. case 'mysql':return 3306;
  8488. case 'pgsql':return 5432;
  8489. case 'sqlsrv':return 1433;
  8490. }
  8491. }
  8492. private function getDefaultAddress(string $driver): string
  8493. {
  8494. switch ($driver) {
  8495. case 'mysql':return 'localhost';
  8496. case 'pgsql':return 'localhost';
  8497. case 'sqlsrv':return 'localhost';
  8498. }
  8499. }
  8500. private function getDriverDefaults(string $driver): array
  8501. {
  8502. return [
  8503. 'driver' => $driver,
  8504. 'address' => $this->getDefaultAddress($driver),
  8505. 'port' => $this->getDefaultPort($driver),
  8506. ];
  8507. }
  8508. public function __construct(array $values)
  8509. {
  8510. $driver = $this->getDefaultDriver($values);
  8511. $defaults = $this->getDriverDefaults($driver);
  8512. $newValues = array_merge($this->values, $defaults, $values);
  8513. $newValues = $this->parseMiddlewares($newValues);
  8514. $diff = array_diff_key($newValues, $this->values);
  8515. if (!empty($diff)) {
  8516. $key = array_keys($diff)[0];
  8517. throw new \Exception("Config has invalid value '$key'");
  8518. }
  8519. $this->values = $newValues;
  8520. }
  8521. private function parseMiddlewares(array $values): array
  8522. {
  8523. $newValues = array();
  8524. $properties = array();
  8525. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  8526. foreach ($middlewares as $middleware) {
  8527. $properties[$middleware] = [];
  8528. }
  8529. foreach ($values as $key => $value) {
  8530. if (strpos($key, '.') === false) {
  8531. $newValues[$key] = $value;
  8532. } else {
  8533. list($middleware, $key2) = explode('.', $key, 2);
  8534. if (isset($properties[$middleware])) {
  8535. $properties[$middleware][$key2] = $value;
  8536. } else {
  8537. throw new \Exception("Config has invalid value '$key'");
  8538. }
  8539. }
  8540. }
  8541. $newValues['middlewares'] = array_reverse($properties, true);
  8542. return $newValues;
  8543. }
  8544. public function getDriver(): string
  8545. {
  8546. return $this->values['driver'];
  8547. }
  8548. public function getAddress(): string
  8549. {
  8550. return $this->values['address'];
  8551. }
  8552. public function getPort(): int
  8553. {
  8554. return $this->values['port'];
  8555. }
  8556. public function getUsername(): string
  8557. {
  8558. return $this->values['username'];
  8559. }
  8560. public function getPassword(): string
  8561. {
  8562. return $this->values['password'];
  8563. }
  8564. public function getDatabase(): string
  8565. {
  8566. return $this->values['database'];
  8567. }
  8568. public function getMiddlewares(): array
  8569. {
  8570. return $this->values['middlewares'];
  8571. }
  8572. public function getControllers(): array
  8573. {
  8574. return array_map('trim', explode(',', $this->values['controllers']));
  8575. }
  8576. public function getCacheType(): string
  8577. {
  8578. return $this->values['cacheType'];
  8579. }
  8580. public function getCachePath(): string
  8581. {
  8582. return $this->values['cachePath'];
  8583. }
  8584. public function getCacheTime(): int
  8585. {
  8586. return $this->values['cacheTime'];
  8587. }
  8588. public function getDebug(): bool
  8589. {
  8590. return $this->values['debug'];
  8591. }
  8592. public function getBasePath(): string
  8593. {
  8594. return $this->values['basePath'];
  8595. }
  8596. public function getOpenApiBase(): array
  8597. {
  8598. return json_decode($this->values['openApiBase'], true);
  8599. }
  8600. }
  8601. }
  8602. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  8603. namespace Tqdev\PhpCrudApi {
  8604. use Nyholm\Psr7Server\ServerRequestCreator;
  8605. use Nyholm\Psr7\Factory\Psr17Factory;
  8606. use Psr\Http\Message\ServerRequestInterface;
  8607. class RequestFactory
  8608. {
  8609. public static function fromGlobals(): ServerRequestInterface
  8610. {
  8611. $psr17Factory = new Psr17Factory();
  8612. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  8613. $serverRequest = $creator->fromGlobals();
  8614. $stream = $psr17Factory->createStreamFromFile('php://input');
  8615. $serverRequest = $serverRequest->withBody($stream);
  8616. return $serverRequest;
  8617. }
  8618. public static function fromString(string $request): ServerRequestInterface
  8619. {
  8620. $parts = explode("\n\n", trim($request), 2);
  8621. $lines = explode("\n", $parts[0]);
  8622. $first = explode(' ', trim(array_shift($lines)), 2);
  8623. $method = $first[0];
  8624. $body = isset($parts[1]) ? $parts[1] : '';
  8625. $url = isset($first[1]) ? $first[1] : '';
  8626. $psr17Factory = new Psr17Factory();
  8627. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  8628. foreach ($lines as $line) {
  8629. list($key, $value) = explode(':', $line, 2);
  8630. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  8631. }
  8632. if ($body) {
  8633. $stream = $psr17Factory->createStream($body);
  8634. $stream->rewind();
  8635. $serverRequest = $serverRequest->withBody($stream);
  8636. }
  8637. return $serverRequest;
  8638. }
  8639. }
  8640. }
  8641. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  8642. namespace Tqdev\PhpCrudApi {
  8643. use Psr\Http\Message\ServerRequestInterface;
  8644. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8645. class RequestUtils
  8646. {
  8647. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  8648. {
  8649. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  8650. return $request->withUri($request->getUri()->withQuery($query));
  8651. }
  8652. public static function getHeader(ServerRequestInterface $request, string $header): string
  8653. {
  8654. $headers = $request->getHeader($header);
  8655. return isset($headers[0]) ? $headers[0] : '';
  8656. }
  8657. public static function getParams(ServerRequestInterface $request): array
  8658. {
  8659. $params = array();
  8660. $query = $request->getUri()->getQuery();
  8661. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  8662. parse_str($query, $params);
  8663. return $params;
  8664. }
  8665. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  8666. {
  8667. $path = $request->getUri()->getPath();
  8668. $pathSegments = explode('/', rtrim($path, '/'));
  8669. if ($part < 0 || $part >= count($pathSegments)) {
  8670. return '';
  8671. }
  8672. return urldecode($pathSegments[$part]);
  8673. }
  8674. public static function getOperation(ServerRequestInterface $request): string
  8675. {
  8676. $method = $request->getMethod();
  8677. $path = RequestUtils::getPathSegment($request, 1);
  8678. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  8679. switch ($path) {
  8680. case 'openapi':
  8681. return 'document';
  8682. case 'columns':
  8683. return $method == 'get' ? 'reflect' : 'remodel';
  8684. case 'records':
  8685. switch ($method) {
  8686. case 'POST':
  8687. return 'create';
  8688. case 'GET':
  8689. return $hasPk ? 'read' : 'list';
  8690. case 'PUT':
  8691. return 'update';
  8692. case 'DELETE':
  8693. return 'delete';
  8694. case 'PATCH':
  8695. return 'increment';
  8696. }
  8697. }
  8698. return 'unknown';
  8699. }
  8700. private static function getJoinTables(string $tableName, array $parameters): array
  8701. {
  8702. $uniqueTableNames = array();
  8703. $uniqueTableNames[$tableName] = true;
  8704. if (isset($parameters['join'])) {
  8705. foreach ($parameters['join'] as $parameter) {
  8706. $tableNames = explode(',', trim($parameter));
  8707. foreach ($tableNames as $tableName) {
  8708. $uniqueTableNames[$tableName] = true;
  8709. }
  8710. }
  8711. }
  8712. return array_keys($uniqueTableNames);
  8713. }
  8714. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  8715. {
  8716. $path = RequestUtils::getPathSegment($request, 1);
  8717. $tableName = RequestUtils::getPathSegment($request, 2);
  8718. $allTableNames = $reflection->getTableNames();
  8719. switch ($path) {
  8720. case 'openapi':
  8721. return $allTableNames;
  8722. case 'columns':
  8723. return $tableName ? [$tableName] : $allTableNames;
  8724. case 'records':
  8725. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  8726. }
  8727. return $allTableNames;
  8728. }
  8729. }
  8730. }
  8731. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  8732. namespace Tqdev\PhpCrudApi {
  8733. use Nyholm\Psr7\Factory\Psr17Factory;
  8734. use Psr\Http\Message\ResponseInterface;
  8735. class ResponseFactory
  8736. {
  8737. const OK = 200;
  8738. const UNAUTHORIZED = 401;
  8739. const FORBIDDEN = 403;
  8740. const NOT_FOUND = 404;
  8741. const METHOD_NOT_ALLOWED = 405;
  8742. const CONFLICT = 409;
  8743. const UNPROCESSABLE_ENTITY = 422;
  8744. const INTERNAL_SERVER_ERROR = 500;
  8745. public static function fromHtml(int $status, string $html): ResponseInterface
  8746. {
  8747. return self::from($status, 'text/html', $html);
  8748. }
  8749. public static function fromObject(int $status, $body): ResponseInterface
  8750. {
  8751. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  8752. return self::from($status, 'application/json', $content);
  8753. }
  8754. private static function from(int $status, string $contentType, string $content): ResponseInterface
  8755. {
  8756. $psr17Factory = new Psr17Factory();
  8757. $response = $psr17Factory->createResponse($status);
  8758. $stream = $psr17Factory->createStream($content);
  8759. $stream->rewind();
  8760. $response = $response->withBody($stream);
  8761. $response = $response->withHeader('Content-Type', $contentType);
  8762. $response = $response->withHeader('Content-Length', strlen($content));
  8763. return $response;
  8764. }
  8765. public static function fromStatus(int $status): ResponseInterface
  8766. {
  8767. $psr17Factory = new Psr17Factory();
  8768. return $psr17Factory->createResponse($status);
  8769. }
  8770. }
  8771. }
  8772. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  8773. namespace Tqdev\PhpCrudApi {
  8774. use Psr\Http\Message\ResponseInterface;
  8775. class ResponseUtils
  8776. {
  8777. public static function output(ResponseInterface $response)
  8778. {
  8779. $status = $response->getStatusCode();
  8780. $headers = $response->getHeaders();
  8781. $body = $response->getBody()->getContents();
  8782. http_response_code($status);
  8783. foreach ($headers as $key => $values) {
  8784. foreach ($values as $value) {
  8785. header("$key: $value");
  8786. }
  8787. }
  8788. echo $body;
  8789. }
  8790. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  8791. {
  8792. $response = $response->withHeader('X-Exception-Name', get_class($e));
  8793. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  8794. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  8795. return $response;
  8796. }
  8797. public static function toString(ResponseInterface $response): string
  8798. {
  8799. $status = $response->getStatusCode();
  8800. $headers = $response->getHeaders();
  8801. $body = $response->getBody()->getContents();
  8802. $str = "$status\n";
  8803. foreach ($headers as $key => $values) {
  8804. foreach ($values as $value) {
  8805. $str .= "$key: $value\n";
  8806. }
  8807. }
  8808. if ($body !== '') {
  8809. $str .= "\n";
  8810. $str .= "$body\n";
  8811. }
  8812. return $str;
  8813. }
  8814. }
  8815. }
  8816. // file: src/index.php
  8817. namespace Tqdev\PhpCrudApi {
  8818. use Tqdev\PhpCrudApi\Api;
  8819. use Tqdev\PhpCrudApi\Config;
  8820. use Tqdev\PhpCrudApi\RequestFactory;
  8821. use Tqdev\PhpCrudApi\ResponseUtils;
  8822. $config = new Config([
  8823. 'username' => 'php-crud-api',
  8824. 'password' => 'php-crud-api',
  8825. 'database' => 'php-crud-api',
  8826. ]);
  8827. $request = RequestFactory::fromGlobals();
  8828. $api = new Api($config);
  8829. $response = $api->handle($request);
  8830. ResponseUtils::output($response);
  8831. }