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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866
  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 $id;
  3769. private $properties;
  3770. private $geometry;
  3771. public function __construct($id, array $properties, /*?Geometry*/ $geometry)
  3772. {
  3773. $this->id = $id;
  3774. $this->properties = $properties;
  3775. $this->geometry = $geometry;
  3776. }
  3777. public function serialize()
  3778. {
  3779. return [
  3780. 'type' => 'Feature',
  3781. 'id' => $this->id,
  3782. 'properties' => $this->properties,
  3783. 'geometry' => $this->geometry,
  3784. ];
  3785. }
  3786. public function jsonSerialize()
  3787. {
  3788. return $this->serialize();
  3789. }
  3790. }
  3791. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  3792. class FeatureCollection implements \JsonSerializable
  3793. {
  3794. private $features;
  3795. private $results;
  3796. public function __construct(array $features, int $results)
  3797. {
  3798. $this->features = $features;
  3799. $this->results = $results;
  3800. }
  3801. public function serialize()
  3802. {
  3803. return [
  3804. 'type' => 'FeatureCollection',
  3805. 'features' => $this->features,
  3806. 'results' => $this->results,
  3807. ];
  3808. }
  3809. public function jsonSerialize()
  3810. {
  3811. return array_filter($this->serialize(), function ($v) {
  3812. return $v !== 0;
  3813. });
  3814. }
  3815. }
  3816. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  3817. class GeoJsonService
  3818. {
  3819. private $reflection;
  3820. private $records;
  3821. public function __construct(ReflectionService $reflection, RecordService $records)
  3822. {
  3823. $this->reflection = $reflection;
  3824. $this->records = $records;
  3825. }
  3826. public function hasTable(string $table): bool
  3827. {
  3828. return $this->reflection->hasTable($table);
  3829. }
  3830. public function getType(string $table): string
  3831. {
  3832. return $this->reflection->getType($table);
  3833. }
  3834. private function getGeometryColumnName(string $tableName, array &$params): string
  3835. {
  3836. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  3837. $table = $this->reflection->getTable($tableName);
  3838. $geometryColumnName = '';
  3839. foreach ($table->getColumnNames() as $columnName) {
  3840. if ($geometryParam && $geometryParam != $columnName) {
  3841. continue;
  3842. }
  3843. $column = $table->getColumn($columnName);
  3844. if ($column->isGeometry()) {
  3845. $geometryColumnName = $columnName;
  3846. break;
  3847. }
  3848. }
  3849. if ($geometryColumnName) {
  3850. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  3851. }
  3852. return $geometryColumnName;
  3853. }
  3854. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  3855. {
  3856. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  3857. if ($boundingBox) {
  3858. $c = explode(',', $boundingBox);
  3859. if (!isset($params['filter'])) {
  3860. $params['filter'] = array();
  3861. }
  3862. $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]))";
  3863. }
  3864. $tile = isset($params['tile']) ? $params['tile'][0] : '';
  3865. if ($tile) {
  3866. $zxy = explode(',', $tile);
  3867. if (count($zxy) == 3) {
  3868. list($z, $x, $y) = $zxy;
  3869. $c = array();
  3870. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x, $y));
  3871. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x + 1, $y + 1));
  3872. $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]))";
  3873. }
  3874. }
  3875. }
  3876. private function convertTileToLatLonOfUpperLeftCorner($z, $x, $y): array
  3877. {
  3878. $n = pow(2, $z);
  3879. $lon = $x / $n * 360.0 - 180.0;
  3880. $lat = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n))));
  3881. return [$lon, $lat];
  3882. }
  3883. private function convertRecordToFeature( /*object*/$record, string $primaryKeyColumnName, string $geometryColumnName)
  3884. {
  3885. $id = null;
  3886. if ($primaryKeyColumnName) {
  3887. $id = $record[$primaryKeyColumnName];
  3888. }
  3889. $geometry = null;
  3890. if (isset($record[$geometryColumnName])) {
  3891. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  3892. }
  3893. $properties = array_diff_key($record, [$primaryKeyColumnName => true, $geometryColumnName => true]);
  3894. return new Feature($id, $properties, $geometry);
  3895. }
  3896. private function getPrimaryKeyColumnName(string $tableName, array &$params): string
  3897. {
  3898. $primaryKeyColumn = $this->reflection->getTable($tableName)->getPk();
  3899. if (!$primaryKeyColumn) {
  3900. return '';
  3901. }
  3902. $primaryKeyColumnName = $primaryKeyColumn->getName();
  3903. $params['mandatory'][] = $tableName . "." . $primaryKeyColumnName;
  3904. return $primaryKeyColumnName;
  3905. }
  3906. public function _list(string $tableName, array $params): FeatureCollection
  3907. {
  3908. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  3909. $this->setBoudingBoxFilter($geometryColumnName, $params);
  3910. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  3911. $records = $this->records->_list($tableName, $params);
  3912. $features = array();
  3913. foreach ($records->getRecords() as $record) {
  3914. $features[] = $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  3915. }
  3916. return new FeatureCollection($features, $records->getResults());
  3917. }
  3918. public function read(string $tableName, string $id, array $params): Feature
  3919. {
  3920. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  3921. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  3922. $record = $this->records->read($tableName, $id, $params);
  3923. return $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  3924. }
  3925. }
  3926. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  3927. class Geometry implements \JsonSerializable
  3928. {
  3929. private $type;
  3930. private $geometry;
  3931. public static $types = [
  3932. "Point",
  3933. "MultiPoint",
  3934. "LineString",
  3935. "MultiLineString",
  3936. "Polygon",
  3937. "MultiPolygon",
  3938. ];
  3939. public function __construct(string $type, array $coordinates)
  3940. {
  3941. $this->type = $type;
  3942. $this->coordinates = $coordinates;
  3943. }
  3944. public static function fromWkt(string $wkt): Geometry
  3945. {
  3946. $bracket = strpos($wkt, '(');
  3947. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  3948. $supported = false;
  3949. foreach (Geometry::$types as $typeName) {
  3950. if (strtoupper($typeName) == $type) {
  3951. $type = $typeName;
  3952. $supported = true;
  3953. }
  3954. }
  3955. if (!$supported) {
  3956. throw new \Exception('Geometry type not supported: ' . $type);
  3957. }
  3958. $coordinates = substr($wkt, $bracket);
  3959. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  3960. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  3961. }
  3962. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  3963. $json = $coordinates;
  3964. $coordinates = json_decode($coordinates);
  3965. if (!$coordinates) {
  3966. throw new \Exception('Could not decode WKT: ' . $wkt);
  3967. }
  3968. return new Geometry($type, $coordinates);
  3969. }
  3970. public function serialize()
  3971. {
  3972. return [
  3973. 'type' => $this->type,
  3974. 'coordinates' => $this->coordinates,
  3975. ];
  3976. }
  3977. public function jsonSerialize()
  3978. {
  3979. return $this->serialize();
  3980. }
  3981. }
  3982. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  3983. abstract class Middleware implements MiddlewareInterface
  3984. {
  3985. protected $next;
  3986. protected $responder;
  3987. private $properties;
  3988. public function __construct(Router $router, Responder $responder, array $properties)
  3989. {
  3990. $router->load($this);
  3991. $this->responder = $responder;
  3992. $this->properties = $properties;
  3993. }
  3994. protected function getArrayProperty(string $key, string $default): array
  3995. {
  3996. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  3997. }
  3998. protected function getProperty(string $key, $default)
  3999. {
  4000. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  4001. }
  4002. }
  4003. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  4004. class VariableStore
  4005. {
  4006. static $values = array();
  4007. public static function get(string $key)
  4008. {
  4009. if (isset(self::$values[$key])) {
  4010. return self::$values[$key];
  4011. }
  4012. return null;
  4013. }
  4014. public static function set(string $key, /* object */ $value)
  4015. {
  4016. self::$values[$key] = $value;
  4017. }
  4018. }
  4019. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  4020. interface Router extends RequestHandlerInterface
  4021. {
  4022. public function register(string $method, string $path, array $handler);
  4023. public function load(Middleware $middleware);
  4024. public function route(ServerRequestInterface $request): ResponseInterface;
  4025. }
  4026. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  4027. class SimpleRouter implements Router
  4028. {
  4029. private $basePath;
  4030. private $responder;
  4031. private $cache;
  4032. private $ttl;
  4033. private $debug;
  4034. private $registration;
  4035. private $routes;
  4036. private $routeHandlers;
  4037. private $middlewares;
  4038. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  4039. {
  4040. $this->basePath = $basePath;
  4041. $this->responder = $responder;
  4042. $this->cache = $cache;
  4043. $this->ttl = $ttl;
  4044. $this->debug = $debug;
  4045. $this->registration = true;
  4046. $this->routes = $this->loadPathTree();
  4047. $this->routeHandlers = [];
  4048. $this->middlewares = array();
  4049. }
  4050. private function loadPathTree(): PathTree
  4051. {
  4052. $data = $this->cache->get('PathTree');
  4053. if ($data != '') {
  4054. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  4055. $this->registration = false;
  4056. } else {
  4057. $tree = new PathTree();
  4058. }
  4059. return $tree;
  4060. }
  4061. public function register(string $method, string $path, array $handler)
  4062. {
  4063. $routeNumber = count($this->routeHandlers);
  4064. $this->routeHandlers[$routeNumber] = $handler;
  4065. if ($this->registration) {
  4066. $parts = explode('/', trim($path, '/'));
  4067. array_unshift($parts, $method);
  4068. $this->routes->put($parts, $routeNumber);
  4069. }
  4070. }
  4071. public function load(Middleware $middleware) /*: void*/
  4072. {
  4073. array_push($this->middlewares, $middleware);
  4074. }
  4075. public function route(ServerRequestInterface $request): ResponseInterface
  4076. {
  4077. if ($this->registration) {
  4078. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  4079. $this->cache->set('PathTree', $data, $this->ttl);
  4080. }
  4081. return $this->handle($request);
  4082. }
  4083. private function getRouteNumbers(ServerRequestInterface $request): array
  4084. {
  4085. $method = strtoupper($request->getMethod());
  4086. $path = array();
  4087. $segment = $method;
  4088. for ($i = 1; $segment; $i++) {
  4089. array_push($path, $segment);
  4090. $segment = RequestUtils::getPathSegment($request, $i);
  4091. }
  4092. return $this->routes->match($path);
  4093. }
  4094. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  4095. {
  4096. if ($this->basePath) {
  4097. $path = $request->getUri()->getPath();
  4098. $basePath = rtrim($this->basePath, '/');
  4099. if (substr($path, 0, strlen($basePath)) == $basePath) {
  4100. $path = substr($path, strlen($basePath));
  4101. $request = $request->withUri($request->getUri()->withPath($path));
  4102. }
  4103. } elseif (isset($_SERVER['PATH_INFO'])) {
  4104. $path = $_SERVER['PATH_INFO'];
  4105. $request = $request->withUri($request->getUri()->withPath($path));
  4106. }
  4107. return $request;
  4108. }
  4109. public function handle(ServerRequestInterface $request): ResponseInterface
  4110. {
  4111. $request = $this->removeBasePath($request);
  4112. if (count($this->middlewares)) {
  4113. $handler = array_pop($this->middlewares);
  4114. return $handler->process($request, $this);
  4115. }
  4116. $routeNumbers = $this->getRouteNumbers($request);
  4117. if (count($routeNumbers) == 0) {
  4118. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  4119. }
  4120. try {
  4121. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  4122. } catch (\PDOException $e) {
  4123. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  4124. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  4125. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  4126. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4127. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  4128. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4129. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  4130. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4131. } else {
  4132. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  4133. }
  4134. if ($this->debug) {
  4135. $response = ResponseUtils::addExceptionHeaders($response, $e);
  4136. }
  4137. }
  4138. return $response;
  4139. }
  4140. }
  4141. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  4142. class AjaxOnlyMiddleware extends Middleware
  4143. {
  4144. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4145. {
  4146. $method = $request->getMethod();
  4147. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  4148. if (!in_array($method, $excludeMethods)) {
  4149. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  4150. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  4151. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  4152. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  4153. }
  4154. }
  4155. return $next->handle($request);
  4156. }
  4157. }
  4158. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  4159. class AuthorizationMiddleware extends Middleware
  4160. {
  4161. private $reflection;
  4162. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4163. {
  4164. parent::__construct($router, $responder, $properties);
  4165. $this->reflection = $reflection;
  4166. }
  4167. private function handleColumns(string $operation, string $tableName) /*: void*/
  4168. {
  4169. $columnHandler = $this->getProperty('columnHandler', '');
  4170. if ($columnHandler) {
  4171. $table = $this->reflection->getTable($tableName);
  4172. foreach ($table->getColumnNames() as $columnName) {
  4173. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  4174. if (!$allowed) {
  4175. $table->removeColumn($columnName);
  4176. }
  4177. }
  4178. }
  4179. }
  4180. private function handleTable(string $operation, string $tableName) /*: void*/
  4181. {
  4182. if (!$this->reflection->hasTable($tableName)) {
  4183. return;
  4184. }
  4185. $allowed = true;
  4186. $tableHandler = $this->getProperty('tableHandler', '');
  4187. if ($tableHandler) {
  4188. $allowed = call_user_func($tableHandler, $operation, $tableName);
  4189. }
  4190. if (!$allowed) {
  4191. $this->reflection->removeTable($tableName);
  4192. } else {
  4193. $this->handleColumns($operation, $tableName);
  4194. }
  4195. }
  4196. private function handleRecords(string $operation, string $tableName) /*: void*/
  4197. {
  4198. if (!$this->reflection->hasTable($tableName)) {
  4199. return;
  4200. }
  4201. $recordHandler = $this->getProperty('recordHandler', '');
  4202. if ($recordHandler) {
  4203. $query = call_user_func($recordHandler, $operation, $tableName);
  4204. $filters = new FilterInfo();
  4205. $table = $this->reflection->getTable($tableName);
  4206. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  4207. parse_str($query, $params);
  4208. $condition = $filters->getCombinedConditions($table, $params);
  4209. VariableStore::set("authorization.conditions.$tableName", $condition);
  4210. }
  4211. }
  4212. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4213. {
  4214. $path = RequestUtils::getPathSegment($request, 1);
  4215. $operation = RequestUtils::getOperation($request);
  4216. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  4217. foreach ($tableNames as $tableName) {
  4218. $this->handleTable($operation, $tableName);
  4219. if ($path == 'records') {
  4220. $this->handleRecords($operation, $tableName);
  4221. }
  4222. }
  4223. if ($path == 'openapi') {
  4224. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  4225. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  4226. }
  4227. return $next->handle($request);
  4228. }
  4229. }
  4230. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  4231. class BasicAuthMiddleware extends Middleware
  4232. {
  4233. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  4234. {
  4235. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  4236. if ($hash && password_verify($password, $hash)) {
  4237. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  4238. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  4239. }
  4240. return true;
  4241. }
  4242. return false;
  4243. }
  4244. private function getValidUsername(string $username, string $password, string $passwordFile): string
  4245. {
  4246. $passwords = $this->readPasswords($passwordFile);
  4247. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  4248. $this->writePasswords($passwordFile, $passwords);
  4249. return $valid ? $username : '';
  4250. }
  4251. private function readPasswords(string $passwordFile): array
  4252. {
  4253. $passwords = [];
  4254. $passwordLines = file($passwordFile);
  4255. foreach ($passwordLines as $passwordLine) {
  4256. if (strpos($passwordLine, ':') !== false) {
  4257. list($username, $hash) = explode(':', trim($passwordLine), 2);
  4258. if (strlen($hash) > 0 && $hash[0] != '$') {
  4259. $hash = password_hash($hash, PASSWORD_DEFAULT);
  4260. }
  4261. $passwords[$username] = $hash;
  4262. }
  4263. }
  4264. return $passwords;
  4265. }
  4266. private function writePasswords(string $passwordFile, array $passwords): bool
  4267. {
  4268. $success = false;
  4269. $passwordFileContents = '';
  4270. foreach ($passwords as $username => $hash) {
  4271. $passwordFileContents .= "$username:$hash\n";
  4272. }
  4273. if (file_get_contents($passwordFile) != $passwordFileContents) {
  4274. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  4275. }
  4276. return $success;
  4277. }
  4278. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  4279. {
  4280. if (isset($_SERVER['PHP_AUTH_USER'])) {
  4281. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  4282. }
  4283. $header = RequestUtils::getHeader($request, 'Authorization');
  4284. $parts = explode(' ', trim($header), 2);
  4285. if (count($parts) != 2) {
  4286. return '';
  4287. }
  4288. if ($parts[0] != 'Basic') {
  4289. return '';
  4290. }
  4291. return base64_decode(strtr($parts[1], '-_', '+/'));
  4292. }
  4293. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4294. {
  4295. if (session_status() == PHP_SESSION_NONE) {
  4296. if (!headers_sent()) {
  4297. session_start();
  4298. }
  4299. }
  4300. $credentials = $this->getAuthorizationCredentials($request);
  4301. if ($credentials) {
  4302. list($username, $password) = array('', '');
  4303. if (strpos($credentials, ':') !== false) {
  4304. list($username, $password) = explode(':', $credentials, 2);
  4305. }
  4306. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  4307. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  4308. $_SESSION['username'] = $validUser;
  4309. if (!$validUser) {
  4310. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  4311. }
  4312. if (!headers_sent()) {
  4313. session_regenerate_id();
  4314. }
  4315. }
  4316. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  4317. $authenticationMode = $this->getProperty('mode', 'required');
  4318. if ($authenticationMode == 'required') {
  4319. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4320. $realm = $this->getProperty('realm', 'Username and password required');
  4321. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  4322. return $response;
  4323. }
  4324. }
  4325. return $next->handle($request);
  4326. }
  4327. }
  4328. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  4329. class CorsMiddleware extends Middleware
  4330. {
  4331. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  4332. {
  4333. $found = false;
  4334. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  4335. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  4336. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  4337. if (preg_match($regex, $origin)) {
  4338. $found = true;
  4339. break;
  4340. }
  4341. }
  4342. return $found;
  4343. }
  4344. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4345. {
  4346. $method = $request->getMethod();
  4347. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  4348. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  4349. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  4350. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  4351. } elseif ($method == 'OPTIONS') {
  4352. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  4353. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  4354. if ($allowHeaders) {
  4355. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  4356. }
  4357. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  4358. if ($allowMethods) {
  4359. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  4360. }
  4361. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  4362. if ($allowCredentials) {
  4363. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  4364. }
  4365. $maxAge = $this->getProperty('maxAge', '1728000');
  4366. if ($maxAge) {
  4367. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  4368. }
  4369. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  4370. if ($exposeHeaders) {
  4371. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  4372. }
  4373. } else {
  4374. $response = $next->handle($request);
  4375. }
  4376. if ($origin) {
  4377. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  4378. if ($allowCredentials) {
  4379. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  4380. }
  4381. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  4382. }
  4383. return $response;
  4384. }
  4385. }
  4386. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  4387. class CustomizationMiddleware extends Middleware
  4388. {
  4389. private $reflection;
  4390. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4391. {
  4392. parent::__construct($router, $responder, $properties);
  4393. $this->reflection = $reflection;
  4394. }
  4395. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4396. {
  4397. $operation = RequestUtils::getOperation($request);
  4398. $tableName = RequestUtils::getPathSegment($request, 2);
  4399. $beforeHandler = $this->getProperty('beforeHandler', '');
  4400. $environment = (object) array();
  4401. if ($beforeHandler !== '') {
  4402. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  4403. $request = $result ?: $request;
  4404. }
  4405. $response = $next->handle($request);
  4406. $afterHandler = $this->getProperty('afterHandler', '');
  4407. if ($afterHandler !== '') {
  4408. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  4409. $response = $result ?: $response;
  4410. }
  4411. return $response;
  4412. }
  4413. }
  4414. // file: src/Tqdev/PhpCrudApi/Middleware/DbAuthMiddleware.php
  4415. class DbAuthMiddleware extends Middleware
  4416. {
  4417. private $reflection;
  4418. private $db;
  4419. private $ordering;
  4420. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  4421. {
  4422. parent::__construct($router, $responder, $properties);
  4423. $this->reflection = $reflection;
  4424. $this->db = $db;
  4425. $this->ordering = new OrderingInfo();
  4426. }
  4427. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4428. {
  4429. if (session_status() == PHP_SESSION_NONE) {
  4430. if (!headers_sent()) {
  4431. session_start();
  4432. }
  4433. }
  4434. $path = RequestUtils::getPathSegment($request, 1);
  4435. $method = $request->getMethod();
  4436. if ($method == 'POST' && $path == 'login') {
  4437. $body = $request->getParsedBody();
  4438. $username = isset($body->username) ? $body->username : '';
  4439. $password = isset($body->password) ? $body->password : '';
  4440. $tableName = $this->getProperty('usersTable', 'users');
  4441. $table = $this->reflection->getTable($tableName);
  4442. $usernameColumnName = $this->getProperty('usernameColumn', 'username');
  4443. $usernameColumn = $table->getColumn($usernameColumnName);
  4444. $passwordColumnName = $this->getProperty('passwordColumn', 'password');
  4445. $passwordColumn = $table->getColumn($passwordColumnName);
  4446. $condition = new ColumnCondition($usernameColumn, 'eq', $username);
  4447. $returnedColumns = $this->getProperty('returnedColumns', '');
  4448. if (!$returnedColumns) {
  4449. $columnNames = $table->getColumnNames();
  4450. } else {
  4451. $columnNames = array_map('trim', explode(',', $returnedColumns));
  4452. $columnNames[] = $passwordColumnName;
  4453. }
  4454. $columnOrdering = $this->ordering->getDefaultColumnOrdering($table);
  4455. $users = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, 0, 1);
  4456. foreach ($users as $user) {
  4457. if (password_verify($password, $user[$passwordColumnName]) == 1) {
  4458. if (!headers_sent()) {
  4459. session_regenerate_id(true);
  4460. }
  4461. unset($user[$passwordColumnName]);
  4462. $_SESSION['user'] = $user;
  4463. return $this->responder->success($user);
  4464. }
  4465. }
  4466. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  4467. }
  4468. if ($method == 'POST' && $path == 'logout') {
  4469. if (isset($_SESSION['user'])) {
  4470. $user = $_SESSION['user'];
  4471. unset($_SESSION['user']);
  4472. if (session_status() != PHP_SESSION_NONE) {
  4473. session_destroy();
  4474. }
  4475. return $this->responder->success($user);
  4476. }
  4477. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4478. }
  4479. if (!isset($_SESSION['user']) || !$_SESSION['user']) {
  4480. $authenticationMode = $this->getProperty('mode', 'required');
  4481. if ($authenticationMode == 'required') {
  4482. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4483. }
  4484. }
  4485. return $next->handle($request);
  4486. }
  4487. }
  4488. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  4489. class FirewallMiddleware extends Middleware
  4490. {
  4491. private function ipMatch(string $ip, string $cidr): bool
  4492. {
  4493. if (strpos($cidr, '/') !== false) {
  4494. list($subnet, $mask) = explode('/', trim($cidr));
  4495. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  4496. return true;
  4497. }
  4498. } else {
  4499. if (ip2long($ip) == ip2long($cidr)) {
  4500. return true;
  4501. }
  4502. }
  4503. return false;
  4504. }
  4505. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  4506. {
  4507. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  4508. if ($this->ipMatch($ipAddress, $allowedIp)) {
  4509. return true;
  4510. }
  4511. }
  4512. return false;
  4513. }
  4514. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4515. {
  4516. $reverseProxy = $this->getProperty('reverseProxy', '');
  4517. if ($reverseProxy) {
  4518. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  4519. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  4520. $ipAddress = $_SERVER['REMOTE_ADDR'];
  4521. } else {
  4522. $ipAddress = '127.0.0.1';
  4523. }
  4524. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  4525. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  4526. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  4527. } else {
  4528. $response = $next->handle($request);
  4529. }
  4530. return $response;
  4531. }
  4532. }
  4533. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  4534. class IpAddressMiddleware extends Middleware
  4535. {
  4536. private $reflection;
  4537. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4538. {
  4539. parent::__construct($router, $responder, $properties);
  4540. $this->reflection = $reflection;
  4541. }
  4542. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  4543. {
  4544. $context = (array) $record;
  4545. $columnNames = $this->getProperty('columns', '');
  4546. if ($columnNames) {
  4547. foreach (explode(',', $columnNames) as $columnName) {
  4548. if ($table->hasColumn($columnName)) {
  4549. if ($operation == 'create') {
  4550. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  4551. } else {
  4552. unset($context[$columnName]);
  4553. }
  4554. }
  4555. }
  4556. }
  4557. return (object) $context;
  4558. }
  4559. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4560. {
  4561. $operation = RequestUtils::getOperation($request);
  4562. if (in_array($operation, ['create', 'update', 'increment'])) {
  4563. $tableNames = $this->getProperty('tables', '');
  4564. $tableName = RequestUtils::getPathSegment($request, 2);
  4565. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  4566. if ($this->reflection->hasTable($tableName)) {
  4567. $record = $request->getParsedBody();
  4568. if ($record !== null) {
  4569. $table = $this->reflection->getTable($tableName);
  4570. if (is_array($record)) {
  4571. foreach ($record as &$r) {
  4572. $r = $this->callHandler($r, $operation, $table);
  4573. }
  4574. } else {
  4575. $record = $this->callHandler($record, $operation, $table);
  4576. }
  4577. $request = $request->withParsedBody($record);
  4578. }
  4579. }
  4580. }
  4581. }
  4582. return $next->handle($request);
  4583. }
  4584. }
  4585. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  4586. class JoinLimitsMiddleware extends Middleware
  4587. {
  4588. private $reflection;
  4589. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4590. {
  4591. parent::__construct($router, $responder, $properties);
  4592. $this->reflection = $reflection;
  4593. }
  4594. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4595. {
  4596. $operation = RequestUtils::getOperation($request);
  4597. $params = RequestUtils::getParams($request);
  4598. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  4599. $maxDepth = (int) $this->getProperty('depth', '3');
  4600. $maxTables = (int) $this->getProperty('tables', '10');
  4601. $maxRecords = (int) $this->getProperty('records', '1000');
  4602. $tableCount = 0;
  4603. $joinPaths = array();
  4604. for ($i = 0; $i < count($params['join']); $i++) {
  4605. $joinPath = array();
  4606. $tables = explode(',', $params['join'][$i]);
  4607. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  4608. array_push($joinPath, $tables[$depth]);
  4609. $tableCount += 1;
  4610. if ($tableCount == $maxTables) {
  4611. break;
  4612. }
  4613. }
  4614. array_push($joinPaths, implode(',', $joinPath));
  4615. if ($tableCount == $maxTables) {
  4616. break;
  4617. }
  4618. }
  4619. $params['join'] = $joinPaths;
  4620. $request = RequestUtils::setParams($request, $params);
  4621. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  4622. }
  4623. return $next->handle($request);
  4624. }
  4625. }
  4626. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  4627. class JwtAuthMiddleware extends Middleware
  4628. {
  4629. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, string $secret, array $requirements): array
  4630. {
  4631. $algorithms = array(
  4632. 'HS256' => 'sha256',
  4633. 'HS384' => 'sha384',
  4634. 'HS512' => 'sha512',
  4635. 'RS256' => 'sha256',
  4636. 'RS384' => 'sha384',
  4637. 'RS512' => 'sha512',
  4638. );
  4639. $token = explode('.', $token);
  4640. if (count($token) < 3) {
  4641. return array();
  4642. }
  4643. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  4644. if (!$secret) {
  4645. return array();
  4646. }
  4647. if ($header['typ'] != 'JWT') {
  4648. return array();
  4649. }
  4650. $algorithm = $header['alg'];
  4651. if (!isset($algorithms[$algorithm])) {
  4652. return array();
  4653. }
  4654. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  4655. return array();
  4656. }
  4657. $hmac = $algorithms[$algorithm];
  4658. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  4659. $data = "$token[0].$token[1]";
  4660. switch ($algorithm[0]) {
  4661. case 'H':
  4662. $hash = hash_hmac($hmac, $data, $secret, true);
  4663. if (function_exists('hash_equals')) {
  4664. $equals = hash_equals($signature, $hash);
  4665. } else {
  4666. $equals = $signature == $hash;
  4667. }
  4668. if (!$equals) {
  4669. return array();
  4670. }
  4671. break;
  4672. case 'R':
  4673. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  4674. if (!$equals) {
  4675. return array();
  4676. }
  4677. break;
  4678. }
  4679. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  4680. if (!$claims) {
  4681. return array();
  4682. }
  4683. foreach ($requirements as $field => $values) {
  4684. if (!empty($values)) {
  4685. if ($field != 'alg') {
  4686. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  4687. return array();
  4688. }
  4689. }
  4690. }
  4691. }
  4692. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  4693. return array();
  4694. }
  4695. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  4696. return array();
  4697. }
  4698. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  4699. return array();
  4700. }
  4701. if (isset($claims['iat']) && !isset($claims['exp'])) {
  4702. if ($time - $leeway > $claims['iat'] + $ttl) {
  4703. return array();
  4704. }
  4705. }
  4706. return $claims;
  4707. }
  4708. private function getClaims(string $token): array
  4709. {
  4710. $time = (int) $this->getProperty('time', time());
  4711. $leeway = (int) $this->getProperty('leeway', '5');
  4712. $ttl = (int) $this->getProperty('ttl', '30');
  4713. $secret = $this->getProperty('secret', '');
  4714. $requirements = array(
  4715. 'alg' => $this->getArrayProperty('algorithms', ''),
  4716. 'aud' => $this->getArrayProperty('audiences', ''),
  4717. 'iss' => $this->getArrayProperty('issuers', ''),
  4718. );
  4719. if (!$secret) {
  4720. return array();
  4721. }
  4722. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  4723. }
  4724. private function getAuthorizationToken(ServerRequestInterface $request): string
  4725. {
  4726. $headerName = $this->getProperty('header', 'X-Authorization');
  4727. $headerValue = RequestUtils::getHeader($request, $headerName);
  4728. $parts = explode(' ', trim($headerValue), 2);
  4729. if (count($parts) != 2) {
  4730. return '';
  4731. }
  4732. if ($parts[0] != 'Bearer') {
  4733. return '';
  4734. }
  4735. return $parts[1];
  4736. }
  4737. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4738. {
  4739. if (session_status() == PHP_SESSION_NONE) {
  4740. if (!headers_sent()) {
  4741. session_start();
  4742. }
  4743. }
  4744. $token = $this->getAuthorizationToken($request);
  4745. if ($token) {
  4746. $claims = $this->getClaims($token);
  4747. $_SESSION['claims'] = $claims;
  4748. if (empty($claims)) {
  4749. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  4750. }
  4751. if (!headers_sent()) {
  4752. session_regenerate_id();
  4753. }
  4754. }
  4755. if (empty($_SESSION['claims'])) {
  4756. $authenticationMode = $this->getProperty('mode', 'required');
  4757. if ($authenticationMode == 'required') {
  4758. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4759. }
  4760. }
  4761. return $next->handle($request);
  4762. }
  4763. }
  4764. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  4765. class MultiTenancyMiddleware extends Middleware
  4766. {
  4767. private $reflection;
  4768. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4769. {
  4770. parent::__construct($router, $responder, $properties);
  4771. $this->reflection = $reflection;
  4772. }
  4773. private function getCondition(string $tableName, array $pairs): Condition
  4774. {
  4775. $condition = new NoCondition();
  4776. $table = $this->reflection->getTable($tableName);
  4777. foreach ($pairs as $k => $v) {
  4778. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  4779. }
  4780. return $condition;
  4781. }
  4782. private function getPairs($handler, string $operation, string $tableName): array
  4783. {
  4784. $result = array();
  4785. $pairs = call_user_func($handler, $operation, $tableName);
  4786. $table = $this->reflection->getTable($tableName);
  4787. foreach ($pairs as $k => $v) {
  4788. if ($table->hasColumn($k)) {
  4789. $result[$k] = $v;
  4790. }
  4791. }
  4792. return $result;
  4793. }
  4794. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  4795. {
  4796. $record = $request->getParsedBody();
  4797. if ($record === null) {
  4798. return $request;
  4799. }
  4800. $multi = is_array($record);
  4801. $records = $multi ? $record : [$record];
  4802. foreach ($records as &$record) {
  4803. foreach ($pairs as $column => $value) {
  4804. if ($operation == 'create') {
  4805. $record->$column = $value;
  4806. } else {
  4807. if (isset($record->$column)) {
  4808. unset($record->$column);
  4809. }
  4810. }
  4811. }
  4812. }
  4813. return $request->withParsedBody($multi ? $records : $records[0]);
  4814. }
  4815. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4816. {
  4817. $handler = $this->getProperty('handler', '');
  4818. if ($handler !== '') {
  4819. $path = RequestUtils::getPathSegment($request, 1);
  4820. if ($path == 'records') {
  4821. $operation = RequestUtils::getOperation($request);
  4822. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  4823. foreach ($tableNames as $i => $tableName) {
  4824. if (!$this->reflection->hasTable($tableName)) {
  4825. continue;
  4826. }
  4827. $pairs = $this->getPairs($handler, $operation, $tableName);
  4828. if ($i == 0) {
  4829. if (in_array($operation, ['create', 'update', 'increment'])) {
  4830. $request = $this->handleRecord($request, $operation, $pairs);
  4831. }
  4832. }
  4833. $condition = $this->getCondition($tableName, $pairs);
  4834. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  4835. }
  4836. }
  4837. }
  4838. return $next->handle($request);
  4839. }
  4840. }
  4841. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  4842. class PageLimitsMiddleware extends Middleware
  4843. {
  4844. private $reflection;
  4845. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4846. {
  4847. parent::__construct($router, $responder, $properties);
  4848. $this->reflection = $reflection;
  4849. }
  4850. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4851. {
  4852. $operation = RequestUtils::getOperation($request);
  4853. if ($operation == 'list') {
  4854. $params = RequestUtils::getParams($request);
  4855. $maxPage = (int) $this->getProperty('pages', '100');
  4856. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  4857. if (strpos($params['page'][0], ',') === false) {
  4858. $page = $params['page'][0];
  4859. } else {
  4860. list($page, $size) = explode(',', $params['page'][0], 2);
  4861. }
  4862. if ($page > $maxPage) {
  4863. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  4864. }
  4865. }
  4866. $maxSize = (int) $this->getProperty('records', '1000');
  4867. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  4868. $params['size'] = array($maxSize);
  4869. } else {
  4870. $params['size'] = array(min($params['size'][0], $maxSize));
  4871. }
  4872. $request = RequestUtils::setParams($request, $params);
  4873. }
  4874. return $next->handle($request);
  4875. }
  4876. }
  4877. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  4878. class SanitationMiddleware extends Middleware
  4879. {
  4880. private $reflection;
  4881. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4882. {
  4883. parent::__construct($router, $responder, $properties);
  4884. $this->reflection = $reflection;
  4885. }
  4886. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  4887. {
  4888. $context = (array) $record;
  4889. $tableName = $table->getName();
  4890. foreach ($context as $columnName => &$value) {
  4891. if ($table->hasColumn($columnName)) {
  4892. $column = $table->getColumn($columnName);
  4893. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  4894. }
  4895. }
  4896. return (object) $context;
  4897. }
  4898. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4899. {
  4900. $operation = RequestUtils::getOperation($request);
  4901. if (in_array($operation, ['create', 'update', 'increment'])) {
  4902. $tableName = RequestUtils::getPathSegment($request, 2);
  4903. if ($this->reflection->hasTable($tableName)) {
  4904. $record = $request->getParsedBody();
  4905. if ($record !== null) {
  4906. $handler = $this->getProperty('handler', '');
  4907. if ($handler !== '') {
  4908. $table = $this->reflection->getTable($tableName);
  4909. if (is_array($record)) {
  4910. foreach ($record as &$r) {
  4911. $r = $this->callHandler($handler, $r, $operation, $table);
  4912. }
  4913. } else {
  4914. $record = $this->callHandler($handler, $record, $operation, $table);
  4915. }
  4916. $request = $request->withParsedBody($record);
  4917. }
  4918. }
  4919. }
  4920. }
  4921. return $next->handle($request);
  4922. }
  4923. }
  4924. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  4925. class ValidationMiddleware extends Middleware
  4926. {
  4927. private $reflection;
  4928. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4929. {
  4930. parent::__construct($router, $responder, $properties);
  4931. $this->reflection = $reflection;
  4932. }
  4933. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  4934. {
  4935. $context = (array) $record;
  4936. $details = array();
  4937. $tableName = $table->getName();
  4938. foreach ($context as $columnName => $value) {
  4939. if ($table->hasColumn($columnName)) {
  4940. $column = $table->getColumn($columnName);
  4941. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  4942. if ($valid !== true && $valid !== '') {
  4943. $details[$columnName] = $valid;
  4944. }
  4945. }
  4946. }
  4947. if (count($details) > 0) {
  4948. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  4949. }
  4950. return null;
  4951. }
  4952. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4953. {
  4954. $operation = RequestUtils::getOperation($request);
  4955. if (in_array($operation, ['create', 'update', 'increment'])) {
  4956. $tableName = RequestUtils::getPathSegment($request, 2);
  4957. if ($this->reflection->hasTable($tableName)) {
  4958. $record = $request->getParsedBody();
  4959. if ($record !== null) {
  4960. $handler = $this->getProperty('handler', '');
  4961. if ($handler !== '') {
  4962. $table = $this->reflection->getTable($tableName);
  4963. if (is_array($record)) {
  4964. foreach ($record as $r) {
  4965. $response = $this->callHandler($handler, $r, $operation, $table);
  4966. if ($response !== null) {
  4967. return $response;
  4968. }
  4969. }
  4970. } else {
  4971. $response = $this->callHandler($handler, $record, $operation, $table);
  4972. if ($response !== null) {
  4973. return $response;
  4974. }
  4975. }
  4976. }
  4977. }
  4978. }
  4979. }
  4980. return $next->handle($request);
  4981. }
  4982. }
  4983. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  4984. class XsrfMiddleware extends Middleware
  4985. {
  4986. private function getToken(): string
  4987. {
  4988. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  4989. if (isset($_COOKIE[$cookieName])) {
  4990. $token = $_COOKIE[$cookieName];
  4991. } else {
  4992. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  4993. $token = bin2hex(random_bytes(8));
  4994. if (!headers_sent()) {
  4995. setcookie($cookieName, $token, 0, '', '', $secure);
  4996. }
  4997. }
  4998. return $token;
  4999. }
  5000. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  5001. {
  5002. $token = $this->getToken();
  5003. $method = $request->getMethod();
  5004. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  5005. if (!in_array($method, $excludeMethods)) {
  5006. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  5007. if ($token != $request->getHeader($headerName)) {
  5008. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  5009. }
  5010. }
  5011. return $next->handle($request);
  5012. }
  5013. }
  5014. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  5015. class OpenApiBuilder
  5016. {
  5017. private $openapi;
  5018. private $reflection;
  5019. private $operations = [
  5020. 'list' => 'get',
  5021. 'create' => 'post',
  5022. 'read' => 'get',
  5023. 'update' => 'put',
  5024. 'delete' => 'delete',
  5025. 'increment' => 'patch',
  5026. ];
  5027. private $types = [
  5028. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  5029. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  5030. 'varchar' => ['type' => 'string'],
  5031. 'clob' => ['type' => 'string'],
  5032. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  5033. 'blob' => ['type' => 'string', 'format' => 'byte'],
  5034. 'decimal' => ['type' => 'string'],
  5035. 'float' => ['type' => 'number', 'format' => 'float'],
  5036. 'double' => ['type' => 'number', 'format' => 'double'],
  5037. 'date' => ['type' => 'string', 'format' => 'date'],
  5038. 'time' => ['type' => 'string', 'format' => 'date-time'],
  5039. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  5040. 'geometry' => ['type' => 'string'],
  5041. 'boolean' => ['type' => 'boolean'],
  5042. ];
  5043. public function __construct(ReflectionService $reflection, $base)
  5044. {
  5045. $this->reflection = $reflection;
  5046. $this->openapi = new OpenApiDefinition($base);
  5047. }
  5048. private function getServerUrl(): string
  5049. {
  5050. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  5051. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  5052. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  5053. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  5054. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  5055. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  5056. }
  5057. private function getAllTableReferences(): array
  5058. {
  5059. $tableReferences = array();
  5060. foreach ($this->reflection->getTableNames() as $tableName) {
  5061. $table = $this->reflection->getTable($tableName);
  5062. foreach ($table->getColumnNames() as $columnName) {
  5063. $column = $table->getColumn($columnName);
  5064. $referencedTableName = $column->getFk();
  5065. if ($referencedTableName) {
  5066. if (!isset($tableReferences[$referencedTableName])) {
  5067. $tableReferences[$referencedTableName] = array();
  5068. }
  5069. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  5070. }
  5071. }
  5072. }
  5073. return $tableReferences;
  5074. }
  5075. public function build(): OpenApiDefinition
  5076. {
  5077. $this->openapi->set("openapi", "3.0.0");
  5078. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  5079. $this->openapi->set("servers|0|url", $this->getServerUrl());
  5080. }
  5081. $tableNames = $this->reflection->getTableNames();
  5082. foreach ($tableNames as $tableName) {
  5083. $this->setPath($tableName);
  5084. }
  5085. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  5086. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  5087. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  5088. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  5089. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  5090. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  5091. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  5092. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  5093. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  5094. $tableReferences = $this->getAllTableReferences();
  5095. foreach ($tableNames as $tableName) {
  5096. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  5097. $this->setComponentSchema($tableName, $references);
  5098. $this->setComponentResponse($tableName);
  5099. $this->setComponentRequestBody($tableName);
  5100. }
  5101. $this->setComponentParameters();
  5102. foreach ($tableNames as $index => $tableName) {
  5103. $this->setTag($index, $tableName);
  5104. }
  5105. return $this->openapi;
  5106. }
  5107. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  5108. {
  5109. $tableHandler = VariableStore::get('authorization.tableHandler');
  5110. if (!$tableHandler) {
  5111. return true;
  5112. }
  5113. return (bool) call_user_func($tableHandler, $operation, $tableName);
  5114. }
  5115. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  5116. {
  5117. $columnHandler = VariableStore::get('authorization.columnHandler');
  5118. if (!$columnHandler) {
  5119. return true;
  5120. }
  5121. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  5122. }
  5123. private function setPath(string $tableName) /*: void*/
  5124. {
  5125. $table = $this->reflection->getTable($tableName);
  5126. $type = $table->getType();
  5127. $pk = $table->getPk();
  5128. $pkName = $pk ? $pk->getName() : '';
  5129. foreach ($this->operations as $operation => $method) {
  5130. if (!$pkName && $operation != 'list') {
  5131. continue;
  5132. }
  5133. if ($type != 'table' && $operation != 'list') {
  5134. continue;
  5135. }
  5136. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5137. continue;
  5138. }
  5139. $parameters = [];
  5140. if (in_array($operation, ['list', 'create'])) {
  5141. $path = sprintf('/records/%s', $tableName);
  5142. if ($operation == 'list') {
  5143. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  5144. }
  5145. } else {
  5146. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  5147. if ($operation == 'read') {
  5148. $parameters = ['pk', 'include', 'exclude', 'join'];
  5149. } else {
  5150. $parameters = ['pk'];
  5151. }
  5152. }
  5153. foreach ($parameters as $p => $parameter) {
  5154. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  5155. }
  5156. if (in_array($operation, ['create', 'update', 'increment'])) {
  5157. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  5158. }
  5159. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  5160. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  5161. switch ($operation) {
  5162. case 'list':
  5163. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  5164. break;
  5165. case 'create':
  5166. if ($pk->getType() == 'integer') {
  5167. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  5168. } else {
  5169. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  5170. }
  5171. break;
  5172. case 'read':
  5173. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  5174. break;
  5175. case 'update':
  5176. case 'delete':
  5177. case 'increment':
  5178. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  5179. break;
  5180. }
  5181. }
  5182. }
  5183. private function setComponentSchema(string $tableName, array $references) /*: void*/
  5184. {
  5185. $table = $this->reflection->getTable($tableName);
  5186. $type = $table->getType();
  5187. $pk = $table->getPk();
  5188. $pkName = $pk ? $pk->getName() : '';
  5189. foreach ($this->operations as $operation => $method) {
  5190. if (!$pkName && $operation != 'list') {
  5191. continue;
  5192. }
  5193. if ($type != 'table' && $operation != 'list') {
  5194. continue;
  5195. }
  5196. if ($operation == 'delete') {
  5197. continue;
  5198. }
  5199. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5200. continue;
  5201. }
  5202. if ($operation == 'list') {
  5203. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  5204. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  5205. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  5206. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  5207. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  5208. } else {
  5209. $prefix = "components|schemas|$operation-$tableName";
  5210. }
  5211. $this->openapi->set("$prefix|type", "object");
  5212. foreach ($table->getColumnNames() as $columnName) {
  5213. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  5214. continue;
  5215. }
  5216. $column = $table->getColumn($columnName);
  5217. $properties = $this->types[$column->getType()];
  5218. foreach ($properties as $key => $value) {
  5219. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  5220. }
  5221. if ($column->getPk()) {
  5222. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  5223. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  5224. }
  5225. $fk = $column->getFk();
  5226. if ($fk) {
  5227. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  5228. }
  5229. }
  5230. }
  5231. }
  5232. private function setComponentResponse(string $tableName) /*: void*/
  5233. {
  5234. $table = $this->reflection->getTable($tableName);
  5235. $type = $table->getType();
  5236. $pk = $table->getPk();
  5237. $pkName = $pk ? $pk->getName() : '';
  5238. foreach (['list', 'read'] as $operation) {
  5239. if (!$pkName && $operation != 'list') {
  5240. continue;
  5241. }
  5242. if ($type != 'table' && $operation != 'list') {
  5243. continue;
  5244. }
  5245. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5246. continue;
  5247. }
  5248. if ($operation == 'list') {
  5249. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  5250. } else {
  5251. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  5252. }
  5253. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  5254. }
  5255. }
  5256. private function setComponentRequestBody(string $tableName) /*: void*/
  5257. {
  5258. $table = $this->reflection->getTable($tableName);
  5259. $type = $table->getType();
  5260. $pk = $table->getPk();
  5261. $pkName = $pk ? $pk->getName() : '';
  5262. if ($pkName && $type == 'table') {
  5263. foreach (['create', 'update', 'increment'] as $operation) {
  5264. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5265. continue;
  5266. }
  5267. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  5268. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  5269. }
  5270. }
  5271. }
  5272. private function setComponentParameters() /*: void*/
  5273. {
  5274. $this->openapi->set("components|parameters|pk|name", "id");
  5275. $this->openapi->set("components|parameters|pk|in", "path");
  5276. $this->openapi->set("components|parameters|pk|schema|type", "string");
  5277. $this->openapi->set("components|parameters|pk|description", "primary key value");
  5278. $this->openapi->set("components|parameters|pk|required", true);
  5279. $this->openapi->set("components|parameters|filter|name", "filter");
  5280. $this->openapi->set("components|parameters|filter|in", "query");
  5281. $this->openapi->set("components|parameters|filter|schema|type", "array");
  5282. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  5283. $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");
  5284. $this->openapi->set("components|parameters|filter|required", false);
  5285. $this->openapi->set("components|parameters|include|name", "include");
  5286. $this->openapi->set("components|parameters|include|in", "query");
  5287. $this->openapi->set("components|parameters|include|schema|type", "string");
  5288. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  5289. $this->openapi->set("components|parameters|include|required", false);
  5290. $this->openapi->set("components|parameters|exclude|name", "exclude");
  5291. $this->openapi->set("components|parameters|exclude|in", "query");
  5292. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  5293. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  5294. $this->openapi->set("components|parameters|exclude|required", false);
  5295. $this->openapi->set("components|parameters|order|name", "order");
  5296. $this->openapi->set("components|parameters|order|in", "query");
  5297. $this->openapi->set("components|parameters|order|schema|type", "array");
  5298. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  5299. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  5300. $this->openapi->set("components|parameters|order|required", false);
  5301. $this->openapi->set("components|parameters|size|name", "size");
  5302. $this->openapi->set("components|parameters|size|in", "query");
  5303. $this->openapi->set("components|parameters|size|schema|type", "string");
  5304. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  5305. $this->openapi->set("components|parameters|size|required", false);
  5306. $this->openapi->set("components|parameters|page|name", "page");
  5307. $this->openapi->set("components|parameters|page|in", "query");
  5308. $this->openapi->set("components|parameters|page|schema|type", "string");
  5309. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  5310. $this->openapi->set("components|parameters|page|required", false);
  5311. $this->openapi->set("components|parameters|join|name", "join");
  5312. $this->openapi->set("components|parameters|join|in", "query");
  5313. $this->openapi->set("components|parameters|join|schema|type", "array");
  5314. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  5315. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  5316. $this->openapi->set("components|parameters|join|required", false);
  5317. }
  5318. private function setTag(int $index, string $tableName) /*: void*/
  5319. {
  5320. $this->openapi->set("tags|$index|name", "$tableName");
  5321. $this->openapi->set("tags|$index|description", "$tableName operations");
  5322. }
  5323. }
  5324. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  5325. class OpenApiDefinition implements \JsonSerializable
  5326. {
  5327. private $root;
  5328. public function __construct($base)
  5329. {
  5330. $this->root = $base;
  5331. }
  5332. public function set(string $path, $value) /*: void*/
  5333. {
  5334. $parts = explode('|', trim($path, '|'));
  5335. $current = &$this->root;
  5336. while (count($parts) > 0) {
  5337. $part = array_shift($parts);
  5338. if (!isset($current[$part])) {
  5339. $current[$part] = [];
  5340. }
  5341. $current = &$current[$part];
  5342. }
  5343. $current = $value;
  5344. }
  5345. public function has(string $path): bool
  5346. {
  5347. $parts = explode('|', trim($path, '|'));
  5348. $current = &$this->root;
  5349. while (count($parts) > 0) {
  5350. $part = array_shift($parts);
  5351. if (!isset($current[$part])) {
  5352. return false;
  5353. }
  5354. $current = &$current[$part];
  5355. }
  5356. return true;
  5357. }
  5358. public function jsonSerialize()
  5359. {
  5360. return $this->root;
  5361. }
  5362. }
  5363. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  5364. class OpenApiService
  5365. {
  5366. private $builder;
  5367. public function __construct(ReflectionService $reflection, array $base)
  5368. {
  5369. $this->builder = new OpenApiBuilder($reflection, $base);
  5370. }
  5371. public function get(): OpenApiDefinition
  5372. {
  5373. return $this->builder->build();
  5374. }
  5375. }
  5376. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  5377. class AndCondition extends Condition
  5378. {
  5379. private $conditions;
  5380. public function __construct(Condition $condition1, Condition $condition2)
  5381. {
  5382. $this->conditions = [$condition1, $condition2];
  5383. }
  5384. public function _and(Condition $condition): Condition
  5385. {
  5386. if ($condition instanceof NoCondition) {
  5387. return $this;
  5388. }
  5389. $this->conditions[] = $condition;
  5390. return $this;
  5391. }
  5392. public function getConditions(): array
  5393. {
  5394. return $this->conditions;
  5395. }
  5396. public static function fromArray(array $conditions): Condition
  5397. {
  5398. $condition = new NoCondition();
  5399. foreach ($conditions as $c) {
  5400. $condition = $condition->_and($c);
  5401. }
  5402. return $condition;
  5403. }
  5404. }
  5405. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  5406. class ColumnCondition extends Condition
  5407. {
  5408. private $column;
  5409. private $operator;
  5410. private $value;
  5411. public function __construct(ReflectedColumn $column, string $operator, string $value)
  5412. {
  5413. $this->column = $column;
  5414. $this->operator = $operator;
  5415. $this->value = $value;
  5416. }
  5417. public function getColumn(): ReflectedColumn
  5418. {
  5419. return $this->column;
  5420. }
  5421. public function getOperator(): string
  5422. {
  5423. return $this->operator;
  5424. }
  5425. public function getValue(): string
  5426. {
  5427. return $this->value;
  5428. }
  5429. }
  5430. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  5431. abstract class Condition
  5432. {
  5433. public function _and(Condition $condition): Condition
  5434. {
  5435. if ($condition instanceof NoCondition) {
  5436. return $this;
  5437. }
  5438. return new AndCondition($this, $condition);
  5439. }
  5440. public function _or(Condition $condition): Condition
  5441. {
  5442. if ($condition instanceof NoCondition) {
  5443. return $this;
  5444. }
  5445. return new OrCondition($this, $condition);
  5446. }
  5447. public function _not(): Condition
  5448. {
  5449. return new NotCondition($this);
  5450. }
  5451. public static function fromString(ReflectedTable $table, string $value): Condition
  5452. {
  5453. $condition = new NoCondition();
  5454. $parts = explode(',', $value, 3);
  5455. if (count($parts) < 2) {
  5456. return $condition;
  5457. }
  5458. if (count($parts) < 3) {
  5459. $parts[2] = '';
  5460. }
  5461. $field = $table->getColumn($parts[0]);
  5462. $command = $parts[1];
  5463. $negate = false;
  5464. $spatial = false;
  5465. if (strlen($command) > 2) {
  5466. if (substr($command, 0, 1) == 'n') {
  5467. $negate = true;
  5468. $command = substr($command, 1);
  5469. }
  5470. if (substr($command, 0, 1) == 's') {
  5471. $spatial = true;
  5472. $command = substr($command, 1);
  5473. }
  5474. }
  5475. if ($spatial) {
  5476. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  5477. $condition = new SpatialCondition($field, $command, $parts[2]);
  5478. }
  5479. } else {
  5480. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  5481. $condition = new ColumnCondition($field, $command, $parts[2]);
  5482. }
  5483. }
  5484. if ($negate) {
  5485. $condition = $condition->_not();
  5486. }
  5487. return $condition;
  5488. }
  5489. }
  5490. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  5491. class NoCondition extends Condition
  5492. {
  5493. public function _and(Condition $condition): Condition
  5494. {
  5495. return $condition;
  5496. }
  5497. public function _or(Condition $condition): Condition
  5498. {
  5499. return $condition;
  5500. }
  5501. public function _not(): Condition
  5502. {
  5503. return $this;
  5504. }
  5505. }
  5506. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  5507. class NotCondition extends Condition
  5508. {
  5509. private $condition;
  5510. public function __construct(Condition $condition)
  5511. {
  5512. $this->condition = $condition;
  5513. }
  5514. public function getCondition(): Condition
  5515. {
  5516. return $this->condition;
  5517. }
  5518. }
  5519. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  5520. class OrCondition extends Condition
  5521. {
  5522. private $conditions;
  5523. public function __construct(Condition $condition1, Condition $condition2)
  5524. {
  5525. $this->conditions = [$condition1, $condition2];
  5526. }
  5527. public function _or(Condition $condition): Condition
  5528. {
  5529. if ($condition instanceof NoCondition) {
  5530. return $this;
  5531. }
  5532. $this->conditions[] = $condition;
  5533. return $this;
  5534. }
  5535. public function getConditions(): array
  5536. {
  5537. return $this->conditions;
  5538. }
  5539. public static function fromArray(array $conditions): Condition
  5540. {
  5541. $condition = new NoCondition();
  5542. foreach ($conditions as $c) {
  5543. $condition = $condition->_or($c);
  5544. }
  5545. return $condition;
  5546. }
  5547. }
  5548. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  5549. class SpatialCondition extends ColumnCondition
  5550. {
  5551. }
  5552. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  5553. class ErrorDocument implements \JsonSerializable
  5554. {
  5555. public $code;
  5556. public $message;
  5557. public $details;
  5558. public function __construct(ErrorCode $errorCode, string $argument, $details)
  5559. {
  5560. $this->code = $errorCode->getCode();
  5561. $this->message = $errorCode->getMessage($argument);
  5562. $this->details = $details;
  5563. }
  5564. public function getCode(): int
  5565. {
  5566. return $this->code;
  5567. }
  5568. public function getMessage(): string
  5569. {
  5570. return $this->message;
  5571. }
  5572. public function serialize()
  5573. {
  5574. return [
  5575. 'code' => $this->code,
  5576. 'message' => $this->message,
  5577. 'details' => $this->details,
  5578. ];
  5579. }
  5580. public function jsonSerialize()
  5581. {
  5582. return array_filter($this->serialize());
  5583. }
  5584. }
  5585. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  5586. class ListDocument implements \JsonSerializable
  5587. {
  5588. private $records;
  5589. private $results;
  5590. public function __construct(array $records, int $results)
  5591. {
  5592. $this->records = $records;
  5593. $this->results = $results;
  5594. }
  5595. public function getRecords(): array
  5596. {
  5597. return $this->records;
  5598. }
  5599. public function getResults(): int
  5600. {
  5601. return $this->results;
  5602. }
  5603. public function serialize()
  5604. {
  5605. return [
  5606. 'records' => $this->records,
  5607. 'results' => $this->results,
  5608. ];
  5609. }
  5610. public function jsonSerialize()
  5611. {
  5612. return array_filter($this->serialize(), function ($v) {
  5613. return $v !== 0;
  5614. });
  5615. }
  5616. }
  5617. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  5618. class ColumnIncluder
  5619. {
  5620. private function isMandatory(string $tableName, string $columnName, array $params): bool
  5621. {
  5622. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  5623. }
  5624. private function select(string $tableName, bool $primaryTable, array $params, string $paramName,
  5625. array $columnNames, bool $include): array{
  5626. if (!isset($params[$paramName])) {
  5627. return $columnNames;
  5628. }
  5629. $columns = array();
  5630. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  5631. $columns[$columnName] = true;
  5632. }
  5633. $result = array();
  5634. foreach ($columnNames as $columnName) {
  5635. $match = isset($columns['*.*']);
  5636. if (!$match) {
  5637. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  5638. }
  5639. if ($primaryTable && !$match) {
  5640. $match = isset($columns['*']) || isset($columns[$columnName]);
  5641. }
  5642. if ($match) {
  5643. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  5644. $result[] = $columnName;
  5645. }
  5646. } else {
  5647. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  5648. $result[] = $columnName;
  5649. }
  5650. }
  5651. }
  5652. return $result;
  5653. }
  5654. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  5655. {
  5656. $tableName = $table->getName();
  5657. $results = $table->getColumnNames();
  5658. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  5659. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  5660. return $results;
  5661. }
  5662. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  5663. {
  5664. $results = array();
  5665. $columnNames = $this->getNames($table, $primaryTable, $params);
  5666. foreach ($columnNames as $columnName) {
  5667. if (property_exists($record, $columnName)) {
  5668. $results[$columnName] = $record->$columnName;
  5669. }
  5670. }
  5671. return $results;
  5672. }
  5673. }
  5674. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  5675. class ErrorCode
  5676. {
  5677. private $code;
  5678. private $message;
  5679. private $status;
  5680. const ERROR_NOT_FOUND = 9999;
  5681. const ROUTE_NOT_FOUND = 1000;
  5682. const TABLE_NOT_FOUND = 1001;
  5683. const ARGUMENT_COUNT_MISMATCH = 1002;
  5684. const RECORD_NOT_FOUND = 1003;
  5685. const ORIGIN_FORBIDDEN = 1004;
  5686. const COLUMN_NOT_FOUND = 1005;
  5687. const TABLE_ALREADY_EXISTS = 1006;
  5688. const COLUMN_ALREADY_EXISTS = 1007;
  5689. const HTTP_MESSAGE_NOT_READABLE = 1008;
  5690. const DUPLICATE_KEY_EXCEPTION = 1009;
  5691. const DATA_INTEGRITY_VIOLATION = 1010;
  5692. const AUTHENTICATION_REQUIRED = 1011;
  5693. const AUTHENTICATION_FAILED = 1012;
  5694. const INPUT_VALIDATION_FAILED = 1013;
  5695. const OPERATION_FORBIDDEN = 1014;
  5696. const OPERATION_NOT_SUPPORTED = 1015;
  5697. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  5698. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  5699. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  5700. const PAGINATION_FORBIDDEN = 1019;
  5701. private $values = [
  5702. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  5703. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  5704. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  5705. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  5706. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  5707. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  5708. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  5709. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  5710. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  5711. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  5712. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  5713. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  5714. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  5715. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  5716. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  5717. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  5718. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  5719. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  5720. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  5721. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  5722. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  5723. ];
  5724. public function __construct(int $code)
  5725. {
  5726. if (!isset($this->values[$code])) {
  5727. $code = 9999;
  5728. }
  5729. $this->code = $code;
  5730. $this->message = $this->values[$code][0];
  5731. $this->status = $this->values[$code][1];
  5732. }
  5733. public function getCode(): int
  5734. {
  5735. return $this->code;
  5736. }
  5737. public function getMessage(string $argument): string
  5738. {
  5739. return sprintf($this->message, $argument);
  5740. }
  5741. public function getStatus(): int
  5742. {
  5743. return $this->status;
  5744. }
  5745. }
  5746. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  5747. class FilterInfo
  5748. {
  5749. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  5750. {
  5751. $key = 'filter' . implode('', $path);
  5752. if (isset($params[$key])) {
  5753. foreach ($params[$key] as $filter) {
  5754. $condition = Condition::fromString($table, $filter);
  5755. if (($condition instanceof NoCondition) == false) {
  5756. $conditions->put($path, $condition);
  5757. }
  5758. }
  5759. }
  5760. }
  5761. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  5762. {
  5763. $conditions = new PathTree();
  5764. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  5765. for ($n = ord('0'); $n <= ord('9'); $n++) {
  5766. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  5767. for ($l = ord('a'); $l <= ord('f'); $l++) {
  5768. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  5769. }
  5770. }
  5771. return $conditions;
  5772. }
  5773. private function combinePathTreeOfConditions(PathTree $tree): Condition
  5774. {
  5775. $andConditions = $tree->getValues();
  5776. $and = AndCondition::fromArray($andConditions);
  5777. $orConditions = [];
  5778. foreach ($tree->getKeys() as $p) {
  5779. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  5780. }
  5781. $or = OrCondition::fromArray($orConditions);
  5782. return $and->_and($or);
  5783. }
  5784. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  5785. {
  5786. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  5787. }
  5788. }
  5789. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  5790. class HabtmValues
  5791. {
  5792. public $pkValues;
  5793. public $fkValues;
  5794. public function __construct(array $pkValues, array $fkValues)
  5795. {
  5796. $this->pkValues = $pkValues;
  5797. $this->fkValues = $fkValues;
  5798. }
  5799. }
  5800. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  5801. class OrderingInfo
  5802. {
  5803. public function getColumnOrdering(ReflectedTable $table, array $params): array
  5804. {
  5805. $fields = array();
  5806. if (isset($params['order'])) {
  5807. foreach ($params['order'] as $order) {
  5808. $parts = explode(',', $order, 3);
  5809. $columnName = $parts[0];
  5810. if (!$table->hasColumn($columnName)) {
  5811. continue;
  5812. }
  5813. $ascending = 'ASC';
  5814. if (count($parts) > 1) {
  5815. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  5816. $ascending = 'DESC';
  5817. }
  5818. }
  5819. $fields[] = [$columnName, $ascending];
  5820. }
  5821. }
  5822. if (count($fields) == 0) {
  5823. return $this->getDefaultColumnOrdering($table);
  5824. }
  5825. return $fields;
  5826. }
  5827. public function getDefaultColumnOrdering(ReflectedTable $table): array
  5828. {
  5829. $fields = array();
  5830. $pk = $table->getPk();
  5831. if ($pk) {
  5832. $fields[] = [$pk->getName(), 'ASC'];
  5833. } else {
  5834. foreach ($table->getColumnNames() as $columnName) {
  5835. $fields[] = [$columnName, 'ASC'];
  5836. }
  5837. }
  5838. return $fields;
  5839. }
  5840. }
  5841. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  5842. class PaginationInfo
  5843. {
  5844. public $DEFAULT_PAGE_SIZE = 20;
  5845. public function hasPage(array $params): bool
  5846. {
  5847. return isset($params['page']);
  5848. }
  5849. public function getPageOffset(array $params): int
  5850. {
  5851. $offset = 0;
  5852. $pageSize = $this->getPageSize($params);
  5853. if (isset($params['page'])) {
  5854. foreach ($params['page'] as $page) {
  5855. $parts = explode(',', $page, 2);
  5856. $page = intval($parts[0]) - 1;
  5857. $offset = $page * $pageSize;
  5858. }
  5859. }
  5860. return $offset;
  5861. }
  5862. private function getPageSize(array $params): int
  5863. {
  5864. $pageSize = $this->DEFAULT_PAGE_SIZE;
  5865. if (isset($params['page'])) {
  5866. foreach ($params['page'] as $page) {
  5867. $parts = explode(',', $page, 2);
  5868. if (count($parts) > 1) {
  5869. $pageSize = intval($parts[1]);
  5870. }
  5871. }
  5872. }
  5873. return $pageSize;
  5874. }
  5875. public function getResultSize(array $params): int
  5876. {
  5877. $numberOfRows = -1;
  5878. if (isset($params['size'])) {
  5879. foreach ($params['size'] as $size) {
  5880. $numberOfRows = intval($size);
  5881. }
  5882. }
  5883. return $numberOfRows;
  5884. }
  5885. public function getPageLimit(array $params): int
  5886. {
  5887. $pageLimit = -1;
  5888. if ($this->hasPage($params)) {
  5889. $pageLimit = $this->getPageSize($params);
  5890. }
  5891. $resultSize = $this->getResultSize($params);
  5892. if ($resultSize >= 0) {
  5893. if ($pageLimit >= 0) {
  5894. $pageLimit = min($pageLimit, $resultSize);
  5895. } else {
  5896. $pageLimit = $resultSize;
  5897. }
  5898. }
  5899. return $pageLimit;
  5900. }
  5901. }
  5902. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  5903. class PathTree implements \JsonSerializable
  5904. {
  5905. const WILDCARD = '*';
  5906. private $tree;
  5907. public function __construct( /* object */&$tree = null)
  5908. {
  5909. if (!$tree) {
  5910. $tree = $this->newTree();
  5911. }
  5912. $this->tree = &$tree;
  5913. }
  5914. public function newTree()
  5915. {
  5916. return (object) ['values' => [], 'branches' => (object) []];
  5917. }
  5918. public function getKeys(): array
  5919. {
  5920. $branches = (array) $this->tree->branches;
  5921. return array_keys($branches);
  5922. }
  5923. public function getValues(): array
  5924. {
  5925. return $this->tree->values;
  5926. }
  5927. public function get(string $key): PathTree
  5928. {
  5929. if (!isset($this->tree->branches->$key)) {
  5930. return null;
  5931. }
  5932. return new PathTree($this->tree->branches->$key);
  5933. }
  5934. public function put(array $path, $value)
  5935. {
  5936. $tree = &$this->tree;
  5937. foreach ($path as $key) {
  5938. if (!isset($tree->branches->$key)) {
  5939. $tree->branches->$key = $this->newTree();
  5940. }
  5941. $tree = &$tree->branches->$key;
  5942. }
  5943. $tree->values[] = $value;
  5944. }
  5945. public function match(array $path): array
  5946. {
  5947. $star = self::WILDCARD;
  5948. $tree = &$this->tree;
  5949. foreach ($path as $key) {
  5950. if (isset($tree->branches->$key)) {
  5951. $tree = &$tree->branches->$key;
  5952. } else if (isset($tree->branches->$star)) {
  5953. $tree = &$tree->branches->$star;
  5954. } else {
  5955. return [];
  5956. }
  5957. }
  5958. return $tree->values;
  5959. }
  5960. public static function fromJson( /* object */$tree): PathTree
  5961. {
  5962. return new PathTree($tree);
  5963. }
  5964. public function jsonSerialize()
  5965. {
  5966. return $this->tree;
  5967. }
  5968. }
  5969. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  5970. class RecordService
  5971. {
  5972. private $db;
  5973. private $reflection;
  5974. private $columns;
  5975. private $joiner;
  5976. private $filters;
  5977. private $ordering;
  5978. private $pagination;
  5979. public function __construct(GenericDB $db, ReflectionService $reflection)
  5980. {
  5981. $this->db = $db;
  5982. $this->reflection = $reflection;
  5983. $this->columns = new ColumnIncluder();
  5984. $this->joiner = new RelationJoiner($reflection, $this->columns);
  5985. $this->filters = new FilterInfo();
  5986. $this->ordering = new OrderingInfo();
  5987. $this->pagination = new PaginationInfo();
  5988. }
  5989. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  5990. {
  5991. $keyset = array_keys((array) $record);
  5992. foreach ($keyset as $key) {
  5993. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  5994. unset($record->$key);
  5995. }
  5996. }
  5997. if ($id != '') {
  5998. $pk = $this->reflection->getTable($tableName)->getPk();
  5999. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  6000. $field = $this->reflection->getTable($tableName)->getColumn($key);
  6001. if ($field->getName() == $pk->getName()) {
  6002. unset($record->$key);
  6003. }
  6004. }
  6005. }
  6006. }
  6007. public function hasTable(string $table): bool
  6008. {
  6009. return $this->reflection->hasTable($table);
  6010. }
  6011. public function getType(string $table): string
  6012. {
  6013. return $this->reflection->getType($table);
  6014. }
  6015. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  6016. {
  6017. $this->sanitizeRecord($tableName, $record, '');
  6018. $table = $this->reflection->getTable($tableName);
  6019. $columnValues = $this->columns->getValues($table, true, $record, $params);
  6020. return $this->db->createSingle($table, $columnValues);
  6021. }
  6022. public function read(string $tableName, string $id, array $params) /*: ?object*/
  6023. {
  6024. $table = $this->reflection->getTable($tableName);
  6025. $this->joiner->addMandatoryColumns($table, $params);
  6026. $columnNames = $this->columns->getNames($table, true, $params);
  6027. $record = $this->db->selectSingle($table, $columnNames, $id);
  6028. if ($record == null) {
  6029. return null;
  6030. }
  6031. $records = array($record);
  6032. $this->joiner->addJoins($table, $records, $params, $this->db);
  6033. return $records[0];
  6034. }
  6035. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  6036. {
  6037. $this->sanitizeRecord($tableName, $record, $id);
  6038. $table = $this->reflection->getTable($tableName);
  6039. $columnValues = $this->columns->getValues($table, true, $record, $params);
  6040. return $this->db->updateSingle($table, $columnValues, $id);
  6041. }
  6042. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  6043. {
  6044. $table = $this->reflection->getTable($tableName);
  6045. return $this->db->deleteSingle($table, $id);
  6046. }
  6047. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  6048. {
  6049. $this->sanitizeRecord($tableName, $record, $id);
  6050. $table = $this->reflection->getTable($tableName);
  6051. $columnValues = $this->columns->getValues($table, true, $record, $params);
  6052. return $this->db->incrementSingle($table, $columnValues, $id);
  6053. }
  6054. public function _list(string $tableName, array $params): ListDocument
  6055. {
  6056. $table = $this->reflection->getTable($tableName);
  6057. $this->joiner->addMandatoryColumns($table, $params);
  6058. $columnNames = $this->columns->getNames($table, true, $params);
  6059. $condition = $this->filters->getCombinedConditions($table, $params);
  6060. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  6061. if (!$this->pagination->hasPage($params)) {
  6062. $offset = 0;
  6063. $limit = $this->pagination->getPageLimit($params);
  6064. $count = 0;
  6065. } else {
  6066. $offset = $this->pagination->getPageOffset($params);
  6067. $limit = $this->pagination->getPageLimit($params);
  6068. $count = $this->db->selectCount($table, $condition);
  6069. }
  6070. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  6071. $this->joiner->addJoins($table, $records, $params, $this->db);
  6072. return new ListDocument($records, $count);
  6073. }
  6074. }
  6075. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  6076. class RelationJoiner
  6077. {
  6078. private $reflection;
  6079. private $ordering;
  6080. private $columns;
  6081. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  6082. {
  6083. $this->reflection = $reflection;
  6084. $this->ordering = new OrderingInfo();
  6085. $this->columns = $columns;
  6086. }
  6087. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  6088. {
  6089. if (!isset($params['join']) || !isset($params['include'])) {
  6090. return;
  6091. }
  6092. $params['mandatory'] = array();
  6093. foreach ($params['join'] as $tableNames) {
  6094. $t1 = $table;
  6095. foreach (explode(',', $tableNames) as $tableName) {
  6096. if (!$this->reflection->hasTable($tableName)) {
  6097. continue;
  6098. }
  6099. $t2 = $this->reflection->getTable($tableName);
  6100. $fks1 = $t1->getFksTo($t2->getName());
  6101. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  6102. if ($t3 != null || count($fks1) > 0) {
  6103. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  6104. }
  6105. foreach ($fks1 as $fk) {
  6106. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  6107. }
  6108. $fks2 = $t2->getFksTo($t1->getName());
  6109. if ($t3 != null || count($fks2) > 0) {
  6110. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  6111. }
  6112. foreach ($fks2 as $fk) {
  6113. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  6114. }
  6115. $t1 = $t2;
  6116. }
  6117. }
  6118. }
  6119. private function getJoinsAsPathTree(array $params): PathTree
  6120. {
  6121. $joins = new PathTree();
  6122. if (isset($params['join'])) {
  6123. foreach ($params['join'] as $tableNames) {
  6124. $path = array();
  6125. foreach (explode(',', $tableNames) as $tableName) {
  6126. $t = $this->reflection->getTable($tableName);
  6127. if ($t != null) {
  6128. $path[] = $t->getName();
  6129. }
  6130. }
  6131. $joins->put($path, true);
  6132. }
  6133. }
  6134. return $joins;
  6135. }
  6136. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  6137. {
  6138. $joins = $this->getJoinsAsPathTree($params);
  6139. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  6140. }
  6141. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  6142. {
  6143. foreach ($this->reflection->getTableNames() as $tableName) {
  6144. $t3 = $this->reflection->getTable($tableName);
  6145. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  6146. return $t3;
  6147. }
  6148. }
  6149. return null;
  6150. }
  6151. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  6152. {
  6153. foreach ($joins->getKeys() as $t2Name) {
  6154. $t2 = $this->reflection->getTable($t2Name);
  6155. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  6156. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  6157. if (!$belongsTo && !$hasMany) {
  6158. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  6159. } else {
  6160. $t3 = null;
  6161. }
  6162. $hasAndBelongsToMany = ($t3 != null);
  6163. $newRecords = array();
  6164. $fkValues = null;
  6165. $pkValues = null;
  6166. $habtmValues = null;
  6167. if ($belongsTo) {
  6168. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  6169. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  6170. }
  6171. if ($hasMany) {
  6172. $pkValues = $this->getPkEmptyValues($t1, $records);
  6173. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  6174. }
  6175. if ($hasAndBelongsToMany) {
  6176. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  6177. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  6178. }
  6179. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  6180. if ($fkValues != null) {
  6181. $this->fillFkValues($t2, $newRecords, $fkValues);
  6182. $this->setFkValues($t1, $t2, $records, $fkValues);
  6183. }
  6184. if ($pkValues != null) {
  6185. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  6186. $this->setPkValues($t1, $t2, $records, $pkValues);
  6187. }
  6188. if ($habtmValues != null) {
  6189. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  6190. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  6191. }
  6192. }
  6193. }
  6194. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  6195. {
  6196. $fkValues = array();
  6197. $fks = $t1->getFksTo($t2->getName());
  6198. foreach ($fks as $fk) {
  6199. $fkName = $fk->getName();
  6200. foreach ($records as $record) {
  6201. if (isset($record[$fkName])) {
  6202. $fkValue = $record[$fkName];
  6203. $fkValues[$fkValue] = null;
  6204. }
  6205. }
  6206. }
  6207. return $fkValues;
  6208. }
  6209. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  6210. {
  6211. $columnNames = $this->columns->getNames($t2, false, $params);
  6212. $fkIds = array_keys($fkValues);
  6213. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  6214. $records[] = $record;
  6215. }
  6216. }
  6217. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  6218. {
  6219. $pkName = $t2->getPk()->getName();
  6220. foreach ($fkRecords as $fkRecord) {
  6221. $pkValue = $fkRecord[$pkName];
  6222. $fkValues[$pkValue] = $fkRecord;
  6223. }
  6224. }
  6225. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  6226. {
  6227. $fks = $t1->getFksTo($t2->getName());
  6228. foreach ($fks as $fk) {
  6229. $fkName = $fk->getName();
  6230. foreach ($records as $i => $record) {
  6231. if (isset($record[$fkName])) {
  6232. $key = $record[$fkName];
  6233. $records[$i][$fkName] = $fkValues[$key];
  6234. }
  6235. }
  6236. }
  6237. }
  6238. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  6239. {
  6240. $pkValues = array();
  6241. $pkName = $t1->getPk()->getName();
  6242. foreach ($records as $record) {
  6243. $key = $record[$pkName];
  6244. $pkValues[$key] = array();
  6245. }
  6246. return $pkValues;
  6247. }
  6248. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  6249. {
  6250. $fks = $t2->getFksTo($t1->getName());
  6251. $columnNames = $this->columns->getNames($t2, false, $params);
  6252. $pkValueKeys = implode(',', array_keys($pkValues));
  6253. $conditions = array();
  6254. foreach ($fks as $fk) {
  6255. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  6256. }
  6257. $condition = OrCondition::fromArray($conditions);
  6258. $columnOrdering = array();
  6259. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  6260. if ($limit != -1) {
  6261. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  6262. }
  6263. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  6264. $records[] = $record;
  6265. }
  6266. }
  6267. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  6268. {
  6269. $fks = $t2->getFksTo($t1->getName());
  6270. foreach ($fks as $fk) {
  6271. $fkName = $fk->getName();
  6272. foreach ($pkRecords as $pkRecord) {
  6273. $key = $pkRecord[$fkName];
  6274. if (isset($pkValues[$key])) {
  6275. $pkValues[$key][] = $pkRecord;
  6276. }
  6277. }
  6278. }
  6279. }
  6280. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  6281. {
  6282. $pkName = $t1->getPk()->getName();
  6283. $t2Name = $t2->getName();
  6284. foreach ($records as $i => $record) {
  6285. $key = $record[$pkName];
  6286. $records[$i][$t2Name] = $pkValues[$key];
  6287. }
  6288. }
  6289. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  6290. {
  6291. $pkValues = $this->getPkEmptyValues($t1, $records);
  6292. $fkValues = array();
  6293. $fk1 = $t3->getFksTo($t1->getName())[0];
  6294. $fk2 = $t3->getFksTo($t2->getName())[0];
  6295. $fk1Name = $fk1->getName();
  6296. $fk2Name = $fk2->getName();
  6297. $columnNames = array($fk1Name, $fk2Name);
  6298. $pkIds = implode(',', array_keys($pkValues));
  6299. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  6300. $columnOrdering = array();
  6301. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  6302. if ($limit != -1) {
  6303. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  6304. }
  6305. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  6306. foreach ($records as $record) {
  6307. $val1 = $record[$fk1Name];
  6308. $val2 = $record[$fk2Name];
  6309. $pkValues[$val1][] = $val2;
  6310. $fkValues[$val2] = null;
  6311. }
  6312. return new HabtmValues($pkValues, $fkValues);
  6313. }
  6314. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  6315. {
  6316. $pkName = $t1->getPk()->getName();
  6317. $t2Name = $t2->getName();
  6318. foreach ($records as $i => $record) {
  6319. $key = $record[$pkName];
  6320. $val = array();
  6321. $fks = $habtmValues->pkValues[$key];
  6322. foreach ($fks as $fk) {
  6323. $val[] = $habtmValues->fkValues[$fk];
  6324. }
  6325. $records[$i][$t2Name] = $val;
  6326. }
  6327. }
  6328. }
  6329. // file: src/Tqdev/PhpCrudApi/Api.php
  6330. class Api implements RequestHandlerInterface
  6331. {
  6332. private $router;
  6333. private $responder;
  6334. private $debug;
  6335. public function __construct(Config $config)
  6336. {
  6337. $db = new GenericDB(
  6338. $config->getDriver(),
  6339. $config->getAddress(),
  6340. $config->getPort(),
  6341. $config->getDatabase(),
  6342. $config->getUsername(),
  6343. $config->getPassword()
  6344. );
  6345. $cache = CacheFactory::create($config);
  6346. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  6347. $responder = new Responder();
  6348. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  6349. foreach ($config->getMiddlewares() as $middleware => $properties) {
  6350. switch ($middleware) {
  6351. case 'cors':
  6352. new CorsMiddleware($router, $responder, $properties);
  6353. break;
  6354. case 'firewall':
  6355. new FirewallMiddleware($router, $responder, $properties);
  6356. break;
  6357. case 'basicAuth':
  6358. new BasicAuthMiddleware($router, $responder, $properties);
  6359. break;
  6360. case 'jwtAuth':
  6361. new JwtAuthMiddleware($router, $responder, $properties);
  6362. break;
  6363. case 'dbAuth':
  6364. new DbAuthMiddleware($router, $responder, $properties, $reflection, $db);
  6365. break;
  6366. case 'validation':
  6367. new ValidationMiddleware($router, $responder, $properties, $reflection);
  6368. break;
  6369. case 'ipAddress':
  6370. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  6371. break;
  6372. case 'sanitation':
  6373. new SanitationMiddleware($router, $responder, $properties, $reflection);
  6374. break;
  6375. case 'multiTenancy':
  6376. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  6377. break;
  6378. case 'authorization':
  6379. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  6380. break;
  6381. case 'xsrf':
  6382. new XsrfMiddleware($router, $responder, $properties);
  6383. break;
  6384. case 'pageLimits':
  6385. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  6386. break;
  6387. case 'joinLimits':
  6388. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  6389. break;
  6390. case 'customization':
  6391. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  6392. break;
  6393. }
  6394. }
  6395. foreach ($config->getControllers() as $controller) {
  6396. switch ($controller) {
  6397. case 'records':
  6398. $records = new RecordService($db, $reflection);
  6399. new RecordController($router, $responder, $records);
  6400. break;
  6401. case 'columns':
  6402. $definition = new DefinitionService($db, $reflection);
  6403. new ColumnController($router, $responder, $reflection, $definition);
  6404. break;
  6405. case 'cache':
  6406. new CacheController($router, $responder, $cache);
  6407. break;
  6408. case 'openapi':
  6409. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  6410. new OpenApiController($router, $responder, $openApi);
  6411. break;
  6412. case 'geojson':
  6413. $records = new RecordService($db, $reflection);
  6414. $geoJson = new GeoJsonService($reflection, $records);
  6415. new GeoJsonController($router, $responder, $geoJson);
  6416. break;
  6417. }
  6418. }
  6419. $this->router = $router;
  6420. $this->responder = $responder;
  6421. $this->debug = $config->getDebug();
  6422. }
  6423. public function handle(ServerRequestInterface $request): ResponseInterface
  6424. {
  6425. $response = null;
  6426. try {
  6427. $response = $this->router->route($request);
  6428. } catch (\Throwable $e) {
  6429. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  6430. if ($this->debug) {
  6431. $response = ResponseUtils::addExceptionHeaders($response, $e);
  6432. }
  6433. }
  6434. return $response;
  6435. }
  6436. }
  6437. // file: src/Tqdev/PhpCrudApi/Config.php
  6438. class Config
  6439. {
  6440. private $values = [
  6441. 'driver' => null,
  6442. 'address' => 'localhost',
  6443. 'port' => null,
  6444. 'username' => null,
  6445. 'password' => null,
  6446. 'database' => null,
  6447. 'middlewares' => 'cors',
  6448. 'controllers' => 'records,geojson,openapi',
  6449. 'cacheType' => 'TempFile',
  6450. 'cachePath' => '',
  6451. 'cacheTime' => 10,
  6452. 'debug' => false,
  6453. 'basePath' => '',
  6454. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  6455. ];
  6456. private function getDefaultDriver(array $values): string
  6457. {
  6458. if (isset($values['driver'])) {
  6459. return $values['driver'];
  6460. }
  6461. return 'mysql';
  6462. }
  6463. private function getDefaultPort(string $driver): int
  6464. {
  6465. switch ($driver) {
  6466. case 'mysql':return 3306;
  6467. case 'pgsql':return 5432;
  6468. case 'sqlsrv':return 1433;
  6469. }
  6470. }
  6471. private function getDefaultAddress(string $driver): string
  6472. {
  6473. switch ($driver) {
  6474. case 'mysql':return 'localhost';
  6475. case 'pgsql':return 'localhost';
  6476. case 'sqlsrv':return 'localhost';
  6477. }
  6478. }
  6479. private function getDriverDefaults(string $driver): array
  6480. {
  6481. return [
  6482. 'driver' => $driver,
  6483. 'address' => $this->getDefaultAddress($driver),
  6484. 'port' => $this->getDefaultPort($driver),
  6485. ];
  6486. }
  6487. public function __construct(array $values)
  6488. {
  6489. $driver = $this->getDefaultDriver($values);
  6490. $defaults = $this->getDriverDefaults($driver);
  6491. $newValues = array_merge($this->values, $defaults, $values);
  6492. $newValues = $this->parseMiddlewares($newValues);
  6493. $diff = array_diff_key($newValues, $this->values);
  6494. if (!empty($diff)) {
  6495. $key = array_keys($diff)[0];
  6496. throw new \Exception("Config has invalid value '$key'");
  6497. }
  6498. $this->values = $newValues;
  6499. }
  6500. private function parseMiddlewares(array $values): array
  6501. {
  6502. $newValues = array();
  6503. $properties = array();
  6504. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  6505. foreach ($middlewares as $middleware) {
  6506. $properties[$middleware] = [];
  6507. }
  6508. foreach ($values as $key => $value) {
  6509. if (strpos($key, '.') === false) {
  6510. $newValues[$key] = $value;
  6511. } else {
  6512. list($middleware, $key2) = explode('.', $key, 2);
  6513. if (isset($properties[$middleware])) {
  6514. $properties[$middleware][$key2] = $value;
  6515. } else {
  6516. throw new \Exception("Config has invalid value '$key'");
  6517. }
  6518. }
  6519. }
  6520. $newValues['middlewares'] = array_reverse($properties, true);
  6521. return $newValues;
  6522. }
  6523. public function getDriver(): string
  6524. {
  6525. return $this->values['driver'];
  6526. }
  6527. public function getAddress(): string
  6528. {
  6529. return $this->values['address'];
  6530. }
  6531. public function getPort(): int
  6532. {
  6533. return $this->values['port'];
  6534. }
  6535. public function getUsername(): string
  6536. {
  6537. return $this->values['username'];
  6538. }
  6539. public function getPassword(): string
  6540. {
  6541. return $this->values['password'];
  6542. }
  6543. public function getDatabase(): string
  6544. {
  6545. return $this->values['database'];
  6546. }
  6547. public function getMiddlewares(): array
  6548. {
  6549. return $this->values['middlewares'];
  6550. }
  6551. public function getControllers(): array
  6552. {
  6553. return array_map('trim', explode(',', $this->values['controllers']));
  6554. }
  6555. public function getCacheType(): string
  6556. {
  6557. return $this->values['cacheType'];
  6558. }
  6559. public function getCachePath(): string
  6560. {
  6561. return $this->values['cachePath'];
  6562. }
  6563. public function getCacheTime(): int
  6564. {
  6565. return $this->values['cacheTime'];
  6566. }
  6567. public function getDebug(): bool
  6568. {
  6569. return $this->values['debug'];
  6570. }
  6571. public function getBasePath(): string
  6572. {
  6573. return $this->values['basePath'];
  6574. }
  6575. public function getOpenApiBase(): array
  6576. {
  6577. return json_decode($this->values['openApiBase'], true);
  6578. }
  6579. }
  6580. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  6581. class RequestFactory
  6582. {
  6583. private static function parseBody(string $body) /*: ?object*/
  6584. {
  6585. $first = substr($body, 0, 1);
  6586. if ($first == '[' || $first == '{') {
  6587. $object = json_decode($body);
  6588. $causeCode = json_last_error();
  6589. if ($causeCode !== JSON_ERROR_NONE) {
  6590. $object = null;
  6591. }
  6592. } else {
  6593. parse_str($body, $input);
  6594. foreach ($input as $key => $value) {
  6595. if (substr($key, -9) == '__is_null') {
  6596. $input[substr($key, 0, -9)] = null;
  6597. unset($input[$key]);
  6598. }
  6599. }
  6600. $object = (object) $input;
  6601. }
  6602. return $object;
  6603. }
  6604. public static function fromGlobals(): ServerRequestInterface
  6605. {
  6606. $psr17Factory = new Psr17Factory();
  6607. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  6608. $serverRequest = $creator->fromGlobals();
  6609. $body = file_get_contents('php://input');
  6610. if ($body) {
  6611. $serverRequest = $serverRequest->withParsedBody(self::parseBody($body));
  6612. }
  6613. return $serverRequest;
  6614. }
  6615. public static function fromString(string $request): ServerRequestInterface
  6616. {
  6617. $parts = explode("\n\n", trim($request), 2);
  6618. $lines = explode("\n", $parts[0]);
  6619. $first = explode(' ', trim(array_shift($lines)), 2);
  6620. $method = $first[0];
  6621. $body = isset($parts[1]) ? $parts[1] : '';
  6622. $url = isset($first[1]) ? $first[1] : '';
  6623. $psr17Factory = new Psr17Factory();
  6624. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  6625. foreach ($lines as $line) {
  6626. list($key, $value) = explode(':', $line, 2);
  6627. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  6628. }
  6629. if ($body) {
  6630. $stream = $psr17Factory->createStream($body);
  6631. $stream->rewind();
  6632. $serverRequest = $serverRequest->withBody($stream);
  6633. $serverRequest = $serverRequest->withParsedBody(self::parseBody($body));
  6634. }
  6635. return $serverRequest;
  6636. }
  6637. }
  6638. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  6639. class RequestUtils
  6640. {
  6641. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  6642. {
  6643. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  6644. return $request->withUri($request->getUri()->withQuery($query));
  6645. }
  6646. public static function getHeader(ServerRequestInterface $request, string $header): string
  6647. {
  6648. $headers = $request->getHeader($header);
  6649. return isset($headers[0]) ? $headers[0] : '';
  6650. }
  6651. public static function getParams(ServerRequestInterface $request): array
  6652. {
  6653. $params = array();
  6654. $query = $request->getUri()->getQuery();
  6655. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  6656. parse_str($query, $params);
  6657. return $params;
  6658. }
  6659. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  6660. {
  6661. $path = $request->getUri()->getPath();
  6662. $pathSegments = explode('/', rtrim($path, '/'));
  6663. if ($part < 0 || $part >= count($pathSegments)) {
  6664. return '';
  6665. }
  6666. return urldecode($pathSegments[$part]);
  6667. }
  6668. public static function getOperation(ServerRequestInterface $request): string
  6669. {
  6670. $method = $request->getMethod();
  6671. $path = RequestUtils::getPathSegment($request, 1);
  6672. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  6673. switch ($path) {
  6674. case 'openapi':
  6675. return 'document';
  6676. case 'columns':
  6677. return $method == 'get' ? 'reflect' : 'remodel';
  6678. case 'records':
  6679. switch ($method) {
  6680. case 'POST':
  6681. return 'create';
  6682. case 'GET':
  6683. return $hasPk ? 'read' : 'list';
  6684. case 'PUT':
  6685. return 'update';
  6686. case 'DELETE':
  6687. return 'delete';
  6688. case 'PATCH':
  6689. return 'increment';
  6690. }
  6691. }
  6692. return 'unknown';
  6693. }
  6694. private static function getJoinTables(string $tableName, array $parameters): array
  6695. {
  6696. $uniqueTableNames = array();
  6697. $uniqueTableNames[$tableName] = true;
  6698. if (isset($parameters['join'])) {
  6699. foreach ($parameters['join'] as $parameter) {
  6700. $tableNames = explode(',', trim($parameter));
  6701. foreach ($tableNames as $tableName) {
  6702. $uniqueTableNames[$tableName] = true;
  6703. }
  6704. }
  6705. }
  6706. return array_keys($uniqueTableNames);
  6707. }
  6708. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  6709. {
  6710. $path = RequestUtils::getPathSegment($request, 1);
  6711. $tableName = RequestUtils::getPathSegment($request, 2);
  6712. $allTableNames = $reflection->getTableNames();
  6713. switch ($path) {
  6714. case 'openapi':
  6715. return $allTableNames;
  6716. case 'columns':
  6717. return $tableName ? [$tableName] : $allTableNames;
  6718. case 'records':
  6719. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  6720. }
  6721. return $allTableNames;
  6722. }
  6723. }
  6724. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  6725. class ResponseFactory
  6726. {
  6727. const OK = 200;
  6728. const UNAUTHORIZED = 401;
  6729. const FORBIDDEN = 403;
  6730. const NOT_FOUND = 404;
  6731. const METHOD_NOT_ALLOWED = 405;
  6732. const CONFLICT = 409;
  6733. const UNPROCESSABLE_ENTITY = 422;
  6734. const INTERNAL_SERVER_ERROR = 500;
  6735. public static function fromObject(int $status, $body): ResponseInterface
  6736. {
  6737. $psr17Factory = new Psr17Factory();
  6738. $response = $psr17Factory->createResponse($status);
  6739. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  6740. $stream = $psr17Factory->createStream($content);
  6741. $stream->rewind();
  6742. $response = $response->withBody($stream);
  6743. $response = $response->withHeader('Content-Type', 'application/json');
  6744. $response = $response->withHeader('Content-Length', strlen($content));
  6745. return $response;
  6746. }
  6747. public static function fromStatus(int $status): ResponseInterface
  6748. {
  6749. $psr17Factory = new Psr17Factory();
  6750. return $psr17Factory->createResponse($status);
  6751. }
  6752. }
  6753. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  6754. class ResponseUtils
  6755. {
  6756. public static function output(ResponseInterface $response)
  6757. {
  6758. $status = $response->getStatusCode();
  6759. $headers = $response->getHeaders();
  6760. $body = $response->getBody()->getContents();
  6761. http_response_code($status);
  6762. foreach ($headers as $key => $values) {
  6763. foreach ($values as $value) {
  6764. header("$key: $value");
  6765. }
  6766. }
  6767. echo $body;
  6768. }
  6769. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  6770. {
  6771. $response = $response->withHeader('X-Exception-Name', get_class($e));
  6772. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  6773. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  6774. return $response;
  6775. }
  6776. public static function toString(ResponseInterface $response): string
  6777. {
  6778. $status = $response->getStatusCode();
  6779. $headers = $response->getHeaders();
  6780. $body = $response->getBody()->getContents();
  6781. $str = "$status\n";
  6782. foreach ($headers as $key => $values) {
  6783. foreach ($values as $value) {
  6784. $str .= "$key: $value\n";
  6785. }
  6786. }
  6787. if ($body !== '') {
  6788. $str .= "\n";
  6789. $str .= "$body\n";
  6790. }
  6791. return $str;
  6792. }
  6793. }
  6794. // file: src/index.php
  6795. $config = new Config([
  6796. 'username' => 'php-crud-api',
  6797. 'password' => 'php-crud-api',
  6798. 'database' => 'php-crud-api',
  6799. 'debug' => false,
  6800. ]);
  6801. $request = RequestFactory::fromGlobals();
  6802. $api = new Api($config);
  6803. $response = $api->handle($request);
  6804. ResponseUtils::output($response);