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 253KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740
  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. namespace Tqdev\PhpCrudApi;
  14. // file: vendor/psr/http-factory/src/RequestFactoryInterface.php
  15. interface RequestFactoryInterface
  16. {
  17. public function createRequest(string $method, $uri): RequestInterface;
  18. }
  19. // file: vendor/psr/http-factory/src/ResponseFactoryInterface.php
  20. interface ResponseFactoryInterface
  21. {
  22. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface;
  23. }
  24. // file: vendor/psr/http-factory/src/ServerRequestFactoryInterface.php
  25. interface ServerRequestFactoryInterface
  26. {
  27. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface;
  28. }
  29. // file: vendor/psr/http-factory/src/StreamFactoryInterface.php
  30. interface StreamFactoryInterface
  31. {
  32. public function createStream(string $content = ''): StreamInterface;
  33. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface;
  34. public function createStreamFromResource($resource): StreamInterface;
  35. }
  36. // file: vendor/psr/http-factory/src/UploadedFileFactoryInterface.php
  37. interface UploadedFileFactoryInterface
  38. {
  39. public function createUploadedFile(
  40. StreamInterface $stream,
  41. int $size = null,
  42. int $error = \UPLOAD_ERR_OK,
  43. string $clientFilename = null,
  44. string $clientMediaType = null
  45. ): UploadedFileInterface;
  46. }
  47. // file: vendor/psr/http-factory/src/UriFactoryInterface.php
  48. interface UriFactoryInterface
  49. {
  50. public function createUri(string $uri = ''): UriInterface;
  51. }
  52. // file: vendor/psr/http-message/src/MessageInterface.php
  53. interface MessageInterface
  54. {
  55. public function getProtocolVersion();
  56. public function withProtocolVersion($version);
  57. public function getHeaders();
  58. public function hasHeader($name);
  59. public function getHeader($name);
  60. public function getHeaderLine($name);
  61. public function withHeader($name, $value);
  62. public function withAddedHeader($name, $value);
  63. public function withoutHeader($name);
  64. public function getBody();
  65. public function withBody(StreamInterface $body);
  66. }
  67. // file: vendor/psr/http-message/src/RequestInterface.php
  68. interface RequestInterface extends MessageInterface
  69. {
  70. public function getRequestTarget();
  71. public function withRequestTarget($requestTarget);
  72. public function getMethod();
  73. public function withMethod($method);
  74. public function getUri();
  75. public function withUri(UriInterface $uri, $preserveHost = false);
  76. }
  77. // file: vendor/psr/http-message/src/ResponseInterface.php
  78. interface ResponseInterface extends MessageInterface
  79. {
  80. public function getStatusCode();
  81. public function withStatus($code, $reasonPhrase = '');
  82. public function getReasonPhrase();
  83. }
  84. // file: vendor/psr/http-message/src/ServerRequestInterface.php
  85. interface ServerRequestInterface extends RequestInterface
  86. {
  87. public function getServerParams();
  88. public function getCookieParams();
  89. public function withCookieParams(array $cookies);
  90. public function getQueryParams();
  91. public function withQueryParams(array $query);
  92. public function getUploadedFiles();
  93. public function withUploadedFiles(array $uploadedFiles);
  94. public function getParsedBody();
  95. public function withParsedBody($data);
  96. public function getAttributes();
  97. public function getAttribute($name, $default = null);
  98. public function withAttribute($name, $value);
  99. public function withoutAttribute($name);
  100. }
  101. // file: vendor/psr/http-message/src/StreamInterface.php
  102. interface StreamInterface
  103. {
  104. public function __toString();
  105. public function close();
  106. public function detach();
  107. public function getSize();
  108. public function tell();
  109. public function eof();
  110. public function isSeekable();
  111. public function seek($offset, $whence = SEEK_SET);
  112. public function rewind();
  113. public function isWritable();
  114. public function write($string);
  115. public function isReadable();
  116. public function read($length);
  117. public function getContents();
  118. public function getMetadata($key = null);
  119. }
  120. // file: vendor/psr/http-message/src/UploadedFileInterface.php
  121. interface UploadedFileInterface
  122. {
  123. public function getStream();
  124. public function moveTo($targetPath);
  125. public function getSize();
  126. public function getError();
  127. public function getClientFilename();
  128. public function getClientMediaType();
  129. }
  130. // file: vendor/psr/http-message/src/UriInterface.php
  131. interface UriInterface
  132. {
  133. public function getScheme();
  134. public function getAuthority();
  135. public function getUserInfo();
  136. public function getHost();
  137. public function getPort();
  138. public function getPath();
  139. public function getQuery();
  140. public function getFragment();
  141. public function withScheme($scheme);
  142. public function withUserInfo($user, $password = null);
  143. public function withHost($host);
  144. public function withPort($port);
  145. public function withPath($path);
  146. public function withQuery($query);
  147. public function withFragment($fragment);
  148. public function __toString();
  149. }
  150. // file: vendor/psr/http-server-handler/src/RequestHandlerInterface.php
  151. interface RequestHandlerInterface
  152. {
  153. public function handle(ServerRequestInterface $request): ResponseInterface;
  154. }
  155. // file: vendor/psr/http-server-middleware/src/MiddlewareInterface.php
  156. interface MiddlewareInterface
  157. {
  158. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
  159. }
  160. // file: vendor/nyholm/psr7/src/Factory/Psr17Factory.php
  161. final class Psr17Factory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
  162. {
  163. public function createRequest(string $method, $uri): RequestInterface
  164. {
  165. return new Request($method, $uri);
  166. }
  167. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface
  168. {
  169. return new Response($code, [], null, '1.1', $reasonPhrase);
  170. }
  171. public function createStream(string $content = ''): StreamInterface
  172. {
  173. return Stream::create($content);
  174. }
  175. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
  176. {
  177. $resource = @\fopen($filename, $mode);
  178. if (false === $resource) {
  179. if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'])) {
  180. throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.');
  181. }
  182. throw new \RuntimeException('The file ' . $filename . ' cannot be opened.');
  183. }
  184. return Stream::create($resource);
  185. }
  186. public function createStreamFromResource($resource): StreamInterface
  187. {
  188. return Stream::create($resource);
  189. }
  190. public function createUploadedFile(StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null): UploadedFileInterface
  191. {
  192. if (null === $size) {
  193. $size = $stream->getSize();
  194. }
  195. return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);
  196. }
  197. public function createUri(string $uri = ''): UriInterface
  198. {
  199. return new Uri($uri);
  200. }
  201. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  202. {
  203. return new ServerRequest($method, $uri, [], null, '1.1', $serverParams);
  204. }
  205. }
  206. // file: vendor/nyholm/psr7/src/MessageTrait.php
  207. trait MessageTrait
  208. {
  209. private $headers = [];
  210. private $headerNames = [];
  211. private $protocol = '1.1';
  212. private $stream;
  213. public function getProtocolVersion(): string
  214. {
  215. return $this->protocol;
  216. }
  217. public function withProtocolVersion($version): self
  218. {
  219. if ($this->protocol === $version) {
  220. return $this;
  221. }
  222. $new = clone $this;
  223. $new->protocol = $version;
  224. return $new;
  225. }
  226. public function getHeaders(): array
  227. {
  228. return $this->headers;
  229. }
  230. public function hasHeader($header): bool
  231. {
  232. return isset($this->headerNames[\strtolower($header)]);
  233. }
  234. public function getHeader($header): array
  235. {
  236. $header = \strtolower($header);
  237. if (!isset($this->headerNames[$header])) {
  238. return [];
  239. }
  240. $header = $this->headerNames[$header];
  241. return $this->headers[$header];
  242. }
  243. public function getHeaderLine($header): string
  244. {
  245. return \implode(', ', $this->getHeader($header));
  246. }
  247. public function withHeader($header, $value): self
  248. {
  249. $value = $this->validateAndTrimHeader($header, $value);
  250. $normalized = \strtolower($header);
  251. $new = clone $this;
  252. if (isset($new->headerNames[$normalized])) {
  253. unset($new->headers[$new->headerNames[$normalized]]);
  254. }
  255. $new->headerNames[$normalized] = $header;
  256. $new->headers[$header] = $value;
  257. return $new;
  258. }
  259. public function withAddedHeader($header, $value): self
  260. {
  261. if (!\is_string($header) || '' === $header) {
  262. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  263. }
  264. $new = clone $this;
  265. $new->setHeaders([$header => $value]);
  266. return $new;
  267. }
  268. public function withoutHeader($header): self
  269. {
  270. $normalized = \strtolower($header);
  271. if (!isset($this->headerNames[$normalized])) {
  272. return $this;
  273. }
  274. $header = $this->headerNames[$normalized];
  275. $new = clone $this;
  276. unset($new->headers[$header], $new->headerNames[$normalized]);
  277. return $new;
  278. }
  279. public function getBody(): StreamInterface
  280. {
  281. if (null === $this->stream) {
  282. $this->stream = Stream::create('');
  283. }
  284. return $this->stream;
  285. }
  286. public function withBody(StreamInterface $body): self
  287. {
  288. if ($body === $this->stream) {
  289. return $this;
  290. }
  291. $new = clone $this;
  292. $new->stream = $body;
  293. return $new;
  294. }
  295. private function setHeaders(array $headers) /*:void*/
  296. {
  297. foreach ($headers as $header => $value) {
  298. $value = $this->validateAndTrimHeader($header, $value);
  299. $normalized = \strtolower($header);
  300. if (isset($this->headerNames[$normalized])) {
  301. $header = $this->headerNames[$normalized];
  302. $this->headers[$header] = \array_merge($this->headers[$header], $value);
  303. } else {
  304. $this->headerNames[$normalized] = $header;
  305. $this->headers[$header] = $value;
  306. }
  307. }
  308. }
  309. private function validateAndTrimHeader($header, $values): array
  310. {
  311. if (!\is_string($header) || 1 !== \preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@", $header)) {
  312. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  313. }
  314. if (!\is_array($values)) {
  315. if ((!\is_numeric($values) && !\is_string($values)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $values)) {
  316. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  317. }
  318. return [\trim((string) $values, " \t")];
  319. }
  320. if (empty($values)) {
  321. throw new \InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
  322. }
  323. $returnValues = [];
  324. foreach ($values as $v) {
  325. if ((!\is_numeric($v) && !\is_string($v)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $v)) {
  326. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  327. }
  328. $returnValues[] = \trim((string) $v, " \t");
  329. }
  330. return $returnValues;
  331. }
  332. }
  333. // file: vendor/nyholm/psr7/src/Request.php
  334. final class Request implements RequestInterface
  335. {
  336. use MessageTrait;
  337. use RequestTrait;
  338. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
  339. {
  340. if (!($uri instanceof UriInterface)) {
  341. $uri = new Uri($uri);
  342. }
  343. $this->method = $method;
  344. $this->uri = $uri;
  345. $this->setHeaders($headers);
  346. $this->protocol = $version;
  347. if (!$this->hasHeader('Host')) {
  348. $this->updateHostFromUri();
  349. }
  350. if ('' !== $body && null !== $body) {
  351. $this->stream = Stream::create($body);
  352. }
  353. }
  354. }
  355. // file: vendor/nyholm/psr7/src/RequestTrait.php
  356. trait RequestTrait
  357. {
  358. private $method;
  359. private $requestTarget;
  360. private $uri;
  361. public function getRequestTarget(): string
  362. {
  363. if (null !== $this->requestTarget) {
  364. return $this->requestTarget;
  365. }
  366. if ('' === $target = $this->uri->getPath()) {
  367. $target = '/';
  368. }
  369. if ('' !== $this->uri->getQuery()) {
  370. $target .= '?' . $this->uri->getQuery();
  371. }
  372. return $target;
  373. }
  374. public function withRequestTarget($requestTarget): self
  375. {
  376. if (\preg_match('#\s#', $requestTarget)) {
  377. throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
  378. }
  379. $new = clone $this;
  380. $new->requestTarget = $requestTarget;
  381. return $new;
  382. }
  383. public function getMethod(): string
  384. {
  385. return $this->method;
  386. }
  387. public function withMethod($method): self
  388. {
  389. if (!\is_string($method)) {
  390. throw new \InvalidArgumentException('Method must be a string');
  391. }
  392. $new = clone $this;
  393. $new->method = $method;
  394. return $new;
  395. }
  396. public function getUri(): UriInterface
  397. {
  398. return $this->uri;
  399. }
  400. public function withUri(UriInterface $uri, $preserveHost = false): self
  401. {
  402. if ($uri === $this->uri) {
  403. return $this;
  404. }
  405. $new = clone $this;
  406. $new->uri = $uri;
  407. if (!$preserveHost || !$this->hasHeader('Host')) {
  408. $new->updateHostFromUri();
  409. }
  410. return $new;
  411. }
  412. private function updateHostFromUri() /*:void*/
  413. {
  414. if ('' === $host = $this->uri->getHost()) {
  415. return;
  416. }
  417. if (null !== ($port = $this->uri->getPort())) {
  418. $host .= ':' . $port;
  419. }
  420. if (isset($this->headerNames['host'])) {
  421. $header = $this->headerNames['host'];
  422. } else {
  423. $this->headerNames['host'] = $header = 'Host';
  424. }
  425. $this->headers = [$header => [$host]] + $this->headers;
  426. }
  427. }
  428. // file: vendor/nyholm/psr7/src/Response.php
  429. final class Response implements ResponseInterface
  430. {
  431. use MessageTrait;
  432. /*private*/ const PHRASES = [
  433. 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing',
  434. 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',
  435. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect',
  436. 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',
  437. 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',
  438. ];
  439. private $reasonPhrase = '';
  440. private $statusCode;
  441. public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
  442. {
  443. if ('' !== $body && null !== $body) {
  444. $this->stream = Stream::create($body);
  445. }
  446. $this->statusCode = $status;
  447. $this->setHeaders($headers);
  448. if (null === $reason && isset(self::PHRASES[$this->statusCode])) {
  449. $this->reasonPhrase = self::PHRASES[$status];
  450. } else {
  451. $this->reasonPhrase = $reason;
  452. }
  453. $this->protocol = $version;
  454. }
  455. public function getStatusCode(): int
  456. {
  457. return $this->statusCode;
  458. }
  459. public function getReasonPhrase(): string
  460. {
  461. return $this->reasonPhrase;
  462. }
  463. public function withStatus($code, $reasonPhrase = ''): self
  464. {
  465. if (!\is_int($code) && !\is_string($code)) {
  466. throw new \InvalidArgumentException('Status code has to be an integer');
  467. }
  468. $code = (int) $code;
  469. if ($code < 100 || $code > 599) {
  470. throw new \InvalidArgumentException('Status code has to be an integer between 100 and 599');
  471. }
  472. $new = clone $this;
  473. $new->statusCode = $code;
  474. if ((null === $reasonPhrase || '' === $reasonPhrase) && isset(self::PHRASES[$new->statusCode])) {
  475. $reasonPhrase = self::PHRASES[$new->statusCode];
  476. }
  477. $new->reasonPhrase = $reasonPhrase;
  478. return $new;
  479. }
  480. }
  481. // file: vendor/nyholm/psr7/src/ServerRequest.php
  482. final class ServerRequest implements ServerRequestInterface
  483. {
  484. use MessageTrait;
  485. use RequestTrait;
  486. private $attributes = [];
  487. private $cookieParams = [];
  488. private $parsedBody;
  489. private $queryParams = [];
  490. private $serverParams;
  491. private $uploadedFiles = [];
  492. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
  493. {
  494. $this->serverParams = $serverParams;
  495. if (!($uri instanceof UriInterface)) {
  496. $uri = new Uri($uri);
  497. }
  498. $this->method = $method;
  499. $this->uri = $uri;
  500. $this->setHeaders($headers);
  501. $this->protocol = $version;
  502. if (!$this->hasHeader('Host')) {
  503. $this->updateHostFromUri();
  504. }
  505. if ('' !== $body && null !== $body) {
  506. $this->stream = Stream::create($body);
  507. }
  508. }
  509. public function getServerParams(): array
  510. {
  511. return $this->serverParams;
  512. }
  513. public function getUploadedFiles(): array
  514. {
  515. return $this->uploadedFiles;
  516. }
  517. public function withUploadedFiles(array $uploadedFiles)
  518. {
  519. $new = clone $this;
  520. $new->uploadedFiles = $uploadedFiles;
  521. return $new;
  522. }
  523. public function getCookieParams(): array
  524. {
  525. return $this->cookieParams;
  526. }
  527. public function withCookieParams(array $cookies)
  528. {
  529. $new = clone $this;
  530. $new->cookieParams = $cookies;
  531. return $new;
  532. }
  533. public function getQueryParams(): array
  534. {
  535. return $this->queryParams;
  536. }
  537. public function withQueryParams(array $query)
  538. {
  539. $new = clone $this;
  540. $new->queryParams = $query;
  541. return $new;
  542. }
  543. public function getParsedBody()
  544. {
  545. return $this->parsedBody;
  546. }
  547. public function withParsedBody($data)
  548. {
  549. if (!\is_array($data) && !\is_object($data) && null !== $data) {
  550. throw new \InvalidArgumentException('First parameter to withParsedBody MUST be object, array or null');
  551. }
  552. $new = clone $this;
  553. $new->parsedBody = $data;
  554. return $new;
  555. }
  556. public function getAttributes(): array
  557. {
  558. return $this->attributes;
  559. }
  560. public function getAttribute($attribute, $default = null)
  561. {
  562. if (false === \array_key_exists($attribute, $this->attributes)) {
  563. return $default;
  564. }
  565. return $this->attributes[$attribute];
  566. }
  567. public function withAttribute($attribute, $value): self
  568. {
  569. $new = clone $this;
  570. $new->attributes[$attribute] = $value;
  571. return $new;
  572. }
  573. public function withoutAttribute($attribute): self
  574. {
  575. if (false === \array_key_exists($attribute, $this->attributes)) {
  576. return $this;
  577. }
  578. $new = clone $this;
  579. unset($new->attributes[$attribute]);
  580. return $new;
  581. }
  582. }
  583. // file: vendor/nyholm/psr7/src/Stream.php
  584. final class Stream implements StreamInterface
  585. {
  586. private $stream;
  587. private $seekable;
  588. private $readable;
  589. private $writable;
  590. private $uri;
  591. private $size;
  592. /*private*/ const READ_WRITE_HASH = [
  593. 'read' => [
  594. 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
  595. 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
  596. 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
  597. 'x+t' => true, 'c+t' => true, 'a+' => true,
  598. ],
  599. 'write' => [
  600. 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
  601. 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
  602. 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
  603. 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
  604. ],
  605. ];
  606. private function __construct()
  607. {
  608. }
  609. public static function create($body = ''): StreamInterface
  610. {
  611. if ($body instanceof StreamInterface) {
  612. return $body;
  613. }
  614. if (\is_string($body)) {
  615. $resource = \fopen('php://temp', 'rw+');
  616. \fwrite($resource, $body);
  617. $body = $resource;
  618. }
  619. if (\is_resource($body)) {
  620. $new = new self();
  621. $new->stream = $body;
  622. $meta = \stream_get_meta_data($new->stream);
  623. $new->seekable = $meta['seekable'];
  624. $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]);
  625. $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]);
  626. $new->uri = $new->getMetadata('uri');
  627. return $new;
  628. }
  629. throw new \InvalidArgumentException('First argument to Stream::create() must be a string, resource or StreamInterface.');
  630. }
  631. public function __destruct()
  632. {
  633. $this->close();
  634. }
  635. public function __toString(): string
  636. {
  637. try {
  638. if ($this->isSeekable()) {
  639. $this->seek(0);
  640. }
  641. return $this->getContents();
  642. } catch (\Exception $e) {
  643. return '';
  644. }
  645. }
  646. public function close() /*:void*/
  647. {
  648. if (isset($this->stream)) {
  649. if (\is_resource($this->stream)) {
  650. \fclose($this->stream);
  651. }
  652. $this->detach();
  653. }
  654. }
  655. public function detach()
  656. {
  657. if (!isset($this->stream)) {
  658. return null;
  659. }
  660. $result = $this->stream;
  661. unset($this->stream);
  662. $this->size = $this->uri = null;
  663. $this->readable = $this->writable = $this->seekable = false;
  664. return $result;
  665. }
  666. public function getSize() /*:?int*/
  667. {
  668. if (null !== $this->size) {
  669. return $this->size;
  670. }
  671. if (!isset($this->stream)) {
  672. return null;
  673. }
  674. if ($this->uri) {
  675. \clearstatcache(true, $this->uri);
  676. }
  677. $stats = \fstat($this->stream);
  678. if (isset($stats['size'])) {
  679. $this->size = $stats['size'];
  680. return $this->size;
  681. }
  682. return null;
  683. }
  684. public function tell(): int
  685. {
  686. if (false === $result = \ftell($this->stream)) {
  687. throw new \RuntimeException('Unable to determine stream position');
  688. }
  689. return $result;
  690. }
  691. public function eof(): bool
  692. {
  693. return !$this->stream || \feof($this->stream);
  694. }
  695. public function isSeekable(): bool
  696. {
  697. return $this->seekable;
  698. }
  699. public function seek($offset, $whence = \SEEK_SET) /*:void*/
  700. {
  701. if (!$this->seekable) {
  702. throw new \RuntimeException('Stream is not seekable');
  703. }
  704. if (-1 === \fseek($this->stream, $offset, $whence)) {
  705. throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, true));
  706. }
  707. }
  708. public function rewind() /*:void*/
  709. {
  710. $this->seek(0);
  711. }
  712. public function isWritable(): bool
  713. {
  714. return $this->writable;
  715. }
  716. public function write($string): int
  717. {
  718. if (!$this->writable) {
  719. throw new \RuntimeException('Cannot write to a non-writable stream');
  720. }
  721. $this->size = null;
  722. if (false === $result = \fwrite($this->stream, $string)) {
  723. throw new \RuntimeException('Unable to write to stream');
  724. }
  725. return $result;
  726. }
  727. public function isReadable(): bool
  728. {
  729. return $this->readable;
  730. }
  731. public function read($length): string
  732. {
  733. if (!$this->readable) {
  734. throw new \RuntimeException('Cannot read from non-readable stream');
  735. }
  736. return \fread($this->stream, $length);
  737. }
  738. public function getContents(): string
  739. {
  740. if (!isset($this->stream)) {
  741. throw new \RuntimeException('Unable to read stream contents');
  742. }
  743. if (false === $contents = \stream_get_contents($this->stream)) {
  744. throw new \RuntimeException('Unable to read stream contents');
  745. }
  746. return $contents;
  747. }
  748. public function getMetadata($key = null)
  749. {
  750. if (!isset($this->stream)) {
  751. return $key ? null : [];
  752. }
  753. $meta = \stream_get_meta_data($this->stream);
  754. if (null === $key) {
  755. return $meta;
  756. }
  757. return $meta[$key] ?? null;
  758. }
  759. }
  760. // file: vendor/nyholm/psr7/src/UploadedFile.php
  761. final class UploadedFile implements UploadedFileInterface
  762. {
  763. /*private*/ const ERRORS = [
  764. \UPLOAD_ERR_OK => 1,
  765. \UPLOAD_ERR_INI_SIZE => 1,
  766. \UPLOAD_ERR_FORM_SIZE => 1,
  767. \UPLOAD_ERR_PARTIAL => 1,
  768. \UPLOAD_ERR_NO_FILE => 1,
  769. \UPLOAD_ERR_NO_TMP_DIR => 1,
  770. \UPLOAD_ERR_CANT_WRITE => 1,
  771. \UPLOAD_ERR_EXTENSION => 1,
  772. ];
  773. private $clientFilename;
  774. private $clientMediaType;
  775. private $error;
  776. private $file;
  777. private $moved = false;
  778. private $size;
  779. private $stream;
  780. public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
  781. {
  782. if (false === \is_int($errorStatus) || !isset(self::ERRORS[$errorStatus])) {
  783. throw new \InvalidArgumentException('Upload file error status must be an integer value and one of the "UPLOAD_ERR_*" constants.');
  784. }
  785. if (false === \is_int($size)) {
  786. throw new \InvalidArgumentException('Upload file size must be an integer');
  787. }
  788. if (null !== $clientFilename && !\is_string($clientFilename)) {
  789. throw new \InvalidArgumentException('Upload file client filename must be a string or null');
  790. }
  791. if (null !== $clientMediaType && !\is_string($clientMediaType)) {
  792. throw new \InvalidArgumentException('Upload file client media type must be a string or null');
  793. }
  794. $this->error = $errorStatus;
  795. $this->size = $size;
  796. $this->clientFilename = $clientFilename;
  797. $this->clientMediaType = $clientMediaType;
  798. if (\UPLOAD_ERR_OK === $this->error) {
  799. if (\is_string($streamOrFile)) {
  800. $this->file = $streamOrFile;
  801. } elseif (\is_resource($streamOrFile)) {
  802. $this->stream = Stream::create($streamOrFile);
  803. } elseif ($streamOrFile instanceof StreamInterface) {
  804. $this->stream = $streamOrFile;
  805. } else {
  806. throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile');
  807. }
  808. }
  809. }
  810. private function validateActive() /*:void*/
  811. {
  812. if (\UPLOAD_ERR_OK !== $this->error) {
  813. throw new \RuntimeException('Cannot retrieve stream due to upload error');
  814. }
  815. if ($this->moved) {
  816. throw new \RuntimeException('Cannot retrieve stream after it has already been moved');
  817. }
  818. }
  819. public function getStream(): StreamInterface
  820. {
  821. $this->validateActive();
  822. if ($this->stream instanceof StreamInterface) {
  823. return $this->stream;
  824. }
  825. $resource = \fopen($this->file, 'r');
  826. return Stream::create($resource);
  827. }
  828. public function moveTo($targetPath) /*:void*/
  829. {
  830. $this->validateActive();
  831. if (!\is_string($targetPath) || '' === $targetPath) {
  832. throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
  833. }
  834. if (null !== $this->file) {
  835. $this->moved = 'cli' === \PHP_SAPI ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath);
  836. } else {
  837. $stream = $this->getStream();
  838. if ($stream->isSeekable()) {
  839. $stream->rewind();
  840. }
  841. $dest = Stream::create(\fopen($targetPath, 'w'));
  842. while (!$stream->eof()) {
  843. if (!$dest->write($stream->read(1048576))) {
  844. break;
  845. }
  846. }
  847. $this->moved = true;
  848. }
  849. if (false === $this->moved) {
  850. throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath));
  851. }
  852. }
  853. public function getSize(): int
  854. {
  855. return $this->size;
  856. }
  857. public function getError(): int
  858. {
  859. return $this->error;
  860. }
  861. public function getClientFilename() /*:?string*/
  862. {
  863. return $this->clientFilename;
  864. }
  865. public function getClientMediaType() /*:?string*/
  866. {
  867. return $this->clientMediaType;
  868. }
  869. }
  870. // file: vendor/nyholm/psr7/src/Uri.php
  871. final class Uri implements UriInterface
  872. {
  873. /*private*/ const SCHEMES = ['http' => 80, 'https' => 443];
  874. /*private*/ const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  875. /*private*/ const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  876. private $scheme = '';
  877. private $userInfo = '';
  878. private $host = '';
  879. private $port;
  880. private $path = '';
  881. private $query = '';
  882. private $fragment = '';
  883. public function __construct(string $uri = '')
  884. {
  885. if ('' !== $uri) {
  886. if (false === $parts = \parse_url($uri)) {
  887. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  888. }
  889. $this->scheme = isset($parts['scheme']) ? \strtolower($parts['scheme']) : '';
  890. $this->userInfo = $parts['user'] ?? '';
  891. $this->host = isset($parts['host']) ? \strtolower($parts['host']) : '';
  892. $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
  893. $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
  894. $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : '';
  895. $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : '';
  896. if (isset($parts['pass'])) {
  897. $this->userInfo .= ':' . $parts['pass'];
  898. }
  899. }
  900. }
  901. public function __toString(): string
  902. {
  903. return self::createUriString($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment);
  904. }
  905. public function getScheme(): string
  906. {
  907. return $this->scheme;
  908. }
  909. public function getAuthority(): string
  910. {
  911. if ('' === $this->host) {
  912. return '';
  913. }
  914. $authority = $this->host;
  915. if ('' !== $this->userInfo) {
  916. $authority = $this->userInfo . '@' . $authority;
  917. }
  918. if (null !== $this->port) {
  919. $authority .= ':' . $this->port;
  920. }
  921. return $authority;
  922. }
  923. public function getUserInfo(): string
  924. {
  925. return $this->userInfo;
  926. }
  927. public function getHost(): string
  928. {
  929. return $this->host;
  930. }
  931. public function getPort() /*:?int*/
  932. {
  933. return $this->port;
  934. }
  935. public function getPath(): string
  936. {
  937. return $this->path;
  938. }
  939. public function getQuery(): string
  940. {
  941. return $this->query;
  942. }
  943. public function getFragment(): string
  944. {
  945. return $this->fragment;
  946. }
  947. public function withScheme($scheme): self
  948. {
  949. if (!\is_string($scheme)) {
  950. throw new \InvalidArgumentException('Scheme must be a string');
  951. }
  952. if ($this->scheme === $scheme = \strtolower($scheme)) {
  953. return $this;
  954. }
  955. $new = clone $this;
  956. $new->scheme = $scheme;
  957. $new->port = $new->filterPort($new->port);
  958. return $new;
  959. }
  960. public function withUserInfo($user, $password = null): self
  961. {
  962. $info = $user;
  963. if (null !== $password && '' !== $password) {
  964. $info .= ':' . $password;
  965. }
  966. if ($this->userInfo === $info) {
  967. return $this;
  968. }
  969. $new = clone $this;
  970. $new->userInfo = $info;
  971. return $new;
  972. }
  973. public function withHost($host): self
  974. {
  975. if (!\is_string($host)) {
  976. throw new \InvalidArgumentException('Host must be a string');
  977. }
  978. if ($this->host === $host = \strtolower($host)) {
  979. return $this;
  980. }
  981. $new = clone $this;
  982. $new->host = $host;
  983. return $new;
  984. }
  985. public function withPort($port): self
  986. {
  987. if ($this->port === $port = $this->filterPort($port)) {
  988. return $this;
  989. }
  990. $new = clone $this;
  991. $new->port = $port;
  992. return $new;
  993. }
  994. public function withPath($path): self
  995. {
  996. if ($this->path === $path = $this->filterPath($path)) {
  997. return $this;
  998. }
  999. $new = clone $this;
  1000. $new->path = $path;
  1001. return $new;
  1002. }
  1003. public function withQuery($query): self
  1004. {
  1005. if ($this->query === $query = $this->filterQueryAndFragment($query)) {
  1006. return $this;
  1007. }
  1008. $new = clone $this;
  1009. $new->query = $query;
  1010. return $new;
  1011. }
  1012. public function withFragment($fragment): self
  1013. {
  1014. if ($this->fragment === $fragment = $this->filterQueryAndFragment($fragment)) {
  1015. return $this;
  1016. }
  1017. $new = clone $this;
  1018. $new->fragment = $fragment;
  1019. return $new;
  1020. }
  1021. private static function createUriString(string $scheme, string $authority, string $path, string $query, string $fragment): string
  1022. {
  1023. $uri = '';
  1024. if ('' !== $scheme) {
  1025. $uri .= $scheme . ':';
  1026. }
  1027. if ('' !== $authority) {
  1028. $uri .= '//' . $authority;
  1029. }
  1030. if ('' !== $path) {
  1031. if ('/' !== $path[0]) {
  1032. if ('' !== $authority) {
  1033. $path = '/' . $path;
  1034. }
  1035. } elseif (isset($path[1]) && '/' === $path[1]) {
  1036. if ('' === $authority) {
  1037. $path = '/' . \ltrim($path, '/');
  1038. }
  1039. }
  1040. $uri .= $path;
  1041. }
  1042. if ('' !== $query) {
  1043. $uri .= '?' . $query;
  1044. }
  1045. if ('' !== $fragment) {
  1046. $uri .= '#' . $fragment;
  1047. }
  1048. return $uri;
  1049. }
  1050. private static function isNonStandardPort(string $scheme, int $port): bool
  1051. {
  1052. return !isset(self::SCHEMES[$scheme]) || $port !== self::SCHEMES[$scheme];
  1053. }
  1054. private function filterPort($port) /*:?int*/
  1055. {
  1056. if (null === $port) {
  1057. return null;
  1058. }
  1059. $port = (int) $port;
  1060. if (1 > $port || 0xffff < $port) {
  1061. throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 1 and 65535', $port));
  1062. }
  1063. return self::isNonStandardPort($this->scheme, $port) ? $port : null;
  1064. }
  1065. private function filterPath($path): string
  1066. {
  1067. if (!\is_string($path)) {
  1068. throw new \InvalidArgumentException('Path must be a string');
  1069. }
  1070. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $path);
  1071. }
  1072. private function filterQueryAndFragment($str): string
  1073. {
  1074. if (!\is_string($str)) {
  1075. throw new \InvalidArgumentException('Query and fragment must be a string');
  1076. }
  1077. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $str);
  1078. }
  1079. private static function rawurlencodeMatchZero(array $match): string
  1080. {
  1081. return \rawurlencode($match[0]);
  1082. }
  1083. }
  1084. // file: vendor/nyholm/psr7-server/src/ServerRequestCreator.php
  1085. final class ServerRequestCreator implements ServerRequestCreatorInterface
  1086. {
  1087. private $serverRequestFactory;
  1088. private $uriFactory;
  1089. private $uploadedFileFactory;
  1090. private $streamFactory;
  1091. public function __construct(
  1092. ServerRequestFactoryInterface $serverRequestFactory,
  1093. UriFactoryInterface $uriFactory,
  1094. UploadedFileFactoryInterface $uploadedFileFactory,
  1095. StreamFactoryInterface $streamFactory
  1096. ) {
  1097. $this->serverRequestFactory = $serverRequestFactory;
  1098. $this->uriFactory = $uriFactory;
  1099. $this->uploadedFileFactory = $uploadedFileFactory;
  1100. $this->streamFactory = $streamFactory;
  1101. }
  1102. public function fromGlobals(): ServerRequestInterface
  1103. {
  1104. $server = $_SERVER;
  1105. if (false === isset($server['REQUEST_METHOD'])) {
  1106. $server['REQUEST_METHOD'] = 'GET';
  1107. }
  1108. $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
  1109. return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $_POST, $_FILES, fopen('php://input', 'r') ?: null);
  1110. }
  1111. public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
  1112. {
  1113. $method = $this->getMethodFromEnv($server);
  1114. $uri = $this->getUriFromEnvWithHTTP($server);
  1115. $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
  1116. $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
  1117. foreach ($headers as $name => $value) {
  1118. $serverRequest = $serverRequest->withAddedHeader($name, $value);
  1119. }
  1120. $serverRequest = $serverRequest
  1121. ->withProtocolVersion($protocol)
  1122. ->withCookieParams($cookie)
  1123. ->withQueryParams($get)
  1124. ->withParsedBody($post)
  1125. ->withUploadedFiles($this->normalizeFiles($files));
  1126. if (null === $body) {
  1127. return $serverRequest;
  1128. }
  1129. if (\is_resource($body)) {
  1130. $body = $this->streamFactory->createStreamFromResource($body);
  1131. } elseif (\is_string($body)) {
  1132. $body = $this->streamFactory->createStream($body);
  1133. } elseif (!$body instanceof StreamInterface) {
  1134. throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
  1135. }
  1136. return $serverRequest->withBody($body);
  1137. }
  1138. public static function getHeadersFromServer(array $server): array
  1139. {
  1140. $headers = [];
  1141. foreach ($server as $key => $value) {
  1142. if (0 === \strpos($key, 'REDIRECT_')) {
  1143. $key = \substr($key, 9);
  1144. if (\array_key_exists($key, $server)) {
  1145. continue;
  1146. }
  1147. }
  1148. if ($value && 0 === \strpos($key, 'HTTP_')) {
  1149. $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
  1150. $headers[$name] = $value;
  1151. continue;
  1152. }
  1153. if ($value && 0 === \strpos($key, 'CONTENT_')) {
  1154. $name = 'content-'.\strtolower(\substr($key, 8));
  1155. $headers[$name] = $value;
  1156. continue;
  1157. }
  1158. }
  1159. return $headers;
  1160. }
  1161. private function getMethodFromEnv(array $environment): string
  1162. {
  1163. if (false === isset($environment['REQUEST_METHOD'])) {
  1164. throw new \InvalidArgumentException('Cannot determine HTTP method');
  1165. }
  1166. return $environment['REQUEST_METHOD'];
  1167. }
  1168. private function getUriFromEnvWithHTTP(array $environment): UriInterface
  1169. {
  1170. $uri = $this->createUriFromArray($environment);
  1171. if (empty($uri->getScheme())) {
  1172. $uri = $uri->withScheme('http');
  1173. }
  1174. return $uri;
  1175. }
  1176. private function normalizeFiles(array $files): array
  1177. {
  1178. $normalized = [];
  1179. foreach ($files as $key => $value) {
  1180. if ($value instanceof UploadedFileInterface) {
  1181. $normalized[$key] = $value;
  1182. } elseif (\is_array($value) && isset($value['tmp_name'])) {
  1183. $normalized[$key] = $this->createUploadedFileFromSpec($value);
  1184. } elseif (\is_array($value)) {
  1185. $normalized[$key] = $this->normalizeFiles($value);
  1186. } else {
  1187. throw new \InvalidArgumentException('Invalid value in files specification');
  1188. }
  1189. }
  1190. return $normalized;
  1191. }
  1192. private function createUploadedFileFromSpec(array $value)
  1193. {
  1194. if (\is_array($value['tmp_name'])) {
  1195. return $this->normalizeNestedFileSpec($value);
  1196. }
  1197. try {
  1198. $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
  1199. } catch (\RuntimeException $e) {
  1200. $stream = $this->streamFactory->createStream();
  1201. }
  1202. return $this->uploadedFileFactory->createUploadedFile(
  1203. $stream,
  1204. (int) $value['size'],
  1205. (int) $value['error'],
  1206. $value['name'],
  1207. $value['type']
  1208. );
  1209. }
  1210. private function normalizeNestedFileSpec(array $files = []): array
  1211. {
  1212. $normalizedFiles = [];
  1213. foreach (\array_keys($files['tmp_name']) as $key) {
  1214. $spec = [
  1215. 'tmp_name' => $files['tmp_name'][$key],
  1216. 'size' => $files['size'][$key],
  1217. 'error' => $files['error'][$key],
  1218. 'name' => $files['name'][$key],
  1219. 'type' => $files['type'][$key],
  1220. ];
  1221. $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
  1222. }
  1223. return $normalizedFiles;
  1224. }
  1225. private function createUriFromArray(array $server): UriInterface
  1226. {
  1227. $uri = $this->uriFactory->createUri('');
  1228. if (isset($server['REQUEST_SCHEME'])) {
  1229. $uri = $uri->withScheme($server['REQUEST_SCHEME']);
  1230. } elseif (isset($server['HTTPS'])) {
  1231. $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
  1232. }
  1233. if (isset($server['HTTP_HOST'])) {
  1234. $uri = $uri->withHost($server['HTTP_HOST']);
  1235. } elseif (isset($server['SERVER_NAME'])) {
  1236. $uri = $uri->withHost($server['SERVER_NAME']);
  1237. }
  1238. if (isset($server['SERVER_PORT'])) {
  1239. $uri = $uri->withPort($server['SERVER_PORT']);
  1240. }
  1241. if (isset($server['REQUEST_URI'])) {
  1242. $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
  1243. }
  1244. if (isset($server['QUERY_STRING'])) {
  1245. $uri = $uri->withQuery($server['QUERY_STRING']);
  1246. }
  1247. return $uri;
  1248. }
  1249. }
  1250. // file: vendor/nyholm/psr7-server/src/ServerRequestCreatorInterface.php
  1251. interface ServerRequestCreatorInterface
  1252. {
  1253. public function fromGlobals(): ServerRequestInterface;
  1254. public function fromArrays(
  1255. array $server,
  1256. array $headers = [],
  1257. array $cookie = [],
  1258. array $get = [],
  1259. array $post = [],
  1260. array $files = [],
  1261. $body = null
  1262. ): ServerRequestInterface;
  1263. public static function getHeadersFromServer(array $server): array;
  1264. }
  1265. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  1266. interface Cache
  1267. {
  1268. public function set(string $key, string $value, int $ttl = 0): bool;
  1269. public function get(string $key): string;
  1270. public function clear(): bool;
  1271. }
  1272. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  1273. class CacheFactory
  1274. {
  1275. const PREFIX = 'phpcrudapi-%s-%s-%s-';
  1276. private static function getPrefix(Config $config): string
  1277. {
  1278. $driver = $config->getDriver();
  1279. $database = $config->getDatabase();
  1280. $filehash = substr(md5(__FILE__), 0, 8);
  1281. return sprintf(self::PREFIX, $driver, $database, $filehash);
  1282. }
  1283. public static function create(Config $config): Cache
  1284. {
  1285. switch ($config->getCacheType()) {
  1286. case 'TempFile':
  1287. $cache = new TempFileCache(self::getPrefix($config), $config->getCachePath());
  1288. break;
  1289. case 'Redis':
  1290. $cache = new RedisCache(self::getPrefix($config), $config->getCachePath());
  1291. break;
  1292. case 'Memcache':
  1293. $cache = new MemcacheCache(self::getPrefix($config), $config->getCachePath());
  1294. break;
  1295. case 'Memcached':
  1296. $cache = new MemcachedCache(self::getPrefix($config), $config->getCachePath());
  1297. break;
  1298. default:
  1299. $cache = new NoCache();
  1300. }
  1301. return $cache;
  1302. }
  1303. }
  1304. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  1305. class MemcacheCache implements Cache
  1306. {
  1307. protected $prefix;
  1308. protected $memcache;
  1309. public function __construct(string $prefix, string $config)
  1310. {
  1311. $this->prefix = $prefix;
  1312. if ($config == '') {
  1313. $address = 'localhost';
  1314. $port = 11211;
  1315. } elseif (strpos($config, ':') === false) {
  1316. $address = $config;
  1317. $port = 11211;
  1318. } else {
  1319. list($address, $port) = explode(':', $config);
  1320. }
  1321. $this->memcache = $this->create();
  1322. $this->memcache->addServer($address, $port);
  1323. }
  1324. protected function create() /*: \Memcache*/
  1325. {
  1326. return new \Memcache();
  1327. }
  1328. public function set(string $key, string $value, int $ttl = 0): bool
  1329. {
  1330. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  1331. }
  1332. public function get(string $key): string
  1333. {
  1334. return $this->memcache->get($this->prefix . $key) ?: '';
  1335. }
  1336. public function clear(): bool
  1337. {
  1338. return $this->memcache->flush();
  1339. }
  1340. }
  1341. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  1342. class MemcachedCache extends MemcacheCache
  1343. {
  1344. protected function create() /*: \Memcached*/
  1345. {
  1346. return new \Memcached();
  1347. }
  1348. public function set(string $key, string $value, int $ttl = 0): bool
  1349. {
  1350. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  1351. }
  1352. }
  1353. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  1354. class NoCache implements Cache
  1355. {
  1356. public function __construct()
  1357. {
  1358. }
  1359. public function set(string $key, string $value, int $ttl = 0): bool
  1360. {
  1361. return true;
  1362. }
  1363. public function get(string $key): string
  1364. {
  1365. return '';
  1366. }
  1367. public function clear(): bool
  1368. {
  1369. return true;
  1370. }
  1371. }
  1372. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  1373. class RedisCache implements Cache
  1374. {
  1375. protected $prefix;
  1376. protected $redis;
  1377. public function __construct(string $prefix, string $config)
  1378. {
  1379. $this->prefix = $prefix;
  1380. if ($config == '') {
  1381. $config = '127.0.0.1';
  1382. }
  1383. $params = explode(':', $config, 6);
  1384. if (isset($params[3])) {
  1385. $params[3] = null;
  1386. }
  1387. $this->redis = new \Redis();
  1388. call_user_func_array(array($this->redis, 'pconnect'), $params);
  1389. }
  1390. public function set(string $key, string $value, int $ttl = 0): bool
  1391. {
  1392. return $this->redis->set($this->prefix . $key, $value, $ttl);
  1393. }
  1394. public function get(string $key): string
  1395. {
  1396. return $this->redis->get($this->prefix . $key) ?: '';
  1397. }
  1398. public function clear(): bool
  1399. {
  1400. return $this->redis->flushDb();
  1401. }
  1402. }
  1403. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  1404. class TempFileCache implements Cache
  1405. {
  1406. const SUFFIX = 'cache';
  1407. private $path;
  1408. private $segments;
  1409. public function __construct(string $prefix, string $config)
  1410. {
  1411. $this->segments = [];
  1412. $s = DIRECTORY_SEPARATOR;
  1413. $ps = PATH_SEPARATOR;
  1414. if ($config == '') {
  1415. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  1416. } elseif (strpos($config, $ps) === false) {
  1417. $this->path = $config;
  1418. } else {
  1419. list($path, $segments) = explode($ps, $config);
  1420. $this->path = $path;
  1421. $this->segments = explode(',', $segments);
  1422. }
  1423. if (file_exists($this->path) && is_dir($this->path)) {
  1424. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  1425. }
  1426. }
  1427. private function getFileName(string $key): string
  1428. {
  1429. $s = DIRECTORY_SEPARATOR;
  1430. $md5 = md5($key);
  1431. $filename = rtrim($this->path, $s) . $s;
  1432. $i = 0;
  1433. foreach ($this->segments as $segment) {
  1434. $filename .= substr($md5, $i, $segment) . $s;
  1435. $i += $segment;
  1436. }
  1437. $filename .= substr($md5, $i);
  1438. return $filename;
  1439. }
  1440. public function set(string $key, string $value, int $ttl = 0): bool
  1441. {
  1442. $filename = $this->getFileName($key);
  1443. $dirname = dirname($filename);
  1444. if (!file_exists($dirname)) {
  1445. if (!mkdir($dirname, 0755, true)) {
  1446. return false;
  1447. }
  1448. }
  1449. $string = $ttl . '|' . $value;
  1450. return $this->filePutContents($filename, $string) !== false;
  1451. }
  1452. private function filePutContents($filename, $string)
  1453. {
  1454. return file_put_contents($filename, $string, LOCK_EX);
  1455. }
  1456. private function fileGetContents($filename)
  1457. {
  1458. $file = fopen($filename, 'rb');
  1459. if ($file === false) {
  1460. return false;
  1461. }
  1462. $lock = flock($file, LOCK_SH);
  1463. if (!$lock) {
  1464. fclose($file);
  1465. return false;
  1466. }
  1467. $string = '';
  1468. while (!feof($file)) {
  1469. $string .= fread($file, 8192);
  1470. }
  1471. flock($file, LOCK_UN);
  1472. fclose($file);
  1473. return $string;
  1474. }
  1475. private function getString($filename): string
  1476. {
  1477. $data = $this->fileGetContents($filename);
  1478. if ($data === false) {
  1479. return '';
  1480. }
  1481. list($ttl, $string) = explode('|', $data, 2);
  1482. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  1483. return '';
  1484. }
  1485. return $string;
  1486. }
  1487. public function get(string $key): string
  1488. {
  1489. $filename = $this->getFileName($key);
  1490. if (!file_exists($filename)) {
  1491. return '';
  1492. }
  1493. $string = $this->getString($filename);
  1494. if ($string == null) {
  1495. return '';
  1496. }
  1497. return $string;
  1498. }
  1499. private function clean(string $path, array $segments, int $len, bool $all) /*: void*/
  1500. {
  1501. $entries = scandir($path);
  1502. foreach ($entries as $entry) {
  1503. if ($entry === '.' || $entry === '..') {
  1504. continue;
  1505. }
  1506. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  1507. if (count($segments) == 0) {
  1508. if (strlen($entry) != $len) {
  1509. continue;
  1510. }
  1511. if (is_file($filename)) {
  1512. if ($all || $this->getString($filename) == null) {
  1513. unlink($filename);
  1514. }
  1515. }
  1516. } else {
  1517. if (strlen($entry) != $segments[0]) {
  1518. continue;
  1519. }
  1520. if (is_dir($filename)) {
  1521. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  1522. rmdir($filename);
  1523. }
  1524. }
  1525. }
  1526. }
  1527. public function clear(): bool
  1528. {
  1529. if (!file_exists($this->path) || !is_dir($this->path)) {
  1530. return false;
  1531. }
  1532. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  1533. return true;
  1534. }
  1535. }
  1536. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  1537. class ReflectedColumn implements \JsonSerializable
  1538. {
  1539. const DEFAULT_LENGTH = 255;
  1540. const DEFAULT_PRECISION = 19;
  1541. const DEFAULT_SCALE = 4;
  1542. private $name;
  1543. private $type;
  1544. private $length;
  1545. private $precision;
  1546. private $scale;
  1547. private $nullable;
  1548. private $pk;
  1549. private $fk;
  1550. public function __construct(string $name, string $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, string $fk)
  1551. {
  1552. $this->name = $name;
  1553. $this->type = $type;
  1554. $this->length = $length;
  1555. $this->precision = $precision;
  1556. $this->scale = $scale;
  1557. $this->nullable = $nullable;
  1558. $this->pk = $pk;
  1559. $this->fk = $fk;
  1560. $this->sanitize();
  1561. }
  1562. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  1563. {
  1564. $name = $columnResult['COLUMN_NAME'];
  1565. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  1566. $type = $reflection->toJdbcType($columnResult['DATA_TYPE'], $length);
  1567. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  1568. $scale = (int) $columnResult['NUMERIC_SCALE'];
  1569. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  1570. $pk = false;
  1571. $fk = '';
  1572. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  1573. }
  1574. public static function fromJson( /* object */$json): ReflectedColumn
  1575. {
  1576. $name = $json->name;
  1577. $type = $json->type;
  1578. $length = isset($json->length) ? $json->length : 0;
  1579. $precision = isset($json->precision) ? $json->precision : 0;
  1580. $scale = isset($json->scale) ? $json->scale : 0;
  1581. $nullable = isset($json->nullable) ? $json->nullable : false;
  1582. $pk = isset($json->pk) ? $json->pk : false;
  1583. $fk = isset($json->fk) ? $json->fk : '';
  1584. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  1585. }
  1586. private function sanitize()
  1587. {
  1588. $this->length = $this->hasLength() ? $this->getLength() : 0;
  1589. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  1590. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  1591. }
  1592. public function getName(): string
  1593. {
  1594. return $this->name;
  1595. }
  1596. public function getNullable(): bool
  1597. {
  1598. return $this->nullable;
  1599. }
  1600. public function getType(): string
  1601. {
  1602. return $this->type;
  1603. }
  1604. public function getLength(): int
  1605. {
  1606. return $this->length ?: self::DEFAULT_LENGTH;
  1607. }
  1608. public function getPrecision(): int
  1609. {
  1610. return $this->precision ?: self::DEFAULT_PRECISION;
  1611. }
  1612. public function getScale(): int
  1613. {
  1614. return $this->scale ?: self::DEFAULT_SCALE;
  1615. }
  1616. public function hasLength(): bool
  1617. {
  1618. return in_array($this->type, ['varchar', 'varbinary']);
  1619. }
  1620. public function hasPrecision(): bool
  1621. {
  1622. return $this->type == 'decimal';
  1623. }
  1624. public function hasScale(): bool
  1625. {
  1626. return $this->type == 'decimal';
  1627. }
  1628. public function isBinary(): bool
  1629. {
  1630. return in_array($this->type, ['blob', 'varbinary']);
  1631. }
  1632. public function isBoolean(): bool
  1633. {
  1634. return $this->type == 'boolean';
  1635. }
  1636. public function isGeometry(): bool
  1637. {
  1638. return $this->type == 'geometry';
  1639. }
  1640. public function isInteger(): bool
  1641. {
  1642. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  1643. }
  1644. public function setPk($value) /*: void*/
  1645. {
  1646. $this->pk = $value;
  1647. }
  1648. public function getPk(): bool
  1649. {
  1650. return $this->pk;
  1651. }
  1652. public function setFk($value) /*: void*/
  1653. {
  1654. $this->fk = $value;
  1655. }
  1656. public function getFk(): string
  1657. {
  1658. return $this->fk;
  1659. }
  1660. public function serialize()
  1661. {
  1662. return [
  1663. 'name' => $this->name,
  1664. 'type' => $this->type,
  1665. 'length' => $this->length,
  1666. 'precision' => $this->precision,
  1667. 'scale' => $this->scale,
  1668. 'nullable' => $this->nullable,
  1669. 'pk' => $this->pk,
  1670. 'fk' => $this->fk,
  1671. ];
  1672. }
  1673. public function jsonSerialize()
  1674. {
  1675. return array_filter($this->serialize());
  1676. }
  1677. }
  1678. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  1679. class ReflectedDatabase implements \JsonSerializable
  1680. {
  1681. private $tableTypes;
  1682. public function __construct(array $tableTypes)
  1683. {
  1684. $this->tableTypes = $tableTypes;
  1685. }
  1686. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  1687. {
  1688. $tableTypes = [];
  1689. foreach ($reflection->getTables() as $table) {
  1690. $tableName = $table['TABLE_NAME'];
  1691. $tableType = $table['TABLE_TYPE'];
  1692. if (in_array($tableName, $reflection->getIgnoredTables())) {
  1693. continue;
  1694. }
  1695. $tableTypes[$tableName] = $tableType;
  1696. }
  1697. return new ReflectedDatabase($tableTypes);
  1698. }
  1699. public static function fromJson( /* object */$json): ReflectedDatabase
  1700. {
  1701. $tableTypes = (array) $json->tables;
  1702. return new ReflectedDatabase($tableTypes);
  1703. }
  1704. public function hasTable(string $tableName): bool
  1705. {
  1706. return isset($this->tableTypes[$tableName]);
  1707. }
  1708. public function getType(string $tableName): string
  1709. {
  1710. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  1711. }
  1712. public function getTableNames(): array
  1713. {
  1714. return array_keys($this->tableTypes);
  1715. }
  1716. public function removeTable(string $tableName): bool
  1717. {
  1718. if (!isset($this->tableTypes[$tableName])) {
  1719. return false;
  1720. }
  1721. unset($this->tableTypes[$tableName]);
  1722. return true;
  1723. }
  1724. public function serialize()
  1725. {
  1726. return [
  1727. 'tables' => $this->tableTypes,
  1728. ];
  1729. }
  1730. public function jsonSerialize()
  1731. {
  1732. return $this->serialize();
  1733. }
  1734. }
  1735. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  1736. class ReflectedTable implements \JsonSerializable
  1737. {
  1738. private $name;
  1739. private $type;
  1740. private $columns;
  1741. private $pk;
  1742. private $fks;
  1743. public function __construct(string $name, string $type, array $columns)
  1744. {
  1745. $this->name = $name;
  1746. $this->type = $type;
  1747. $this->columns = [];
  1748. foreach ($columns as $column) {
  1749. $columnName = $column->getName();
  1750. $this->columns[$columnName] = $column;
  1751. }
  1752. $this->pk = null;
  1753. foreach ($columns as $column) {
  1754. if ($column->getPk() == true) {
  1755. $this->pk = $column;
  1756. }
  1757. }
  1758. $this->fks = [];
  1759. foreach ($columns as $column) {
  1760. $columnName = $column->getName();
  1761. $referencedTableName = $column->getFk();
  1762. if ($referencedTableName != '') {
  1763. $this->fks[$columnName] = $referencedTableName;
  1764. }
  1765. }
  1766. }
  1767. public static function fromReflection(GenericReflection $reflection, string $name, string $type): ReflectedTable
  1768. {
  1769. $columns = [];
  1770. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  1771. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  1772. $columns[$column->getName()] = $column;
  1773. }
  1774. $columnNames = $reflection->getTablePrimaryKeys($name);
  1775. if (count($columnNames) == 1) {
  1776. $columnName = $columnNames[0];
  1777. if (isset($columns[$columnName])) {
  1778. $pk = $columns[$columnName];
  1779. $pk->setPk(true);
  1780. }
  1781. }
  1782. $fks = $reflection->getTableForeignKeys($name);
  1783. foreach ($fks as $columnName => $table) {
  1784. $columns[$columnName]->setFk($table);
  1785. }
  1786. return new ReflectedTable($name, $type, array_values($columns));
  1787. }
  1788. public static function fromJson( /* object */$json): ReflectedTable
  1789. {
  1790. $name = $json->name;
  1791. $type = $json->type;
  1792. $columns = [];
  1793. if (isset($json->columns) && is_array($json->columns)) {
  1794. foreach ($json->columns as $column) {
  1795. $columns[] = ReflectedColumn::fromJson($column);
  1796. }
  1797. }
  1798. return new ReflectedTable($name, $type, $columns);
  1799. }
  1800. public function hasColumn(string $columnName): bool
  1801. {
  1802. return isset($this->columns[$columnName]);
  1803. }
  1804. public function hasPk(): bool
  1805. {
  1806. return $this->pk != null;
  1807. }
  1808. public function getPk() /*: ?ReflectedColumn */
  1809. {
  1810. return $this->pk;
  1811. }
  1812. public function getName(): string
  1813. {
  1814. return $this->name;
  1815. }
  1816. public function getType(): string
  1817. {
  1818. return $this->type;
  1819. }
  1820. public function getColumnNames(): array
  1821. {
  1822. return array_keys($this->columns);
  1823. }
  1824. public function getColumn($columnName): ReflectedColumn
  1825. {
  1826. return $this->columns[$columnName];
  1827. }
  1828. public function getFksTo(string $tableName): array
  1829. {
  1830. $columns = array();
  1831. foreach ($this->fks as $columnName => $referencedTableName) {
  1832. if ($tableName == $referencedTableName) {
  1833. $columns[] = $this->columns[$columnName];
  1834. }
  1835. }
  1836. return $columns;
  1837. }
  1838. public function removeColumn(string $columnName): bool
  1839. {
  1840. if (!isset($this->columns[$columnName])) {
  1841. return false;
  1842. }
  1843. unset($this->columns[$columnName]);
  1844. return true;
  1845. }
  1846. public function serialize()
  1847. {
  1848. return [
  1849. 'name' => $this->name,
  1850. 'type' => $this->type,
  1851. 'columns' => array_values($this->columns),
  1852. ];
  1853. }
  1854. public function jsonSerialize()
  1855. {
  1856. return $this->serialize();
  1857. }
  1858. }
  1859. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  1860. class DefinitionService
  1861. {
  1862. private $db;
  1863. private $reflection;
  1864. public function __construct(GenericDB $db, ReflectionService $reflection)
  1865. {
  1866. $this->db = $db;
  1867. $this->reflection = $reflection;
  1868. }
  1869. public function updateTable(string $tableName, /* object */ $changes): bool
  1870. {
  1871. $table = $this->reflection->getTable($tableName);
  1872. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  1873. if ($table->getName() != $newTable->getName()) {
  1874. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  1875. return false;
  1876. }
  1877. }
  1878. return true;
  1879. }
  1880. public function updateColumn(string $tableName, string $columnName, /* object */ $changes): bool
  1881. {
  1882. $table = $this->reflection->getTable($tableName);
  1883. $column = $table->getColumn($columnName);
  1884. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  1885. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  1886. $oldColumn = $table->getPk();
  1887. if ($oldColumn->getName() != $columnName) {
  1888. $oldColumn->setPk(false);
  1889. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  1890. return false;
  1891. }
  1892. }
  1893. }
  1894. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  1895. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  1896. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  1897. return false;
  1898. }
  1899. }
  1900. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  1901. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  1902. return false;
  1903. }
  1904. }
  1905. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  1906. $newColumn->setPk(false);
  1907. $newColumn->setFk('');
  1908. if ($newColumn->getName() != $column->getName()) {
  1909. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  1910. return false;
  1911. }
  1912. }
  1913. if ($newColumn->getType() != $column->getType() ||
  1914. $newColumn->getLength() != $column->getLength() ||
  1915. $newColumn->getPrecision() != $column->getPrecision() ||
  1916. $newColumn->getScale() != $column->getScale()
  1917. ) {
  1918. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  1919. return false;
  1920. }
  1921. }
  1922. if ($newColumn->getNullable() != $column->getNullable()) {
  1923. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  1924. return false;
  1925. }
  1926. }
  1927. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  1928. if ($newColumn->getFk()) {
  1929. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  1930. return false;
  1931. }
  1932. }
  1933. if ($newColumn->getPk()) {
  1934. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  1935. return false;
  1936. }
  1937. }
  1938. return true;
  1939. }
  1940. public function addTable( /* object */$definition)
  1941. {
  1942. $newTable = ReflectedTable::fromJson($definition);
  1943. if (!$this->db->definition()->addTable($newTable)) {
  1944. return false;
  1945. }
  1946. return true;
  1947. }
  1948. public function addColumn(string $tableName, /* object */ $definition)
  1949. {
  1950. $newColumn = ReflectedColumn::fromJson($definition);
  1951. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  1952. return false;
  1953. }
  1954. if ($newColumn->getFk()) {
  1955. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  1956. return false;
  1957. }
  1958. }
  1959. if ($newColumn->getPk()) {
  1960. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  1961. return false;
  1962. }
  1963. }
  1964. return true;
  1965. }
  1966. public function removeTable(string $tableName)
  1967. {
  1968. if (!$this->db->definition()->removeTable($tableName)) {
  1969. return false;
  1970. }
  1971. return true;
  1972. }
  1973. public function removeColumn(string $tableName, string $columnName)
  1974. {
  1975. $table = $this->reflection->getTable($tableName);
  1976. $newColumn = $table->getColumn($columnName);
  1977. if ($newColumn->getPk()) {
  1978. $newColumn->setPk(false);
  1979. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  1980. return false;
  1981. }
  1982. }
  1983. if ($newColumn->getFk()) {
  1984. $newColumn->setFk("");
  1985. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  1986. return false;
  1987. }
  1988. }
  1989. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  1990. return false;
  1991. }
  1992. return true;
  1993. }
  1994. }
  1995. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  1996. class ReflectionService
  1997. {
  1998. private $db;
  1999. private $cache;
  2000. private $ttl;
  2001. private $database;
  2002. private $tables;
  2003. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  2004. {
  2005. $this->db = $db;
  2006. $this->cache = $cache;
  2007. $this->ttl = $ttl;
  2008. $this->database = $this->loadDatabase(true);
  2009. $this->tables = [];
  2010. }
  2011. private function loadDatabase(bool $useCache): ReflectedDatabase
  2012. {
  2013. $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
  2014. if ($data != '') {
  2015. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  2016. } else {
  2017. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  2018. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  2019. $this->cache->set('ReflectedDatabase', $data, $this->ttl);
  2020. }
  2021. return $database;
  2022. }
  2023. private function loadTable(string $tableName, bool $useCache): ReflectedTable
  2024. {
  2025. $data = $useCache ? $this->cache->get("ReflectedTable($tableName)") : '';
  2026. if ($data != '') {
  2027. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  2028. } else {
  2029. $tableType = $this->database->getType($tableName);
  2030. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  2031. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  2032. $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
  2033. }
  2034. return $table;
  2035. }
  2036. public function refreshTables()
  2037. {
  2038. $this->database = $this->loadDatabase(false);
  2039. }
  2040. public function refreshTable(string $tableName)
  2041. {
  2042. $this->tables[$tableName] = $this->loadTable($tableName, false);
  2043. }
  2044. public function hasTable(string $tableName): bool
  2045. {
  2046. return $this->database->hasTable($tableName);
  2047. }
  2048. public function getType(string $tableName): string
  2049. {
  2050. return $this->database->getType($tableName);
  2051. }
  2052. public function getTable(string $tableName): ReflectedTable
  2053. {
  2054. if (!isset($this->tables[$tableName])) {
  2055. $this->tables[$tableName] = $this->loadTable($tableName, true);
  2056. }
  2057. return $this->tables[$tableName];
  2058. }
  2059. public function getTableNames(): array
  2060. {
  2061. return $this->database->getTableNames();
  2062. }
  2063. public function getDatabaseName(): string
  2064. {
  2065. return $this->database->getName();
  2066. }
  2067. public function removeTable(string $tableName): bool
  2068. {
  2069. unset($this->tables[$tableName]);
  2070. return $this->database->removeTable($tableName);
  2071. }
  2072. }
  2073. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  2074. class CacheController
  2075. {
  2076. private $cache;
  2077. private $responder;
  2078. public function __construct(Router $router, Responder $responder, Cache $cache)
  2079. {
  2080. $router->register('GET', '/cache/clear', array($this, 'clear'));
  2081. $this->cache = $cache;
  2082. $this->responder = $responder;
  2083. }
  2084. public function clear(ServerRequestInterface $request): ResponseInterface
  2085. {
  2086. return $this->responder->success($this->cache->clear());
  2087. }
  2088. }
  2089. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  2090. class ColumnController
  2091. {
  2092. private $responder;
  2093. private $reflection;
  2094. private $definition;
  2095. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  2096. {
  2097. $router->register('GET', '/columns', array($this, 'getDatabase'));
  2098. $router->register('GET', '/columns/*', array($this, 'getTable'));
  2099. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  2100. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  2101. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  2102. $router->register('POST', '/columns', array($this, 'addTable'));
  2103. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  2104. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  2105. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  2106. $this->responder = $responder;
  2107. $this->reflection = $reflection;
  2108. $this->definition = $definition;
  2109. }
  2110. public function getDatabase(ServerRequestInterface $request): ResponseInterface
  2111. {
  2112. $tables = [];
  2113. foreach ($this->reflection->getTableNames() as $table) {
  2114. $tables[] = $this->reflection->getTable($table);
  2115. }
  2116. $database = ['tables' => $tables];
  2117. return $this->responder->success($database);
  2118. }
  2119. public function getTable(ServerRequestInterface $request): ResponseInterface
  2120. {
  2121. $tableName = RequestUtils::getPathSegment($request, 2);
  2122. if (!$this->reflection->hasTable($tableName)) {
  2123. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2124. }
  2125. $table = $this->reflection->getTable($tableName);
  2126. return $this->responder->success($table);
  2127. }
  2128. public function getColumn(ServerRequestInterface $request): ResponseInterface
  2129. {
  2130. $tableName = RequestUtils::getPathSegment($request, 2);
  2131. $columnName = RequestUtils::getPathSegment($request, 3);
  2132. if (!$this->reflection->hasTable($tableName)) {
  2133. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2134. }
  2135. $table = $this->reflection->getTable($tableName);
  2136. if (!$table->hasColumn($columnName)) {
  2137. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  2138. }
  2139. $column = $table->getColumn($columnName);
  2140. return $this->responder->success($column);
  2141. }
  2142. public function updateTable(ServerRequestInterface $request): ResponseInterface
  2143. {
  2144. $tableName = RequestUtils::getPathSegment($request, 2);
  2145. if (!$this->reflection->hasTable($tableName)) {
  2146. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2147. }
  2148. $success = $this->definition->updateTable($tableName, $request->getParsedBody());
  2149. if ($success) {
  2150. $this->reflection->refreshTables();
  2151. }
  2152. return $this->responder->success($success);
  2153. }
  2154. public function updateColumn(ServerRequestInterface $request): ResponseInterface
  2155. {
  2156. $tableName = RequestUtils::getPathSegment($request, 2);
  2157. $columnName = RequestUtils::getPathSegment($request, 3);
  2158. if (!$this->reflection->hasTable($tableName)) {
  2159. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2160. }
  2161. $table = $this->reflection->getTable($tableName);
  2162. if (!$table->hasColumn($columnName)) {
  2163. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  2164. }
  2165. $success = $this->definition->updateColumn($tableName, $columnName, $request->getParsedBody());
  2166. if ($success) {
  2167. $this->reflection->refreshTable($tableName);
  2168. }
  2169. return $this->responder->success($success);
  2170. }
  2171. public function addTable(ServerRequestInterface $request): ResponseInterface
  2172. {
  2173. $tableName = $request->getParsedBody()->name;
  2174. if ($this->reflection->hasTable($tableName)) {
  2175. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  2176. }
  2177. $success = $this->definition->addTable($request->getParsedBody());
  2178. if ($success) {
  2179. $this->reflection->refreshTables();
  2180. }
  2181. return $this->responder->success($success);
  2182. }
  2183. public function addColumn(ServerRequestInterface $request): ResponseInterface
  2184. {
  2185. $tableName = RequestUtils::getPathSegment($request, 2);
  2186. if (!$this->reflection->hasTable($tableName)) {
  2187. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2188. }
  2189. $columnName = $request->getParsedBody()->name;
  2190. $table = $this->reflection->getTable($tableName);
  2191. if ($table->hasColumn($columnName)) {
  2192. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  2193. }
  2194. $success = $this->definition->addColumn($tableName, $request->getParsedBody());
  2195. if ($success) {
  2196. $this->reflection->refreshTable($tableName);
  2197. }
  2198. return $this->responder->success($success);
  2199. }
  2200. public function removeTable(ServerRequestInterface $request): ResponseInterface
  2201. {
  2202. $tableName = RequestUtils::getPathSegment($request, 2);
  2203. if (!$this->reflection->hasTable($tableName)) {
  2204. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2205. }
  2206. $success = $this->definition->removeTable($tableName);
  2207. if ($success) {
  2208. $this->reflection->refreshTables();
  2209. }
  2210. return $this->responder->success($success);
  2211. }
  2212. public function removeColumn(ServerRequestInterface $request): ResponseInterface
  2213. {
  2214. $tableName = RequestUtils::getPathSegment($request, 2);
  2215. $columnName = RequestUtils::getPathSegment($request, 3);
  2216. if (!$this->reflection->hasTable($tableName)) {
  2217. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2218. }
  2219. $table = $this->reflection->getTable($tableName);
  2220. if (!$table->hasColumn($columnName)) {
  2221. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  2222. }
  2223. $success = $this->definition->removeColumn($tableName, $columnName);
  2224. if ($success) {
  2225. $this->reflection->refreshTable($tableName);
  2226. }
  2227. return $this->responder->success($success);
  2228. }
  2229. }
  2230. // file: src/Tqdev/PhpCrudApi/Controller/GeoJsonController.php
  2231. class GeoJsonController
  2232. {
  2233. private $service;
  2234. private $responder;
  2235. private $geoJsonConverter;
  2236. public function __construct(Router $router, Responder $responder, GeoJsonService $service)
  2237. {
  2238. $router->register('GET', '/geojson/*', array($this, '_list'));
  2239. $router->register('GET', '/geojson/*/*', array($this, 'read'));
  2240. $this->service = $service;
  2241. $this->responder = $responder;
  2242. }
  2243. public function _list(ServerRequestInterface $request): ResponseInterface
  2244. {
  2245. $table = RequestUtils::getPathSegment($request, 2);
  2246. $params = RequestUtils::getParams($request);
  2247. if (!$this->service->hasTable($table)) {
  2248. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2249. }
  2250. return $this->responder->success($this->service->_list($table, $params));
  2251. }
  2252. public function read(ServerRequestInterface $request): ResponseInterface
  2253. {
  2254. $table = RequestUtils::getPathSegment($request, 2);
  2255. if (!$this->service->hasTable($table)) {
  2256. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2257. }
  2258. if ($this->service->getType($table) != 'table') {
  2259. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2260. }
  2261. $id = RequestUtils::getPathSegment($request, 3);
  2262. $params = RequestUtils::getParams($request);
  2263. if (strpos($id, ',') !== false) {
  2264. $ids = explode(',', $id);
  2265. $result = (object) array('type' => 'FeatureCollection', 'features' => array());
  2266. for ($i = 0; $i < count($ids); $i++) {
  2267. array_push($result->features, $this->service->read($table, $ids[$i], $params));
  2268. }
  2269. return $this->responder->success($result);
  2270. } else {
  2271. $response = $this->service->read($table, $id, $params);
  2272. if ($response === null) {
  2273. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  2274. }
  2275. return $this->responder->success($response);
  2276. }
  2277. }
  2278. }
  2279. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  2280. class OpenApiController
  2281. {
  2282. private $openApi;
  2283. private $responder;
  2284. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  2285. {
  2286. $router->register('GET', '/openapi', array($this, 'openapi'));
  2287. $this->openApi = $openApi;
  2288. $this->responder = $responder;
  2289. }
  2290. public function openapi(ServerRequestInterface $request): ResponseInterface
  2291. {
  2292. return $this->responder->success($this->openApi->get());
  2293. }
  2294. }
  2295. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  2296. class RecordController
  2297. {
  2298. private $service;
  2299. private $responder;
  2300. public function __construct(Router $router, Responder $responder, RecordService $service)
  2301. {
  2302. $router->register('GET', '/records/*', array($this, '_list'));
  2303. $router->register('POST', '/records/*', array($this, 'create'));
  2304. $router->register('GET', '/records/*/*', array($this, 'read'));
  2305. $router->register('PUT', '/records/*/*', array($this, 'update'));
  2306. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  2307. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  2308. $this->service = $service;
  2309. $this->responder = $responder;
  2310. }
  2311. public function _list(ServerRequestInterface $request): ResponseInterface
  2312. {
  2313. $table = RequestUtils::getPathSegment($request, 2);
  2314. $params = RequestUtils::getParams($request);
  2315. if (!$this->service->hasTable($table)) {
  2316. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2317. }
  2318. return $this->responder->success($this->service->_list($table, $params));
  2319. }
  2320. public function read(ServerRequestInterface $request): ResponseInterface
  2321. {
  2322. $table = RequestUtils::getPathSegment($request, 2);
  2323. if (!$this->service->hasTable($table)) {
  2324. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2325. }
  2326. if ($this->service->getType($table) != 'table') {
  2327. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2328. }
  2329. $id = RequestUtils::getPathSegment($request, 3);
  2330. $params = RequestUtils::getParams($request);
  2331. if (strpos($id, ',') !== false) {
  2332. $ids = explode(',', $id);
  2333. $result = [];
  2334. for ($i = 0; $i < count($ids); $i++) {
  2335. array_push($result, $this->service->read($table, $ids[$i], $params));
  2336. }
  2337. return $this->responder->success($result);
  2338. } else {
  2339. $response = $this->service->read($table, $id, $params);
  2340. if ($response === null) {
  2341. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  2342. }
  2343. return $this->responder->success($response);
  2344. }
  2345. }
  2346. public function create(ServerRequestInterface $request): ResponseInterface
  2347. {
  2348. $table = RequestUtils::getPathSegment($request, 2);
  2349. if (!$this->service->hasTable($table)) {
  2350. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2351. }
  2352. if ($this->service->getType($table) != 'table') {
  2353. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2354. }
  2355. $record = $request->getParsedBody();
  2356. if ($record === null) {
  2357. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  2358. }
  2359. $params = RequestUtils::getParams($request);
  2360. if (is_array($record)) {
  2361. $result = array();
  2362. foreach ($record as $r) {
  2363. $result[] = $this->service->create($table, $r, $params);
  2364. }
  2365. return $this->responder->success($result);
  2366. } else {
  2367. return $this->responder->success($this->service->create($table, $record, $params));
  2368. }
  2369. }
  2370. public function update(ServerRequestInterface $request): ResponseInterface
  2371. {
  2372. $table = RequestUtils::getPathSegment($request, 2);
  2373. if (!$this->service->hasTable($table)) {
  2374. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2375. }
  2376. if ($this->service->getType($table) != 'table') {
  2377. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2378. }
  2379. $id = RequestUtils::getPathSegment($request, 3);
  2380. $params = RequestUtils::getParams($request);
  2381. $record = $request->getParsedBody();
  2382. if ($record === null) {
  2383. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  2384. }
  2385. $ids = explode(',', $id);
  2386. if (is_array($record)) {
  2387. if (count($ids) != count($record)) {
  2388. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2389. }
  2390. $result = array();
  2391. for ($i = 0; $i < count($ids); $i++) {
  2392. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  2393. }
  2394. return $this->responder->success($result);
  2395. } else {
  2396. if (count($ids) != 1) {
  2397. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2398. }
  2399. return $this->responder->success($this->service->update($table, $id, $record, $params));
  2400. }
  2401. }
  2402. public function delete(ServerRequestInterface $request): ResponseInterface
  2403. {
  2404. $table = RequestUtils::getPathSegment($request, 2);
  2405. if (!$this->service->hasTable($table)) {
  2406. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2407. }
  2408. if ($this->service->getType($table) != 'table') {
  2409. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2410. }
  2411. $id = RequestUtils::getPathSegment($request, 3);
  2412. $params = RequestUtils::getParams($request);
  2413. $ids = explode(',', $id);
  2414. if (count($ids) > 1) {
  2415. $result = array();
  2416. for ($i = 0; $i < count($ids); $i++) {
  2417. $result[] = $this->service->delete($table, $ids[$i], $params);
  2418. }
  2419. return $this->responder->success($result);
  2420. } else {
  2421. return $this->responder->success($this->service->delete($table, $id, $params));
  2422. }
  2423. }
  2424. public function increment(ServerRequestInterface $request): ResponseInterface
  2425. {
  2426. $table = RequestUtils::getPathSegment($request, 2);
  2427. if (!$this->service->hasTable($table)) {
  2428. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2429. }
  2430. if ($this->service->getType($table) != 'table') {
  2431. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2432. }
  2433. $id = RequestUtils::getPathSegment($request, 3);
  2434. $record = $request->getParsedBody();
  2435. if ($record === null) {
  2436. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  2437. }
  2438. $params = RequestUtils::getParams($request);
  2439. $ids = explode(',', $id);
  2440. if (is_array($record)) {
  2441. if (count($ids) != count($record)) {
  2442. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2443. }
  2444. $result = array();
  2445. for ($i = 0; $i < count($ids); $i++) {
  2446. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  2447. }
  2448. return $this->responder->success($result);
  2449. } else {
  2450. if (count($ids) != 1) {
  2451. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2452. }
  2453. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  2454. }
  2455. }
  2456. }
  2457. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  2458. class Responder
  2459. {
  2460. public function error(int $error, string $argument, $details = null): ResponseInterface
  2461. {
  2462. $errorCode = new ErrorCode($error);
  2463. $status = $errorCode->getStatus();
  2464. $document = new ErrorDocument($errorCode, $argument, $details);
  2465. return ResponseFactory::fromObject($status, $document);
  2466. }
  2467. public function success($result): ResponseInterface
  2468. {
  2469. return ResponseFactory::fromObject(ResponseFactory::OK, $result);
  2470. }
  2471. }
  2472. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  2473. class ColumnConverter
  2474. {
  2475. private $driver;
  2476. public function __construct(string $driver)
  2477. {
  2478. $this->driver = $driver;
  2479. }
  2480. public function convertColumnValue(ReflectedColumn $column): string
  2481. {
  2482. if ($column->isBinary()) {
  2483. switch ($this->driver) {
  2484. case 'mysql':
  2485. return "FROM_BASE64(?)";
  2486. case 'pgsql':
  2487. return "decode(?, 'base64')";
  2488. case 'sqlsrv':
  2489. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  2490. }
  2491. }
  2492. if ($column->isGeometry()) {
  2493. switch ($this->driver) {
  2494. case 'mysql':
  2495. case 'pgsql':
  2496. return "ST_GeomFromText(?)";
  2497. case 'sqlsrv':
  2498. return "geometry::STGeomFromText(?,0)";
  2499. }
  2500. }
  2501. return '?';
  2502. }
  2503. public function convertColumnName(ReflectedColumn $column, $value): string
  2504. {
  2505. if ($column->isBinary()) {
  2506. switch ($this->driver) {
  2507. case 'mysql':
  2508. return "TO_BASE64($value) as $value";
  2509. case 'pgsql':
  2510. return "encode($value::bytea, 'base64') as $value";
  2511. case 'sqlsrv':
  2512. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  2513. }
  2514. }
  2515. if ($column->isGeometry()) {
  2516. switch ($this->driver) {
  2517. case 'mysql':
  2518. case 'pgsql':
  2519. return "ST_AsText($value) as $value";
  2520. case 'sqlsrv':
  2521. return "REPLACE($value.STAsText(),' (','(') as $value";
  2522. }
  2523. }
  2524. return $value;
  2525. }
  2526. }
  2527. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  2528. class ColumnsBuilder
  2529. {
  2530. private $driver;
  2531. private $converter;
  2532. public function __construct(string $driver)
  2533. {
  2534. $this->driver = $driver;
  2535. $this->converter = new ColumnConverter($driver);
  2536. }
  2537. public function getOffsetLimit(int $offset, int $limit): string
  2538. {
  2539. if ($limit < 0 || $offset < 0) {
  2540. return '';
  2541. }
  2542. switch ($this->driver) {
  2543. case 'mysql':return " LIMIT $offset, $limit";
  2544. case 'pgsql':return " LIMIT $limit OFFSET $offset";
  2545. case 'sqlsrv':return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  2546. }
  2547. }
  2548. private function quoteColumnName(ReflectedColumn $column): string
  2549. {
  2550. return '"' . $column->getName() . '"';
  2551. }
  2552. public function getOrderBy(ReflectedTable $table, array $columnOrdering): string
  2553. {
  2554. if (count($columnOrdering) == 0) {
  2555. return '';
  2556. }
  2557. $results = array();
  2558. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  2559. $column = $table->getColumn($columnName);
  2560. $quotedColumnName = $this->quoteColumnName($column);
  2561. $results[] = $quotedColumnName . ' ' . $ordering;
  2562. }
  2563. return ' ORDER BY ' . implode(',', $results);
  2564. }
  2565. public function getSelect(ReflectedTable $table, array $columnNames): string
  2566. {
  2567. $results = array();
  2568. foreach ($columnNames as $columnName) {
  2569. $column = $table->getColumn($columnName);
  2570. $quotedColumnName = $this->quoteColumnName($column);
  2571. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  2572. $results[] = $quotedColumnName;
  2573. }
  2574. return implode(',', $results);
  2575. }
  2576. public function getInsert(ReflectedTable $table, array $columnValues): string
  2577. {
  2578. $columns = array();
  2579. $values = array();
  2580. foreach ($columnValues as $columnName => $columnValue) {
  2581. $column = $table->getColumn($columnName);
  2582. $quotedColumnName = $this->quoteColumnName($column);
  2583. $columns[] = $quotedColumnName;
  2584. $columnValue = $this->converter->convertColumnValue($column);
  2585. $values[] = $columnValue;
  2586. }
  2587. $columnsSql = '(' . implode(',', $columns) . ')';
  2588. $valuesSql = '(' . implode(',', $values) . ')';
  2589. $outputColumn = $this->quoteColumnName($table->getPk());
  2590. switch ($this->driver) {
  2591. case 'mysql':return "$columnsSql VALUES $valuesSql";
  2592. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  2593. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  2594. }
  2595. }
  2596. public function getUpdate(ReflectedTable $table, array $columnValues): string
  2597. {
  2598. $results = array();
  2599. foreach ($columnValues as $columnName => $columnValue) {
  2600. $column = $table->getColumn($columnName);
  2601. $quotedColumnName = $this->quoteColumnName($column);
  2602. $columnValue = $this->converter->convertColumnValue($column);
  2603. $results[] = $quotedColumnName . '=' . $columnValue;
  2604. }
  2605. return implode(',', $results);
  2606. }
  2607. public function getIncrement(ReflectedTable $table, array $columnValues): string
  2608. {
  2609. $results = array();
  2610. foreach ($columnValues as $columnName => $columnValue) {
  2611. if (!is_numeric($columnValue)) {
  2612. continue;
  2613. }
  2614. $column = $table->getColumn($columnName);
  2615. $quotedColumnName = $this->quoteColumnName($column);
  2616. $columnValue = $this->converter->convertColumnValue($column);
  2617. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  2618. }
  2619. return implode(',', $results);
  2620. }
  2621. }
  2622. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  2623. class ConditionsBuilder
  2624. {
  2625. private $driver;
  2626. public function __construct(string $driver)
  2627. {
  2628. $this->driver = $driver;
  2629. }
  2630. private function getConditionSql(Condition $condition, array &$arguments): string
  2631. {
  2632. if ($condition instanceof AndCondition) {
  2633. return $this->getAndConditionSql($condition, $arguments);
  2634. }
  2635. if ($condition instanceof OrCondition) {
  2636. return $this->getOrConditionSql($condition, $arguments);
  2637. }
  2638. if ($condition instanceof NotCondition) {
  2639. return $this->getNotConditionSql($condition, $arguments);
  2640. }
  2641. if ($condition instanceof SpatialCondition) {
  2642. return $this->getSpatialConditionSql($condition, $arguments);
  2643. }
  2644. if ($condition instanceof ColumnCondition) {
  2645. return $this->getColumnConditionSql($condition, $arguments);
  2646. }
  2647. throw new \Exception('Unknown Condition: ' . get_class($condition));
  2648. }
  2649. private function getAndConditionSql(AndCondition $and, array &$arguments): string
  2650. {
  2651. $parts = [];
  2652. foreach ($and->getConditions() as $condition) {
  2653. $parts[] = $this->getConditionSql($condition, $arguments);
  2654. }
  2655. return '(' . implode(' AND ', $parts) . ')';
  2656. }
  2657. private function getOrConditionSql(OrCondition $or, array &$arguments): string
  2658. {
  2659. $parts = [];
  2660. foreach ($or->getConditions() as $condition) {
  2661. $parts[] = $this->getConditionSql($condition, $arguments);
  2662. }
  2663. return '(' . implode(' OR ', $parts) . ')';
  2664. }
  2665. private function getNotConditionSql(NotCondition $not, array &$arguments): string
  2666. {
  2667. $condition = $not->getCondition();
  2668. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  2669. }
  2670. private function quoteColumnName(ReflectedColumn $column): string
  2671. {
  2672. return '"' . $column->getName() . '"';
  2673. }
  2674. private function escapeLikeValue(string $value): string
  2675. {
  2676. return addcslashes($value, '%_');
  2677. }
  2678. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): string
  2679. {
  2680. $column = $this->quoteColumnName($condition->getColumn());
  2681. $operator = $condition->getOperator();
  2682. $value = $condition->getValue();
  2683. switch ($operator) {
  2684. case 'cs':
  2685. $sql = "$column LIKE ?";
  2686. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  2687. break;
  2688. case 'sw':
  2689. $sql = "$column LIKE ?";
  2690. $arguments[] = $this->escapeLikeValue($value) . '%';
  2691. break;
  2692. case 'ew':
  2693. $sql = "$column LIKE ?";
  2694. $arguments[] = '%' . $this->escapeLikeValue($value);
  2695. break;
  2696. case 'eq':
  2697. $sql = "$column = ?";
  2698. $arguments[] = $value;
  2699. break;
  2700. case 'lt':
  2701. $sql = "$column < ?";
  2702. $arguments[] = $value;
  2703. break;
  2704. case 'le':
  2705. $sql = "$column <= ?";
  2706. $arguments[] = $value;
  2707. break;
  2708. case 'ge':
  2709. $sql = "$column >= ?";
  2710. $arguments[] = $value;
  2711. break;
  2712. case 'gt':
  2713. $sql = "$column > ?";
  2714. $arguments[] = $value;
  2715. break;
  2716. case 'bt':
  2717. $parts = explode(',', $value, 2);
  2718. $count = count($parts);
  2719. if ($count == 2) {
  2720. $sql = "($column >= ? AND $column <= ?)";
  2721. $arguments[] = $parts[0];
  2722. $arguments[] = $parts[1];
  2723. } else {
  2724. $sql = "FALSE";
  2725. }
  2726. break;
  2727. case 'in':
  2728. $parts = explode(',', $value);
  2729. $count = count($parts);
  2730. if ($count > 0) {
  2731. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  2732. $sql = "$column IN ($qmarks)";
  2733. for ($i = 0; $i < $count; $i++) {
  2734. $arguments[] = $parts[$i];
  2735. }
  2736. } else {
  2737. $sql = "FALSE";
  2738. }
  2739. break;
  2740. case 'is':
  2741. $sql = "$column IS NULL";
  2742. break;
  2743. }
  2744. return $sql;
  2745. }
  2746. private function getSpatialFunctionName(string $operator): string
  2747. {
  2748. switch ($operator) {
  2749. case 'co':return 'ST_Contains';
  2750. case 'cr':return 'ST_Crosses';
  2751. case 'di':return 'ST_Disjoint';
  2752. case 'eq':return 'ST_Equals';
  2753. case 'in':return 'ST_Intersects';
  2754. case 'ov':return 'ST_Overlaps';
  2755. case 'to':return 'ST_Touches';
  2756. case 'wi':return 'ST_Within';
  2757. case 'ic':return 'ST_IsClosed';
  2758. case 'is':return 'ST_IsSimple';
  2759. case 'iv':return 'ST_IsValid';
  2760. }
  2761. }
  2762. private function hasSpatialArgument(string $operator): bool
  2763. {
  2764. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  2765. }
  2766. private function getSpatialFunctionCall(string $functionName, string $column, bool $hasArgument): string
  2767. {
  2768. switch ($this->driver) {
  2769. case 'mysql':
  2770. case 'pgsql':
  2771. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  2772. return "$functionName($column, $argument)=TRUE";
  2773. case 'sqlsrv':
  2774. $functionName = str_replace('ST_', 'ST', $functionName);
  2775. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  2776. return "$column.$functionName($argument)=1";
  2777. }
  2778. }
  2779. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): string
  2780. {
  2781. $column = $this->quoteColumnName($condition->getColumn());
  2782. $operator = $condition->getOperator();
  2783. $value = $condition->getValue();
  2784. $functionName = $this->getSpatialFunctionName($operator);
  2785. $hasArgument = $this->hasSpatialArgument($operator);
  2786. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  2787. if ($hasArgument) {
  2788. $arguments[] = $value;
  2789. }
  2790. return $sql;
  2791. }
  2792. public function getWhereClause(Condition $condition, array &$arguments): string
  2793. {
  2794. if ($condition instanceof NoCondition) {
  2795. return '';
  2796. }
  2797. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  2798. }
  2799. }
  2800. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  2801. class DataConverter
  2802. {
  2803. private $driver;
  2804. public function __construct(string $driver)
  2805. {
  2806. $this->driver = $driver;
  2807. }
  2808. private function convertRecordValue($conversion, $value)
  2809. {
  2810. switch ($conversion) {
  2811. case 'boolean':
  2812. return $value ? true : false;
  2813. case 'integer':
  2814. return (int) $value;
  2815. }
  2816. return $value;
  2817. }
  2818. private function getRecordValueConversion(ReflectedColumn $column): string
  2819. {
  2820. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  2821. return 'boolean';
  2822. }
  2823. if ($this->driver == 'sqlsrv' && $column->getType() == 'bigint') {
  2824. return 'integer';
  2825. }
  2826. return 'none';
  2827. }
  2828. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  2829. {
  2830. foreach ($columnNames as $columnName) {
  2831. $column = $table->getColumn($columnName);
  2832. $conversion = $this->getRecordValueConversion($column);
  2833. if ($conversion != 'none') {
  2834. foreach ($records as $i => $record) {
  2835. $value = $records[$i][$columnName];
  2836. if ($value === null) {
  2837. continue;
  2838. }
  2839. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  2840. }
  2841. }
  2842. }
  2843. }
  2844. private function convertInputValue($conversion, $value)
  2845. {
  2846. switch ($conversion) {
  2847. case 'base64url_to_base64':
  2848. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  2849. }
  2850. return $value;
  2851. }
  2852. private function getInputValueConversion(ReflectedColumn $column): string
  2853. {
  2854. if ($column->isBinary()) {
  2855. return 'base64url_to_base64';
  2856. }
  2857. return 'none';
  2858. }
  2859. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  2860. {
  2861. $columnNames = array_keys($columnValues);
  2862. foreach ($columnNames as $columnName) {
  2863. $column = $table->getColumn($columnName);
  2864. $conversion = $this->getInputValueConversion($column);
  2865. if ($conversion != 'none') {
  2866. $value = $columnValues[$columnName];
  2867. if ($value !== null) {
  2868. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  2869. }
  2870. }
  2871. }
  2872. }
  2873. }
  2874. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  2875. class GenericDB
  2876. {
  2877. private $driver;
  2878. private $database;
  2879. private $pdo;
  2880. private $reflection;
  2881. private $definition;
  2882. private $conditions;
  2883. private $columns;
  2884. private $converter;
  2885. private function getDsn(string $address, int $port, string $database): string
  2886. {
  2887. switch ($this->driver) {
  2888. case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  2889. case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  2890. case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
  2891. }
  2892. }
  2893. private function getCommands(): array
  2894. {
  2895. switch ($this->driver) {
  2896. case 'mysql':return [
  2897. 'SET SESSION sql_warnings=1;',
  2898. 'SET NAMES utf8mb4;',
  2899. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  2900. ];
  2901. case 'pgsql':return [
  2902. "SET NAMES 'UTF8';",
  2903. ];
  2904. case 'sqlsrv':return [
  2905. ];
  2906. }
  2907. }
  2908. private function getOptions(): array
  2909. {
  2910. $options = array(
  2911. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  2912. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  2913. );
  2914. switch ($this->driver) {
  2915. case 'mysql':return $options + [
  2916. \PDO::ATTR_EMULATE_PREPARES => false,
  2917. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  2918. \PDO::ATTR_PERSISTENT => true,
  2919. ];
  2920. case 'pgsql':return $options + [
  2921. \PDO::ATTR_EMULATE_PREPARES => false,
  2922. \PDO::ATTR_PERSISTENT => true,
  2923. ];
  2924. case 'sqlsrv':return $options + [
  2925. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  2926. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  2927. ];
  2928. }
  2929. }
  2930. public function __construct(string $driver, string $address, int $port, string $database, string $username, string $password)
  2931. {
  2932. $this->driver = $driver;
  2933. $this->database = $database;
  2934. $dsn = $this->getDsn($address, $port, $database);
  2935. $options = $this->getOptions();
  2936. $this->pdo = new \PDO($dsn, $username, $password, $options);
  2937. $commands = $this->getCommands();
  2938. foreach ($commands as $command) {
  2939. $this->pdo->query($command);
  2940. }
  2941. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  2942. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  2943. $this->conditions = new ConditionsBuilder($driver);
  2944. $this->columns = new ColumnsBuilder($driver);
  2945. $this->converter = new DataConverter($driver);
  2946. }
  2947. public function pdo(): \PDO
  2948. {
  2949. return $this->pdo;
  2950. }
  2951. public function reflection(): GenericReflection
  2952. {
  2953. return $this->reflection;
  2954. }
  2955. public function definition(): GenericDefinition
  2956. {
  2957. return $this->definition;
  2958. }
  2959. private function addMiddlewareConditions(string $tableName, Condition $condition): Condition
  2960. {
  2961. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  2962. if ($condition1) {
  2963. $condition = $condition->_and($condition1);
  2964. }
  2965. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  2966. if ($condition2) {
  2967. $condition = $condition->_and($condition2);
  2968. }
  2969. return $condition;
  2970. }
  2971. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  2972. {
  2973. $this->converter->convertColumnValues($table, $columnValues);
  2974. $insertColumns = $this->columns->getInsert($table, $columnValues);
  2975. $tableName = $table->getName();
  2976. $pkName = $table->getPk()->getName();
  2977. $parameters = array_values($columnValues);
  2978. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  2979. $stmt = $this->query($sql, $parameters);
  2980. if (isset($columnValues[$pkName])) {
  2981. return $columnValues[$pkName];
  2982. }
  2983. switch ($this->driver) {
  2984. case 'mysql':
  2985. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  2986. break;
  2987. }
  2988. $pkValue = $stmt->fetchColumn(0);
  2989. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  2990. return (int) $pkValue;
  2991. }
  2992. return $pkValue;
  2993. }
  2994. public function selectSingle(ReflectedTable $table, array $columnNames, string $id) /*: ?array*/
  2995. {
  2996. $selectColumns = $this->columns->getSelect($table, $columnNames);
  2997. $tableName = $table->getName();
  2998. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  2999. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3000. $parameters = array();
  3001. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3002. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  3003. $stmt = $this->query($sql, $parameters);
  3004. $record = $stmt->fetch() ?: null;
  3005. if ($record === null) {
  3006. return null;
  3007. }
  3008. $records = array($record);
  3009. $this->converter->convertRecords($table, $columnNames, $records);
  3010. return $records[0];
  3011. }
  3012. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  3013. {
  3014. if (count($ids) == 0) {
  3015. return [];
  3016. }
  3017. $selectColumns = $this->columns->getSelect($table, $columnNames);
  3018. $tableName = $table->getName();
  3019. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  3020. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3021. $parameters = array();
  3022. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3023. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  3024. $stmt = $this->query($sql, $parameters);
  3025. $records = $stmt->fetchAll();
  3026. $this->converter->convertRecords($table, $columnNames, $records);
  3027. return $records;
  3028. }
  3029. public function selectCount(ReflectedTable $table, Condition $condition): int
  3030. {
  3031. $tableName = $table->getName();
  3032. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3033. $parameters = array();
  3034. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3035. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  3036. $stmt = $this->query($sql, $parameters);
  3037. return $stmt->fetchColumn(0);
  3038. }
  3039. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  3040. {
  3041. if ($limit == 0) {
  3042. return array();
  3043. }
  3044. $selectColumns = $this->columns->getSelect($table, $columnNames);
  3045. $tableName = $table->getName();
  3046. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3047. $parameters = array();
  3048. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3049. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  3050. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  3051. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  3052. $stmt = $this->query($sql, $parameters);
  3053. $records = $stmt->fetchAll();
  3054. $this->converter->convertRecords($table, $columnNames, $records);
  3055. return $records;
  3056. }
  3057. public function updateSingle(ReflectedTable $table, array $columnValues, string $id)
  3058. {
  3059. if (count($columnValues) == 0) {
  3060. return 0;
  3061. }
  3062. $this->converter->convertColumnValues($table, $columnValues);
  3063. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  3064. $tableName = $table->getName();
  3065. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  3066. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3067. $parameters = array_values($columnValues);
  3068. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3069. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  3070. $stmt = $this->query($sql, $parameters);
  3071. return $stmt->rowCount();
  3072. }
  3073. public function deleteSingle(ReflectedTable $table, string $id)
  3074. {
  3075. $tableName = $table->getName();
  3076. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  3077. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3078. $parameters = array();
  3079. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3080. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  3081. $stmt = $this->query($sql, $parameters);
  3082. return $stmt->rowCount();
  3083. }
  3084. public function incrementSingle(ReflectedTable $table, array $columnValues, string $id)
  3085. {
  3086. if (count($columnValues) == 0) {
  3087. return 0;
  3088. }
  3089. $this->converter->convertColumnValues($table, $columnValues);
  3090. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  3091. $tableName = $table->getName();
  3092. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  3093. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3094. $parameters = array_values($columnValues);
  3095. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3096. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  3097. $stmt = $this->query($sql, $parameters);
  3098. return $stmt->rowCount();
  3099. }
  3100. private function query(string $sql, array $parameters): \PDOStatement
  3101. {
  3102. $stmt = $this->pdo->prepare($sql);
  3103. $stmt->execute($parameters);
  3104. return $stmt;
  3105. }
  3106. }
  3107. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  3108. class GenericDefinition
  3109. {
  3110. private $pdo;
  3111. private $driver;
  3112. private $database;
  3113. private $typeConverter;
  3114. private $reflection;
  3115. public function __construct(\PDO $pdo, string $driver, string $database)
  3116. {
  3117. $this->pdo = $pdo;
  3118. $this->driver = $driver;
  3119. $this->database = $database;
  3120. $this->typeConverter = new TypeConverter($driver);
  3121. $this->reflection = new GenericReflection($pdo, $driver, $database);
  3122. }
  3123. private function quote(string $identifier): string
  3124. {
  3125. return '"' . str_replace('"', '', $identifier) . '"';
  3126. }
  3127. public function getColumnType(ReflectedColumn $column, bool $update): string
  3128. {
  3129. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  3130. return 'serial';
  3131. }
  3132. $type = $this->typeConverter->fromJdbc($column->getType());
  3133. if ($column->hasPrecision() && $column->hasScale()) {
  3134. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  3135. } else if ($column->hasPrecision()) {
  3136. $size = '(' . $column->getPrecision() . ')';
  3137. } else if ($column->hasLength()) {
  3138. $size = '(' . $column->getLength() . ')';
  3139. } else {
  3140. $size = '';
  3141. }
  3142. $null = $this->getColumnNullType($column, $update);
  3143. $auto = $this->getColumnAutoIncrement($column, $update);
  3144. return $type . $size . $null . $auto;
  3145. }
  3146. private function getPrimaryKey(string $tableName): string
  3147. {
  3148. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  3149. if (count($pks) == 1) {
  3150. return $pks[0];
  3151. }
  3152. return "";
  3153. }
  3154. private function canAutoIncrement(ReflectedColumn $column): bool
  3155. {
  3156. return in_array($column->getType(), ['integer', 'bigint']);
  3157. }
  3158. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): string
  3159. {
  3160. if (!$this->canAutoIncrement($column)) {
  3161. return '';
  3162. }
  3163. switch ($this->driver) {
  3164. case 'mysql':
  3165. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  3166. case 'pgsql':
  3167. case 'sqlsrv':
  3168. return '';
  3169. }
  3170. }
  3171. private function getColumnNullType(ReflectedColumn $column, bool $update): string
  3172. {
  3173. if ($this->driver == 'pgsql' && $update) {
  3174. return '';
  3175. }
  3176. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  3177. }
  3178. private function getTableRenameSQL(string $tableName, string $newTableName): string
  3179. {
  3180. $p1 = $this->quote($tableName);
  3181. $p2 = $this->quote($newTableName);
  3182. switch ($this->driver) {
  3183. case 'mysql':
  3184. return "RENAME TABLE $p1 TO $p2";
  3185. case 'pgsql':
  3186. return "ALTER TABLE $p1 RENAME TO $p2";
  3187. case 'sqlsrv':
  3188. return "EXEC sp_rename $p1, $p2";
  3189. }
  3190. }
  3191. private function getColumnRenameSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3192. {
  3193. $p1 = $this->quote($tableName);
  3194. $p2 = $this->quote($columnName);
  3195. $p3 = $this->quote($newColumn->getName());
  3196. switch ($this->driver) {
  3197. case 'mysql':
  3198. $p4 = $this->getColumnType($newColumn, true);
  3199. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3200. case 'pgsql':
  3201. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  3202. case 'sqlsrv':
  3203. $p4 = $this->quote($tableName . '.' . $columnName);
  3204. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  3205. }
  3206. }
  3207. private function getColumnRetypeSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3208. {
  3209. $p1 = $this->quote($tableName);
  3210. $p2 = $this->quote($columnName);
  3211. $p3 = $this->quote($newColumn->getName());
  3212. $p4 = $this->getColumnType($newColumn, true);
  3213. switch ($this->driver) {
  3214. case 'mysql':
  3215. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3216. case 'pgsql':
  3217. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  3218. case 'sqlsrv':
  3219. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  3220. }
  3221. }
  3222. private function getSetColumnNullableSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3223. {
  3224. $p1 = $this->quote($tableName);
  3225. $p2 = $this->quote($columnName);
  3226. $p3 = $this->quote($newColumn->getName());
  3227. $p4 = $this->getColumnType($newColumn, true);
  3228. switch ($this->driver) {
  3229. case 'mysql':
  3230. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3231. case 'pgsql':
  3232. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  3233. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  3234. case 'sqlsrv':
  3235. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  3236. }
  3237. }
  3238. private function getSetColumnPkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3239. {
  3240. $p1 = $this->quote($tableName);
  3241. $p2 = $this->quote($columnName);
  3242. $p3 = $this->quote($tableName . '_pkey');
  3243. switch ($this->driver) {
  3244. case 'mysql':
  3245. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  3246. return "ALTER TABLE $p1 $p4";
  3247. case 'pgsql':
  3248. case 'sqlsrv':
  3249. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  3250. return "ALTER TABLE $p1 $p4";
  3251. }
  3252. }
  3253. private function getSetColumnPkSequenceSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3254. {
  3255. $p1 = $this->quote($tableName);
  3256. $p2 = $this->quote($columnName);
  3257. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  3258. switch ($this->driver) {
  3259. case 'mysql':
  3260. return "select 1";
  3261. case 'pgsql':
  3262. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  3263. case 'sqlsrv':
  3264. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  3265. }
  3266. }
  3267. private function getSetColumnPkSequenceStartSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3268. {
  3269. $p1 = $this->quote($tableName);
  3270. $p2 = $this->quote($columnName);
  3271. switch ($this->driver) {
  3272. case 'mysql':
  3273. return "select 1";
  3274. case 'pgsql':
  3275. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  3276. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  3277. case 'sqlsrv':
  3278. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  3279. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  3280. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  3281. }
  3282. }
  3283. private function getSetColumnPkDefaultSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3284. {
  3285. $p1 = $this->quote($tableName);
  3286. $p2 = $this->quote($columnName);
  3287. switch ($this->driver) {
  3288. case 'mysql':
  3289. $p3 = $this->quote($newColumn->getName());
  3290. $p4 = $this->getColumnType($newColumn, true);
  3291. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3292. case 'pgsql':
  3293. if ($newColumn->getPk()) {
  3294. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  3295. $p4 = "SET DEFAULT nextval($p3)";
  3296. } else {
  3297. $p4 = 'DROP DEFAULT';
  3298. }
  3299. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  3300. case 'sqlsrv':
  3301. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  3302. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  3303. if ($newColumn->getPk()) {
  3304. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  3305. } else {
  3306. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  3307. }
  3308. }
  3309. }
  3310. private function getAddColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3311. {
  3312. $p1 = $this->quote($tableName);
  3313. $p2 = $this->quote($columnName);
  3314. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  3315. $p4 = $this->quote($newColumn->getFk());
  3316. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  3317. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  3318. }
  3319. private function getRemoveColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3320. {
  3321. $p1 = $this->quote($tableName);
  3322. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  3323. switch ($this->driver) {
  3324. case 'mysql':
  3325. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  3326. case 'pgsql':
  3327. case 'sqlsrv':
  3328. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  3329. }
  3330. }
  3331. private function getAddTableSQL(ReflectedTable $newTable): string
  3332. {
  3333. $tableName = $newTable->getName();
  3334. $p1 = $this->quote($tableName);
  3335. $fields = [];
  3336. $constraints = [];
  3337. foreach ($newTable->getColumnNames() as $columnName) {
  3338. $pkColumn = $this->getPrimaryKey($tableName);
  3339. $newColumn = $newTable->getColumn($columnName);
  3340. $f1 = $this->quote($columnName);
  3341. $f2 = $this->getColumnType($newColumn, false);
  3342. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  3343. $f4 = $this->quote($newColumn->getFk());
  3344. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  3345. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  3346. $fields[] = "$f1 $f2";
  3347. if ($newColumn->getPk()) {
  3348. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  3349. }
  3350. if ($newColumn->getFk()) {
  3351. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  3352. }
  3353. }
  3354. $p2 = implode(',', array_merge($fields, $constraints));
  3355. return "CREATE TABLE $p1 ($p2);";
  3356. }
  3357. private function getAddColumnSQL(string $tableName, ReflectedColumn $newColumn): string
  3358. {
  3359. $p1 = $this->quote($tableName);
  3360. $p2 = $this->quote($newColumn->getName());
  3361. $p3 = $this->getColumnType($newColumn, false);
  3362. switch ($this->driver) {
  3363. case 'mysql':
  3364. case 'pgsql':
  3365. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  3366. case 'sqlsrv':
  3367. return "ALTER TABLE $p1 ADD $p2 $p3";
  3368. }
  3369. }
  3370. private function getRemoveTableSQL(string $tableName): string
  3371. {
  3372. $p1 = $this->quote($tableName);
  3373. switch ($this->driver) {
  3374. case 'mysql':
  3375. case 'pgsql':
  3376. return "DROP TABLE $p1 CASCADE;";
  3377. case 'sqlsrv':
  3378. return "DROP TABLE $p1;";
  3379. }
  3380. }
  3381. private function getRemoveColumnSQL(string $tableName, string $columnName): string
  3382. {
  3383. $p1 = $this->quote($tableName);
  3384. $p2 = $this->quote($columnName);
  3385. switch ($this->driver) {
  3386. case 'mysql':
  3387. case 'pgsql':
  3388. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  3389. case 'sqlsrv':
  3390. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  3391. }
  3392. }
  3393. public function renameTable(string $tableName, string $newTableName)
  3394. {
  3395. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  3396. return $this->query($sql);
  3397. }
  3398. public function renameColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3399. {
  3400. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  3401. return $this->query($sql);
  3402. }
  3403. public function retypeColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3404. {
  3405. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  3406. return $this->query($sql);
  3407. }
  3408. public function setColumnNullable(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3409. {
  3410. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  3411. return $this->query($sql);
  3412. }
  3413. public function addColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3414. {
  3415. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  3416. $this->query($sql);
  3417. if ($this->canAutoIncrement($newColumn)) {
  3418. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  3419. $this->query($sql);
  3420. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  3421. $this->query($sql);
  3422. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  3423. $this->query($sql);
  3424. }
  3425. return true;
  3426. }
  3427. public function removeColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3428. {
  3429. if ($this->canAutoIncrement($newColumn)) {
  3430. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  3431. $this->query($sql);
  3432. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  3433. $this->query($sql);
  3434. }
  3435. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  3436. $this->query($sql);
  3437. return true;
  3438. }
  3439. public function addColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3440. {
  3441. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  3442. return $this->query($sql);
  3443. }
  3444. public function removeColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3445. {
  3446. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  3447. return $this->query($sql);
  3448. }
  3449. public function addTable(ReflectedTable $newTable)
  3450. {
  3451. $sql = $this->getAddTableSQL($newTable);
  3452. return $this->query($sql);
  3453. }
  3454. public function addColumn(string $tableName, ReflectedColumn $newColumn)
  3455. {
  3456. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  3457. return $this->query($sql);
  3458. }
  3459. public function removeTable(string $tableName)
  3460. {
  3461. $sql = $this->getRemoveTableSQL($tableName);
  3462. return $this->query($sql);
  3463. }
  3464. public function removeColumn(string $tableName, string $columnName)
  3465. {
  3466. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  3467. return $this->query($sql);
  3468. }
  3469. private function query(string $sql): bool
  3470. {
  3471. $stmt = $this->pdo->prepare($sql);
  3472. return $stmt->execute();
  3473. }
  3474. }
  3475. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  3476. class GenericReflection
  3477. {
  3478. private $pdo;
  3479. private $driver;
  3480. private $database;
  3481. private $typeConverter;
  3482. public function __construct(\PDO $pdo, string $driver, string $database)
  3483. {
  3484. $this->pdo = $pdo;
  3485. $this->driver = $driver;
  3486. $this->database = $database;
  3487. $this->typeConverter = new TypeConverter($driver);
  3488. }
  3489. public function getIgnoredTables(): array
  3490. {
  3491. switch ($this->driver) {
  3492. case 'mysql':return [];
  3493. case 'pgsql':return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  3494. case 'sqlsrv':return [];
  3495. }
  3496. }
  3497. private function getTablesSQL(): string
  3498. {
  3499. switch ($this->driver) {
  3500. 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"';
  3501. 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";';
  3502. 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"';
  3503. }
  3504. }
  3505. private function getTableColumnsSQL(): string
  3506. {
  3507. switch ($this->driver) {
  3508. 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" = ?';
  3509. 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;';
  3510. 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 \'\' <> ?';
  3511. }
  3512. }
  3513. private function getTablePrimaryKeysSQL(): string
  3514. {
  3515. switch ($this->driver) {
  3516. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  3517. 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\'';
  3518. 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 \'\' <> ?';
  3519. }
  3520. }
  3521. private function getTableForeignKeysSQL(): string
  3522. {
  3523. switch ($this->driver) {
  3524. 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" = ?';
  3525. 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\'';
  3526. 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 \'\' <> ?';
  3527. }
  3528. }
  3529. public function getDatabaseName(): string
  3530. {
  3531. return $this->database;
  3532. }
  3533. public function getTables(): array
  3534. {
  3535. $sql = $this->getTablesSQL();
  3536. $results = $this->query($sql, [$this->database]);
  3537. foreach ($results as &$result) {
  3538. switch ($this->driver) {
  3539. case 'mysql':
  3540. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  3541. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  3542. break;
  3543. case 'pgsql':
  3544. $map = ['r' => 'table', 'v' => 'view'];
  3545. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  3546. break;
  3547. case 'sqlsrv':
  3548. $map = ['U' => 'table', 'V' => 'view'];
  3549. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  3550. break;
  3551. }
  3552. }
  3553. return $results;
  3554. }
  3555. public function getTableColumns(string $tableName, string $type): array
  3556. {
  3557. $sql = $this->getTableColumnsSQL();
  3558. $results = $this->query($sql, [$tableName, $this->database]);
  3559. if ($type == 'view') {
  3560. foreach ($results as &$result) {
  3561. $result['IS_NULLABLE'] = false;
  3562. }
  3563. }
  3564. return $results;
  3565. }
  3566. public function getTablePrimaryKeys(string $tableName): array
  3567. {
  3568. $sql = $this->getTablePrimaryKeysSQL();
  3569. $results = $this->query($sql, [$tableName, $this->database]);
  3570. $primaryKeys = [];
  3571. foreach ($results as $result) {
  3572. $primaryKeys[] = $result['COLUMN_NAME'];
  3573. }
  3574. return $primaryKeys;
  3575. }
  3576. public function getTableForeignKeys(string $tableName): array
  3577. {
  3578. $sql = $this->getTableForeignKeysSQL();
  3579. $results = $this->query($sql, [$tableName, $this->database]);
  3580. $foreignKeys = [];
  3581. foreach ($results as $result) {
  3582. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  3583. }
  3584. return $foreignKeys;
  3585. }
  3586. public function toJdbcType(string $type, int $size): string
  3587. {
  3588. return $this->typeConverter->toJdbc($type, $size);
  3589. }
  3590. private function query(string $sql, array $parameters): array
  3591. {
  3592. $stmt = $this->pdo->prepare($sql);
  3593. $stmt->execute($parameters);
  3594. return $stmt->fetchAll();
  3595. }
  3596. }
  3597. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  3598. class TypeConverter
  3599. {
  3600. private $driver;
  3601. public function __construct(string $driver)
  3602. {
  3603. $this->driver = $driver;
  3604. }
  3605. private $fromJdbc = [
  3606. 'mysql' => [
  3607. 'clob' => 'longtext',
  3608. 'boolean' => 'bit',
  3609. 'blob' => 'longblob',
  3610. 'timestamp' => 'datetime',
  3611. ],
  3612. 'pgsql' => [
  3613. 'clob' => 'text',
  3614. 'blob' => 'bytea',
  3615. ],
  3616. 'sqlsrv' => [
  3617. 'boolean' => 'bit',
  3618. 'varchar' => 'nvarchar',
  3619. 'clob' => 'ntext',
  3620. 'blob' => 'image',
  3621. ],
  3622. ];
  3623. private $toJdbc = [
  3624. 'simplified' => [
  3625. 'char' => 'varchar',
  3626. 'longvarchar' => 'clob',
  3627. 'nchar' => 'varchar',
  3628. 'nvarchar' => 'varchar',
  3629. 'longnvarchar' => 'clob',
  3630. 'binary' => 'varbinary',
  3631. 'longvarbinary' => 'blob',
  3632. 'tinyint' => 'integer',
  3633. 'smallint' => 'integer',
  3634. 'real' => 'float',
  3635. 'numeric' => 'decimal',
  3636. 'time_with_timezone' => 'time',
  3637. 'timestamp_with_timezone' => 'timestamp',
  3638. ],
  3639. 'mysql' => [
  3640. 'bit' => 'boolean',
  3641. 'tinyblob' => 'blob',
  3642. 'mediumblob' => 'blob',
  3643. 'longblob' => 'blob',
  3644. 'tinytext' => 'clob',
  3645. 'mediumtext' => 'clob',
  3646. 'longtext' => 'clob',
  3647. 'text' => 'clob',
  3648. 'mediumint' => 'integer',
  3649. 'int' => 'integer',
  3650. 'polygon' => 'geometry',
  3651. 'point' => 'geometry',
  3652. 'datetime' => 'timestamp',
  3653. 'year' => 'integer',
  3654. 'enum' => 'varchar',
  3655. 'json' => 'clob',
  3656. ],
  3657. 'pgsql' => [
  3658. 'bigserial' => 'bigint',
  3659. 'bit varying' => 'bit',
  3660. 'box' => 'geometry',
  3661. 'bytea' => 'blob',
  3662. 'bpchar' => 'char',
  3663. 'character varying' => 'varchar',
  3664. 'character' => 'char',
  3665. 'cidr' => 'varchar',
  3666. 'circle' => 'geometry',
  3667. 'double precision' => 'double',
  3668. 'inet' => 'integer',
  3669. 'json' => 'clob',
  3670. 'jsonb' => 'clob',
  3671. 'line' => 'geometry',
  3672. 'lseg' => 'geometry',
  3673. 'macaddr' => 'varchar',
  3674. 'money' => 'decimal',
  3675. 'path' => 'geometry',
  3676. 'point' => 'geometry',
  3677. 'polygon' => 'geometry',
  3678. 'real' => 'float',
  3679. 'serial' => 'integer',
  3680. 'text' => 'clob',
  3681. 'time without time zone' => 'time',
  3682. 'time with time zone' => 'time_with_timezone',
  3683. 'timestamp without time zone' => 'timestamp',
  3684. 'timestamp with time zone' => 'timestamp_with_timezone',
  3685. 'uuid' => 'char',
  3686. 'xml' => 'clob',
  3687. ],
  3688. 'sqlsrv' => [
  3689. 'varbinary(0)' => 'blob',
  3690. 'bit' => 'boolean',
  3691. 'datetime' => 'timestamp',
  3692. 'datetime2' => 'timestamp',
  3693. 'float' => 'double',
  3694. 'image' => 'blob',
  3695. 'int' => 'integer',
  3696. 'money' => 'decimal',
  3697. 'ntext' => 'clob',
  3698. 'smalldatetime' => 'timestamp',
  3699. 'smallmoney' => 'decimal',
  3700. 'text' => 'clob',
  3701. 'timestamp' => 'binary',
  3702. 'udt' => 'varbinary',
  3703. 'uniqueidentifier' => 'char',
  3704. 'xml' => 'clob',
  3705. ],
  3706. ];
  3707. private $valid = [
  3708. 'bigint' => true,
  3709. 'binary' => true,
  3710. 'bit' => true,
  3711. 'blob' => true,
  3712. 'boolean' => true,
  3713. 'char' => true,
  3714. 'clob' => true,
  3715. 'date' => true,
  3716. 'decimal' => true,
  3717. 'distinct' => true,
  3718. 'double' => true,
  3719. 'float' => true,
  3720. 'integer' => true,
  3721. 'longnvarchar' => true,
  3722. 'longvarbinary' => true,
  3723. 'longvarchar' => true,
  3724. 'nchar' => true,
  3725. 'nclob' => true,
  3726. 'numeric' => true,
  3727. 'nvarchar' => true,
  3728. 'real' => true,
  3729. 'smallint' => true,
  3730. 'time' => true,
  3731. 'time_with_timezone' => true,
  3732. 'timestamp' => true,
  3733. 'timestamp_with_timezone' => true,
  3734. 'tinyint' => true,
  3735. 'varbinary' => true,
  3736. 'varchar' => true,
  3737. 'geometry' => true,
  3738. ];
  3739. public function toJdbc(string $type, int $size): string
  3740. {
  3741. $jdbcType = strtolower($type);
  3742. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  3743. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  3744. }
  3745. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  3746. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  3747. }
  3748. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  3749. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  3750. }
  3751. if (!isset($this->valid[$jdbcType])) {
  3752. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  3753. }
  3754. return $jdbcType;
  3755. }
  3756. public function fromJdbc(string $type): string
  3757. {
  3758. $jdbcType = strtolower($type);
  3759. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  3760. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  3761. }
  3762. return $jdbcType;
  3763. }
  3764. }
  3765. // file: src/Tqdev/PhpCrudApi/GeoJson/Feature.php
  3766. class Feature implements \JsonSerializable
  3767. {
  3768. private $properties;
  3769. private $geometry;
  3770. public function __construct(array $properties, /*?Geometry*/ $geometry)
  3771. {
  3772. $this->properties = $properties;
  3773. $this->geometry = $geometry;
  3774. }
  3775. public function serialize()
  3776. {
  3777. return [
  3778. 'type' => 'Feature',
  3779. 'properties' => $this->properties,
  3780. 'geometry' => $this->geometry,
  3781. ];
  3782. }
  3783. public function jsonSerialize()
  3784. {
  3785. return $this->serialize();
  3786. }
  3787. }
  3788. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  3789. class FeatureCollection implements \JsonSerializable
  3790. {
  3791. private $features;
  3792. private $results;
  3793. public function __construct(array $features, int $results)
  3794. {
  3795. $this->features = $features;
  3796. $this->results = $results;
  3797. }
  3798. public function serialize()
  3799. {
  3800. return [
  3801. 'type' => 'FeatureCollection',
  3802. 'features' => $this->features,
  3803. 'results' => $this->results,
  3804. ];
  3805. }
  3806. public function jsonSerialize()
  3807. {
  3808. return array_filter($this->serialize(), function ($v) {
  3809. return $v !== 0;
  3810. });
  3811. }
  3812. }
  3813. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  3814. class GeoJsonService
  3815. {
  3816. private $reflection;
  3817. private $records;
  3818. public function __construct(ReflectionService $reflection, RecordService $records)
  3819. {
  3820. $this->reflection = $reflection;
  3821. $this->records = $records;
  3822. }
  3823. public function hasTable(string $table): bool
  3824. {
  3825. return $this->reflection->hasTable($table);
  3826. }
  3827. public function getType(string $table): string
  3828. {
  3829. return $this->reflection->getType($table);
  3830. }
  3831. private function getGeometryColumnName(string $tableName, array &$params): string
  3832. {
  3833. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  3834. $table = $this->reflection->getTable($tableName);
  3835. $geometryColumnName = '';
  3836. foreach ($table->getColumnNames() as $columnName) {
  3837. if ($geometryParam && $geometryParam != $columnName) {
  3838. continue;
  3839. }
  3840. $column = $table->getColumn($columnName);
  3841. if ($column->isGeometry()) {
  3842. $geometryColumnName = $columnName;
  3843. break;
  3844. }
  3845. }
  3846. if ($geometryColumnName) {
  3847. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  3848. }
  3849. return $geometryColumnName;
  3850. }
  3851. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  3852. {
  3853. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  3854. if ($boundingBox) {
  3855. $c = explode(',', $boundingBox);
  3856. if (!isset($params['filter'])) {
  3857. $params['filter'] = array();
  3858. }
  3859. $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]))";
  3860. }
  3861. }
  3862. private function convertRecordToFeature( /*object*/$record, string $geometryColumnName)
  3863. {
  3864. $geometry = null;
  3865. if (isset($record[$geometryColumnName])) {
  3866. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  3867. }
  3868. $properties = array_diff_key($record, [$geometryColumnName => true]);
  3869. return new Feature($properties, $geometry);
  3870. }
  3871. public function _list(string $tableName, array $params): FeatureCollection
  3872. {
  3873. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  3874. $this->setBoudingBoxFilter($geometryColumnName, $params);
  3875. $records = $this->records->_list($tableName, $params);
  3876. $features = array();
  3877. foreach ($records->getRecords() as $record) {
  3878. $features[] = $this->convertRecordToFeature($record, $geometryColumnName);
  3879. }
  3880. return new FeatureCollection($features, $records->getResults());
  3881. }
  3882. public function read(string $tableName, string $id, array $params): Feature
  3883. {
  3884. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  3885. $this->setBoudingBoxFilter($geometryColumnName, $params);
  3886. $record = $this->records->read($tableName, $id, $params);
  3887. return $this->convertRecordToFeature($record, $geometryColumnName);
  3888. }
  3889. }
  3890. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  3891. class Geometry implements \JsonSerializable
  3892. {
  3893. private $type;
  3894. private $geometry;
  3895. public static $types = [
  3896. "Point",
  3897. "MultiPoint",
  3898. "LineString",
  3899. "MultiLineString",
  3900. "Polygon",
  3901. "MultiPolygon",
  3902. ];
  3903. public function __construct(string $type, array $coordinates)
  3904. {
  3905. $this->type = $type;
  3906. $this->coordinates = $coordinates;
  3907. }
  3908. public static function fromWkt(string $wkt): Geometry
  3909. {
  3910. $bracket = strpos($wkt, '(');
  3911. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  3912. $supported = false;
  3913. foreach (Geometry::$types as $typeName) {
  3914. if (strtoupper($typeName) == $type) {
  3915. $type = $typeName;
  3916. $supported = true;
  3917. }
  3918. }
  3919. if (!$supported) {
  3920. throw new \Exception('Geometry type not supported: ' . $type);
  3921. }
  3922. $coordinates = substr($wkt, $bracket);
  3923. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  3924. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  3925. }
  3926. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  3927. $json = $coordinates;
  3928. $coordinates = json_decode($coordinates);
  3929. if (!$coordinates) {
  3930. throw new \Exception('Could not decode WKT: ' . $wkt);
  3931. }
  3932. return new Geometry($type, $coordinates);
  3933. }
  3934. public function serialize()
  3935. {
  3936. return [
  3937. 'type' => $this->type,
  3938. 'coordinates' => $this->coordinates,
  3939. ];
  3940. }
  3941. public function jsonSerialize()
  3942. {
  3943. return $this->serialize();
  3944. }
  3945. }
  3946. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  3947. abstract class Middleware implements MiddlewareInterface
  3948. {
  3949. protected $next;
  3950. protected $responder;
  3951. private $properties;
  3952. public function __construct(Router $router, Responder $responder, array $properties)
  3953. {
  3954. $router->load($this);
  3955. $this->responder = $responder;
  3956. $this->properties = $properties;
  3957. }
  3958. protected function getArrayProperty(string $key, string $default): array
  3959. {
  3960. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  3961. }
  3962. protected function getProperty(string $key, $default)
  3963. {
  3964. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  3965. }
  3966. }
  3967. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  3968. class VariableStore
  3969. {
  3970. static $values = array();
  3971. public static function get(string $key)
  3972. {
  3973. if (isset(self::$values[$key])) {
  3974. return self::$values[$key];
  3975. }
  3976. return null;
  3977. }
  3978. public static function set(string $key, /* object */ $value)
  3979. {
  3980. self::$values[$key] = $value;
  3981. }
  3982. }
  3983. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  3984. interface Router extends RequestHandlerInterface
  3985. {
  3986. public function register(string $method, string $path, array $handler);
  3987. public function load(Middleware $middleware);
  3988. public function route(ServerRequestInterface $request): ResponseInterface;
  3989. }
  3990. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  3991. class SimpleRouter implements Router
  3992. {
  3993. private $basePath;
  3994. private $responder;
  3995. private $cache;
  3996. private $ttl;
  3997. private $debug;
  3998. private $registration;
  3999. private $routes;
  4000. private $routeHandlers;
  4001. private $middlewares;
  4002. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  4003. {
  4004. $this->basePath = $basePath;
  4005. $this->responder = $responder;
  4006. $this->cache = $cache;
  4007. $this->ttl = $ttl;
  4008. $this->debug = $debug;
  4009. $this->registration = true;
  4010. $this->routes = $this->loadPathTree();
  4011. $this->routeHandlers = [];
  4012. $this->middlewares = array();
  4013. }
  4014. private function loadPathTree(): PathTree
  4015. {
  4016. $data = $this->cache->get('PathTree');
  4017. if ($data != '') {
  4018. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  4019. $this->registration = false;
  4020. } else {
  4021. $tree = new PathTree();
  4022. }
  4023. return $tree;
  4024. }
  4025. public function register(string $method, string $path, array $handler)
  4026. {
  4027. $routeNumber = count($this->routeHandlers);
  4028. $this->routeHandlers[$routeNumber] = $handler;
  4029. if ($this->registration) {
  4030. $parts = explode('/', trim($path, '/'));
  4031. array_unshift($parts, $method);
  4032. $this->routes->put($parts, $routeNumber);
  4033. }
  4034. }
  4035. public function load(Middleware $middleware) /*: void*/
  4036. {
  4037. array_push($this->middlewares, $middleware);
  4038. }
  4039. public function route(ServerRequestInterface $request): ResponseInterface
  4040. {
  4041. if ($this->registration) {
  4042. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  4043. $this->cache->set('PathTree', $data, $this->ttl);
  4044. }
  4045. return $this->handle($request);
  4046. }
  4047. private function getRouteNumbers(ServerRequestInterface $request): array
  4048. {
  4049. $method = strtoupper($request->getMethod());
  4050. $path = array();
  4051. $segment = $method;
  4052. for ($i = 1; $segment; $i++) {
  4053. array_push($path, $segment);
  4054. $segment = RequestUtils::getPathSegment($request, $i);
  4055. }
  4056. return $this->routes->match($path);
  4057. }
  4058. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  4059. {
  4060. if ($this->basePath) {
  4061. $path = $request->getUri()->getPath();
  4062. $basePath = rtrim($this->basePath, '/');
  4063. if (substr($path, 0, strlen($basePath)) == $basePath) {
  4064. $path = substr($path, strlen($basePath));
  4065. $request = $request->withUri($request->getUri()->withPath($path));
  4066. }
  4067. } elseif (isset($_SERVER['PATH_INFO'])) {
  4068. $path = $_SERVER['PATH_INFO'];
  4069. $request = $request->withUri($request->getUri()->withPath($path));
  4070. }
  4071. return $request;
  4072. }
  4073. public function handle(ServerRequestInterface $request): ResponseInterface
  4074. {
  4075. $request = $this->removeBasePath($request);
  4076. if (count($this->middlewares)) {
  4077. $handler = array_pop($this->middlewares);
  4078. return $handler->process($request, $this);
  4079. }
  4080. $routeNumbers = $this->getRouteNumbers($request);
  4081. if (count($routeNumbers) == 0) {
  4082. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  4083. }
  4084. try {
  4085. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  4086. } catch (\PDOException $e) {
  4087. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  4088. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  4089. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  4090. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4091. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  4092. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4093. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  4094. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4095. } else {
  4096. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  4097. }
  4098. if ($this->debug) {
  4099. $response = ResponseUtils::addExceptionHeaders($response, $e);
  4100. }
  4101. }
  4102. return $response;
  4103. }
  4104. }
  4105. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  4106. class AjaxOnlyMiddleware extends Middleware
  4107. {
  4108. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4109. {
  4110. $method = $request->getMethod();
  4111. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  4112. if (!in_array($method, $excludeMethods)) {
  4113. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  4114. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  4115. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  4116. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  4117. }
  4118. }
  4119. return $next->handle($request);
  4120. }
  4121. }
  4122. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  4123. class AuthorizationMiddleware extends Middleware
  4124. {
  4125. private $reflection;
  4126. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4127. {
  4128. parent::__construct($router, $responder, $properties);
  4129. $this->reflection = $reflection;
  4130. }
  4131. private function handleColumns(string $operation, string $tableName) /*: void*/
  4132. {
  4133. $columnHandler = $this->getProperty('columnHandler', '');
  4134. if ($columnHandler) {
  4135. $table = $this->reflection->getTable($tableName);
  4136. foreach ($table->getColumnNames() as $columnName) {
  4137. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  4138. if (!$allowed) {
  4139. $table->removeColumn($columnName);
  4140. }
  4141. }
  4142. }
  4143. }
  4144. private function handleTable(string $operation, string $tableName) /*: void*/
  4145. {
  4146. if (!$this->reflection->hasTable($tableName)) {
  4147. return;
  4148. }
  4149. $tableHandler = $this->getProperty('tableHandler', '');
  4150. if ($tableHandler) {
  4151. $allowed = call_user_func($tableHandler, $operation, $tableName);
  4152. if (!$allowed) {
  4153. $this->reflection->removeTable($tableName);
  4154. } else {
  4155. $this->handleColumns($operation, $tableName);
  4156. }
  4157. }
  4158. }
  4159. private function handleRecords(string $operation, string $tableName) /*: void*/
  4160. {
  4161. if (!$this->reflection->hasTable($tableName)) {
  4162. return;
  4163. }
  4164. $recordHandler = $this->getProperty('recordHandler', '');
  4165. if ($recordHandler) {
  4166. $query = call_user_func($recordHandler, $operation, $tableName);
  4167. $filters = new FilterInfo();
  4168. $table = $this->reflection->getTable($tableName);
  4169. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  4170. parse_str($query, $params);
  4171. $condition = $filters->getCombinedConditions($table, $params);
  4172. VariableStore::set("authorization.conditions.$tableName", $condition);
  4173. }
  4174. }
  4175. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4176. {
  4177. $path = RequestUtils::getPathSegment($request, 1);
  4178. $operation = RequestUtils::getOperation($request);
  4179. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  4180. foreach ($tableNames as $tableName) {
  4181. $this->handleTable($operation, $tableName);
  4182. if ($path == 'records') {
  4183. $this->handleRecords($operation, $tableName);
  4184. }
  4185. }
  4186. if ($path == 'openapi') {
  4187. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  4188. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  4189. }
  4190. return $next->handle($request);
  4191. }
  4192. }
  4193. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  4194. class BasicAuthMiddleware extends Middleware
  4195. {
  4196. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  4197. {
  4198. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  4199. if ($hash && password_verify($password, $hash)) {
  4200. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  4201. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  4202. }
  4203. return true;
  4204. }
  4205. return false;
  4206. }
  4207. private function getValidUsername(string $username, string $password, string $passwordFile): string
  4208. {
  4209. $passwords = $this->readPasswords($passwordFile);
  4210. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  4211. $this->writePasswords($passwordFile, $passwords);
  4212. return $valid ? $username : '';
  4213. }
  4214. private function readPasswords(string $passwordFile): array
  4215. {
  4216. $passwords = [];
  4217. $passwordLines = file($passwordFile);
  4218. foreach ($passwordLines as $passwordLine) {
  4219. if (strpos($passwordLine, ':') !== false) {
  4220. list($username, $hash) = explode(':', trim($passwordLine), 2);
  4221. if (strlen($hash) > 0 && $hash[0] != '$') {
  4222. $hash = password_hash($hash, PASSWORD_DEFAULT);
  4223. }
  4224. $passwords[$username] = $hash;
  4225. }
  4226. }
  4227. return $passwords;
  4228. }
  4229. private function writePasswords(string $passwordFile, array $passwords): bool
  4230. {
  4231. $success = false;
  4232. $passwordFileContents = '';
  4233. foreach ($passwords as $username => $hash) {
  4234. $passwordFileContents .= "$username:$hash\n";
  4235. }
  4236. if (file_get_contents($passwordFile) != $passwordFileContents) {
  4237. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  4238. }
  4239. return $success;
  4240. }
  4241. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  4242. {
  4243. if (isset($_SERVER['PHP_AUTH_USER'])) {
  4244. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  4245. }
  4246. $header = RequestUtils::getHeader($request, 'Authorization');
  4247. $parts = explode(' ', trim($header), 2);
  4248. if (count($parts) != 2) {
  4249. return '';
  4250. }
  4251. if ($parts[0] != 'Basic') {
  4252. return '';
  4253. }
  4254. return base64_decode(strtr($parts[1], '-_', '+/'));
  4255. }
  4256. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4257. {
  4258. if (session_status() == PHP_SESSION_NONE) {
  4259. session_start();
  4260. }
  4261. $credentials = $this->getAuthorizationCredentials($request);
  4262. if ($credentials) {
  4263. list($username, $password) = array('', '');
  4264. if (strpos($credentials, ':') !== false) {
  4265. list($username, $password) = explode(':', $credentials, 2);
  4266. }
  4267. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  4268. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  4269. $_SESSION['username'] = $validUser;
  4270. if (!$validUser) {
  4271. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  4272. }
  4273. if (!headers_sent()) {
  4274. session_regenerate_id();
  4275. }
  4276. }
  4277. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  4278. $authenticationMode = $this->getProperty('mode', 'required');
  4279. if ($authenticationMode == 'required') {
  4280. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4281. $realm = $this->getProperty('realm', 'Username and password required');
  4282. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  4283. return $response;
  4284. }
  4285. }
  4286. return $next->handle($request);
  4287. }
  4288. }
  4289. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  4290. class CorsMiddleware extends Middleware
  4291. {
  4292. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  4293. {
  4294. $found = false;
  4295. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  4296. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  4297. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  4298. if (preg_match($regex, $origin)) {
  4299. $found = true;
  4300. break;
  4301. }
  4302. }
  4303. return $found;
  4304. }
  4305. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4306. {
  4307. $method = $request->getMethod();
  4308. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  4309. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  4310. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  4311. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  4312. } elseif ($method == 'OPTIONS') {
  4313. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  4314. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  4315. if ($allowHeaders) {
  4316. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  4317. }
  4318. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  4319. if ($allowMethods) {
  4320. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  4321. }
  4322. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  4323. if ($allowCredentials) {
  4324. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  4325. }
  4326. $maxAge = $this->getProperty('maxAge', '1728000');
  4327. if ($maxAge) {
  4328. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  4329. }
  4330. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  4331. if ($exposeHeaders) {
  4332. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  4333. }
  4334. } else {
  4335. $response = $next->handle($request);
  4336. }
  4337. if ($origin) {
  4338. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  4339. if ($allowCredentials) {
  4340. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  4341. }
  4342. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  4343. }
  4344. return $response;
  4345. }
  4346. }
  4347. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  4348. class CustomizationMiddleware extends Middleware
  4349. {
  4350. private $reflection;
  4351. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4352. {
  4353. parent::__construct($router, $responder, $properties);
  4354. $this->reflection = $reflection;
  4355. }
  4356. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4357. {
  4358. $operation = RequestUtils::getOperation($request);
  4359. $tableName = RequestUtils::getPathSegment($request, 2);
  4360. $beforeHandler = $this->getProperty('beforeHandler', '');
  4361. $environment = (object) array();
  4362. if ($beforeHandler !== '') {
  4363. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  4364. $request = $result ?: $request;
  4365. }
  4366. $response = $next->handle($request);
  4367. $afterHandler = $this->getProperty('afterHandler', '');
  4368. if ($afterHandler !== '') {
  4369. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  4370. $response = $result ?: $response;
  4371. }
  4372. return $response;
  4373. }
  4374. }
  4375. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  4376. class FirewallMiddleware extends Middleware
  4377. {
  4378. private function ipMatch(string $ip, string $cidr): bool
  4379. {
  4380. if (strpos($cidr, '/') !== false) {
  4381. list($subnet, $mask) = explode('/', trim($cidr));
  4382. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  4383. return true;
  4384. }
  4385. } else {
  4386. if (ip2long($ip) == ip2long($cidr)) {
  4387. return true;
  4388. }
  4389. }
  4390. return false;
  4391. }
  4392. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  4393. {
  4394. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  4395. if ($this->ipMatch($ipAddress, $allowedIp)) {
  4396. return true;
  4397. }
  4398. }
  4399. return false;
  4400. }
  4401. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4402. {
  4403. $reverseProxy = $this->getProperty('reverseProxy', '');
  4404. if ($reverseProxy) {
  4405. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  4406. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  4407. $ipAddress = $_SERVER['REMOTE_ADDR'];
  4408. } else {
  4409. $ipAddress = '127.0.0.1';
  4410. }
  4411. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  4412. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  4413. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  4414. } else {
  4415. $response = $next->handle($request);
  4416. }
  4417. return $response;
  4418. }
  4419. }
  4420. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  4421. class IpAddressMiddleware extends Middleware
  4422. {
  4423. private $reflection;
  4424. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4425. {
  4426. parent::__construct($router, $responder, $properties);
  4427. $this->reflection = $reflection;
  4428. }
  4429. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  4430. {
  4431. $context = (array) $record;
  4432. $columnNames = $this->getProperty('columns', '');
  4433. if ($columnNames) {
  4434. foreach (explode(',', $columnNames) as $columnName) {
  4435. if ($table->hasColumn($columnName)) {
  4436. if ($operation == 'create') {
  4437. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  4438. } else {
  4439. unset($context[$columnName]);
  4440. }
  4441. }
  4442. }
  4443. }
  4444. return (object) $context;
  4445. }
  4446. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4447. {
  4448. $operation = RequestUtils::getOperation($request);
  4449. if (in_array($operation, ['create', 'update', 'increment'])) {
  4450. $tableNames = $this->getProperty('tables', '');
  4451. $tableName = RequestUtils::getPathSegment($request, 2);
  4452. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  4453. if ($this->reflection->hasTable($tableName)) {
  4454. $record = $request->getParsedBody();
  4455. if ($record !== null) {
  4456. $table = $this->reflection->getTable($tableName);
  4457. if (is_array($record)) {
  4458. foreach ($record as &$r) {
  4459. $r = $this->callHandler($r, $operation, $table);
  4460. }
  4461. } else {
  4462. $record = $this->callHandler($record, $operation, $table);
  4463. }
  4464. $request = $request->withParsedBody($record);
  4465. }
  4466. }
  4467. }
  4468. }
  4469. return $next->handle($request);
  4470. }
  4471. }
  4472. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  4473. class JoinLimitsMiddleware extends Middleware
  4474. {
  4475. private $reflection;
  4476. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4477. {
  4478. parent::__construct($router, $responder, $properties);
  4479. $this->reflection = $reflection;
  4480. }
  4481. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4482. {
  4483. $operation = RequestUtils::getOperation($request);
  4484. $params = RequestUtils::getParams($request);
  4485. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  4486. $maxDepth = (int) $this->getProperty('depth', '3');
  4487. $maxTables = (int) $this->getProperty('tables', '10');
  4488. $maxRecords = (int) $this->getProperty('records', '1000');
  4489. $tableCount = 0;
  4490. $joinPaths = array();
  4491. for ($i = 0; $i < count($params['join']); $i++) {
  4492. $joinPath = array();
  4493. $tables = explode(',', $params['join'][$i]);
  4494. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  4495. array_push($joinPath, $tables[$depth]);
  4496. $tableCount += 1;
  4497. if ($tableCount == $maxTables) {
  4498. break;
  4499. }
  4500. }
  4501. array_push($joinPaths, implode(',', $joinPath));
  4502. if ($tableCount == $maxTables) {
  4503. break;
  4504. }
  4505. }
  4506. $params['join'] = $joinPaths;
  4507. $request = RequestUtils::setParams($request, $params);
  4508. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  4509. }
  4510. return $next->handle($request);
  4511. }
  4512. }
  4513. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  4514. class JwtAuthMiddleware extends Middleware
  4515. {
  4516. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, string $secret, array $requirements): array
  4517. {
  4518. $algorithms = array(
  4519. 'HS256' => 'sha256',
  4520. 'HS384' => 'sha384',
  4521. 'HS512' => 'sha512',
  4522. 'RS256' => 'sha256',
  4523. 'RS384' => 'sha384',
  4524. 'RS512' => 'sha512',
  4525. );
  4526. $token = explode('.', $token);
  4527. if (count($token) < 3) {
  4528. return array();
  4529. }
  4530. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  4531. if (!$secret) {
  4532. return array();
  4533. }
  4534. if ($header['typ'] != 'JWT') {
  4535. return array();
  4536. }
  4537. $algorithm = $header['alg'];
  4538. if (!isset($algorithms[$algorithm])) {
  4539. return array();
  4540. }
  4541. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  4542. return array();
  4543. }
  4544. $hmac = $algorithms[$algorithm];
  4545. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  4546. $data = "$token[0].$token[1]";
  4547. switch ($algorithm[0]) {
  4548. case 'H':
  4549. $hash = hash_hmac($hmac, $data, $secret, true);
  4550. if (function_exists('hash_equals')) {
  4551. $equals = hash_equals($signature, $hash);
  4552. } else {
  4553. $equals = $signature == $hash;
  4554. }
  4555. if (!$equals) {
  4556. return array();
  4557. }
  4558. break;
  4559. case 'R':
  4560. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  4561. if (!$equals) {
  4562. return array();
  4563. }
  4564. break;
  4565. }
  4566. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  4567. if (!$claims) {
  4568. return array();
  4569. }
  4570. foreach ($requirements as $field => $values) {
  4571. if (!empty($values)) {
  4572. if ($field != 'alg') {
  4573. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  4574. return array();
  4575. }
  4576. }
  4577. }
  4578. }
  4579. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  4580. return array();
  4581. }
  4582. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  4583. return array();
  4584. }
  4585. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  4586. return array();
  4587. }
  4588. if (isset($claims['iat']) && !isset($claims['exp'])) {
  4589. if ($time - $leeway > $claims['iat'] + $ttl) {
  4590. return array();
  4591. }
  4592. }
  4593. return $claims;
  4594. }
  4595. private function getClaims(string $token): array
  4596. {
  4597. $time = (int) $this->getProperty('time', time());
  4598. $leeway = (int) $this->getProperty('leeway', '5');
  4599. $ttl = (int) $this->getProperty('ttl', '30');
  4600. $secret = $this->getProperty('secret', '');
  4601. $requirements = array(
  4602. 'alg' => $this->getArrayProperty('algorithms', ''),
  4603. 'aud' => $this->getArrayProperty('audiences', ''),
  4604. 'iss' => $this->getArrayProperty('issuers', ''),
  4605. );
  4606. if (!$secret) {
  4607. return array();
  4608. }
  4609. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  4610. }
  4611. private function getAuthorizationToken(ServerRequestInterface $request): string
  4612. {
  4613. $headerName = $this->getProperty('header', 'X-Authorization');
  4614. $headerValue = RequestUtils::getHeader($request, $headerName);
  4615. $parts = explode(' ', trim($headerValue), 2);
  4616. if (count($parts) != 2) {
  4617. return '';
  4618. }
  4619. if ($parts[0] != 'Bearer') {
  4620. return '';
  4621. }
  4622. return $parts[1];
  4623. }
  4624. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4625. {
  4626. if (session_status() == PHP_SESSION_NONE) {
  4627. session_start();
  4628. }
  4629. $token = $this->getAuthorizationToken($request);
  4630. if ($token) {
  4631. $claims = $this->getClaims($token);
  4632. $_SESSION['claims'] = $claims;
  4633. if (empty($claims)) {
  4634. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  4635. }
  4636. if (!headers_sent()) {
  4637. session_regenerate_id();
  4638. }
  4639. }
  4640. if (empty($_SESSION['claims'])) {
  4641. $authenticationMode = $this->getProperty('mode', 'required');
  4642. if ($authenticationMode == 'required') {
  4643. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4644. }
  4645. }
  4646. return $next->handle($request);
  4647. }
  4648. }
  4649. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  4650. class MultiTenancyMiddleware extends Middleware
  4651. {
  4652. private $reflection;
  4653. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4654. {
  4655. parent::__construct($router, $responder, $properties);
  4656. $this->reflection = $reflection;
  4657. }
  4658. private function getCondition(string $tableName, array $pairs): Condition
  4659. {
  4660. $condition = new NoCondition();
  4661. $table = $this->reflection->getTable($tableName);
  4662. foreach ($pairs as $k => $v) {
  4663. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  4664. }
  4665. return $condition;
  4666. }
  4667. private function getPairs($handler, string $operation, string $tableName): array
  4668. {
  4669. $result = array();
  4670. $pairs = call_user_func($handler, $operation, $tableName);
  4671. $table = $this->reflection->getTable($tableName);
  4672. foreach ($pairs as $k => $v) {
  4673. if ($table->hasColumn($k)) {
  4674. $result[$k] = $v;
  4675. }
  4676. }
  4677. return $result;
  4678. }
  4679. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  4680. {
  4681. $record = $request->getParsedBody();
  4682. if ($record === null) {
  4683. return $request;
  4684. }
  4685. $multi = is_array($record);
  4686. $records = $multi ? $record : [$record];
  4687. foreach ($records as &$record) {
  4688. foreach ($pairs as $column => $value) {
  4689. if ($operation == 'create') {
  4690. $record->$column = $value;
  4691. } else {
  4692. if (isset($record->$column)) {
  4693. unset($record->$column);
  4694. }
  4695. }
  4696. }
  4697. }
  4698. return $request->withParsedBody($multi ? $records : $records[0]);
  4699. }
  4700. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4701. {
  4702. $handler = $this->getProperty('handler', '');
  4703. if ($handler !== '') {
  4704. $path = RequestUtils::getPathSegment($request, 1);
  4705. if ($path == 'records') {
  4706. $operation = RequestUtils::getOperation($request);
  4707. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  4708. foreach ($tableNames as $i => $tableName) {
  4709. if (!$this->reflection->hasTable($tableName)) {
  4710. continue;
  4711. }
  4712. $pairs = $this->getPairs($handler, $operation, $tableName);
  4713. if ($i == 0) {
  4714. if (in_array($operation, ['create', 'update', 'increment'])) {
  4715. $request = $this->handleRecord($request, $operation, $pairs);
  4716. }
  4717. }
  4718. $condition = $this->getCondition($tableName, $pairs);
  4719. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  4720. }
  4721. }
  4722. }
  4723. return $next->handle($request);
  4724. }
  4725. }
  4726. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  4727. class PageLimitsMiddleware extends Middleware
  4728. {
  4729. private $reflection;
  4730. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4731. {
  4732. parent::__construct($router, $responder, $properties);
  4733. $this->reflection = $reflection;
  4734. }
  4735. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4736. {
  4737. $operation = RequestUtils::getOperation($request);
  4738. if ($operation == 'list') {
  4739. $params = RequestUtils::getParams($request);
  4740. $maxPage = (int) $this->getProperty('pages', '100');
  4741. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  4742. if (strpos($params['page'][0], ',') === false) {
  4743. $page = $params['page'][0];
  4744. } else {
  4745. list($page, $size) = explode(',', $params['page'][0], 2);
  4746. }
  4747. if ($page > $maxPage) {
  4748. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  4749. }
  4750. }
  4751. $maxSize = (int) $this->getProperty('records', '1000');
  4752. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  4753. $params['size'] = array($maxSize);
  4754. } else {
  4755. $params['size'] = array(min($params['size'][0], $maxSize));
  4756. }
  4757. $request = RequestUtils::setParams($request, $params);
  4758. }
  4759. return $next->handle($request);
  4760. }
  4761. }
  4762. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  4763. class SanitationMiddleware extends Middleware
  4764. {
  4765. private $reflection;
  4766. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4767. {
  4768. parent::__construct($router, $responder, $properties);
  4769. $this->reflection = $reflection;
  4770. }
  4771. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  4772. {
  4773. $context = (array) $record;
  4774. $tableName = $table->getName();
  4775. foreach ($context as $columnName => &$value) {
  4776. if ($table->hasColumn($columnName)) {
  4777. $column = $table->getColumn($columnName);
  4778. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  4779. }
  4780. }
  4781. return (object) $context;
  4782. }
  4783. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4784. {
  4785. $operation = RequestUtils::getOperation($request);
  4786. if (in_array($operation, ['create', 'update', 'increment'])) {
  4787. $tableName = RequestUtils::getPathSegment($request, 2);
  4788. if ($this->reflection->hasTable($tableName)) {
  4789. $record = $request->getParsedBody();
  4790. if ($record !== null) {
  4791. $handler = $this->getProperty('handler', '');
  4792. if ($handler !== '') {
  4793. $table = $this->reflection->getTable($tableName);
  4794. if (is_array($record)) {
  4795. foreach ($record as &$r) {
  4796. $r = $this->callHandler($handler, $r, $operation, $table);
  4797. }
  4798. } else {
  4799. $record = $this->callHandler($handler, $record, $operation, $table);
  4800. }
  4801. $request = $request->withParsedBody($record);
  4802. }
  4803. }
  4804. }
  4805. }
  4806. return $next->handle($request);
  4807. }
  4808. }
  4809. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  4810. class ValidationMiddleware extends Middleware
  4811. {
  4812. private $reflection;
  4813. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4814. {
  4815. parent::__construct($router, $responder, $properties);
  4816. $this->reflection = $reflection;
  4817. }
  4818. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  4819. {
  4820. $context = (array) $record;
  4821. $details = array();
  4822. $tableName = $table->getName();
  4823. foreach ($context as $columnName => $value) {
  4824. if ($table->hasColumn($columnName)) {
  4825. $column = $table->getColumn($columnName);
  4826. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  4827. if ($valid !== true && $valid !== '') {
  4828. $details[$columnName] = $valid;
  4829. }
  4830. }
  4831. }
  4832. if (count($details) > 0) {
  4833. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  4834. }
  4835. return null;
  4836. }
  4837. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4838. {
  4839. $operation = RequestUtils::getOperation($request);
  4840. if (in_array($operation, ['create', 'update', 'increment'])) {
  4841. $tableName = RequestUtils::getPathSegment($request, 2);
  4842. if ($this->reflection->hasTable($tableName)) {
  4843. $record = $request->getParsedBody();
  4844. if ($record !== null) {
  4845. $handler = $this->getProperty('handler', '');
  4846. if ($handler !== '') {
  4847. $table = $this->reflection->getTable($tableName);
  4848. if (is_array($record)) {
  4849. foreach ($record as $r) {
  4850. $response = $this->callHandler($handler, $r, $operation, $table);
  4851. if ($response !== null) {
  4852. return $response;
  4853. }
  4854. }
  4855. } else {
  4856. $response = $this->callHandler($handler, $record, $operation, $table);
  4857. if ($response !== null) {
  4858. return $response;
  4859. }
  4860. }
  4861. }
  4862. }
  4863. }
  4864. }
  4865. return $next->handle($request);
  4866. }
  4867. }
  4868. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  4869. class XsrfMiddleware extends Middleware
  4870. {
  4871. private function getToken(): string
  4872. {
  4873. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  4874. if (isset($_COOKIE[$cookieName])) {
  4875. $token = $_COOKIE[$cookieName];
  4876. } else {
  4877. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  4878. $token = bin2hex(random_bytes(8));
  4879. if (!headers_sent()) {
  4880. setcookie($cookieName, $token, 0, '', '', $secure);
  4881. }
  4882. }
  4883. return $token;
  4884. }
  4885. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4886. {
  4887. $token = $this->getToken();
  4888. $method = $request->getMethod();
  4889. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  4890. if (!in_array($method, $excludeMethods)) {
  4891. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  4892. if ($token != $request->getHeader($headerName)) {
  4893. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  4894. }
  4895. }
  4896. return $next->handle($request);
  4897. }
  4898. }
  4899. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  4900. class OpenApiBuilder
  4901. {
  4902. private $openapi;
  4903. private $reflection;
  4904. private $operations = [
  4905. 'list' => 'get',
  4906. 'create' => 'post',
  4907. 'read' => 'get',
  4908. 'update' => 'put',
  4909. 'delete' => 'delete',
  4910. 'increment' => 'patch',
  4911. ];
  4912. private $types = [
  4913. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  4914. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  4915. 'varchar' => ['type' => 'string'],
  4916. 'clob' => ['type' => 'string'],
  4917. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  4918. 'blob' => ['type' => 'string', 'format' => 'byte'],
  4919. 'decimal' => ['type' => 'string'],
  4920. 'float' => ['type' => 'number', 'format' => 'float'],
  4921. 'double' => ['type' => 'number', 'format' => 'double'],
  4922. 'date' => ['type' => 'string', 'format' => 'date'],
  4923. 'time' => ['type' => 'string', 'format' => 'date-time'],
  4924. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  4925. 'geometry' => ['type' => 'string'],
  4926. 'boolean' => ['type' => 'boolean'],
  4927. ];
  4928. public function __construct(ReflectionService $reflection, $base)
  4929. {
  4930. $this->reflection = $reflection;
  4931. $this->openapi = new OpenApiDefinition($base);
  4932. }
  4933. private function getServerUrl(): string
  4934. {
  4935. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  4936. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  4937. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  4938. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  4939. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  4940. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  4941. }
  4942. private function getAllTableReferences(): array
  4943. {
  4944. $tableReferences = array();
  4945. foreach ($this->reflection->getTableNames() as $tableName) {
  4946. $table = $this->reflection->getTable($tableName);
  4947. foreach ($table->getColumnNames() as $columnName) {
  4948. $column = $table->getColumn($columnName);
  4949. $referencedTableName = $column->getFk();
  4950. if ($referencedTableName) {
  4951. if (!isset($tableReferences[$referencedTableName])) {
  4952. $tableReferences[$referencedTableName] = array();
  4953. }
  4954. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  4955. }
  4956. }
  4957. }
  4958. return $tableReferences;
  4959. }
  4960. public function build(): OpenApiDefinition
  4961. {
  4962. $this->openapi->set("openapi", "3.0.0");
  4963. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  4964. $this->openapi->set("servers|0|url", $this->getServerUrl());
  4965. }
  4966. $tableNames = $this->reflection->getTableNames();
  4967. foreach ($tableNames as $tableName) {
  4968. $this->setPath($tableName);
  4969. }
  4970. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  4971. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  4972. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  4973. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  4974. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  4975. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  4976. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  4977. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  4978. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  4979. $tableReferences = $this->getAllTableReferences();
  4980. foreach ($tableNames as $tableName) {
  4981. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  4982. $this->setComponentSchema($tableName, $references);
  4983. $this->setComponentResponse($tableName);
  4984. $this->setComponentRequestBody($tableName);
  4985. }
  4986. $this->setComponentParameters();
  4987. foreach ($tableNames as $index => $tableName) {
  4988. $this->setTag($index, $tableName);
  4989. }
  4990. return $this->openapi;
  4991. }
  4992. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  4993. {
  4994. $tableHandler = VariableStore::get('authorization.tableHandler');
  4995. if (!$tableHandler) {
  4996. return true;
  4997. }
  4998. return (bool) call_user_func($tableHandler, $operation, $tableName);
  4999. }
  5000. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  5001. {
  5002. $columnHandler = VariableStore::get('authorization.columnHandler');
  5003. if (!$columnHandler) {
  5004. return true;
  5005. }
  5006. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  5007. }
  5008. private function setPath(string $tableName) /*: void*/
  5009. {
  5010. $table = $this->reflection->getTable($tableName);
  5011. $type = $table->getType();
  5012. $pk = $table->getPk();
  5013. $pkName = $pk ? $pk->getName() : '';
  5014. foreach ($this->operations as $operation => $method) {
  5015. if (!$pkName && $operation != 'list') {
  5016. continue;
  5017. }
  5018. if ($type != 'table' && $operation != 'list') {
  5019. continue;
  5020. }
  5021. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5022. continue;
  5023. }
  5024. $parameters = [];
  5025. if (in_array($operation, ['list', 'create'])) {
  5026. $path = sprintf('/records/%s', $tableName);
  5027. if ($operation == 'list') {
  5028. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  5029. }
  5030. } else {
  5031. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  5032. if ($operation == 'read') {
  5033. $parameters = ['pk', 'include', 'exclude', 'join'];
  5034. } else {
  5035. $parameters = ['pk'];
  5036. }
  5037. }
  5038. foreach ($parameters as $p => $parameter) {
  5039. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  5040. }
  5041. if (in_array($operation, ['create', 'update', 'increment'])) {
  5042. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  5043. }
  5044. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  5045. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  5046. switch ($operation) {
  5047. case 'list':
  5048. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  5049. break;
  5050. case 'create':
  5051. if ($pk->getType() == 'integer') {
  5052. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  5053. } else {
  5054. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  5055. }
  5056. break;
  5057. case 'read':
  5058. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  5059. break;
  5060. case 'update':
  5061. case 'delete':
  5062. case 'increment':
  5063. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  5064. break;
  5065. }
  5066. }
  5067. }
  5068. private function setComponentSchema(string $tableName, array $references) /*: void*/
  5069. {
  5070. $table = $this->reflection->getTable($tableName);
  5071. $type = $table->getType();
  5072. $pk = $table->getPk();
  5073. $pkName = $pk ? $pk->getName() : '';
  5074. foreach ($this->operations as $operation => $method) {
  5075. if (!$pkName && $operation != 'list') {
  5076. continue;
  5077. }
  5078. if ($type != 'table' && $operation != 'list') {
  5079. continue;
  5080. }
  5081. if ($operation == 'delete') {
  5082. continue;
  5083. }
  5084. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5085. continue;
  5086. }
  5087. if ($operation == 'list') {
  5088. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  5089. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  5090. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  5091. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  5092. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  5093. } else {
  5094. $prefix = "components|schemas|$operation-$tableName";
  5095. }
  5096. $this->openapi->set("$prefix|type", "object");
  5097. foreach ($table->getColumnNames() as $columnName) {
  5098. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  5099. continue;
  5100. }
  5101. $column = $table->getColumn($columnName);
  5102. $properties = $this->types[$column->getType()];
  5103. foreach ($properties as $key => $value) {
  5104. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  5105. }
  5106. if ($column->getPk()) {
  5107. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  5108. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  5109. }
  5110. $fk = $column->getFk();
  5111. if ($fk) {
  5112. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  5113. }
  5114. }
  5115. }
  5116. }
  5117. private function setComponentResponse(string $tableName) /*: void*/
  5118. {
  5119. $table = $this->reflection->getTable($tableName);
  5120. $type = $table->getType();
  5121. $pk = $table->getPk();
  5122. $pkName = $pk ? $pk->getName() : '';
  5123. foreach (['list', 'read'] as $operation) {
  5124. if (!$pkName && $operation != 'list') {
  5125. continue;
  5126. }
  5127. if ($type != 'table' && $operation != 'list') {
  5128. continue;
  5129. }
  5130. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5131. continue;
  5132. }
  5133. if ($operation == 'list') {
  5134. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  5135. } else {
  5136. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  5137. }
  5138. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  5139. }
  5140. }
  5141. private function setComponentRequestBody(string $tableName) /*: void*/
  5142. {
  5143. $table = $this->reflection->getTable($tableName);
  5144. $type = $table->getType();
  5145. $pk = $table->getPk();
  5146. $pkName = $pk ? $pk->getName() : '';
  5147. if ($pkName && $type == 'table') {
  5148. foreach (['create', 'update', 'increment'] as $operation) {
  5149. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5150. continue;
  5151. }
  5152. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  5153. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  5154. }
  5155. }
  5156. }
  5157. private function setComponentParameters() /*: void*/
  5158. {
  5159. $this->openapi->set("components|parameters|pk|name", "id");
  5160. $this->openapi->set("components|parameters|pk|in", "path");
  5161. $this->openapi->set("components|parameters|pk|schema|type", "string");
  5162. $this->openapi->set("components|parameters|pk|description", "primary key value");
  5163. $this->openapi->set("components|parameters|pk|required", true);
  5164. $this->openapi->set("components|parameters|filter|name", "filter");
  5165. $this->openapi->set("components|parameters|filter|in", "query");
  5166. $this->openapi->set("components|parameters|filter|schema|type", "array");
  5167. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  5168. $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");
  5169. $this->openapi->set("components|parameters|filter|required", false);
  5170. $this->openapi->set("components|parameters|include|name", "include");
  5171. $this->openapi->set("components|parameters|include|in", "query");
  5172. $this->openapi->set("components|parameters|include|schema|type", "string");
  5173. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  5174. $this->openapi->set("components|parameters|include|required", false);
  5175. $this->openapi->set("components|parameters|exclude|name", "exclude");
  5176. $this->openapi->set("components|parameters|exclude|in", "query");
  5177. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  5178. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  5179. $this->openapi->set("components|parameters|exclude|required", false);
  5180. $this->openapi->set("components|parameters|order|name", "order");
  5181. $this->openapi->set("components|parameters|order|in", "query");
  5182. $this->openapi->set("components|parameters|order|schema|type", "array");
  5183. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  5184. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  5185. $this->openapi->set("components|parameters|order|required", false);
  5186. $this->openapi->set("components|parameters|size|name", "size");
  5187. $this->openapi->set("components|parameters|size|in", "query");
  5188. $this->openapi->set("components|parameters|size|schema|type", "string");
  5189. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  5190. $this->openapi->set("components|parameters|size|required", false);
  5191. $this->openapi->set("components|parameters|page|name", "page");
  5192. $this->openapi->set("components|parameters|page|in", "query");
  5193. $this->openapi->set("components|parameters|page|schema|type", "string");
  5194. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  5195. $this->openapi->set("components|parameters|page|required", false);
  5196. $this->openapi->set("components|parameters|join|name", "join");
  5197. $this->openapi->set("components|parameters|join|in", "query");
  5198. $this->openapi->set("components|parameters|join|schema|type", "array");
  5199. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  5200. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  5201. $this->openapi->set("components|parameters|join|required", false);
  5202. }
  5203. private function setTag(int $index, string $tableName) /*: void*/
  5204. {
  5205. $this->openapi->set("tags|$index|name", "$tableName");
  5206. $this->openapi->set("tags|$index|description", "$tableName operations");
  5207. }
  5208. }
  5209. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  5210. class OpenApiDefinition implements \JsonSerializable
  5211. {
  5212. private $root;
  5213. public function __construct($base)
  5214. {
  5215. $this->root = $base;
  5216. }
  5217. public function set(string $path, $value) /*: void*/
  5218. {
  5219. $parts = explode('|', trim($path, '|'));
  5220. $current = &$this->root;
  5221. while (count($parts) > 0) {
  5222. $part = array_shift($parts);
  5223. if (!isset($current[$part])) {
  5224. $current[$part] = [];
  5225. }
  5226. $current = &$current[$part];
  5227. }
  5228. $current = $value;
  5229. }
  5230. public function has(string $path): bool
  5231. {
  5232. $parts = explode('|', trim($path, '|'));
  5233. $current = &$this->root;
  5234. while (count($parts) > 0) {
  5235. $part = array_shift($parts);
  5236. if (!isset($current[$part])) {
  5237. return false;
  5238. }
  5239. $current = &$current[$part];
  5240. }
  5241. return true;
  5242. }
  5243. public function jsonSerialize()
  5244. {
  5245. return $this->root;
  5246. }
  5247. }
  5248. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  5249. class OpenApiService
  5250. {
  5251. private $builder;
  5252. public function __construct(ReflectionService $reflection, array $base)
  5253. {
  5254. $this->builder = new OpenApiBuilder($reflection, $base);
  5255. }
  5256. public function get(): OpenApiDefinition
  5257. {
  5258. return $this->builder->build();
  5259. }
  5260. }
  5261. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  5262. class AndCondition extends Condition
  5263. {
  5264. private $conditions;
  5265. public function __construct(Condition $condition1, Condition $condition2)
  5266. {
  5267. $this->conditions = [$condition1, $condition2];
  5268. }
  5269. public function _and(Condition $condition): Condition
  5270. {
  5271. if ($condition instanceof NoCondition) {
  5272. return $this;
  5273. }
  5274. $this->conditions[] = $condition;
  5275. return $this;
  5276. }
  5277. public function getConditions(): array
  5278. {
  5279. return $this->conditions;
  5280. }
  5281. public static function fromArray(array $conditions): Condition
  5282. {
  5283. $condition = new NoCondition();
  5284. foreach ($conditions as $c) {
  5285. $condition = $condition->_and($c);
  5286. }
  5287. return $condition;
  5288. }
  5289. }
  5290. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  5291. class ColumnCondition extends Condition
  5292. {
  5293. private $column;
  5294. private $operator;
  5295. private $value;
  5296. public function __construct(ReflectedColumn $column, string $operator, string $value)
  5297. {
  5298. $this->column = $column;
  5299. $this->operator = $operator;
  5300. $this->value = $value;
  5301. }
  5302. public function getColumn(): ReflectedColumn
  5303. {
  5304. return $this->column;
  5305. }
  5306. public function getOperator(): string
  5307. {
  5308. return $this->operator;
  5309. }
  5310. public function getValue(): string
  5311. {
  5312. return $this->value;
  5313. }
  5314. }
  5315. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  5316. abstract class Condition
  5317. {
  5318. public function _and(Condition $condition): Condition
  5319. {
  5320. if ($condition instanceof NoCondition) {
  5321. return $this;
  5322. }
  5323. return new AndCondition($this, $condition);
  5324. }
  5325. public function _or(Condition $condition): Condition
  5326. {
  5327. if ($condition instanceof NoCondition) {
  5328. return $this;
  5329. }
  5330. return new OrCondition($this, $condition);
  5331. }
  5332. public function _not(): Condition
  5333. {
  5334. return new NotCondition($this);
  5335. }
  5336. public static function fromString(ReflectedTable $table, string $value): Condition
  5337. {
  5338. $condition = new NoCondition();
  5339. $parts = explode(',', $value, 3);
  5340. if (count($parts) < 2) {
  5341. return $condition;
  5342. }
  5343. if (count($parts) < 3) {
  5344. $parts[2] = '';
  5345. }
  5346. $field = $table->getColumn($parts[0]);
  5347. $command = $parts[1];
  5348. $negate = false;
  5349. $spatial = false;
  5350. if (strlen($command) > 2) {
  5351. if (substr($command, 0, 1) == 'n') {
  5352. $negate = true;
  5353. $command = substr($command, 1);
  5354. }
  5355. if (substr($command, 0, 1) == 's') {
  5356. $spatial = true;
  5357. $command = substr($command, 1);
  5358. }
  5359. }
  5360. if ($spatial) {
  5361. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  5362. $condition = new SpatialCondition($field, $command, $parts[2]);
  5363. }
  5364. } else {
  5365. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  5366. $condition = new ColumnCondition($field, $command, $parts[2]);
  5367. }
  5368. }
  5369. if ($negate) {
  5370. $condition = $condition->_not();
  5371. }
  5372. return $condition;
  5373. }
  5374. }
  5375. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  5376. class NoCondition extends Condition
  5377. {
  5378. public function _and(Condition $condition): Condition
  5379. {
  5380. return $condition;
  5381. }
  5382. public function _or(Condition $condition): Condition
  5383. {
  5384. return $condition;
  5385. }
  5386. public function _not(): Condition
  5387. {
  5388. return $this;
  5389. }
  5390. }
  5391. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  5392. class NotCondition extends Condition
  5393. {
  5394. private $condition;
  5395. public function __construct(Condition $condition)
  5396. {
  5397. $this->condition = $condition;
  5398. }
  5399. public function getCondition(): Condition
  5400. {
  5401. return $this->condition;
  5402. }
  5403. }
  5404. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  5405. class OrCondition extends Condition
  5406. {
  5407. private $conditions;
  5408. public function __construct(Condition $condition1, Condition $condition2)
  5409. {
  5410. $this->conditions = [$condition1, $condition2];
  5411. }
  5412. public function _or(Condition $condition): Condition
  5413. {
  5414. if ($condition instanceof NoCondition) {
  5415. return $this;
  5416. }
  5417. $this->conditions[] = $condition;
  5418. return $this;
  5419. }
  5420. public function getConditions(): array
  5421. {
  5422. return $this->conditions;
  5423. }
  5424. public static function fromArray(array $conditions): Condition
  5425. {
  5426. $condition = new NoCondition();
  5427. foreach ($conditions as $c) {
  5428. $condition = $condition->_or($c);
  5429. }
  5430. return $condition;
  5431. }
  5432. }
  5433. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  5434. class SpatialCondition extends ColumnCondition
  5435. {
  5436. }
  5437. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  5438. class ErrorDocument implements \JsonSerializable
  5439. {
  5440. public $code;
  5441. public $message;
  5442. public $details;
  5443. public function __construct(ErrorCode $errorCode, string $argument, $details)
  5444. {
  5445. $this->code = $errorCode->getCode();
  5446. $this->message = $errorCode->getMessage($argument);
  5447. $this->details = $details;
  5448. }
  5449. public function getCode(): int
  5450. {
  5451. return $this->code;
  5452. }
  5453. public function getMessage(): string
  5454. {
  5455. return $this->message;
  5456. }
  5457. public function serialize()
  5458. {
  5459. return [
  5460. 'code' => $this->code,
  5461. 'message' => $this->message,
  5462. 'details' => $this->details,
  5463. ];
  5464. }
  5465. public function jsonSerialize()
  5466. {
  5467. return array_filter($this->serialize());
  5468. }
  5469. }
  5470. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  5471. class ListDocument implements \JsonSerializable
  5472. {
  5473. private $records;
  5474. private $results;
  5475. public function __construct(array $records, int $results)
  5476. {
  5477. $this->records = $records;
  5478. $this->results = $results;
  5479. }
  5480. public function getRecords(): array
  5481. {
  5482. return $this->records;
  5483. }
  5484. public function getResults(): int
  5485. {
  5486. return $this->results;
  5487. }
  5488. public function serialize()
  5489. {
  5490. return [
  5491. 'records' => $this->records,
  5492. 'results' => $this->results,
  5493. ];
  5494. }
  5495. public function jsonSerialize()
  5496. {
  5497. return array_filter($this->serialize(), function ($v) {
  5498. return $v !== 0;
  5499. });
  5500. }
  5501. }
  5502. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  5503. class ColumnIncluder
  5504. {
  5505. private function isMandatory(string $tableName, string $columnName, array $params): bool
  5506. {
  5507. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  5508. }
  5509. private function select(string $tableName, bool $primaryTable, array $params, string $paramName,
  5510. array $columnNames, bool $include): array{
  5511. if (!isset($params[$paramName])) {
  5512. return $columnNames;
  5513. }
  5514. $columns = array();
  5515. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  5516. $columns[$columnName] = true;
  5517. }
  5518. $result = array();
  5519. foreach ($columnNames as $columnName) {
  5520. $match = isset($columns['*.*']);
  5521. if (!$match) {
  5522. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  5523. }
  5524. if ($primaryTable && !$match) {
  5525. $match = isset($columns['*']) || isset($columns[$columnName]);
  5526. }
  5527. if ($match) {
  5528. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  5529. $result[] = $columnName;
  5530. }
  5531. } else {
  5532. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  5533. $result[] = $columnName;
  5534. }
  5535. }
  5536. }
  5537. return $result;
  5538. }
  5539. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  5540. {
  5541. $tableName = $table->getName();
  5542. $results = $table->getColumnNames();
  5543. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  5544. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  5545. return $results;
  5546. }
  5547. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  5548. {
  5549. $results = array();
  5550. $columnNames = $this->getNames($table, $primaryTable, $params);
  5551. foreach ($columnNames as $columnName) {
  5552. if (property_exists($record, $columnName)) {
  5553. $results[$columnName] = $record->$columnName;
  5554. }
  5555. }
  5556. return $results;
  5557. }
  5558. }
  5559. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  5560. class ErrorCode
  5561. {
  5562. private $code;
  5563. private $message;
  5564. private $status;
  5565. const ERROR_NOT_FOUND = 9999;
  5566. const ROUTE_NOT_FOUND = 1000;
  5567. const TABLE_NOT_FOUND = 1001;
  5568. const ARGUMENT_COUNT_MISMATCH = 1002;
  5569. const RECORD_NOT_FOUND = 1003;
  5570. const ORIGIN_FORBIDDEN = 1004;
  5571. const COLUMN_NOT_FOUND = 1005;
  5572. const TABLE_ALREADY_EXISTS = 1006;
  5573. const COLUMN_ALREADY_EXISTS = 1007;
  5574. const HTTP_MESSAGE_NOT_READABLE = 1008;
  5575. const DUPLICATE_KEY_EXCEPTION = 1009;
  5576. const DATA_INTEGRITY_VIOLATION = 1010;
  5577. const AUTHENTICATION_REQUIRED = 1011;
  5578. const AUTHENTICATION_FAILED = 1012;
  5579. const INPUT_VALIDATION_FAILED = 1013;
  5580. const OPERATION_FORBIDDEN = 1014;
  5581. const OPERATION_NOT_SUPPORTED = 1015;
  5582. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  5583. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  5584. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  5585. const PAGINATION_FORBIDDEN = 1019;
  5586. private $values = [
  5587. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  5588. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  5589. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  5590. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  5591. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  5592. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  5593. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  5594. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  5595. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  5596. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  5597. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  5598. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  5599. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  5600. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  5601. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  5602. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  5603. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  5604. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  5605. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  5606. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  5607. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  5608. ];
  5609. public function __construct(int $code)
  5610. {
  5611. if (!isset($this->values[$code])) {
  5612. $code = 9999;
  5613. }
  5614. $this->code = $code;
  5615. $this->message = $this->values[$code][0];
  5616. $this->status = $this->values[$code][1];
  5617. }
  5618. public function getCode(): int
  5619. {
  5620. return $this->code;
  5621. }
  5622. public function getMessage(string $argument): string
  5623. {
  5624. return sprintf($this->message, $argument);
  5625. }
  5626. public function getStatus(): int
  5627. {
  5628. return $this->status;
  5629. }
  5630. }
  5631. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  5632. class FilterInfo
  5633. {
  5634. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  5635. {
  5636. $key = 'filter' . implode('', $path);
  5637. if (isset($params[$key])) {
  5638. foreach ($params[$key] as $filter) {
  5639. $condition = Condition::fromString($table, $filter);
  5640. if (($condition instanceof NoCondition) == false) {
  5641. $conditions->put($path, $condition);
  5642. }
  5643. }
  5644. }
  5645. }
  5646. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  5647. {
  5648. $conditions = new PathTree();
  5649. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  5650. for ($n = ord('0'); $n <= ord('9'); $n++) {
  5651. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  5652. for ($l = ord('a'); $l <= ord('f'); $l++) {
  5653. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  5654. }
  5655. }
  5656. return $conditions;
  5657. }
  5658. private function combinePathTreeOfConditions(PathTree $tree): Condition
  5659. {
  5660. $andConditions = $tree->getValues();
  5661. $and = AndCondition::fromArray($andConditions);
  5662. $orConditions = [];
  5663. foreach ($tree->getKeys() as $p) {
  5664. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  5665. }
  5666. $or = OrCondition::fromArray($orConditions);
  5667. return $and->_and($or);
  5668. }
  5669. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  5670. {
  5671. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  5672. }
  5673. }
  5674. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  5675. class HabtmValues
  5676. {
  5677. public $pkValues;
  5678. public $fkValues;
  5679. public function __construct(array $pkValues, array $fkValues)
  5680. {
  5681. $this->pkValues = $pkValues;
  5682. $this->fkValues = $fkValues;
  5683. }
  5684. }
  5685. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  5686. class OrderingInfo
  5687. {
  5688. public function getColumnOrdering(ReflectedTable $table, array $params): array
  5689. {
  5690. $fields = array();
  5691. if (isset($params['order'])) {
  5692. foreach ($params['order'] as $order) {
  5693. $parts = explode(',', $order, 3);
  5694. $columnName = $parts[0];
  5695. if (!$table->hasColumn($columnName)) {
  5696. continue;
  5697. }
  5698. $ascending = 'ASC';
  5699. if (count($parts) > 1) {
  5700. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  5701. $ascending = 'DESC';
  5702. }
  5703. }
  5704. $fields[] = [$columnName, $ascending];
  5705. }
  5706. }
  5707. if (count($fields) == 0) {
  5708. return $this->getDefaultColumnOrdering($table);
  5709. }
  5710. return $fields;
  5711. }
  5712. public function getDefaultColumnOrdering(ReflectedTable $table): array
  5713. {
  5714. $fields = array();
  5715. $pk = $table->getPk();
  5716. if ($pk) {
  5717. $fields[] = [$pk->getName(), 'ASC'];
  5718. } else {
  5719. foreach ($table->getColumnNames() as $columnName) {
  5720. $fields[] = [$columnName, 'ASC'];
  5721. }
  5722. }
  5723. return $fields;
  5724. }
  5725. }
  5726. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  5727. class PaginationInfo
  5728. {
  5729. public $DEFAULT_PAGE_SIZE = 20;
  5730. public function hasPage(array $params): bool
  5731. {
  5732. return isset($params['page']);
  5733. }
  5734. public function getPageOffset(array $params): int
  5735. {
  5736. $offset = 0;
  5737. $pageSize = $this->getPageSize($params);
  5738. if (isset($params['page'])) {
  5739. foreach ($params['page'] as $page) {
  5740. $parts = explode(',', $page, 2);
  5741. $page = intval($parts[0]) - 1;
  5742. $offset = $page * $pageSize;
  5743. }
  5744. }
  5745. return $offset;
  5746. }
  5747. private function getPageSize(array $params): int
  5748. {
  5749. $pageSize = $this->DEFAULT_PAGE_SIZE;
  5750. if (isset($params['page'])) {
  5751. foreach ($params['page'] as $page) {
  5752. $parts = explode(',', $page, 2);
  5753. if (count($parts) > 1) {
  5754. $pageSize = intval($parts[1]);
  5755. }
  5756. }
  5757. }
  5758. return $pageSize;
  5759. }
  5760. public function getResultSize(array $params): int
  5761. {
  5762. $numberOfRows = -1;
  5763. if (isset($params['size'])) {
  5764. foreach ($params['size'] as $size) {
  5765. $numberOfRows = intval($size);
  5766. }
  5767. }
  5768. return $numberOfRows;
  5769. }
  5770. public function getPageLimit(array $params): int
  5771. {
  5772. $pageLimit = -1;
  5773. if ($this->hasPage($params)) {
  5774. $pageLimit = $this->getPageSize($params);
  5775. }
  5776. $resultSize = $this->getResultSize($params);
  5777. if ($resultSize >= 0) {
  5778. if ($pageLimit >= 0) {
  5779. $pageLimit = min($pageLimit, $resultSize);
  5780. } else {
  5781. $pageLimit = $resultSize;
  5782. }
  5783. }
  5784. return $pageLimit;
  5785. }
  5786. }
  5787. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  5788. class PathTree implements \JsonSerializable
  5789. {
  5790. const WILDCARD = '*';
  5791. private $tree;
  5792. public function __construct( /* object */&$tree = null)
  5793. {
  5794. if (!$tree) {
  5795. $tree = $this->newTree();
  5796. }
  5797. $this->tree = &$tree;
  5798. }
  5799. public function newTree()
  5800. {
  5801. return (object) ['values' => [], 'branches' => (object) []];
  5802. }
  5803. public function getKeys(): array
  5804. {
  5805. $branches = (array) $this->tree->branches;
  5806. return array_keys($branches);
  5807. }
  5808. public function getValues(): array
  5809. {
  5810. return $this->tree->values;
  5811. }
  5812. public function get(string $key): PathTree
  5813. {
  5814. if (!isset($this->tree->branches->$key)) {
  5815. return null;
  5816. }
  5817. return new PathTree($this->tree->branches->$key);
  5818. }
  5819. public function put(array $path, $value)
  5820. {
  5821. $tree = &$this->tree;
  5822. foreach ($path as $key) {
  5823. if (!isset($tree->branches->$key)) {
  5824. $tree->branches->$key = $this->newTree();
  5825. }
  5826. $tree = &$tree->branches->$key;
  5827. }
  5828. $tree->values[] = $value;
  5829. }
  5830. public function match(array $path): array
  5831. {
  5832. $star = self::WILDCARD;
  5833. $tree = &$this->tree;
  5834. foreach ($path as $key) {
  5835. if (isset($tree->branches->$key)) {
  5836. $tree = &$tree->branches->$key;
  5837. } else if (isset($tree->branches->$star)) {
  5838. $tree = &$tree->branches->$star;
  5839. } else {
  5840. return [];
  5841. }
  5842. }
  5843. return $tree->values;
  5844. }
  5845. public static function fromJson( /* object */$tree): PathTree
  5846. {
  5847. return new PathTree($tree);
  5848. }
  5849. public function jsonSerialize()
  5850. {
  5851. return $this->tree;
  5852. }
  5853. }
  5854. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  5855. class RecordService
  5856. {
  5857. private $db;
  5858. private $reflection;
  5859. private $columns;
  5860. private $joiner;
  5861. private $filters;
  5862. private $ordering;
  5863. private $pagination;
  5864. public function __construct(GenericDB $db, ReflectionService $reflection)
  5865. {
  5866. $this->db = $db;
  5867. $this->reflection = $reflection;
  5868. $this->columns = new ColumnIncluder();
  5869. $this->joiner = new RelationJoiner($reflection, $this->columns);
  5870. $this->filters = new FilterInfo();
  5871. $this->ordering = new OrderingInfo();
  5872. $this->pagination = new PaginationInfo();
  5873. }
  5874. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  5875. {
  5876. $keyset = array_keys((array) $record);
  5877. foreach ($keyset as $key) {
  5878. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  5879. unset($record->$key);
  5880. }
  5881. }
  5882. if ($id != '') {
  5883. $pk = $this->reflection->getTable($tableName)->getPk();
  5884. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  5885. $field = $this->reflection->getTable($tableName)->getColumn($key);
  5886. if ($field->getName() == $pk->getName()) {
  5887. unset($record->$key);
  5888. }
  5889. }
  5890. }
  5891. }
  5892. public function hasTable(string $table): bool
  5893. {
  5894. return $this->reflection->hasTable($table);
  5895. }
  5896. public function getType(string $table): string
  5897. {
  5898. return $this->reflection->getType($table);
  5899. }
  5900. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  5901. {
  5902. $this->sanitizeRecord($tableName, $record, '');
  5903. $table = $this->reflection->getTable($tableName);
  5904. $columnValues = $this->columns->getValues($table, true, $record, $params);
  5905. return $this->db->createSingle($table, $columnValues);
  5906. }
  5907. public function read(string $tableName, string $id, array $params) /*: ?object*/
  5908. {
  5909. $table = $this->reflection->getTable($tableName);
  5910. $this->joiner->addMandatoryColumns($table, $params);
  5911. $columnNames = $this->columns->getNames($table, true, $params);
  5912. $record = $this->db->selectSingle($table, $columnNames, $id);
  5913. if ($record == null) {
  5914. return null;
  5915. }
  5916. $records = array($record);
  5917. $this->joiner->addJoins($table, $records, $params, $this->db);
  5918. return $records[0];
  5919. }
  5920. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  5921. {
  5922. $this->sanitizeRecord($tableName, $record, $id);
  5923. $table = $this->reflection->getTable($tableName);
  5924. $columnValues = $this->columns->getValues($table, true, $record, $params);
  5925. return $this->db->updateSingle($table, $columnValues, $id);
  5926. }
  5927. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  5928. {
  5929. $table = $this->reflection->getTable($tableName);
  5930. return $this->db->deleteSingle($table, $id);
  5931. }
  5932. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  5933. {
  5934. $this->sanitizeRecord($tableName, $record, $id);
  5935. $table = $this->reflection->getTable($tableName);
  5936. $columnValues = $this->columns->getValues($table, true, $record, $params);
  5937. return $this->db->incrementSingle($table, $columnValues, $id);
  5938. }
  5939. public function _list(string $tableName, array $params): ListDocument
  5940. {
  5941. $table = $this->reflection->getTable($tableName);
  5942. $this->joiner->addMandatoryColumns($table, $params);
  5943. $columnNames = $this->columns->getNames($table, true, $params);
  5944. $condition = $this->filters->getCombinedConditions($table, $params);
  5945. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  5946. if (!$this->pagination->hasPage($params)) {
  5947. $offset = 0;
  5948. $limit = $this->pagination->getPageLimit($params);
  5949. $count = 0;
  5950. } else {
  5951. $offset = $this->pagination->getPageOffset($params);
  5952. $limit = $this->pagination->getPageLimit($params);
  5953. $count = $this->db->selectCount($table, $condition);
  5954. }
  5955. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  5956. $this->joiner->addJoins($table, $records, $params, $this->db);
  5957. return new ListDocument($records, $count);
  5958. }
  5959. }
  5960. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  5961. class RelationJoiner
  5962. {
  5963. private $reflection;
  5964. private $columns;
  5965. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  5966. {
  5967. $this->reflection = $reflection;
  5968. $this->ordering = new OrderingInfo();
  5969. $this->columns = $columns;
  5970. }
  5971. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  5972. {
  5973. if (!isset($params['join']) || !isset($params['include'])) {
  5974. return;
  5975. }
  5976. $params['mandatory'] = array();
  5977. foreach ($params['join'] as $tableNames) {
  5978. $t1 = $table;
  5979. foreach (explode(',', $tableNames) as $tableName) {
  5980. if (!$this->reflection->hasTable($tableName)) {
  5981. continue;
  5982. }
  5983. $t2 = $this->reflection->getTable($tableName);
  5984. $fks1 = $t1->getFksTo($t2->getName());
  5985. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  5986. if ($t3 != null || count($fks1) > 0) {
  5987. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  5988. }
  5989. foreach ($fks1 as $fk) {
  5990. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  5991. }
  5992. $fks2 = $t2->getFksTo($t1->getName());
  5993. if ($t3 != null || count($fks2) > 0) {
  5994. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  5995. }
  5996. foreach ($fks2 as $fk) {
  5997. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  5998. }
  5999. $t1 = $t2;
  6000. }
  6001. }
  6002. }
  6003. private function getJoinsAsPathTree(array $params): PathTree
  6004. {
  6005. $joins = new PathTree();
  6006. if (isset($params['join'])) {
  6007. foreach ($params['join'] as $tableNames) {
  6008. $path = array();
  6009. foreach (explode(',', $tableNames) as $tableName) {
  6010. $t = $this->reflection->getTable($tableName);
  6011. if ($t != null) {
  6012. $path[] = $t->getName();
  6013. }
  6014. }
  6015. $joins->put($path, true);
  6016. }
  6017. }
  6018. return $joins;
  6019. }
  6020. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  6021. {
  6022. $joins = $this->getJoinsAsPathTree($params);
  6023. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  6024. }
  6025. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  6026. {
  6027. foreach ($this->reflection->getTableNames() as $tableName) {
  6028. $t3 = $this->reflection->getTable($tableName);
  6029. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  6030. return $t3;
  6031. }
  6032. }
  6033. return null;
  6034. }
  6035. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  6036. {
  6037. foreach ($joins->getKeys() as $t2Name) {
  6038. $t2 = $this->reflection->getTable($t2Name);
  6039. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  6040. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  6041. if (!$belongsTo && !$hasMany) {
  6042. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  6043. } else {
  6044. $t3 = null;
  6045. }
  6046. $hasAndBelongsToMany = ($t3 != null);
  6047. $newRecords = array();
  6048. $fkValues = null;
  6049. $pkValues = null;
  6050. $habtmValues = null;
  6051. if ($belongsTo) {
  6052. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  6053. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  6054. }
  6055. if ($hasMany) {
  6056. $pkValues = $this->getPkEmptyValues($t1, $records);
  6057. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  6058. }
  6059. if ($hasAndBelongsToMany) {
  6060. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  6061. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  6062. }
  6063. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  6064. if ($fkValues != null) {
  6065. $this->fillFkValues($t2, $newRecords, $fkValues);
  6066. $this->setFkValues($t1, $t2, $records, $fkValues);
  6067. }
  6068. if ($pkValues != null) {
  6069. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  6070. $this->setPkValues($t1, $t2, $records, $pkValues);
  6071. }
  6072. if ($habtmValues != null) {
  6073. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  6074. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  6075. }
  6076. }
  6077. }
  6078. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  6079. {
  6080. $fkValues = array();
  6081. $fks = $t1->getFksTo($t2->getName());
  6082. foreach ($fks as $fk) {
  6083. $fkName = $fk->getName();
  6084. foreach ($records as $record) {
  6085. if (isset($record[$fkName])) {
  6086. $fkValue = $record[$fkName];
  6087. $fkValues[$fkValue] = null;
  6088. }
  6089. }
  6090. }
  6091. return $fkValues;
  6092. }
  6093. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  6094. {
  6095. $columnNames = $this->columns->getNames($t2, false, $params);
  6096. $fkIds = array_keys($fkValues);
  6097. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  6098. $records[] = $record;
  6099. }
  6100. }
  6101. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  6102. {
  6103. $pkName = $t2->getPk()->getName();
  6104. foreach ($fkRecords as $fkRecord) {
  6105. $pkValue = $fkRecord[$pkName];
  6106. $fkValues[$pkValue] = $fkRecord;
  6107. }
  6108. }
  6109. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  6110. {
  6111. $fks = $t1->getFksTo($t2->getName());
  6112. foreach ($fks as $fk) {
  6113. $fkName = $fk->getName();
  6114. foreach ($records as $i => $record) {
  6115. if (isset($record[$fkName])) {
  6116. $key = $record[$fkName];
  6117. $records[$i][$fkName] = $fkValues[$key];
  6118. }
  6119. }
  6120. }
  6121. }
  6122. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  6123. {
  6124. $pkValues = array();
  6125. $pkName = $t1->getPk()->getName();
  6126. foreach ($records as $record) {
  6127. $key = $record[$pkName];
  6128. $pkValues[$key] = array();
  6129. }
  6130. return $pkValues;
  6131. }
  6132. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  6133. {
  6134. $fks = $t2->getFksTo($t1->getName());
  6135. $columnNames = $this->columns->getNames($t2, false, $params);
  6136. $pkValueKeys = implode(',', array_keys($pkValues));
  6137. $conditions = array();
  6138. foreach ($fks as $fk) {
  6139. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  6140. }
  6141. $condition = OrCondition::fromArray($conditions);
  6142. $columnOrdering = array();
  6143. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  6144. if ($limit != -1) {
  6145. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  6146. }
  6147. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  6148. $records[] = $record;
  6149. }
  6150. }
  6151. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  6152. {
  6153. $fks = $t2->getFksTo($t1->getName());
  6154. foreach ($fks as $fk) {
  6155. $fkName = $fk->getName();
  6156. foreach ($pkRecords as $pkRecord) {
  6157. $key = $pkRecord[$fkName];
  6158. if (isset($pkValues[$key])) {
  6159. $pkValues[$key][] = $pkRecord;
  6160. }
  6161. }
  6162. }
  6163. }
  6164. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  6165. {
  6166. $pkName = $t1->getPk()->getName();
  6167. $t2Name = $t2->getName();
  6168. foreach ($records as $i => $record) {
  6169. $key = $record[$pkName];
  6170. $records[$i][$t2Name] = $pkValues[$key];
  6171. }
  6172. }
  6173. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  6174. {
  6175. $pkValues = $this->getPkEmptyValues($t1, $records);
  6176. $fkValues = array();
  6177. $fk1 = $t3->getFksTo($t1->getName())[0];
  6178. $fk2 = $t3->getFksTo($t2->getName())[0];
  6179. $fk1Name = $fk1->getName();
  6180. $fk2Name = $fk2->getName();
  6181. $columnNames = array($fk1Name, $fk2Name);
  6182. $pkIds = implode(',', array_keys($pkValues));
  6183. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  6184. $columnOrdering = array();
  6185. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  6186. if ($limit != -1) {
  6187. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  6188. }
  6189. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  6190. foreach ($records as $record) {
  6191. $val1 = $record[$fk1Name];
  6192. $val2 = $record[$fk2Name];
  6193. $pkValues[$val1][] = $val2;
  6194. $fkValues[$val2] = null;
  6195. }
  6196. return new HabtmValues($pkValues, $fkValues);
  6197. }
  6198. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  6199. {
  6200. $pkName = $t1->getPk()->getName();
  6201. $t2Name = $t2->getName();
  6202. foreach ($records as $i => $record) {
  6203. $key = $record[$pkName];
  6204. $val = array();
  6205. $fks = $habtmValues->pkValues[$key];
  6206. foreach ($fks as $fk) {
  6207. $val[] = $habtmValues->fkValues[$fk];
  6208. }
  6209. $records[$i][$t2Name] = $val;
  6210. }
  6211. }
  6212. }
  6213. // file: src/Tqdev/PhpCrudApi/Api.php
  6214. class Api implements RequestHandlerInterface
  6215. {
  6216. private $router;
  6217. private $responder;
  6218. private $debug;
  6219. public function __construct(Config $config)
  6220. {
  6221. $db = new GenericDB(
  6222. $config->getDriver(),
  6223. $config->getAddress(),
  6224. $config->getPort(),
  6225. $config->getDatabase(),
  6226. $config->getUsername(),
  6227. $config->getPassword()
  6228. );
  6229. $cache = CacheFactory::create($config);
  6230. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  6231. $responder = new Responder();
  6232. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  6233. foreach ($config->getMiddlewares() as $middleware => $properties) {
  6234. switch ($middleware) {
  6235. case 'cors':
  6236. new CorsMiddleware($router, $responder, $properties);
  6237. break;
  6238. case 'firewall':
  6239. new FirewallMiddleware($router, $responder, $properties);
  6240. break;
  6241. case 'basicAuth':
  6242. new BasicAuthMiddleware($router, $responder, $properties);
  6243. break;
  6244. case 'jwtAuth':
  6245. new JwtAuthMiddleware($router, $responder, $properties);
  6246. break;
  6247. case 'validation':
  6248. new ValidationMiddleware($router, $responder, $properties, $reflection);
  6249. break;
  6250. case 'ipAddress':
  6251. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  6252. break;
  6253. case 'sanitation':
  6254. new SanitationMiddleware($router, $responder, $properties, $reflection);
  6255. break;
  6256. case 'multiTenancy':
  6257. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  6258. break;
  6259. case 'authorization':
  6260. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  6261. break;
  6262. case 'xsrf':
  6263. new XsrfMiddleware($router, $responder, $properties);
  6264. break;
  6265. case 'pageLimits':
  6266. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  6267. break;
  6268. case 'joinLimits':
  6269. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  6270. break;
  6271. case 'customization':
  6272. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  6273. break;
  6274. }
  6275. }
  6276. foreach ($config->getControllers() as $controller) {
  6277. switch ($controller) {
  6278. case 'records':
  6279. $records = new RecordService($db, $reflection);
  6280. new RecordController($router, $responder, $records);
  6281. break;
  6282. case 'columns':
  6283. $definition = new DefinitionService($db, $reflection);
  6284. new ColumnController($router, $responder, $reflection, $definition);
  6285. break;
  6286. case 'cache':
  6287. new CacheController($router, $responder, $cache);
  6288. break;
  6289. case 'openapi':
  6290. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  6291. new OpenApiController($router, $responder, $openApi);
  6292. break;
  6293. case 'geojson':
  6294. $records = new RecordService($db, $reflection);
  6295. $geoJson = new GeoJsonService($reflection, $records);
  6296. new GeoJsonController($router, $responder, $geoJson);
  6297. break;
  6298. }
  6299. }
  6300. $this->router = $router;
  6301. $this->responder = $responder;
  6302. $this->debug = $config->getDebug();
  6303. }
  6304. public function handle(ServerRequestInterface $request): ResponseInterface
  6305. {
  6306. $response = null;
  6307. try {
  6308. $response = $this->router->route($request);
  6309. } catch (\Throwable $e) {
  6310. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  6311. if ($this->debug) {
  6312. $response = ResponseUtils::addExceptionHeaders($response, $e);
  6313. }
  6314. }
  6315. return $response;
  6316. }
  6317. }
  6318. // file: src/Tqdev/PhpCrudApi/Config.php
  6319. class Config
  6320. {
  6321. private $values = [
  6322. 'driver' => null,
  6323. 'address' => 'localhost',
  6324. 'port' => null,
  6325. 'username' => null,
  6326. 'password' => null,
  6327. 'database' => null,
  6328. 'middlewares' => 'cors',
  6329. 'controllers' => 'records,geojson,openapi',
  6330. 'cacheType' => 'TempFile',
  6331. 'cachePath' => '',
  6332. 'cacheTime' => 10,
  6333. 'debug' => false,
  6334. 'basePath' => '',
  6335. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  6336. ];
  6337. private function getDefaultDriver(array $values): string
  6338. {
  6339. if (isset($values['driver'])) {
  6340. return $values['driver'];
  6341. }
  6342. return 'mysql';
  6343. }
  6344. private function getDefaultPort(string $driver): int
  6345. {
  6346. switch ($driver) {
  6347. case 'mysql':return 3306;
  6348. case 'pgsql':return 5432;
  6349. case 'sqlsrv':return 1433;
  6350. }
  6351. }
  6352. private function getDefaultAddress(string $driver): string
  6353. {
  6354. switch ($driver) {
  6355. case 'mysql':return 'localhost';
  6356. case 'pgsql':return 'localhost';
  6357. case 'sqlsrv':return 'localhost';
  6358. }
  6359. }
  6360. private function getDriverDefaults(string $driver): array
  6361. {
  6362. return [
  6363. 'driver' => $driver,
  6364. 'address' => $this->getDefaultAddress($driver),
  6365. 'port' => $this->getDefaultPort($driver),
  6366. ];
  6367. }
  6368. public function __construct(array $values)
  6369. {
  6370. $driver = $this->getDefaultDriver($values);
  6371. $defaults = $this->getDriverDefaults($driver);
  6372. $newValues = array_merge($this->values, $defaults, $values);
  6373. $newValues = $this->parseMiddlewares($newValues);
  6374. $diff = array_diff_key($newValues, $this->values);
  6375. if (!empty($diff)) {
  6376. $key = array_keys($diff)[0];
  6377. throw new \Exception("Config has invalid value '$key'");
  6378. }
  6379. $this->values = $newValues;
  6380. }
  6381. private function parseMiddlewares(array $values): array
  6382. {
  6383. $newValues = array();
  6384. $properties = array();
  6385. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  6386. foreach ($middlewares as $middleware) {
  6387. $properties[$middleware] = [];
  6388. }
  6389. foreach ($values as $key => $value) {
  6390. if (strpos($key, '.') === false) {
  6391. $newValues[$key] = $value;
  6392. } else {
  6393. list($middleware, $key2) = explode('.', $key, 2);
  6394. if (isset($properties[$middleware])) {
  6395. $properties[$middleware][$key2] = $value;
  6396. } else {
  6397. throw new \Exception("Config has invalid value '$key'");
  6398. }
  6399. }
  6400. }
  6401. $newValues['middlewares'] = array_reverse($properties, true);
  6402. return $newValues;
  6403. }
  6404. public function getDriver(): string
  6405. {
  6406. return $this->values['driver'];
  6407. }
  6408. public function getAddress(): string
  6409. {
  6410. return $this->values['address'];
  6411. }
  6412. public function getPort(): int
  6413. {
  6414. return $this->values['port'];
  6415. }
  6416. public function getUsername(): string
  6417. {
  6418. return $this->values['username'];
  6419. }
  6420. public function getPassword(): string
  6421. {
  6422. return $this->values['password'];
  6423. }
  6424. public function getDatabase(): string
  6425. {
  6426. return $this->values['database'];
  6427. }
  6428. public function getMiddlewares(): array
  6429. {
  6430. return $this->values['middlewares'];
  6431. }
  6432. public function getControllers(): array
  6433. {
  6434. return array_map('trim', explode(',', $this->values['controllers']));
  6435. }
  6436. public function getCacheType(): string
  6437. {
  6438. return $this->values['cacheType'];
  6439. }
  6440. public function getCachePath(): string
  6441. {
  6442. return $this->values['cachePath'];
  6443. }
  6444. public function getCacheTime(): int
  6445. {
  6446. return $this->values['cacheTime'];
  6447. }
  6448. public function getDebug(): bool
  6449. {
  6450. return $this->values['debug'];
  6451. }
  6452. public function getBasePath(): string
  6453. {
  6454. return $this->values['basePath'];
  6455. }
  6456. public function getOpenApiBase(): array
  6457. {
  6458. return json_decode($this->values['openApiBase'], true);
  6459. }
  6460. }
  6461. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  6462. class RequestFactory
  6463. {
  6464. private static function parseBody(string $body) /*: ?object*/
  6465. {
  6466. $first = substr($body, 0, 1);
  6467. if ($first == '[' || $first == '{') {
  6468. $object = json_decode($body);
  6469. $causeCode = json_last_error();
  6470. if ($causeCode !== JSON_ERROR_NONE) {
  6471. $object = null;
  6472. }
  6473. } else {
  6474. parse_str($body, $input);
  6475. foreach ($input as $key => $value) {
  6476. if (substr($key, -9) == '__is_null') {
  6477. $input[substr($key, 0, -9)] = null;
  6478. unset($input[$key]);
  6479. }
  6480. }
  6481. $object = (object) $input;
  6482. }
  6483. return $object;
  6484. }
  6485. public static function fromGlobals(): ServerRequestInterface
  6486. {
  6487. $psr17Factory = new Psr17Factory();
  6488. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  6489. $serverRequest = $creator->fromGlobals();
  6490. $body = file_get_contents('php://input');
  6491. if ($body) {
  6492. $serverRequest = $serverRequest->withParsedBody(self::parseBody($body));
  6493. }
  6494. return $serverRequest;
  6495. }
  6496. public static function fromString(string $request): ServerRequestInterface
  6497. {
  6498. $parts = explode("\n\n", trim($request), 2);
  6499. $lines = explode("\n", $parts[0]);
  6500. $first = explode(' ', trim(array_shift($lines)), 2);
  6501. $method = $first[0];
  6502. $body = isset($parts[1]) ? $parts[1] : '';
  6503. $url = isset($first[1]) ? $first[1] : '';
  6504. $psr17Factory = new Psr17Factory();
  6505. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  6506. foreach ($lines as $line) {
  6507. list($key, $value) = explode(':', $line, 2);
  6508. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  6509. }
  6510. if ($body) {
  6511. $stream = $psr17Factory->createStream($body);
  6512. $stream->rewind();
  6513. $serverRequest = $serverRequest->withBody($stream);
  6514. $serverRequest = $serverRequest->withParsedBody(self::parseBody($body));
  6515. }
  6516. return $serverRequest;
  6517. }
  6518. }
  6519. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  6520. class RequestUtils
  6521. {
  6522. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  6523. {
  6524. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  6525. return $request->withUri($request->getUri()->withQuery($query));
  6526. }
  6527. public static function getHeader(ServerRequestInterface $request, string $header): string
  6528. {
  6529. $headers = $request->getHeader($header);
  6530. return isset($headers[0]) ? $headers[0] : '';
  6531. }
  6532. public static function getParams(ServerRequestInterface $request): array
  6533. {
  6534. $params = array();
  6535. $query = $request->getUri()->getQuery();
  6536. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  6537. parse_str($query, $params);
  6538. return $params;
  6539. }
  6540. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  6541. {
  6542. $path = $request->getUri()->getPath();
  6543. $pathSegments = explode('/', rtrim($path, '/'));
  6544. if ($part < 0 || $part >= count($pathSegments)) {
  6545. return '';
  6546. }
  6547. return urldecode($pathSegments[$part]);
  6548. }
  6549. public static function getOperation(ServerRequestInterface $request): string
  6550. {
  6551. $method = $request->getMethod();
  6552. $path = RequestUtils::getPathSegment($request, 1);
  6553. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  6554. switch ($path) {
  6555. case 'openapi':
  6556. return 'document';
  6557. case 'columns':
  6558. return $method == 'get' ? 'reflect' : 'remodel';
  6559. case 'records':
  6560. switch ($method) {
  6561. case 'POST':
  6562. return 'create';
  6563. case 'GET':
  6564. return $hasPk ? 'read' : 'list';
  6565. case 'PUT':
  6566. return 'update';
  6567. case 'DELETE':
  6568. return 'delete';
  6569. case 'PATCH':
  6570. return 'increment';
  6571. }
  6572. }
  6573. return 'unknown';
  6574. }
  6575. private static function getJoinTables(string $tableName, array $parameters): array
  6576. {
  6577. $uniqueTableNames = array();
  6578. $uniqueTableNames[$tableName] = true;
  6579. if (isset($parameters['join'])) {
  6580. foreach ($parameters['join'] as $parameter) {
  6581. $tableNames = explode(',', trim($parameter));
  6582. foreach ($tableNames as $tableName) {
  6583. $uniqueTableNames[$tableName] = true;
  6584. }
  6585. }
  6586. }
  6587. return array_keys($uniqueTableNames);
  6588. }
  6589. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  6590. {
  6591. $path = RequestUtils::getPathSegment($request, 1);
  6592. $tableName = RequestUtils::getPathSegment($request, 2);
  6593. $allTableNames = $reflection->getTableNames();
  6594. switch ($path) {
  6595. case 'openapi':
  6596. return $allTableNames;
  6597. case 'columns':
  6598. return $tableName ? [$tableName] : $allTableNames;
  6599. case 'records':
  6600. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  6601. }
  6602. return $allTableNames;
  6603. }
  6604. }
  6605. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  6606. class ResponseFactory
  6607. {
  6608. const OK = 200;
  6609. const UNAUTHORIZED = 401;
  6610. const FORBIDDEN = 403;
  6611. const NOT_FOUND = 404;
  6612. const METHOD_NOT_ALLOWED = 405;
  6613. const CONFLICT = 409;
  6614. const UNPROCESSABLE_ENTITY = 422;
  6615. const INTERNAL_SERVER_ERROR = 500;
  6616. public static function fromObject(int $status, $body): ResponseInterface
  6617. {
  6618. $psr17Factory = new Psr17Factory();
  6619. $response = $psr17Factory->createResponse($status);
  6620. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  6621. $stream = $psr17Factory->createStream($content);
  6622. $stream->rewind();
  6623. $response = $response->withBody($stream);
  6624. $response = $response->withHeader('Content-Type', 'application/json');
  6625. $response = $response->withHeader('Content-Length', strlen($content));
  6626. return $response;
  6627. }
  6628. public static function fromStatus(int $status): ResponseInterface
  6629. {
  6630. $psr17Factory = new Psr17Factory();
  6631. return $psr17Factory->createResponse($status);
  6632. }
  6633. }
  6634. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  6635. class ResponseUtils
  6636. {
  6637. public static function output(ResponseInterface $response)
  6638. {
  6639. $status = $response->getStatusCode();
  6640. $headers = $response->getHeaders();
  6641. $body = $response->getBody()->getContents();
  6642. http_response_code($status);
  6643. foreach ($headers as $key => $values) {
  6644. foreach ($values as $value) {
  6645. header("$key: $value");
  6646. }
  6647. }
  6648. echo $body;
  6649. }
  6650. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  6651. {
  6652. $response = $response->withHeader('X-Exception-Name', get_class($e));
  6653. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  6654. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  6655. return $response;
  6656. }
  6657. public static function toString(ResponseInterface $response): string
  6658. {
  6659. $status = $response->getStatusCode();
  6660. $headers = $response->getHeaders();
  6661. $body = $response->getBody()->getContents();
  6662. $str = "$status\n";
  6663. foreach ($headers as $key => $values) {
  6664. foreach ($values as $value) {
  6665. $str .= "$key: $value\n";
  6666. }
  6667. }
  6668. if ($body !== '') {
  6669. $str .= "\n";
  6670. $str .= "$body\n";
  6671. }
  6672. return $str;
  6673. }
  6674. }
  6675. // file: src/index.php
  6676. $config = new Config([
  6677. 'username' => 'php-crud-api',
  6678. 'password' => 'php-crud-api',
  6679. 'database' => 'php-crud-api',
  6680. ]);
  6681. $request = RequestFactory::fromGlobals();
  6682. $api = new Api($config);
  6683. $response = $api->handle($request);
  6684. ResponseUtils::output($response);