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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898
  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. namespace Tqdev\PhpCrudApi;
  8. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  9. interface Cache
  10. {
  11. public function set(String $key, String $value, int $ttl = 0): bool;
  12. public function get(String $key): String;
  13. public function clear(): bool;
  14. }
  15. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  16. class CacheFactory
  17. {
  18. const PREFIX = 'phpcrudapi-%s-%s-%s-';
  19. private static function getPrefix(Config $config): String
  20. {
  21. $driver = $config->getDriver();
  22. $database = $config->getDatabase();
  23. $filehash = substr(md5(__FILE__), 0, 8);
  24. return sprintf(self::PREFIX, $driver, $database, $filehash);
  25. }
  26. public static function create(Config $config): Cache
  27. {
  28. switch ($config->getCacheType()) {
  29. case 'TempFile':
  30. $cache = new TempFileCache(self::getPrefix($config), $config->getCachePath());
  31. break;
  32. case 'Redis':
  33. $cache = new RedisCache(self::getPrefix($config), $config->getCachePath());
  34. break;
  35. case 'Memcache':
  36. $cache = new MemcacheCache(self::getPrefix($config), $config->getCachePath());
  37. break;
  38. case 'Memcached':
  39. $cache = new MemcachedCache(self::getPrefix($config), $config->getCachePath());
  40. break;
  41. default:
  42. $cache = new NoCache();
  43. }
  44. return $cache;
  45. }
  46. }
  47. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  48. class MemcacheCache implements Cache
  49. {
  50. protected $prefix;
  51. protected $memcache;
  52. public function __construct(String $prefix, String $config)
  53. {
  54. $this->prefix = $prefix;
  55. if ($config == '') {
  56. $address = 'localhost';
  57. $port = 11211;
  58. } elseif (strpos($config, ':') === false) {
  59. $address = $config;
  60. $port = 11211;
  61. } else {
  62. list($address, $port) = explode(':', $config);
  63. }
  64. $this->memcache = $this->create();
  65. $this->memcache->addServer($address, $port);
  66. }
  67. protected function create() /*: \Memcache*/
  68. {
  69. return new \Memcache();
  70. }
  71. public function set(String $key, String $value, int $ttl = 0): bool
  72. {
  73. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  74. }
  75. public function get(String $key): String
  76. {
  77. return $this->memcache->get($this->prefix . $key) ?: '';
  78. }
  79. public function clear(): bool
  80. {
  81. return $this->memcache->flush();
  82. }
  83. }
  84. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  85. class MemcachedCache extends MemcacheCache
  86. {
  87. protected function create() /*: \Memcached*/
  88. {
  89. return new \Memcached();
  90. }
  91. public function set(String $key, String $value, int $ttl = 0): bool
  92. {
  93. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  94. }
  95. }
  96. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  97. class NoCache implements Cache
  98. {
  99. public function __construct()
  100. {
  101. }
  102. public function set(String $key, String $value, int $ttl = 0): bool
  103. {
  104. return true;
  105. }
  106. public function get(String $key): String
  107. {
  108. return '';
  109. }
  110. public function clear(): bool
  111. {
  112. return true;
  113. }
  114. }
  115. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  116. class RedisCache implements Cache
  117. {
  118. protected $prefix;
  119. protected $redis;
  120. public function __construct(String $prefix, String $config)
  121. {
  122. $this->prefix = $prefix;
  123. if ($config == '') {
  124. $config = '127.0.0.1';
  125. }
  126. $params = explode(':', $config, 6);
  127. if (isset($params[3])) {
  128. $params[3] = null;
  129. }
  130. $this->redis = new \Redis();
  131. call_user_func_array(array($this->redis, 'pconnect'), $params);
  132. }
  133. public function set(String $key, String $value, int $ttl = 0): bool
  134. {
  135. return $this->redis->set($this->prefix . $key, $value, $ttl);
  136. }
  137. public function get(String $key): String
  138. {
  139. return $this->redis->get($this->prefix . $key) ?: '';
  140. }
  141. public function clear(): bool
  142. {
  143. return $this->redis->flushDb();
  144. }
  145. }
  146. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  147. class TempFileCache implements Cache
  148. {
  149. const SUFFIX = 'cache';
  150. private $path;
  151. private $segments;
  152. public function __construct(String $prefix, String $config)
  153. {
  154. $this->segments = [];
  155. $s = DIRECTORY_SEPARATOR;
  156. $ps = PATH_SEPARATOR;
  157. if ($config == '') {
  158. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  159. } elseif (strpos($config, $ps) === false) {
  160. $this->path = $config;
  161. } else {
  162. list($path, $segments) = explode($ps, $config);
  163. $this->path = $path;
  164. $this->segments = explode(',', $segments);
  165. }
  166. if (file_exists($this->path) && is_dir($this->path)) {
  167. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  168. }
  169. }
  170. private function getFileName(String $key): String
  171. {
  172. $s = DIRECTORY_SEPARATOR;
  173. $md5 = md5($key);
  174. $filename = rtrim($this->path, $s) . $s;
  175. $i = 0;
  176. foreach ($this->segments as $segment) {
  177. $filename .= substr($md5, $i, $segment) . $s;
  178. $i += $segment;
  179. }
  180. $filename .= substr($md5, $i);
  181. return $filename;
  182. }
  183. public function set(String $key, String $value, int $ttl = 0): bool
  184. {
  185. $filename = $this->getFileName($key);
  186. $dirname = dirname($filename);
  187. if (!file_exists($dirname)) {
  188. if (!mkdir($dirname, 0755, true)) {
  189. return false;
  190. }
  191. }
  192. $string = $ttl . '|' . $value;
  193. return $this->filePutContents($filename, $string) !== false;
  194. }
  195. private function filePutContents($filename, $string)
  196. {
  197. return file_put_contents($filename, $string, LOCK_EX);
  198. }
  199. private function fileGetContents($filename)
  200. {
  201. $file = fopen($filename, 'rb');
  202. if ($file === false) {
  203. return false;
  204. }
  205. $lock = flock($file, LOCK_SH);
  206. if (!$lock) {
  207. fclose($file);
  208. return false;
  209. }
  210. $string = '';
  211. while (!feof($file)) {
  212. $string .= fread($file, 8192);
  213. }
  214. flock($file, LOCK_UN);
  215. fclose($file);
  216. return $string;
  217. }
  218. private function getString($filename): String
  219. {
  220. $data = $this->fileGetContents($filename);
  221. if ($data === false) {
  222. return '';
  223. }
  224. list($ttl, $string) = explode('|', $data, 2);
  225. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  226. return '';
  227. }
  228. return $string;
  229. }
  230. public function get(String $key): String
  231. {
  232. $filename = $this->getFileName($key);
  233. if (!file_exists($filename)) {
  234. return '';
  235. }
  236. $string = $this->getString($filename);
  237. if ($string == null) {
  238. return '';
  239. }
  240. return $string;
  241. }
  242. private function clean(String $path, array $segments, int $len, bool $all) /*: void*/
  243. {
  244. $entries = scandir($path);
  245. foreach ($entries as $entry) {
  246. if ($entry === '.' || $entry === '..') {
  247. continue;
  248. }
  249. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  250. if (count($segments) == 0) {
  251. if (strlen($entry) != $len) {
  252. continue;
  253. }
  254. if (is_file($filename)) {
  255. if ($all || $this->getString($filename) == null) {
  256. unlink($filename);
  257. }
  258. }
  259. } else {
  260. if (strlen($entry) != $segments[0]) {
  261. continue;
  262. }
  263. if (is_dir($filename)) {
  264. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  265. rmdir($filename);
  266. }
  267. }
  268. }
  269. }
  270. public function clear(): bool
  271. {
  272. if (!file_exists($this->path) || !is_dir($this->path)) {
  273. return false;
  274. }
  275. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  276. return true;
  277. }
  278. }
  279. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  280. class ReflectedColumn implements \JsonSerializable
  281. {
  282. const DEFAULT_LENGTH = 255;
  283. const DEFAULT_PRECISION = 19;
  284. const DEFAULT_SCALE = 4;
  285. private $name;
  286. private $type;
  287. private $length;
  288. private $precision;
  289. private $scale;
  290. private $nullable;
  291. private $pk;
  292. private $fk;
  293. public function __construct(String $name, String $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, String $fk)
  294. {
  295. $this->name = $name;
  296. $this->type = $type;
  297. $this->length = $length;
  298. $this->precision = $precision;
  299. $this->scale = $scale;
  300. $this->nullable = $nullable;
  301. $this->pk = $pk;
  302. $this->fk = $fk;
  303. $this->sanitize();
  304. }
  305. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  306. {
  307. $name = $columnResult['COLUMN_NAME'];
  308. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  309. $type = $reflection->toJdbcType($columnResult['DATA_TYPE'], $length);
  310. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  311. $scale = (int) $columnResult['NUMERIC_SCALE'];
  312. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  313. $pk = false;
  314. $fk = '';
  315. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  316. }
  317. public static function fromJson( /* object */$json): ReflectedColumn
  318. {
  319. $name = $json->name;
  320. $type = $json->type;
  321. $length = isset($json->length) ? $json->length : 0;
  322. $precision = isset($json->precision) ? $json->precision : 0;
  323. $scale = isset($json->scale) ? $json->scale : 0;
  324. $nullable = isset($json->nullable) ? $json->nullable : false;
  325. $pk = isset($json->pk) ? $json->pk : false;
  326. $fk = isset($json->fk) ? $json->fk : '';
  327. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  328. }
  329. private function sanitize()
  330. {
  331. $this->length = $this->hasLength() ? $this->getLength() : 0;
  332. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  333. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  334. }
  335. public function getName(): String
  336. {
  337. return $this->name;
  338. }
  339. public function getNullable(): bool
  340. {
  341. return $this->nullable;
  342. }
  343. public function getType(): String
  344. {
  345. return $this->type;
  346. }
  347. public function getLength(): int
  348. {
  349. return $this->length ?: self::DEFAULT_LENGTH;
  350. }
  351. public function getPrecision(): int
  352. {
  353. return $this->precision ?: self::DEFAULT_PRECISION;
  354. }
  355. public function getScale(): int
  356. {
  357. return $this->scale ?: self::DEFAULT_SCALE;
  358. }
  359. public function hasLength(): bool
  360. {
  361. return in_array($this->type, ['varchar', 'varbinary']);
  362. }
  363. public function hasPrecision(): bool
  364. {
  365. return $this->type == 'decimal';
  366. }
  367. public function hasScale(): bool
  368. {
  369. return $this->type == 'decimal';
  370. }
  371. public function isBinary(): bool
  372. {
  373. return in_array($this->type, ['blob', 'varbinary']);
  374. }
  375. public function isBoolean(): bool
  376. {
  377. return $this->type == 'boolean';
  378. }
  379. public function isGeometry(): bool
  380. {
  381. return $this->type == 'geometry';
  382. }
  383. public function isInteger(): bool
  384. {
  385. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  386. }
  387. public function setPk($value) /*: void*/
  388. {
  389. $this->pk = $value;
  390. }
  391. public function getPk(): bool
  392. {
  393. return $this->pk;
  394. }
  395. public function setFk($value) /*: void*/
  396. {
  397. $this->fk = $value;
  398. }
  399. public function getFk(): String
  400. {
  401. return $this->fk;
  402. }
  403. public function serialize()
  404. {
  405. return [
  406. 'name' => $this->name,
  407. 'type' => $this->type,
  408. 'length' => $this->length,
  409. 'precision' => $this->precision,
  410. 'scale' => $this->scale,
  411. 'nullable' => $this->nullable,
  412. 'pk' => $this->pk,
  413. 'fk' => $this->fk,
  414. ];
  415. }
  416. public function jsonSerialize()
  417. {
  418. return array_filter($this->serialize());
  419. }
  420. }
  421. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  422. class ReflectedDatabase implements \JsonSerializable
  423. {
  424. private $tableTypes;
  425. public function __construct(array $tableTypes)
  426. {
  427. $this->tableTypes = $tableTypes;
  428. }
  429. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  430. {
  431. $tableTypes = [];
  432. foreach ($reflection->getTables() as $table) {
  433. $tableName = $table['TABLE_NAME'];
  434. $tableType = $table['TABLE_TYPE'];
  435. if (in_array($tableName, $reflection->getIgnoredTables())) {
  436. continue;
  437. }
  438. $tableTypes[$tableName] = $tableType;
  439. }
  440. return new ReflectedDatabase($tableTypes);
  441. }
  442. public static function fromJson( /* object */$json): ReflectedDatabase
  443. {
  444. $tableTypes = (array) $json->tables;
  445. return new ReflectedDatabase($tableTypes);
  446. }
  447. public function hasTable(String $tableName): bool
  448. {
  449. return isset($this->tableTypes[$tableName]);
  450. }
  451. public function getType(String $tableName): String
  452. {
  453. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  454. }
  455. public function getTableNames(): array
  456. {
  457. return array_keys($this->tableTypes);
  458. }
  459. public function removeTable(String $tableName): bool
  460. {
  461. if (!isset($this->tableTypes[$tableName])) {
  462. return false;
  463. }
  464. unset($this->tableTypes[$tableName]);
  465. return true;
  466. }
  467. public function serialize()
  468. {
  469. return [
  470. 'tables' => $this->tableTypes,
  471. ];
  472. }
  473. public function jsonSerialize()
  474. {
  475. return $this->serialize();
  476. }
  477. }
  478. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  479. class ReflectedTable implements \JsonSerializable
  480. {
  481. private $name;
  482. private $type;
  483. private $columns;
  484. private $pk;
  485. private $fks;
  486. public function __construct(String $name, String $type, array $columns)
  487. {
  488. $this->name = $name;
  489. $this->type = $type;
  490. $this->columns = [];
  491. foreach ($columns as $column) {
  492. $columnName = $column->getName();
  493. $this->columns[$columnName] = $column;
  494. }
  495. $this->pk = null;
  496. foreach ($columns as $column) {
  497. if ($column->getPk() == true) {
  498. $this->pk = $column;
  499. }
  500. }
  501. $this->fks = [];
  502. foreach ($columns as $column) {
  503. $columnName = $column->getName();
  504. $referencedTableName = $column->getFk();
  505. if ($referencedTableName != '') {
  506. $this->fks[$columnName] = $referencedTableName;
  507. }
  508. }
  509. }
  510. public static function fromReflection(GenericReflection $reflection, String $name, String $type): ReflectedTable
  511. {
  512. $columns = [];
  513. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  514. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  515. $columns[$column->getName()] = $column;
  516. }
  517. $columnNames = $reflection->getTablePrimaryKeys($name);
  518. if (count($columnNames) == 1) {
  519. $columnName = $columnNames[0];
  520. if (isset($columns[$columnName])) {
  521. $pk = $columns[$columnName];
  522. $pk->setPk(true);
  523. }
  524. }
  525. $fks = $reflection->getTableForeignKeys($name);
  526. foreach ($fks as $columnName => $table) {
  527. $columns[$columnName]->setFk($table);
  528. }
  529. return new ReflectedTable($name, $type, array_values($columns));
  530. }
  531. public static function fromJson( /* object */$json): ReflectedTable
  532. {
  533. $name = $json->name;
  534. $type = $json->type;
  535. $columns = [];
  536. if (isset($json->columns) && is_array($json->columns)) {
  537. foreach ($json->columns as $column) {
  538. $columns[] = ReflectedColumn::fromJson($column);
  539. }
  540. }
  541. return new ReflectedTable($name, $type, $columns);
  542. }
  543. public function hasColumn(String $columnName): bool
  544. {
  545. return isset($this->columns[$columnName]);
  546. }
  547. public function hasPk(): bool
  548. {
  549. return $this->pk != null;
  550. }
  551. public function getPk() /*: ?ReflectedColumn */
  552. {
  553. return $this->pk;
  554. }
  555. public function getName(): String
  556. {
  557. return $this->name;
  558. }
  559. public function getType(): String
  560. {
  561. return $this->type;
  562. }
  563. public function getColumnNames(): array
  564. {
  565. return array_keys($this->columns);
  566. }
  567. public function getColumn($columnName): ReflectedColumn
  568. {
  569. return $this->columns[$columnName];
  570. }
  571. public function getFksTo(String $tableName): array
  572. {
  573. $columns = array();
  574. foreach ($this->fks as $columnName => $referencedTableName) {
  575. if ($tableName == $referencedTableName) {
  576. $columns[] = $this->columns[$columnName];
  577. }
  578. }
  579. return $columns;
  580. }
  581. public function removeColumn(String $columnName): bool
  582. {
  583. if (!isset($this->columns[$columnName])) {
  584. return false;
  585. }
  586. unset($this->columns[$columnName]);
  587. return true;
  588. }
  589. public function serialize()
  590. {
  591. return [
  592. 'name' => $this->name,
  593. 'type' => $this->type,
  594. 'columns' => array_values($this->columns),
  595. ];
  596. }
  597. public function jsonSerialize()
  598. {
  599. return $this->serialize();
  600. }
  601. }
  602. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  603. class DefinitionService
  604. {
  605. private $db;
  606. private $reflection;
  607. public function __construct(GenericDB $db, ReflectionService $reflection)
  608. {
  609. $this->db = $db;
  610. $this->reflection = $reflection;
  611. }
  612. public function updateTable(String $tableName, /* object */ $changes): bool
  613. {
  614. $table = $this->reflection->getTable($tableName);
  615. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  616. if ($table->getName() != $newTable->getName()) {
  617. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  618. return false;
  619. }
  620. }
  621. return true;
  622. }
  623. public function updateColumn(String $tableName, String $columnName, /* object */ $changes): bool
  624. {
  625. $table = $this->reflection->getTable($tableName);
  626. $column = $table->getColumn($columnName);
  627. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  628. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  629. $oldColumn = $table->getPk();
  630. if ($oldColumn->getName() != $columnName) {
  631. $oldColumn->setPk(false);
  632. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  633. return false;
  634. }
  635. }
  636. }
  637. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  638. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  639. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  640. return false;
  641. }
  642. }
  643. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  644. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  645. return false;
  646. }
  647. }
  648. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  649. $newColumn->setPk(false);
  650. $newColumn->setFk('');
  651. if ($newColumn->getName() != $column->getName()) {
  652. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  653. return false;
  654. }
  655. }
  656. if ($newColumn->getType() != $column->getType() ||
  657. $newColumn->getLength() != $column->getLength() ||
  658. $newColumn->getPrecision() != $column->getPrecision() ||
  659. $newColumn->getScale() != $column->getScale()
  660. ) {
  661. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  662. return false;
  663. }
  664. }
  665. if ($newColumn->getNullable() != $column->getNullable()) {
  666. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  667. return false;
  668. }
  669. }
  670. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  671. if ($newColumn->getFk()) {
  672. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  673. return false;
  674. }
  675. }
  676. if ($newColumn->getPk()) {
  677. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  678. return false;
  679. }
  680. }
  681. return true;
  682. }
  683. public function addTable( /* object */$definition)
  684. {
  685. $newTable = ReflectedTable::fromJson($definition);
  686. if (!$this->db->definition()->addTable($newTable)) {
  687. return false;
  688. }
  689. return true;
  690. }
  691. public function addColumn(String $tableName, /* object */ $definition)
  692. {
  693. $newColumn = ReflectedColumn::fromJson($definition);
  694. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  695. return false;
  696. }
  697. if ($newColumn->getFk()) {
  698. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  699. return false;
  700. }
  701. }
  702. if ($newColumn->getPk()) {
  703. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  704. return false;
  705. }
  706. }
  707. return true;
  708. }
  709. public function removeTable(String $tableName)
  710. {
  711. if (!$this->db->definition()->removeTable($tableName)) {
  712. return false;
  713. }
  714. return true;
  715. }
  716. public function removeColumn(String $tableName, String $columnName)
  717. {
  718. $table = $this->reflection->getTable($tableName);
  719. $newColumn = $table->getColumn($columnName);
  720. if ($newColumn->getPk()) {
  721. $newColumn->setPk(false);
  722. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  723. return false;
  724. }
  725. }
  726. if ($newColumn->getFk()) {
  727. $newColumn->setFk("");
  728. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  729. return false;
  730. }
  731. }
  732. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  733. return false;
  734. }
  735. return true;
  736. }
  737. }
  738. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  739. class ReflectionService
  740. {
  741. private $db;
  742. private $cache;
  743. private $ttl;
  744. private $database;
  745. private $tables;
  746. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  747. {
  748. $this->db = $db;
  749. $this->cache = $cache;
  750. $this->ttl = $ttl;
  751. $this->database = $this->loadDatabase(true);
  752. $this->tables = [];
  753. }
  754. private function loadDatabase(bool $useCache): ReflectedDatabase
  755. {
  756. $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
  757. if ($data != '') {
  758. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  759. } else {
  760. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  761. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  762. $this->cache->set('ReflectedDatabase', $data, $this->ttl);
  763. }
  764. return $database;
  765. }
  766. private function loadTable(String $tableName, bool $useCache): ReflectedTable
  767. {
  768. $data = $useCache ? $this->cache->get("ReflectedTable($tableName)") : '';
  769. if ($data != '') {
  770. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  771. } else {
  772. $tableType = $this->database->getType($tableName);
  773. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  774. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  775. $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
  776. }
  777. return $table;
  778. }
  779. public function refreshTables()
  780. {
  781. $this->database = $this->loadDatabase(false);
  782. }
  783. public function refreshTable(String $tableName)
  784. {
  785. $this->tables[$tableName] = $this->loadTable($tableName, false);
  786. }
  787. public function hasTable(String $tableName): bool
  788. {
  789. return $this->database->hasTable($tableName);
  790. }
  791. public function getType(String $tableName): String
  792. {
  793. return $this->database->getType($tableName);
  794. }
  795. public function getTable(String $tableName): ReflectedTable
  796. {
  797. if (!isset($this->tables[$tableName])) {
  798. $this->tables[$tableName] = $this->loadTable($tableName, true);
  799. }
  800. return $this->tables[$tableName];
  801. }
  802. public function getTableNames(): array
  803. {
  804. return $this->database->getTableNames();
  805. }
  806. public function getDatabaseName(): String
  807. {
  808. return $this->database->getName();
  809. }
  810. public function removeTable(String $tableName): bool
  811. {
  812. unset($this->tables[$tableName]);
  813. return $this->database->removeTable($tableName);
  814. }
  815. }
  816. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  817. class CacheController
  818. {
  819. private $cache;
  820. private $responder;
  821. public function __construct(Router $router, Responder $responder, Cache $cache)
  822. {
  823. $router->register('GET', '/cache/clear', array($this, 'clear'));
  824. $this->cache = $cache;
  825. $this->responder = $responder;
  826. }
  827. public function clear(Request $request): Response
  828. {
  829. return $this->responder->success($this->cache->clear());
  830. }
  831. }
  832. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  833. class ColumnController
  834. {
  835. private $responder;
  836. private $reflection;
  837. private $definition;
  838. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  839. {
  840. $router->register('GET', '/columns', array($this, 'getDatabase'));
  841. $router->register('GET', '/columns/*', array($this, 'getTable'));
  842. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  843. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  844. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  845. $router->register('POST', '/columns', array($this, 'addTable'));
  846. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  847. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  848. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  849. $this->responder = $responder;
  850. $this->reflection = $reflection;
  851. $this->definition = $definition;
  852. }
  853. public function getDatabase(Request $request): Response
  854. {
  855. $tables = [];
  856. foreach ($this->reflection->getTableNames() as $table) {
  857. $tables[] = $this->reflection->getTable($table);
  858. }
  859. $database = ['tables' => $tables];
  860. return $this->responder->success($database);
  861. }
  862. public function getTable(Request $request): Response
  863. {
  864. $tableName = $request->getPathSegment(2);
  865. if (!$this->reflection->hasTable($tableName)) {
  866. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  867. }
  868. $table = $this->reflection->getTable($tableName);
  869. return $this->responder->success($table);
  870. }
  871. public function getColumn(Request $request): Response
  872. {
  873. $tableName = $request->getPathSegment(2);
  874. $columnName = $request->getPathSegment(3);
  875. if (!$this->reflection->hasTable($tableName)) {
  876. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  877. }
  878. $table = $this->reflection->getTable($tableName);
  879. if (!$table->hasColumn($columnName)) {
  880. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  881. }
  882. $column = $table->getColumn($columnName);
  883. return $this->responder->success($column);
  884. }
  885. public function updateTable(Request $request): Response
  886. {
  887. $tableName = $request->getPathSegment(2);
  888. if (!$this->reflection->hasTable($tableName)) {
  889. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  890. }
  891. $success = $this->definition->updateTable($tableName, $request->getBody());
  892. if ($success) {
  893. $this->reflection->refreshTables();
  894. }
  895. return $this->responder->success($success);
  896. }
  897. public function updateColumn(Request $request): Response
  898. {
  899. $tableName = $request->getPathSegment(2);
  900. $columnName = $request->getPathSegment(3);
  901. if (!$this->reflection->hasTable($tableName)) {
  902. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  903. }
  904. $table = $this->reflection->getTable($tableName);
  905. if (!$table->hasColumn($columnName)) {
  906. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  907. }
  908. $success = $this->definition->updateColumn($tableName, $columnName, $request->getBody());
  909. if ($success) {
  910. $this->reflection->refreshTable($tableName);
  911. }
  912. return $this->responder->success($success);
  913. }
  914. public function addTable(Request $request): Response
  915. {
  916. $tableName = $request->getBody()->name;
  917. if ($this->reflection->hasTable($tableName)) {
  918. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  919. }
  920. $success = $this->definition->addTable($request->getBody());
  921. if ($success) {
  922. $this->reflection->refreshTables();
  923. }
  924. return $this->responder->success($success);
  925. }
  926. public function addColumn(Request $request): Response
  927. {
  928. $tableName = $request->getPathSegment(2);
  929. if (!$this->reflection->hasTable($tableName)) {
  930. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  931. }
  932. $columnName = $request->getBody()->name;
  933. $table = $this->reflection->getTable($tableName);
  934. if ($table->hasColumn($columnName)) {
  935. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  936. }
  937. $success = $this->definition->addColumn($tableName, $request->getBody());
  938. if ($success) {
  939. $this->reflection->refreshTable($tableName);
  940. }
  941. return $this->responder->success($success);
  942. }
  943. public function removeTable(Request $request): Response
  944. {
  945. $tableName = $request->getPathSegment(2);
  946. if (!$this->reflection->hasTable($tableName)) {
  947. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  948. }
  949. $success = $this->definition->removeTable($tableName);
  950. if ($success) {
  951. $this->reflection->refreshTables();
  952. }
  953. return $this->responder->success($success);
  954. }
  955. public function removeColumn(Request $request): Response
  956. {
  957. $tableName = $request->getPathSegment(2);
  958. $columnName = $request->getPathSegment(3);
  959. if (!$this->reflection->hasTable($tableName)) {
  960. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  961. }
  962. $table = $this->reflection->getTable($tableName);
  963. if (!$table->hasColumn($columnName)) {
  964. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  965. }
  966. $success = $this->definition->removeColumn($tableName, $columnName);
  967. if ($success) {
  968. $this->reflection->refreshTable($tableName);
  969. }
  970. return $this->responder->success($success);
  971. }
  972. }
  973. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  974. class OpenApiController
  975. {
  976. private $openApi;
  977. private $responder;
  978. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  979. {
  980. $router->register('GET', '/openapi', array($this, 'openapi'));
  981. $this->openApi = $openApi;
  982. $this->responder = $responder;
  983. }
  984. public function openapi(Request $request): Response
  985. {
  986. return $this->responder->success($this->openApi->get());
  987. }
  988. }
  989. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  990. class RecordController
  991. {
  992. private $service;
  993. private $responder;
  994. public function __construct(Router $router, Responder $responder, RecordService $service)
  995. {
  996. $router->register('GET', '/records/*', array($this, '_list'));
  997. $router->register('POST', '/records/*', array($this, 'create'));
  998. $router->register('GET', '/records/*/*', array($this, 'read'));
  999. $router->register('PUT', '/records/*/*', array($this, 'update'));
  1000. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  1001. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  1002. $this->service = $service;
  1003. $this->responder = $responder;
  1004. }
  1005. public function _list(Request $request): Response
  1006. {
  1007. $table = $request->getPathSegment(2);
  1008. $params = $request->getParams();
  1009. if (!$this->service->hasTable($table)) {
  1010. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1011. }
  1012. return $this->responder->success($this->service->_list($table, $params));
  1013. }
  1014. public function read(Request $request): Response
  1015. {
  1016. $table = $request->getPathSegment(2);
  1017. if (!$this->service->hasTable($table)) {
  1018. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1019. }
  1020. if ($this->service->getType($table) != 'table') {
  1021. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  1022. }
  1023. $id = $request->getPathSegment(3);
  1024. $params = $request->getParams();
  1025. if (strpos($id, ',') !== false) {
  1026. $ids = explode(',', $id);
  1027. $result = [];
  1028. for ($i = 0; $i < count($ids); $i++) {
  1029. array_push($result, $this->service->read($table, $ids[$i], $params));
  1030. }
  1031. return $this->responder->success($result);
  1032. } else {
  1033. $response = $this->service->read($table, $id, $params);
  1034. if ($response === null) {
  1035. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  1036. }
  1037. return $this->responder->success($response);
  1038. }
  1039. }
  1040. public function create(Request $request): Response
  1041. {
  1042. $table = $request->getPathSegment(2);
  1043. if (!$this->service->hasTable($table)) {
  1044. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1045. }
  1046. if ($this->service->getType($table) != 'table') {
  1047. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  1048. }
  1049. $record = $request->getBody();
  1050. if ($record === null) {
  1051. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  1052. }
  1053. $params = $request->getParams();
  1054. if (is_array($record)) {
  1055. $result = array();
  1056. foreach ($record as $r) {
  1057. $result[] = $this->service->create($table, $r, $params);
  1058. }
  1059. return $this->responder->success($result);
  1060. } else {
  1061. return $this->responder->success($this->service->create($table, $record, $params));
  1062. }
  1063. }
  1064. public function update(Request $request): Response
  1065. {
  1066. $table = $request->getPathSegment(2);
  1067. if (!$this->service->hasTable($table)) {
  1068. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1069. }
  1070. if ($this->service->getType($table) != 'table') {
  1071. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  1072. }
  1073. $id = $request->getPathSegment(3);
  1074. $params = $request->getParams();
  1075. $record = $request->getBody();
  1076. if ($record === null) {
  1077. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  1078. }
  1079. $ids = explode(',', $id);
  1080. if (is_array($record)) {
  1081. if (count($ids) != count($record)) {
  1082. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1083. }
  1084. $result = array();
  1085. for ($i = 0; $i < count($ids); $i++) {
  1086. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  1087. }
  1088. return $this->responder->success($result);
  1089. } else {
  1090. if (count($ids) != 1) {
  1091. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1092. }
  1093. return $this->responder->success($this->service->update($table, $id, $record, $params));
  1094. }
  1095. }
  1096. public function delete(Request $request): Response
  1097. {
  1098. $table = $request->getPathSegment(2);
  1099. if (!$this->service->hasTable($table)) {
  1100. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1101. }
  1102. if ($this->service->getType($table) != 'table') {
  1103. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  1104. }
  1105. $id = $request->getPathSegment(3);
  1106. $params = $request->getParams();
  1107. $ids = explode(',', $id);
  1108. if (count($ids) > 1) {
  1109. $result = array();
  1110. for ($i = 0; $i < count($ids); $i++) {
  1111. $result[] = $this->service->delete($table, $ids[$i], $params);
  1112. }
  1113. return $this->responder->success($result);
  1114. } else {
  1115. return $this->responder->success($this->service->delete($table, $id, $params));
  1116. }
  1117. }
  1118. public function increment(Request $request): Response
  1119. {
  1120. $table = $request->getPathSegment(2);
  1121. if (!$this->service->hasTable($table)) {
  1122. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1123. }
  1124. if ($this->service->getType($table) != 'table') {
  1125. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  1126. }
  1127. $id = $request->getPathSegment(3);
  1128. $record = $request->getBody();
  1129. if ($record === null) {
  1130. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  1131. }
  1132. $params = $request->getParams();
  1133. $ids = explode(',', $id);
  1134. if (is_array($record)) {
  1135. if (count($ids) != count($record)) {
  1136. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1137. }
  1138. $result = array();
  1139. for ($i = 0; $i < count($ids); $i++) {
  1140. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  1141. }
  1142. return $this->responder->success($result);
  1143. } else {
  1144. if (count($ids) != 1) {
  1145. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1146. }
  1147. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  1148. }
  1149. }
  1150. }
  1151. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  1152. class Responder
  1153. {
  1154. public function error(int $error, String $argument, $details = null): Response
  1155. {
  1156. $errorCode = new ErrorCode($error);
  1157. $status = $errorCode->getStatus();
  1158. $document = new ErrorDocument($errorCode, $argument, $details);
  1159. return new Response($status, $document);
  1160. }
  1161. public function success($result): Response
  1162. {
  1163. return new Response(Response::OK, $result);
  1164. }
  1165. }
  1166. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  1167. class ColumnConverter
  1168. {
  1169. private $driver;
  1170. public function __construct(String $driver)
  1171. {
  1172. $this->driver = $driver;
  1173. }
  1174. public function convertColumnValue(ReflectedColumn $column): String
  1175. {
  1176. if ($column->isBinary()) {
  1177. switch ($this->driver) {
  1178. case 'mysql':
  1179. return "FROM_BASE64(?)";
  1180. case 'pgsql':
  1181. return "decode(?, 'base64')";
  1182. case 'sqlsrv':
  1183. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  1184. }
  1185. }
  1186. if ($column->isGeometry()) {
  1187. switch ($this->driver) {
  1188. case 'mysql':
  1189. case 'pgsql':
  1190. return "ST_GeomFromText(?)";
  1191. case 'sqlsrv':
  1192. return "geometry::STGeomFromText(?,0)";
  1193. }
  1194. }
  1195. return '?';
  1196. }
  1197. public function convertColumnName(ReflectedColumn $column, $value): String
  1198. {
  1199. if ($column->isBinary()) {
  1200. switch ($this->driver) {
  1201. case 'mysql':
  1202. return "TO_BASE64($value) as $value";
  1203. case 'pgsql':
  1204. return "encode($value::bytea, 'base64') as $value";
  1205. case 'sqlsrv':
  1206. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  1207. }
  1208. }
  1209. if ($column->isGeometry()) {
  1210. switch ($this->driver) {
  1211. case 'mysql':
  1212. case 'pgsql':
  1213. return "ST_AsText($value) as $value";
  1214. case 'sqlsrv':
  1215. return "REPLACE($value.STAsText(),' (','(') as $value";
  1216. }
  1217. }
  1218. return $value;
  1219. }
  1220. }
  1221. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  1222. class ColumnsBuilder
  1223. {
  1224. private $driver;
  1225. private $converter;
  1226. public function __construct(String $driver)
  1227. {
  1228. $this->driver = $driver;
  1229. $this->converter = new ColumnConverter($driver);
  1230. }
  1231. public function getOffsetLimit(int $offset, int $limit): String
  1232. {
  1233. if ($limit < 0 || $offset < 0) {
  1234. return '';
  1235. }
  1236. switch ($this->driver) {
  1237. case 'mysql':return " LIMIT $offset, $limit";
  1238. case 'pgsql':return " LIMIT $limit OFFSET $offset";
  1239. case 'sqlsrv':return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  1240. }
  1241. }
  1242. private function quoteColumnName(ReflectedColumn $column): String
  1243. {
  1244. return '"' . $column->getName() . '"';
  1245. }
  1246. public function getOrderBy(ReflectedTable $table, array $columnOrdering): String
  1247. {
  1248. if (count($columnOrdering)==0) {
  1249. return '';
  1250. }
  1251. $results = array();
  1252. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  1253. $column = $table->getColumn($columnName);
  1254. $quotedColumnName = $this->quoteColumnName($column);
  1255. $results[] = $quotedColumnName . ' ' . $ordering;
  1256. }
  1257. return ' ORDER BY '.implode(',', $results);
  1258. }
  1259. public function getSelect(ReflectedTable $table, array $columnNames): String
  1260. {
  1261. $results = array();
  1262. foreach ($columnNames as $columnName) {
  1263. $column = $table->getColumn($columnName);
  1264. $quotedColumnName = $this->quoteColumnName($column);
  1265. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  1266. $results[] = $quotedColumnName;
  1267. }
  1268. return implode(',', $results);
  1269. }
  1270. public function getInsert(ReflectedTable $table, array $columnValues): String
  1271. {
  1272. $columns = array();
  1273. $values = array();
  1274. foreach ($columnValues as $columnName => $columnValue) {
  1275. $column = $table->getColumn($columnName);
  1276. $quotedColumnName = $this->quoteColumnName($column);
  1277. $columns[] = $quotedColumnName;
  1278. $columnValue = $this->converter->convertColumnValue($column);
  1279. $values[] = $columnValue;
  1280. }
  1281. $columnsSql = '(' . implode(',', $columns) . ')';
  1282. $valuesSql = '(' . implode(',', $values) . ')';
  1283. $outputColumn = $this->quoteColumnName($table->getPk());
  1284. switch ($this->driver) {
  1285. case 'mysql':return "$columnsSql VALUES $valuesSql";
  1286. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  1287. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  1288. }
  1289. }
  1290. public function getUpdate(ReflectedTable $table, array $columnValues): String
  1291. {
  1292. $results = array();
  1293. foreach ($columnValues as $columnName => $columnValue) {
  1294. $column = $table->getColumn($columnName);
  1295. $quotedColumnName = $this->quoteColumnName($column);
  1296. $columnValue = $this->converter->convertColumnValue($column);
  1297. $results[] = $quotedColumnName . '=' . $columnValue;
  1298. }
  1299. return implode(',', $results);
  1300. }
  1301. public function getIncrement(ReflectedTable $table, array $columnValues): String
  1302. {
  1303. $results = array();
  1304. foreach ($columnValues as $columnName => $columnValue) {
  1305. if (!is_numeric($columnValue)) {
  1306. continue;
  1307. }
  1308. $column = $table->getColumn($columnName);
  1309. $quotedColumnName = $this->quoteColumnName($column);
  1310. $columnValue = $this->converter->convertColumnValue($column);
  1311. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  1312. }
  1313. return implode(',', $results);
  1314. }
  1315. }
  1316. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  1317. class ConditionsBuilder
  1318. {
  1319. private $driver;
  1320. public function __construct(String $driver)
  1321. {
  1322. $this->driver = $driver;
  1323. }
  1324. private function getConditionSql(Condition $condition, array &$arguments): String
  1325. {
  1326. if ($condition instanceof AndCondition) {
  1327. return $this->getAndConditionSql($condition, $arguments);
  1328. }
  1329. if ($condition instanceof OrCondition) {
  1330. return $this->getOrConditionSql($condition, $arguments);
  1331. }
  1332. if ($condition instanceof NotCondition) {
  1333. return $this->getNotConditionSql($condition, $arguments);
  1334. }
  1335. if ($condition instanceof SpatialCondition) {
  1336. return $this->getSpatialConditionSql($condition, $arguments);
  1337. }
  1338. if ($condition instanceof ColumnCondition) {
  1339. return $this->getColumnConditionSql($condition, $arguments);
  1340. }
  1341. throw new \Exception('Unknown Condition: ' . get_class($condition));
  1342. }
  1343. private function getAndConditionSql(AndCondition $and, array &$arguments): String
  1344. {
  1345. $parts = [];
  1346. foreach ($and->getConditions() as $condition) {
  1347. $parts[] = $this->getConditionSql($condition, $arguments);
  1348. }
  1349. return '(' . implode(' AND ', $parts) . ')';
  1350. }
  1351. private function getOrConditionSql(OrCondition $or, array &$arguments): String
  1352. {
  1353. $parts = [];
  1354. foreach ($or->getConditions() as $condition) {
  1355. $parts[] = $this->getConditionSql($condition, $arguments);
  1356. }
  1357. return '(' . implode(' OR ', $parts) . ')';
  1358. }
  1359. private function getNotConditionSql(NotCondition $not, array &$arguments): String
  1360. {
  1361. $condition = $not->getCondition();
  1362. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  1363. }
  1364. private function quoteColumnName(ReflectedColumn $column): String
  1365. {
  1366. return '"' . $column->getName() . '"';
  1367. }
  1368. private function escapeLikeValue(String $value): String
  1369. {
  1370. return addcslashes($value, '%_');
  1371. }
  1372. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): String
  1373. {
  1374. $column = $this->quoteColumnName($condition->getColumn());
  1375. $operator = $condition->getOperator();
  1376. $value = $condition->getValue();
  1377. switch ($operator) {
  1378. case 'cs':
  1379. $sql = "$column LIKE ?";
  1380. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  1381. break;
  1382. case 'sw':
  1383. $sql = "$column LIKE ?";
  1384. $arguments[] = $this->escapeLikeValue($value) . '%';
  1385. break;
  1386. case 'ew':
  1387. $sql = "$column LIKE ?";
  1388. $arguments[] = '%' . $this->escapeLikeValue($value);
  1389. break;
  1390. case 'eq':
  1391. $sql = "$column = ?";
  1392. $arguments[] = $value;
  1393. break;
  1394. case 'lt':
  1395. $sql = "$column < ?";
  1396. $arguments[] = $value;
  1397. break;
  1398. case 'le':
  1399. $sql = "$column <= ?";
  1400. $arguments[] = $value;
  1401. break;
  1402. case 'ge':
  1403. $sql = "$column >= ?";
  1404. $arguments[] = $value;
  1405. break;
  1406. case 'gt':
  1407. $sql = "$column > ?";
  1408. $arguments[] = $value;
  1409. break;
  1410. case 'bt':
  1411. $parts = explode(',', $value, 2);
  1412. $count = count($parts);
  1413. if ($count == 2) {
  1414. $sql = "($column >= ? AND $column <= ?)";
  1415. $arguments[] = $parts[0];
  1416. $arguments[] = $parts[1];
  1417. } else {
  1418. $sql = "FALSE";
  1419. }
  1420. break;
  1421. case 'in':
  1422. $parts = explode(',', $value);
  1423. $count = count($parts);
  1424. if ($count > 0) {
  1425. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  1426. $sql = "$column IN ($qmarks)";
  1427. for ($i = 0; $i < $count; $i++) {
  1428. $arguments[] = $parts[$i];
  1429. }
  1430. } else {
  1431. $sql = "FALSE";
  1432. }
  1433. break;
  1434. case 'is':
  1435. $sql = "$column IS NULL";
  1436. break;
  1437. }
  1438. return $sql;
  1439. }
  1440. private function getSpatialFunctionName(String $operator): String
  1441. {
  1442. switch ($operator) {
  1443. case 'co':return 'ST_Contains';
  1444. case 'cr':return 'ST_Crosses';
  1445. case 'di':return 'ST_Disjoint';
  1446. case 'eq':return 'ST_Equals';
  1447. case 'in':return 'ST_Intersects';
  1448. case 'ov':return 'ST_Overlaps';
  1449. case 'to':return 'ST_Touches';
  1450. case 'wi':return 'ST_Within';
  1451. case 'ic':return 'ST_IsClosed';
  1452. case 'is':return 'ST_IsSimple';
  1453. case 'iv':return 'ST_IsValid';
  1454. }
  1455. }
  1456. private function hasSpatialArgument(String $operator): bool
  1457. {
  1458. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  1459. }
  1460. private function getSpatialFunctionCall(String $functionName, String $column, bool $hasArgument): String
  1461. {
  1462. switch ($this->driver) {
  1463. case 'mysql':
  1464. case 'pgsql':
  1465. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  1466. return "$functionName($column, $argument)=TRUE";
  1467. case 'sqlsrv':
  1468. $functionName = str_replace('ST_', 'ST', $functionName);
  1469. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  1470. return "$column.$functionName($argument)=1";
  1471. }
  1472. }
  1473. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): String
  1474. {
  1475. $column = $this->quoteColumnName($condition->getColumn());
  1476. $operator = $condition->getOperator();
  1477. $value = $condition->getValue();
  1478. $functionName = $this->getSpatialFunctionName($operator);
  1479. $hasArgument = $this->hasSpatialArgument($operator);
  1480. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  1481. if ($hasArgument) {
  1482. $arguments[] = $value;
  1483. }
  1484. return $sql;
  1485. }
  1486. public function getWhereClause(Condition $condition, array &$arguments): String
  1487. {
  1488. if ($condition instanceof NoCondition) {
  1489. return '';
  1490. }
  1491. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  1492. }
  1493. }
  1494. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  1495. class DataConverter
  1496. {
  1497. private $driver;
  1498. public function __construct(String $driver)
  1499. {
  1500. $this->driver = $driver;
  1501. }
  1502. private function convertRecordValue($conversion, $value)
  1503. {
  1504. switch ($conversion) {
  1505. case 'boolean':
  1506. return $value ? true : false;
  1507. case 'integer':
  1508. return (int) $value;
  1509. }
  1510. return $value;
  1511. }
  1512. private function getRecordValueConversion(ReflectedColumn $column): String
  1513. {
  1514. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  1515. return 'boolean';
  1516. }
  1517. if ($this->driver == 'sqlsrv' && $column->getType() == 'bigint') {
  1518. return 'integer';
  1519. }
  1520. return 'none';
  1521. }
  1522. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  1523. {
  1524. foreach ($columnNames as $columnName) {
  1525. $column = $table->getColumn($columnName);
  1526. $conversion = $this->getRecordValueConversion($column);
  1527. if ($conversion != 'none') {
  1528. foreach ($records as $i => $record) {
  1529. $value = $records[$i][$columnName];
  1530. if ($value === null) {
  1531. continue;
  1532. }
  1533. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  1534. }
  1535. }
  1536. }
  1537. }
  1538. private function convertInputValue($conversion, $value)
  1539. {
  1540. switch ($conversion) {
  1541. case 'base64url_to_base64':
  1542. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  1543. }
  1544. return $value;
  1545. }
  1546. private function getInputValueConversion(ReflectedColumn $column): String
  1547. {
  1548. if ($column->isBinary()) {
  1549. return 'base64url_to_base64';
  1550. }
  1551. return 'none';
  1552. }
  1553. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  1554. {
  1555. $columnNames = array_keys($columnValues);
  1556. foreach ($columnNames as $columnName) {
  1557. $column = $table->getColumn($columnName);
  1558. $conversion = $this->getInputValueConversion($column);
  1559. if ($conversion != 'none') {
  1560. $value = $columnValues[$columnName];
  1561. if ($value !== null) {
  1562. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  1563. }
  1564. }
  1565. }
  1566. }
  1567. }
  1568. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  1569. class GenericDB
  1570. {
  1571. private $driver;
  1572. private $database;
  1573. private $pdo;
  1574. private $reflection;
  1575. private $definition;
  1576. private $conditions;
  1577. private $columns;
  1578. private $converter;
  1579. private function getDsn(String $address, String $port = null, String $database = null): String
  1580. {
  1581. switch ($this->driver) {
  1582. case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  1583. case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  1584. case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
  1585. }
  1586. }
  1587. private function getCommands(): array
  1588. {
  1589. switch ($this->driver) {
  1590. case 'mysql':return [
  1591. 'SET SESSION sql_warnings=1;',
  1592. 'SET NAMES utf8mb4;',
  1593. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  1594. ];
  1595. case 'pgsql':return [
  1596. "SET NAMES 'UTF8';",
  1597. ];
  1598. case 'sqlsrv':return [
  1599. ];
  1600. }
  1601. }
  1602. private function getOptions(): array
  1603. {
  1604. $options = array(
  1605. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  1606. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  1607. );
  1608. switch ($this->driver) {
  1609. case 'mysql':return $options + [
  1610. \PDO::ATTR_EMULATE_PREPARES => false,
  1611. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  1612. \PDO::ATTR_PERSISTENT => true,
  1613. ];
  1614. case 'pgsql':return $options + [
  1615. \PDO::ATTR_EMULATE_PREPARES => false,
  1616. \PDO::ATTR_PERSISTENT => true,
  1617. ];
  1618. case 'sqlsrv':return $options + [
  1619. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  1620. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  1621. ];
  1622. }
  1623. }
  1624. public function __construct(String $driver, String $address, String $port = null, String $database = null, String $username = null, String $password = null)
  1625. {
  1626. $this->driver = $driver;
  1627. $this->database = $database;
  1628. $dsn = $this->getDsn($address, $port, $database);
  1629. $options = $this->getOptions();
  1630. $this->pdo = new \PDO($dsn, $username, $password, $options);
  1631. $commands = $this->getCommands();
  1632. foreach ($commands as $command) {
  1633. $this->pdo->query($command);
  1634. }
  1635. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  1636. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  1637. $this->conditions = new ConditionsBuilder($driver);
  1638. $this->columns = new ColumnsBuilder($driver);
  1639. $this->converter = new DataConverter($driver);
  1640. }
  1641. public function pdo(): \PDO
  1642. {
  1643. return $this->pdo;
  1644. }
  1645. public function reflection(): GenericReflection
  1646. {
  1647. return $this->reflection;
  1648. }
  1649. public function definition(): GenericDefinition
  1650. {
  1651. return $this->definition;
  1652. }
  1653. private function addMiddlewareConditions(String $tableName, Condition $condition): Condition
  1654. {
  1655. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  1656. if ($condition1) {
  1657. $condition = $condition->_and($condition1);
  1658. }
  1659. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  1660. if ($condition2) {
  1661. $condition = $condition->_and($condition2);
  1662. }
  1663. return $condition;
  1664. }
  1665. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  1666. {
  1667. $this->converter->convertColumnValues($table, $columnValues);
  1668. $insertColumns = $this->columns->getInsert($table, $columnValues);
  1669. $tableName = $table->getName();
  1670. $pkName = $table->getPk()->getName();
  1671. $parameters = array_values($columnValues);
  1672. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  1673. $stmt = $this->query($sql, $parameters);
  1674. if (isset($columnValues[$pkName])) {
  1675. return $columnValues[$pkName];
  1676. }
  1677. switch ($this->driver) {
  1678. case 'mysql':
  1679. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  1680. break;
  1681. }
  1682. $pkValue = $stmt->fetchColumn(0);
  1683. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  1684. return (int) $pkValue;
  1685. }
  1686. return $pkValue;
  1687. }
  1688. public function selectSingle(ReflectedTable $table, array $columnNames, String $id) /*: ?array*/
  1689. {
  1690. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1691. $tableName = $table->getName();
  1692. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1693. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1694. $parameters = array();
  1695. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1696. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  1697. $stmt = $this->query($sql, $parameters);
  1698. $record = $stmt->fetch() ?: null;
  1699. if ($record === null) {
  1700. return null;
  1701. }
  1702. $records = array($record);
  1703. $this->converter->convertRecords($table, $columnNames, $records);
  1704. return $records[0];
  1705. }
  1706. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  1707. {
  1708. if (count($ids) == 0) {
  1709. return [];
  1710. }
  1711. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1712. $tableName = $table->getName();
  1713. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  1714. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1715. $parameters = array();
  1716. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1717. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  1718. $stmt = $this->query($sql, $parameters);
  1719. $records = $stmt->fetchAll();
  1720. $this->converter->convertRecords($table, $columnNames, $records);
  1721. return $records;
  1722. }
  1723. public function selectCount(ReflectedTable $table, Condition $condition): int
  1724. {
  1725. $tableName = $table->getName();
  1726. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1727. $parameters = array();
  1728. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1729. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  1730. $stmt = $this->query($sql, $parameters);
  1731. return $stmt->fetchColumn(0);
  1732. }
  1733. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  1734. {
  1735. if ($limit == 0) {
  1736. return array();
  1737. }
  1738. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1739. $tableName = $table->getName();
  1740. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1741. $parameters = array();
  1742. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1743. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  1744. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  1745. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  1746. $stmt = $this->query($sql, $parameters);
  1747. $records = $stmt->fetchAll();
  1748. $this->converter->convertRecords($table, $columnNames, $records);
  1749. return $records;
  1750. }
  1751. public function updateSingle(ReflectedTable $table, array $columnValues, String $id)
  1752. {
  1753. if (count($columnValues) == 0) {
  1754. return 0;
  1755. }
  1756. $this->converter->convertColumnValues($table, $columnValues);
  1757. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  1758. $tableName = $table->getName();
  1759. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1760. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1761. $parameters = array_values($columnValues);
  1762. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1763. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  1764. $stmt = $this->query($sql, $parameters);
  1765. return $stmt->rowCount();
  1766. }
  1767. public function deleteSingle(ReflectedTable $table, String $id)
  1768. {
  1769. $tableName = $table->getName();
  1770. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1771. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1772. $parameters = array();
  1773. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1774. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  1775. $stmt = $this->query($sql, $parameters);
  1776. return $stmt->rowCount();
  1777. }
  1778. public function incrementSingle(ReflectedTable $table, array $columnValues, String $id)
  1779. {
  1780. if (count($columnValues) == 0) {
  1781. return 0;
  1782. }
  1783. $this->converter->convertColumnValues($table, $columnValues);
  1784. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  1785. $tableName = $table->getName();
  1786. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1787. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1788. $parameters = array_values($columnValues);
  1789. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1790. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  1791. $stmt = $this->query($sql, $parameters);
  1792. return $stmt->rowCount();
  1793. }
  1794. private function query(String $sql, array $parameters): \PDOStatement
  1795. {
  1796. $stmt = $this->pdo->prepare($sql);
  1797. $stmt->execute($parameters);
  1798. return $stmt;
  1799. }
  1800. }
  1801. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  1802. class GenericDefinition
  1803. {
  1804. private $pdo;
  1805. private $driver;
  1806. private $database;
  1807. private $typeConverter;
  1808. private $reflection;
  1809. public function __construct(\PDO $pdo, String $driver, String $database)
  1810. {
  1811. $this->pdo = $pdo;
  1812. $this->driver = $driver;
  1813. $this->database = $database;
  1814. $this->typeConverter = new TypeConverter($driver);
  1815. $this->reflection = new GenericReflection($pdo, $driver, $database);
  1816. }
  1817. private function quote(String $identifier): String
  1818. {
  1819. return '"' . str_replace('"', '', $identifier) . '"';
  1820. }
  1821. public function getColumnType(ReflectedColumn $column, bool $update): String
  1822. {
  1823. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  1824. return 'serial';
  1825. }
  1826. $type = $this->typeConverter->fromJdbc($column->getType());
  1827. if ($column->hasPrecision() && $column->hasScale()) {
  1828. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  1829. } else if ($column->hasPrecision()) {
  1830. $size = '(' . $column->getPrecision() . ')';
  1831. } else if ($column->hasLength()) {
  1832. $size = '(' . $column->getLength() . ')';
  1833. } else {
  1834. $size = '';
  1835. }
  1836. $null = $this->getColumnNullType($column, $update);
  1837. $auto = $this->getColumnAutoIncrement($column, $update);
  1838. return $type . $size . $null . $auto;
  1839. }
  1840. private function getPrimaryKey(String $tableName): String
  1841. {
  1842. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  1843. if (count($pks) == 1) {
  1844. return $pks[0];
  1845. }
  1846. return "";
  1847. }
  1848. private function canAutoIncrement(ReflectedColumn $column): bool
  1849. {
  1850. return in_array($column->getType(), ['integer', 'bigint']);
  1851. }
  1852. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): String
  1853. {
  1854. if (!$this->canAutoIncrement($column)) {
  1855. return '';
  1856. }
  1857. switch ($this->driver) {
  1858. case 'mysql':
  1859. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  1860. case 'pgsql':
  1861. case 'sqlsrv':
  1862. return '';
  1863. }
  1864. }
  1865. private function getColumnNullType(ReflectedColumn $column, bool $update): String
  1866. {
  1867. if ($this->driver == 'pgsql' && $update) {
  1868. return '';
  1869. }
  1870. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  1871. }
  1872. private function getTableRenameSQL(String $tableName, String $newTableName): String
  1873. {
  1874. $p1 = $this->quote($tableName);
  1875. $p2 = $this->quote($newTableName);
  1876. switch ($this->driver) {
  1877. case 'mysql':
  1878. return "RENAME TABLE $p1 TO $p2";
  1879. case 'pgsql':
  1880. return "ALTER TABLE $p1 RENAME TO $p2";
  1881. case 'sqlsrv':
  1882. return "EXEC sp_rename $p1, $p2";
  1883. }
  1884. }
  1885. private function getColumnRenameSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1886. {
  1887. $p1 = $this->quote($tableName);
  1888. $p2 = $this->quote($columnName);
  1889. $p3 = $this->quote($newColumn->getName());
  1890. switch ($this->driver) {
  1891. case 'mysql':
  1892. $p4 = $this->getColumnType($newColumn, true);
  1893. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1894. case 'pgsql':
  1895. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  1896. case 'sqlsrv':
  1897. $p4 = $this->quote($tableName . '.' . $columnName);
  1898. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  1899. }
  1900. }
  1901. private function getColumnRetypeSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1902. {
  1903. $p1 = $this->quote($tableName);
  1904. $p2 = $this->quote($columnName);
  1905. $p3 = $this->quote($newColumn->getName());
  1906. $p4 = $this->getColumnType($newColumn, true);
  1907. switch ($this->driver) {
  1908. case 'mysql':
  1909. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1910. case 'pgsql':
  1911. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  1912. case 'sqlsrv':
  1913. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  1914. }
  1915. }
  1916. private function getSetColumnNullableSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1917. {
  1918. $p1 = $this->quote($tableName);
  1919. $p2 = $this->quote($columnName);
  1920. $p3 = $this->quote($newColumn->getName());
  1921. $p4 = $this->getColumnType($newColumn, true);
  1922. switch ($this->driver) {
  1923. case 'mysql':
  1924. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1925. case 'pgsql':
  1926. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  1927. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  1928. case 'sqlsrv':
  1929. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  1930. }
  1931. }
  1932. private function getSetColumnPkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1933. {
  1934. $p1 = $this->quote($tableName);
  1935. $p2 = $this->quote($columnName);
  1936. $p3 = $this->quote($tableName . '_pkey');
  1937. switch ($this->driver) {
  1938. case 'mysql':
  1939. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  1940. return "ALTER TABLE $p1 $p4";
  1941. case 'pgsql':
  1942. case 'sqlsrv':
  1943. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  1944. return "ALTER TABLE $p1 $p4";
  1945. }
  1946. }
  1947. private function getSetColumnPkSequenceSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1948. {
  1949. $p1 = $this->quote($tableName);
  1950. $p2 = $this->quote($columnName);
  1951. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1952. switch ($this->driver) {
  1953. case 'mysql':
  1954. return "select 1";
  1955. case 'pgsql':
  1956. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  1957. case 'sqlsrv':
  1958. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  1959. }
  1960. }
  1961. private function getSetColumnPkSequenceStartSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1962. {
  1963. $p1 = $this->quote($tableName);
  1964. $p2 = $this->quote($columnName);
  1965. switch ($this->driver) {
  1966. case 'mysql':
  1967. return "select 1";
  1968. case 'pgsql':
  1969. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1970. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  1971. case 'sqlsrv':
  1972. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1973. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  1974. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  1975. }
  1976. }
  1977. private function getSetColumnPkDefaultSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1978. {
  1979. $p1 = $this->quote($tableName);
  1980. $p2 = $this->quote($columnName);
  1981. switch ($this->driver) {
  1982. case 'mysql':
  1983. $p3 = $this->quote($newColumn->getName());
  1984. $p4 = $this->getColumnType($newColumn, true);
  1985. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1986. case 'pgsql':
  1987. if ($newColumn->getPk()) {
  1988. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1989. $p4 = "SET DEFAULT nextval($p3)";
  1990. } else {
  1991. $p4 = 'DROP DEFAULT';
  1992. }
  1993. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  1994. case 'sqlsrv':
  1995. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1996. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  1997. if ($newColumn->getPk()) {
  1998. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  1999. } else {
  2000. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  2001. }
  2002. }
  2003. }
  2004. private function getAddColumnFkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  2005. {
  2006. $p1 = $this->quote($tableName);
  2007. $p2 = $this->quote($columnName);
  2008. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2009. $p4 = $this->quote($newColumn->getFk());
  2010. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  2011. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  2012. }
  2013. private function getRemoveColumnFkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  2014. {
  2015. $p1 = $this->quote($tableName);
  2016. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2017. switch ($this->driver) {
  2018. case 'mysql':
  2019. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  2020. case 'pgsql':
  2021. case 'sqlsrv':
  2022. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  2023. }
  2024. }
  2025. private function getAddTableSQL(ReflectedTable $newTable): String
  2026. {
  2027. $tableName = $newTable->getName();
  2028. $p1 = $this->quote($tableName);
  2029. $fields = [];
  2030. $constraints = [];
  2031. foreach ($newTable->getColumnNames() as $columnName) {
  2032. $pkColumn = $this->getPrimaryKey($tableName);
  2033. $newColumn = $newTable->getColumn($columnName);
  2034. $f1 = $this->quote($columnName);
  2035. $f2 = $this->getColumnType($newColumn, false);
  2036. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2037. $f4 = $this->quote($newColumn->getFk());
  2038. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  2039. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  2040. $fields[] = "$f1 $f2";
  2041. if ($newColumn->getPk()) {
  2042. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  2043. }
  2044. if ($newColumn->getFk()) {
  2045. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  2046. }
  2047. }
  2048. $p2 = implode(',', array_merge($fields, $constraints));
  2049. return "CREATE TABLE $p1 ($p2);";
  2050. }
  2051. private function getAddColumnSQL(String $tableName, ReflectedColumn $newColumn): String
  2052. {
  2053. $p1 = $this->quote($tableName);
  2054. $p2 = $this->quote($newColumn->getName());
  2055. $p3 = $this->getColumnType($newColumn, false);
  2056. switch ($this->driver) {
  2057. case 'mysql':
  2058. case 'pgsql':
  2059. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  2060. case 'sqlsrv':
  2061. return "ALTER TABLE $p1 ADD $p2 $p3";
  2062. }
  2063. }
  2064. private function getRemoveTableSQL(String $tableName): String
  2065. {
  2066. $p1 = $this->quote($tableName);
  2067. switch ($this->driver) {
  2068. case 'mysql':
  2069. case 'pgsql':
  2070. return "DROP TABLE $p1 CASCADE;";
  2071. case 'sqlsrv':
  2072. return "DROP TABLE $p1;";
  2073. }
  2074. }
  2075. private function getRemoveColumnSQL(String $tableName, String $columnName): String
  2076. {
  2077. $p1 = $this->quote($tableName);
  2078. $p2 = $this->quote($columnName);
  2079. switch ($this->driver) {
  2080. case 'mysql':
  2081. case 'pgsql':
  2082. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  2083. case 'sqlsrv':
  2084. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  2085. }
  2086. }
  2087. public function renameTable(String $tableName, String $newTableName)
  2088. {
  2089. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  2090. return $this->query($sql);
  2091. }
  2092. public function renameColumn(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2093. {
  2094. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  2095. return $this->query($sql);
  2096. }
  2097. public function retypeColumn(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2098. {
  2099. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  2100. return $this->query($sql);
  2101. }
  2102. public function setColumnNullable(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2103. {
  2104. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  2105. return $this->query($sql);
  2106. }
  2107. public function addColumnPrimaryKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2108. {
  2109. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  2110. $this->query($sql);
  2111. if ($this->canAutoIncrement($newColumn)) {
  2112. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  2113. $this->query($sql);
  2114. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  2115. $this->query($sql);
  2116. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  2117. $this->query($sql);
  2118. }
  2119. return true;
  2120. }
  2121. public function removeColumnPrimaryKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2122. {
  2123. if ($this->canAutoIncrement($newColumn)) {
  2124. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  2125. $this->query($sql);
  2126. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  2127. $this->query($sql);
  2128. }
  2129. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  2130. $this->query($sql);
  2131. return true;
  2132. }
  2133. public function addColumnForeignKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2134. {
  2135. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  2136. return $this->query($sql);
  2137. }
  2138. public function removeColumnForeignKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2139. {
  2140. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  2141. return $this->query($sql);
  2142. }
  2143. public function addTable(ReflectedTable $newTable)
  2144. {
  2145. $sql = $this->getAddTableSQL($newTable);
  2146. return $this->query($sql);
  2147. }
  2148. public function addColumn(String $tableName, ReflectedColumn $newColumn)
  2149. {
  2150. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  2151. return $this->query($sql);
  2152. }
  2153. public function removeTable(String $tableName)
  2154. {
  2155. $sql = $this->getRemoveTableSQL($tableName);
  2156. return $this->query($sql);
  2157. }
  2158. public function removeColumn(String $tableName, String $columnName)
  2159. {
  2160. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  2161. return $this->query($sql);
  2162. }
  2163. private function query(String $sql): bool
  2164. {
  2165. $stmt = $this->pdo->prepare($sql);
  2166. return $stmt->execute();
  2167. }
  2168. }
  2169. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  2170. class GenericReflection
  2171. {
  2172. private $pdo;
  2173. private $driver;
  2174. private $database;
  2175. private $typeConverter;
  2176. public function __construct(\PDO $pdo, String $driver, String $database)
  2177. {
  2178. $this->pdo = $pdo;
  2179. $this->driver = $driver;
  2180. $this->database = $database;
  2181. $this->typeConverter = new TypeConverter($driver);
  2182. }
  2183. public function getIgnoredTables(): array
  2184. {
  2185. switch ($this->driver) {
  2186. case 'mysql':return [];
  2187. case 'pgsql':return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  2188. case 'sqlsrv':return [];
  2189. }
  2190. }
  2191. private function getTablesSQL(): String
  2192. {
  2193. switch ($this->driver) {
  2194. 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"';
  2195. 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";';
  2196. 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"';
  2197. }
  2198. }
  2199. private function getTableColumnsSQL(): String
  2200. {
  2201. switch ($this->driver) {
  2202. 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" = ?';
  2203. 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;';
  2204. 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 \'\' <> ?';
  2205. }
  2206. }
  2207. private function getTablePrimaryKeysSQL(): String
  2208. {
  2209. switch ($this->driver) {
  2210. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  2211. 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\'';
  2212. 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 \'\' <> ?';
  2213. }
  2214. }
  2215. private function getTableForeignKeysSQL(): String
  2216. {
  2217. switch ($this->driver) {
  2218. 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" = ?';
  2219. 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\'';
  2220. 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 \'\' <> ?';
  2221. }
  2222. }
  2223. public function getDatabaseName(): String
  2224. {
  2225. return $this->database;
  2226. }
  2227. public function getTables(): array
  2228. {
  2229. $sql = $this->getTablesSQL();
  2230. $results = $this->query($sql, [$this->database]);
  2231. foreach ($results as &$result) {
  2232. switch ($this->driver) {
  2233. case 'mysql':
  2234. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  2235. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  2236. break;
  2237. case 'pgsql':
  2238. $map = ['r' => 'table', 'v' => 'view'];
  2239. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  2240. break;
  2241. case 'sqlsrv':
  2242. $map = ['U' => 'table', 'V' => 'view'];
  2243. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  2244. break;
  2245. }
  2246. }
  2247. return $results;
  2248. }
  2249. public function getTableColumns(String $tableName, String $type): array
  2250. {
  2251. $sql = $this->getTableColumnsSQL();
  2252. $results = $this->query($sql, [$tableName, $this->database]);
  2253. if ($type == 'view') {
  2254. foreach ($results as &$result) {
  2255. $result['IS_NULLABLE'] = false;
  2256. }
  2257. }
  2258. return $results;
  2259. }
  2260. public function getTablePrimaryKeys(String $tableName): array
  2261. {
  2262. $sql = $this->getTablePrimaryKeysSQL();
  2263. $results = $this->query($sql, [$tableName, $this->database]);
  2264. $primaryKeys = [];
  2265. foreach ($results as $result) {
  2266. $primaryKeys[] = $result['COLUMN_NAME'];
  2267. }
  2268. return $primaryKeys;
  2269. }
  2270. public function getTableForeignKeys(String $tableName): array
  2271. {
  2272. $sql = $this->getTableForeignKeysSQL();
  2273. $results = $this->query($sql, [$tableName, $this->database]);
  2274. $foreignKeys = [];
  2275. foreach ($results as $result) {
  2276. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  2277. }
  2278. return $foreignKeys;
  2279. }
  2280. public function toJdbcType(String $type, int $size): String
  2281. {
  2282. return $this->typeConverter->toJdbc($type, $size);
  2283. }
  2284. private function query(String $sql, array $parameters): array
  2285. {
  2286. $stmt = $this->pdo->prepare($sql);
  2287. $stmt->execute($parameters);
  2288. return $stmt->fetchAll();
  2289. }
  2290. }
  2291. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  2292. class TypeConverter
  2293. {
  2294. private $driver;
  2295. public function __construct(String $driver)
  2296. {
  2297. $this->driver = $driver;
  2298. }
  2299. private $fromJdbc = [
  2300. 'mysql' => [
  2301. 'clob' => 'longtext',
  2302. 'boolean' => 'bit',
  2303. 'blob' => 'longblob',
  2304. 'timestamp' => 'datetime',
  2305. ],
  2306. 'pgsql' => [
  2307. 'clob' => 'text',
  2308. 'blob' => 'bytea',
  2309. ],
  2310. 'sqlsrv' => [
  2311. 'boolean' => 'bit',
  2312. 'varchar' => 'nvarchar',
  2313. 'clob' => 'ntext',
  2314. 'blob' => 'image',
  2315. ],
  2316. ];
  2317. private $toJdbc = [
  2318. 'simplified' => [
  2319. 'char' => 'varchar',
  2320. 'longvarchar' => 'clob',
  2321. 'nchar' => 'varchar',
  2322. 'nvarchar' => 'varchar',
  2323. 'longnvarchar' => 'clob',
  2324. 'binary' => 'varbinary',
  2325. 'longvarbinary' => 'blob',
  2326. 'tinyint' => 'integer',
  2327. 'smallint' => 'integer',
  2328. 'real' => 'float',
  2329. 'numeric' => 'decimal',
  2330. 'time_with_timezone' => 'time',
  2331. 'timestamp_with_timezone' => 'timestamp',
  2332. ],
  2333. 'mysql' => [
  2334. 'bit' => 'boolean',
  2335. 'tinyblob' => 'blob',
  2336. 'mediumblob' => 'blob',
  2337. 'longblob' => 'blob',
  2338. 'tinytext' => 'clob',
  2339. 'mediumtext' => 'clob',
  2340. 'longtext' => 'clob',
  2341. 'text' => 'clob',
  2342. 'mediumint' => 'integer',
  2343. 'int' => 'integer',
  2344. 'polygon' => 'geometry',
  2345. 'point' => 'geometry',
  2346. 'datetime' => 'timestamp',
  2347. 'year' => 'integer',
  2348. 'enum' => 'varchar',
  2349. 'json' => 'clob',
  2350. ],
  2351. 'pgsql' => [
  2352. 'bigserial' => 'bigint',
  2353. 'bit varying' => 'bit',
  2354. 'box' => 'geometry',
  2355. 'bytea' => 'blob',
  2356. 'character varying' => 'varchar',
  2357. 'character' => 'char',
  2358. 'cidr' => 'varchar',
  2359. 'circle' => 'geometry',
  2360. 'double precision' => 'double',
  2361. 'inet' => 'integer',
  2362. 'json' => 'clob',
  2363. 'jsonb' => 'clob',
  2364. 'line' => 'geometry',
  2365. 'lseg' => 'geometry',
  2366. 'macaddr' => 'varchar',
  2367. 'money' => 'decimal',
  2368. 'path' => 'geometry',
  2369. 'point' => 'geometry',
  2370. 'polygon' => 'geometry',
  2371. 'real' => 'float',
  2372. 'serial' => 'integer',
  2373. 'text' => 'clob',
  2374. 'time without time zone' => 'time',
  2375. 'time with time zone' => 'time_with_timezone',
  2376. 'timestamp without time zone' => 'timestamp',
  2377. 'timestamp with time zone' => 'timestamp_with_timezone',
  2378. 'uuid' => 'char',
  2379. 'xml' => 'clob',
  2380. ],
  2381. 'sqlsrv' => [
  2382. 'varbinary(0)' => 'blob',
  2383. 'bit' => 'boolean',
  2384. 'datetime' => 'timestamp',
  2385. 'datetime2' => 'timestamp',
  2386. 'float' => 'double',
  2387. 'image' => 'blob',
  2388. 'int' => 'integer',
  2389. 'money' => 'decimal',
  2390. 'ntext' => 'clob',
  2391. 'smalldatetime' => 'timestamp',
  2392. 'smallmoney' => 'decimal',
  2393. 'text' => 'clob',
  2394. 'timestamp' => 'binary',
  2395. 'udt' => 'varbinary',
  2396. 'uniqueidentifier' => 'char',
  2397. 'xml' => 'clob',
  2398. ],
  2399. ];
  2400. private $valid = [
  2401. 'bigint' => true,
  2402. 'binary' => true,
  2403. 'bit' => true,
  2404. 'blob' => true,
  2405. 'boolean' => true,
  2406. 'char' => true,
  2407. 'clob' => true,
  2408. 'date' => true,
  2409. 'decimal' => true,
  2410. 'distinct' => true,
  2411. 'double' => true,
  2412. 'float' => true,
  2413. 'integer' => true,
  2414. 'longnvarchar' => true,
  2415. 'longvarbinary' => true,
  2416. 'longvarchar' => true,
  2417. 'nchar' => true,
  2418. 'nclob' => true,
  2419. 'numeric' => true,
  2420. 'nvarchar' => true,
  2421. 'real' => true,
  2422. 'smallint' => true,
  2423. 'time' => true,
  2424. 'time_with_timezone' => true,
  2425. 'timestamp' => true,
  2426. 'timestamp_with_timezone' => true,
  2427. 'tinyint' => true,
  2428. 'varbinary' => true,
  2429. 'varchar' => true,
  2430. 'geometry' => true,
  2431. ];
  2432. public function toJdbc(String $type, int $size): String
  2433. {
  2434. $jdbcType = strtolower($type);
  2435. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  2436. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  2437. }
  2438. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  2439. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  2440. }
  2441. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  2442. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  2443. }
  2444. if (!isset($this->valid[$jdbcType])) {
  2445. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  2446. }
  2447. return $jdbcType;
  2448. }
  2449. public function fromJdbc(String $type): String
  2450. {
  2451. $jdbcType = strtolower($type);
  2452. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  2453. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  2454. }
  2455. return $jdbcType;
  2456. }
  2457. }
  2458. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Handler.php
  2459. interface Handler
  2460. {
  2461. public function handle(Request $request): Response;
  2462. }
  2463. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  2464. abstract class Middleware implements Handler
  2465. {
  2466. protected $next;
  2467. protected $responder;
  2468. private $properties;
  2469. public function __construct(Router $router, Responder $responder, array $properties)
  2470. {
  2471. $router->load($this);
  2472. $this->responder = $responder;
  2473. $this->properties = $properties;
  2474. }
  2475. public function setNext(Handler $handler) /*: void*/
  2476. {
  2477. $this->next = $handler;
  2478. }
  2479. protected function getArrayProperty(String $key, String $default): array
  2480. {
  2481. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  2482. }
  2483. protected function getProperty(String $key, $default)
  2484. {
  2485. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  2486. }
  2487. }
  2488. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  2489. class VariableStore
  2490. {
  2491. static $values = array();
  2492. public static function get(String $key)
  2493. {
  2494. if (isset(self::$values[$key])) {
  2495. return self::$values[$key];
  2496. }
  2497. return null;
  2498. }
  2499. public static function set(String $key, /* object */ $value)
  2500. {
  2501. self::$values[$key] = $value;
  2502. }
  2503. }
  2504. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  2505. interface Router extends Handler
  2506. {
  2507. public function register(String $method, String $path, array $handler);
  2508. public function load(Middleware $middleware);
  2509. public function route(Request $request): Response;
  2510. }
  2511. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  2512. class SimpleRouter implements Router
  2513. {
  2514. private $responder;
  2515. private $cache;
  2516. private $ttl;
  2517. private $registration;
  2518. private $routes;
  2519. private $routeHandlers;
  2520. private $middlewares;
  2521. public function __construct(Responder $responder, Cache $cache, int $ttl)
  2522. {
  2523. $this->responder = $responder;
  2524. $this->cache = $cache;
  2525. $this->ttl = $ttl;
  2526. $this->registration = true;
  2527. $this->routes = $this->loadPathTree();
  2528. $this->routeHandlers = [];
  2529. $this->middlewares = array();
  2530. }
  2531. private function loadPathTree(): PathTree
  2532. {
  2533. $data = $this->cache->get('PathTree');
  2534. if ($data != '') {
  2535. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  2536. $this->registration = false;
  2537. } else {
  2538. $tree = new PathTree();
  2539. }
  2540. return $tree;
  2541. }
  2542. public function register(String $method, String $path, array $handler)
  2543. {
  2544. $routeNumber = count($this->routeHandlers);
  2545. $this->routeHandlers[$routeNumber] = $handler;
  2546. if ($this->registration) {
  2547. $parts = explode('/', trim($path, '/'));
  2548. array_unshift($parts, $method);
  2549. $this->routes->put($parts, $routeNumber);
  2550. }
  2551. }
  2552. public function load(Middleware $middleware) /*: void*/
  2553. {
  2554. if (count($this->middlewares) > 0) {
  2555. $next = $this->middlewares[0];
  2556. } else {
  2557. $next = $this;
  2558. }
  2559. $middleware->setNext($next);
  2560. array_unshift($this->middlewares, $middleware);
  2561. }
  2562. public function route(Request $request): Response
  2563. {
  2564. if ($this->registration) {
  2565. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  2566. $this->cache->set('PathTree', $data, $this->ttl);
  2567. }
  2568. $obj = $this;
  2569. if (count($this->middlewares) > 0) {
  2570. $obj = $this->middlewares[0];
  2571. }
  2572. return $obj->handle($request);
  2573. }
  2574. private function getRouteNumbers(Request $request): array
  2575. {
  2576. $method = strtoupper($request->getMethod());
  2577. $path = explode('/', trim($request->getPath(0), '/'));
  2578. array_unshift($path, $method);
  2579. return $this->routes->match($path);
  2580. }
  2581. public function handle(Request $request): Response
  2582. {
  2583. $routeNumbers = $this->getRouteNumbers($request);
  2584. if (count($routeNumbers) == 0) {
  2585. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getPath());
  2586. }
  2587. return call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  2588. }
  2589. }
  2590. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  2591. class AjaxOnlyMiddleware extends Middleware
  2592. {
  2593. public function handle(Request $request): Response
  2594. {
  2595. $method = $request->getMethod();
  2596. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  2597. if (!in_array($method, $excludeMethods)) {
  2598. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  2599. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  2600. if ($headerValue != $request->getHeader($headerName)) {
  2601. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  2602. }
  2603. }
  2604. return $this->next->handle($request);
  2605. }
  2606. }
  2607. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  2608. class AuthorizationMiddleware extends Middleware
  2609. {
  2610. private $reflection;
  2611. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2612. {
  2613. parent::__construct($router, $responder, $properties);
  2614. $this->reflection = $reflection;
  2615. $this->utils = new RequestUtils($reflection);
  2616. }
  2617. private function handleColumns(String $operation, String $tableName) /*: void*/
  2618. {
  2619. $columnHandler = $this->getProperty('columnHandler', '');
  2620. if ($columnHandler) {
  2621. $table = $this->reflection->getTable($tableName);
  2622. foreach ($table->getColumnNames() as $columnName) {
  2623. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  2624. if (!$allowed) {
  2625. $table->removeColumn($columnName);
  2626. }
  2627. }
  2628. }
  2629. }
  2630. private function handleTable(String $operation, String $tableName) /*: void*/
  2631. {
  2632. if (!$this->reflection->hasTable($tableName)) {
  2633. return;
  2634. }
  2635. $tableHandler = $this->getProperty('tableHandler', '');
  2636. if ($tableHandler) {
  2637. $allowed = call_user_func($tableHandler, $operation, $tableName);
  2638. if (!$allowed) {
  2639. $this->reflection->removeTable($tableName);
  2640. } else {
  2641. $this->handleColumns($operation, $tableName);
  2642. }
  2643. }
  2644. }
  2645. private function handleRecords(String $operation, String $tableName) /*: void*/
  2646. {
  2647. if (!$this->reflection->hasTable($tableName)) {
  2648. return;
  2649. }
  2650. $recordHandler = $this->getProperty('recordHandler', '');
  2651. if ($recordHandler) {
  2652. $query = call_user_func($recordHandler, $operation, $tableName);
  2653. $filters = new FilterInfo();
  2654. $table = $this->reflection->getTable($tableName);
  2655. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  2656. parse_str($query, $params);
  2657. $condition = $filters->getCombinedConditions($table, $params);
  2658. VariableStore::set("authorization.conditions.$tableName", $condition);
  2659. }
  2660. }
  2661. public function handle(Request $request): Response
  2662. {
  2663. $path = $request->getPathSegment(1);
  2664. $operation = $this->utils->getOperation($request);
  2665. $tableNames = $this->utils->getTableNames($request);
  2666. foreach ($tableNames as $tableName) {
  2667. $this->handleTable($operation, $tableName);
  2668. if ($path == 'records') {
  2669. $this->handleRecords($operation, $tableName);
  2670. }
  2671. }
  2672. if ($path == 'openapi') {
  2673. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  2674. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  2675. }
  2676. return $this->next->handle($request);
  2677. }
  2678. }
  2679. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  2680. class BasicAuthMiddleware extends Middleware
  2681. {
  2682. private function hasCorrectPassword(String $username, String $password, array &$passwords): bool
  2683. {
  2684. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  2685. if ($hash && password_verify($password, $hash)) {
  2686. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  2687. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  2688. }
  2689. return true;
  2690. }
  2691. return false;
  2692. }
  2693. private function getValidUsername(String $username, String $password, String $passwordFile): String
  2694. {
  2695. $passwords = $this->readPasswords($passwordFile);
  2696. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  2697. $this->writePasswords($passwordFile, $passwords);
  2698. return $valid ? $username : '';
  2699. }
  2700. private function readPasswords(String $passwordFile): array
  2701. {
  2702. $passwords = [];
  2703. $passwordLines = file($passwordFile);
  2704. foreach ($passwordLines as $passwordLine) {
  2705. if (strpos($passwordLine, ':') !== false) {
  2706. list($username, $hash) = explode(':', trim($passwordLine), 2);
  2707. if (strlen($hash) > 0 && $hash[0] != '$') {
  2708. $hash = password_hash($hash, PASSWORD_DEFAULT);
  2709. }
  2710. $passwords[$username] = $hash;
  2711. }
  2712. }
  2713. return $passwords;
  2714. }
  2715. private function writePasswords(String $passwordFile, array $passwords): bool
  2716. {
  2717. $success = false;
  2718. $passwordFileContents = '';
  2719. foreach ($passwords as $username => $hash) {
  2720. $passwordFileContents .= "$username:$hash\n";
  2721. }
  2722. if (file_get_contents($passwordFile) != $passwordFileContents) {
  2723. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  2724. }
  2725. return $success;
  2726. }
  2727. private function getAuthorizationCredentials(Request $request): String
  2728. {
  2729. if (isset($_SERVER['PHP_AUTH_USER'])) {
  2730. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  2731. }
  2732. $parts = explode(' ', trim($request->getHeader('Authorization')), 2);
  2733. if (count($parts) != 2) {
  2734. return '';
  2735. }
  2736. if ($parts[0] != 'Basic') {
  2737. return '';
  2738. }
  2739. return base64_decode(strtr($parts[1], '-_', '+/'));
  2740. }
  2741. public function handle(Request $request): Response
  2742. {
  2743. if (session_status() == PHP_SESSION_NONE) {
  2744. session_start();
  2745. }
  2746. $credentials = $this->getAuthorizationCredentials($request);
  2747. if ($credentials) {
  2748. list($username, $password) = array('', '');
  2749. if (strpos($credentials, ':') !== false) {
  2750. list($username, $password) = explode(':', $credentials, 2);
  2751. }
  2752. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  2753. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  2754. $_SESSION['username'] = $validUser;
  2755. if (!$validUser) {
  2756. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  2757. }
  2758. if (!headers_sent()) {
  2759. session_regenerate_id();
  2760. }
  2761. }
  2762. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  2763. $authenticationMode = $this->getProperty('mode', 'required');
  2764. if ($authenticationMode == 'required') {
  2765. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  2766. $realm = $this->getProperty('realm', 'Username and password required');
  2767. $response->addHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  2768. return $response;
  2769. }
  2770. }
  2771. return $this->next->handle($request);
  2772. }
  2773. }
  2774. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  2775. class CorsMiddleware extends Middleware
  2776. {
  2777. private function isOriginAllowed(String $origin, String $allowedOrigins): bool
  2778. {
  2779. $found = false;
  2780. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  2781. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  2782. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  2783. if (preg_match($regex, $origin)) {
  2784. $found = true;
  2785. break;
  2786. }
  2787. }
  2788. return $found;
  2789. }
  2790. public function handle(Request $request): Response
  2791. {
  2792. $method = $request->getMethod();
  2793. $origin = $request->getHeader('Origin');
  2794. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  2795. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  2796. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  2797. } elseif ($method == 'OPTIONS') {
  2798. $response = new Response(Response::OK, '');
  2799. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  2800. if ($allowHeaders) {
  2801. $response->addHeader('Access-Control-Allow-Headers', $allowHeaders);
  2802. }
  2803. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  2804. if ($allowMethods) {
  2805. $response->addHeader('Access-Control-Allow-Methods', $allowMethods);
  2806. }
  2807. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  2808. if ($allowCredentials) {
  2809. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  2810. }
  2811. $maxAge = $this->getProperty('maxAge', '1728000');
  2812. if ($maxAge) {
  2813. $response->addHeader('Access-Control-Max-Age', $maxAge);
  2814. }
  2815. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  2816. if ($exposeHeaders) {
  2817. $response->addHeader('Access-Control-Expose-Headers', $exposeHeaders);
  2818. }
  2819. } else {
  2820. $response = $this->next->handle($request);
  2821. }
  2822. if ($origin) {
  2823. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  2824. if ($allowCredentials) {
  2825. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  2826. }
  2827. $response->addHeader('Access-Control-Allow-Origin', $origin);
  2828. }
  2829. return $response;
  2830. }
  2831. }
  2832. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  2833. class CustomizationMiddleware extends Middleware
  2834. {
  2835. private $reflection;
  2836. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2837. {
  2838. parent::__construct($router, $responder, $properties);
  2839. $this->reflection = $reflection;
  2840. $this->utils = new RequestUtils($reflection);
  2841. }
  2842. public function handle(Request $request): Response
  2843. {
  2844. $operation = $this->utils->getOperation($request);
  2845. $tableName = $request->getPathSegment(2);
  2846. $beforeHandler = $this->getProperty('beforeHandler', '');
  2847. $environment = (object) array();
  2848. if ($beforeHandler !== '') {
  2849. call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  2850. }
  2851. $response = $this->next->handle($request);
  2852. $afterHandler = $this->getProperty('afterHandler', '');
  2853. if ($afterHandler !== '') {
  2854. call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  2855. }
  2856. return $response;
  2857. }
  2858. }
  2859. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  2860. class FirewallMiddleware extends Middleware
  2861. {
  2862. private function ipMatch(String $ip, String $cidr): bool
  2863. {
  2864. if (strpos($cidr, '/') !== false) {
  2865. list($subnet, $mask) = explode('/', trim($cidr));
  2866. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  2867. return true;
  2868. }
  2869. } else {
  2870. if (ip2long($ip) == ip2long($cidr)) {
  2871. return true;
  2872. }
  2873. }
  2874. return false;
  2875. }
  2876. private function isIpAllowed(String $ipAddress, String $allowedIpAddresses): bool
  2877. {
  2878. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  2879. if ($this->ipMatch($ipAddress, $allowedIp)) {
  2880. return true;
  2881. }
  2882. }
  2883. return false;
  2884. }
  2885. public function handle(Request $request): Response
  2886. {
  2887. $reverseProxy = $this->getProperty('reverseProxy', '');
  2888. if ($reverseProxy) {
  2889. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  2890. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  2891. $ipAddress = $_SERVER['REMOTE_ADDR'];
  2892. } else {
  2893. $ipAddress = '127.0.0.1';
  2894. }
  2895. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  2896. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  2897. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  2898. } else {
  2899. $response = $this->next->handle($request);
  2900. }
  2901. return $response;
  2902. }
  2903. }
  2904. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  2905. class IpAddressMiddleware extends Middleware
  2906. {
  2907. private $reflection;
  2908. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2909. {
  2910. parent::__construct($router, $responder, $properties);
  2911. $this->reflection = $reflection;
  2912. $this->utils = new RequestUtils($reflection);
  2913. }
  2914. private function callHandler($record, String $operation, ReflectedTable $table) /*: object */
  2915. {
  2916. $context = (array) $record;
  2917. $columnNames = $this->getProperty('columns', '');
  2918. if ($columnNames) {
  2919. foreach (explode(',', $columnNames) as $columnName) {
  2920. if ($table->hasColumn($columnName)) {
  2921. if ($operation == 'create') {
  2922. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  2923. } else {
  2924. unset($context[$columnName]);
  2925. }
  2926. }
  2927. }
  2928. }
  2929. return (object) $context;
  2930. }
  2931. public function handle(Request $request): Response
  2932. {
  2933. $operation = $this->utils->getOperation($request);
  2934. if (in_array($operation, ['create', 'update', 'increment'])) {
  2935. $tableNames = $this->getProperty('tables', '');
  2936. $tableName = $request->getPathSegment(2);
  2937. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  2938. if ($this->reflection->hasTable($tableName)) {
  2939. $record = $request->getBody();
  2940. if ($record !== null) {
  2941. $table = $this->reflection->getTable($tableName);
  2942. if (is_array($record)) {
  2943. foreach ($record as &$r) {
  2944. $r = $this->callHandler($r, $operation, $table);
  2945. }
  2946. } else {
  2947. $record = $this->callHandler($record, $operation, $table);
  2948. }
  2949. $request->setBody($record);
  2950. }
  2951. }
  2952. }
  2953. }
  2954. return $this->next->handle($request);
  2955. }
  2956. }
  2957. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  2958. class JoinLimitsMiddleware extends Middleware
  2959. {
  2960. private $reflection;
  2961. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2962. {
  2963. parent::__construct($router, $responder, $properties);
  2964. $this->reflection = $reflection;
  2965. $this->utils = new RequestUtils($reflection);
  2966. }
  2967. public function handle(Request $request): Response
  2968. {
  2969. $operation = $this->utils->getOperation($request);
  2970. $params = $request->getParams();
  2971. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  2972. $maxDepth = (int) $this->getProperty('depth', '3');
  2973. $maxTables = (int) $this->getProperty('tables', '10');
  2974. $maxRecords = (int) $this->getProperty('records', '1000');
  2975. $tableCount = 0;
  2976. $joinPaths = array();
  2977. for ($i = 0; $i < count($params['join']); $i++) {
  2978. $joinPath = array();
  2979. $tables = explode(',', $params['join'][$i]);
  2980. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  2981. array_push($joinPath, $tables[$depth]);
  2982. $tableCount += 1;
  2983. if ($tableCount == $maxTables) {
  2984. break;
  2985. }
  2986. }
  2987. array_push($joinPaths, implode(',', $joinPath));
  2988. if ($tableCount == $maxTables) {
  2989. break;
  2990. }
  2991. }
  2992. $params['join'] = $joinPaths;
  2993. $request->setParams($params);
  2994. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  2995. }
  2996. return $this->next->handle($request);
  2997. }
  2998. }
  2999. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  3000. class JwtAuthMiddleware extends Middleware
  3001. {
  3002. private function getVerifiedClaims(String $token, int $time, int $leeway, int $ttl, String $secret, array $requirements): array
  3003. {
  3004. $algorithms = array(
  3005. 'HS256' => 'sha256',
  3006. 'HS384' => 'sha384',
  3007. 'HS512' => 'sha512',
  3008. 'RS256' => 'sha256',
  3009. 'RS384' => 'sha384',
  3010. 'RS512' => 'sha512',
  3011. );
  3012. $token = explode('.', $token);
  3013. if (count($token) < 3) {
  3014. return array();
  3015. }
  3016. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  3017. if (!$secret) {
  3018. return array();
  3019. }
  3020. if ($header['typ'] != 'JWT') {
  3021. return array();
  3022. }
  3023. $algorithm = $header['alg'];
  3024. if (!isset($algorithms[$algorithm])) {
  3025. return array();
  3026. }
  3027. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  3028. return array();
  3029. }
  3030. $hmac = $algorithms[$algorithm];
  3031. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  3032. $data = "$token[0].$token[1]";
  3033. switch ($algorithm[0]) {
  3034. case 'H':
  3035. $hash = hash_hmac($hmac, $data, $secret, true);
  3036. if (function_exists('hash_equals')) {
  3037. $equals = hash_equals($signature, $hash);
  3038. } else {
  3039. $equals = $signature == $hash;
  3040. }
  3041. if (!$equals) {
  3042. return array();
  3043. }
  3044. break;
  3045. case 'R':
  3046. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  3047. if (!$equals) {
  3048. return array();
  3049. }
  3050. break;
  3051. }
  3052. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  3053. if (!$claims) {
  3054. return array();
  3055. }
  3056. foreach ($requirements as $field => $values) {
  3057. if (!empty($values)) {
  3058. if ($field != 'alg') {
  3059. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  3060. return array();
  3061. }
  3062. }
  3063. }
  3064. }
  3065. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  3066. return array();
  3067. }
  3068. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  3069. return array();
  3070. }
  3071. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  3072. return array();
  3073. }
  3074. if (isset($claims['iat']) && !isset($claims['exp'])) {
  3075. if ($time - $leeway > $claims['iat'] + $ttl) {
  3076. return array();
  3077. }
  3078. }
  3079. return $claims;
  3080. }
  3081. private function getClaims(String $token): array
  3082. {
  3083. $time = (int) $this->getProperty('time', time());
  3084. $leeway = (int) $this->getProperty('leeway', '5');
  3085. $ttl = (int) $this->getProperty('ttl', '30');
  3086. $secret = $this->getProperty('secret', '');
  3087. $requirements = array(
  3088. 'alg' => $this->getArrayProperty('algorithms', ''),
  3089. 'aud' => $this->getArrayProperty('audiences', ''),
  3090. 'iss' => $this->getArrayProperty('issuers', ''),
  3091. );
  3092. if (!$secret) {
  3093. return array();
  3094. }
  3095. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  3096. }
  3097. private function getAuthorizationToken(Request $request): String
  3098. {
  3099. $header = $this->getProperty('header', 'X-Authorization');
  3100. $parts = explode(' ', trim($request->getHeader($header)), 2);
  3101. if (count($parts) != 2) {
  3102. return '';
  3103. }
  3104. if ($parts[0] != 'Bearer') {
  3105. return '';
  3106. }
  3107. return $parts[1];
  3108. }
  3109. public function handle(Request $request): Response
  3110. {
  3111. if (session_status() == PHP_SESSION_NONE) {
  3112. session_start();
  3113. }
  3114. $token = $this->getAuthorizationToken($request);
  3115. if ($token) {
  3116. $claims = $this->getClaims($token);
  3117. $_SESSION['claims'] = $claims;
  3118. if (empty($claims)) {
  3119. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  3120. }
  3121. if (!headers_sent()) {
  3122. session_regenerate_id();
  3123. }
  3124. }
  3125. if (empty($_SESSION['claims'])) {
  3126. $authenticationMode = $this->getProperty('mode', 'required');
  3127. if ($authenticationMode == 'required') {
  3128. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  3129. }
  3130. }
  3131. return $this->next->handle($request);
  3132. }
  3133. }
  3134. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  3135. class MultiTenancyMiddleware extends Middleware
  3136. {
  3137. private $reflection;
  3138. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3139. {
  3140. parent::__construct($router, $responder, $properties);
  3141. $this->reflection = $reflection;
  3142. $this->utils = new RequestUtils($reflection);
  3143. }
  3144. private function getCondition(String $tableName, array $pairs): Condition
  3145. {
  3146. $condition = new NoCondition();
  3147. $table = $this->reflection->getTable($tableName);
  3148. foreach ($pairs as $k => $v) {
  3149. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  3150. }
  3151. return $condition;
  3152. }
  3153. private function getPairs($handler, String $operation, String $tableName): array
  3154. {
  3155. $result = array();
  3156. $pairs = call_user_func($handler, $operation, $tableName);
  3157. $table = $this->reflection->getTable($tableName);
  3158. foreach ($pairs as $k => $v) {
  3159. if ($table->hasColumn($k)) {
  3160. $result[$k] = $v;
  3161. }
  3162. }
  3163. return $result;
  3164. }
  3165. private function handleRecord(Request $request, String $operation, array $pairs) /*: void*/
  3166. {
  3167. $record = $request->getBody();
  3168. if ($record === null) {
  3169. return;
  3170. }
  3171. $multi = is_array($record);
  3172. $records = $multi ? $record : [$record];
  3173. foreach ($records as &$record) {
  3174. foreach ($pairs as $column => $value) {
  3175. if ($operation == 'create') {
  3176. $record->$column = $value;
  3177. } else {
  3178. if (isset($record->$column)) {
  3179. unset($record->$column);
  3180. }
  3181. }
  3182. }
  3183. }
  3184. $request->setBody($multi ? $records : $records[0]);
  3185. }
  3186. public function handle(Request $request): Response
  3187. {
  3188. $handler = $this->getProperty('handler', '');
  3189. if ($handler !== '') {
  3190. $path = $request->getPathSegment(1);
  3191. if ($path == 'records') {
  3192. $operation = $this->utils->getOperation($request);
  3193. $tableNames = $this->utils->getTableNames($request);
  3194. foreach ($tableNames as $i => $tableName) {
  3195. if (!$this->reflection->hasTable($tableName)) {
  3196. continue;
  3197. }
  3198. $pairs = $this->getPairs($handler, $operation, $tableName);
  3199. if ($i == 0) {
  3200. if (in_array($operation, ['create', 'update', 'increment'])) {
  3201. $this->handleRecord($request, $operation, $pairs);
  3202. }
  3203. }
  3204. $condition = $this->getCondition($tableName, $pairs);
  3205. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  3206. }
  3207. }
  3208. }
  3209. return $this->next->handle($request);
  3210. }
  3211. }
  3212. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  3213. class PageLimitsMiddleware extends Middleware
  3214. {
  3215. private $reflection;
  3216. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3217. {
  3218. parent::__construct($router, $responder, $properties);
  3219. $this->reflection = $reflection;
  3220. $this->utils = new RequestUtils($reflection);
  3221. }
  3222. public function handle(Request $request): Response
  3223. {
  3224. $operation = $this->utils->getOperation($request);
  3225. if ($operation == 'list') {
  3226. $params = $request->getParams();
  3227. $maxPage = (int) $this->getProperty('pages', '100');
  3228. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  3229. if (strpos($params['page'][0], ',') === false) {
  3230. $page = $params['page'][0];
  3231. } else {
  3232. list($page, $size) = explode(',', $params['page'][0], 2);
  3233. }
  3234. if ($page > $maxPage) {
  3235. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  3236. }
  3237. }
  3238. $maxSize = (int) $this->getProperty('records', '1000');
  3239. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  3240. $params['size'] = array($maxSize);
  3241. } else {
  3242. $params['size'] = array(min($params['size'][0], $maxSize));
  3243. }
  3244. $request->setParams($params);
  3245. }
  3246. return $this->next->handle($request);
  3247. }
  3248. }
  3249. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  3250. class SanitationMiddleware extends Middleware
  3251. {
  3252. private $reflection;
  3253. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3254. {
  3255. parent::__construct($router, $responder, $properties);
  3256. $this->reflection = $reflection;
  3257. $this->utils = new RequestUtils($reflection);
  3258. }
  3259. private function callHandler($handler, $record, String $operation, ReflectedTable $table) /*: object */
  3260. {
  3261. $context = (array) $record;
  3262. $tableName = $table->getName();
  3263. foreach ($context as $columnName => &$value) {
  3264. if ($table->hasColumn($columnName)) {
  3265. $column = $table->getColumn($columnName);
  3266. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  3267. }
  3268. }
  3269. return (object) $context;
  3270. }
  3271. public function handle(Request $request): Response
  3272. {
  3273. $operation = $this->utils->getOperation($request);
  3274. if (in_array($operation, ['create', 'update', 'increment'])) {
  3275. $tableName = $request->getPathSegment(2);
  3276. if ($this->reflection->hasTable($tableName)) {
  3277. $record = $request->getBody();
  3278. if ($record !== null) {
  3279. $handler = $this->getProperty('handler', '');
  3280. if ($handler !== '') {
  3281. $table = $this->reflection->getTable($tableName);
  3282. if (is_array($record)) {
  3283. foreach ($record as &$r) {
  3284. $r = $this->callHandler($handler, $r, $operation, $table);
  3285. }
  3286. } else {
  3287. $record = $this->callHandler($handler, $record, $operation, $table);
  3288. }
  3289. $request->setBody($record);
  3290. }
  3291. }
  3292. }
  3293. }
  3294. return $this->next->handle($request);
  3295. }
  3296. }
  3297. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  3298. class ValidationMiddleware extends Middleware
  3299. {
  3300. private $reflection;
  3301. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3302. {
  3303. parent::__construct($router, $responder, $properties);
  3304. $this->reflection = $reflection;
  3305. $this->utils = new RequestUtils($reflection);
  3306. }
  3307. private function callHandler($handler, $record, String $operation, ReflectedTable $table) /*: Response?*/
  3308. {
  3309. $context = (array) $record;
  3310. $details = array();
  3311. $tableName = $table->getName();
  3312. foreach ($context as $columnName => $value) {
  3313. if ($table->hasColumn($columnName)) {
  3314. $column = $table->getColumn($columnName);
  3315. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  3316. if ($valid !== true && $valid !== '') {
  3317. $details[$columnName] = $valid;
  3318. }
  3319. }
  3320. }
  3321. if (count($details) > 0) {
  3322. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  3323. }
  3324. return null;
  3325. }
  3326. public function handle(Request $request): Response
  3327. {
  3328. $operation = $this->utils->getOperation($request);
  3329. if (in_array($operation, ['create', 'update', 'increment'])) {
  3330. $tableName = $request->getPathSegment(2);
  3331. if ($this->reflection->hasTable($tableName)) {
  3332. $record = $request->getBody();
  3333. if ($record !== null) {
  3334. $handler = $this->getProperty('handler', '');
  3335. if ($handler !== '') {
  3336. $table = $this->reflection->getTable($tableName);
  3337. if (is_array($record)) {
  3338. foreach ($record as $r) {
  3339. $response = $this->callHandler($handler, $r, $operation, $table);
  3340. if ($response !== null) {
  3341. return $response;
  3342. }
  3343. }
  3344. } else {
  3345. $response = $this->callHandler($handler, $record, $operation, $table);
  3346. if ($response !== null) {
  3347. return $response;
  3348. }
  3349. }
  3350. }
  3351. }
  3352. }
  3353. }
  3354. return $this->next->handle($request);
  3355. }
  3356. }
  3357. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  3358. class XsrfMiddleware extends Middleware
  3359. {
  3360. private function getToken(): String
  3361. {
  3362. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  3363. if (isset($_COOKIE[$cookieName])) {
  3364. $token = $_COOKIE[$cookieName];
  3365. } else {
  3366. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  3367. $token = bin2hex(random_bytes(8));
  3368. if (!headers_sent()) {
  3369. setcookie($cookieName, $token, 0, '', '', $secure);
  3370. }
  3371. }
  3372. return $token;
  3373. }
  3374. public function handle(Request $request): Response
  3375. {
  3376. $token = $this->getToken();
  3377. $method = $request->getMethod();
  3378. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  3379. if (!in_array($method, $excludeMethods)) {
  3380. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  3381. if ($token != $request->getHeader($headerName)) {
  3382. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  3383. }
  3384. }
  3385. return $this->next->handle($request);
  3386. }
  3387. }
  3388. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  3389. class OpenApiBuilder
  3390. {
  3391. private $openapi;
  3392. private $reflection;
  3393. private $operations = [
  3394. 'list' => 'get',
  3395. 'create' => 'post',
  3396. 'read' => 'get',
  3397. 'update' => 'put',
  3398. 'delete' => 'delete',
  3399. 'increment' => 'patch',
  3400. ];
  3401. private $types = [
  3402. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  3403. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  3404. 'varchar' => ['type' => 'string'],
  3405. 'clob' => ['type' => 'string'],
  3406. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  3407. 'blob' => ['type' => 'string', 'format' => 'byte'],
  3408. 'decimal' => ['type' => 'string'],
  3409. 'float' => ['type' => 'number', 'format' => 'float'],
  3410. 'double' => ['type' => 'number', 'format' => 'double'],
  3411. 'date' => ['type' => 'string', 'format' => 'date'],
  3412. 'time' => ['type' => 'string', 'format' => 'date-time'],
  3413. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  3414. 'geometry' => ['type' => 'string'],
  3415. 'boolean' => ['type' => 'boolean'],
  3416. ];
  3417. public function __construct(ReflectionService $reflection, $base)
  3418. {
  3419. $this->reflection = $reflection;
  3420. $this->openapi = new OpenApiDefinition($base);
  3421. }
  3422. private function getServerUrl(): String
  3423. {
  3424. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  3425. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  3426. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  3427. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  3428. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  3429. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  3430. }
  3431. private function getAllTableReferences(): array
  3432. {
  3433. $tableReferences = array();
  3434. foreach ($this->reflection->getTableNames() as $tableName) {
  3435. $table = $this->reflection->getTable($tableName);
  3436. foreach ($table->getColumnNames() as $columnName) {
  3437. $column = $table->getColumn($columnName);
  3438. $referencedTableName = $column->getFk();
  3439. if ($referencedTableName) {
  3440. if (!isset($tableReferences[$referencedTableName])) {
  3441. $tableReferences[$referencedTableName] = array();
  3442. }
  3443. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  3444. }
  3445. }
  3446. }
  3447. return $tableReferences;
  3448. }
  3449. public function build(): OpenApiDefinition
  3450. {
  3451. $this->openapi->set("openapi", "3.0.0");
  3452. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  3453. $this->openapi->set("servers|0|url", $this->getServerUrl());
  3454. }
  3455. $tableNames = $this->reflection->getTableNames();
  3456. foreach ($tableNames as $tableName) {
  3457. $this->setPath($tableName);
  3458. }
  3459. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  3460. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  3461. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  3462. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  3463. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  3464. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  3465. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  3466. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  3467. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  3468. $tableReferences = $this->getAllTableReferences();
  3469. foreach ($tableNames as $tableName) {
  3470. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  3471. $this->setComponentSchema($tableName, $references);
  3472. $this->setComponentResponse($tableName);
  3473. $this->setComponentRequestBody($tableName);
  3474. }
  3475. $this->setComponentParameters();
  3476. foreach ($tableNames as $index => $tableName) {
  3477. $this->setTag($index, $tableName);
  3478. }
  3479. return $this->openapi;
  3480. }
  3481. private function isOperationOnTableAllowed(String $operation, String $tableName): bool
  3482. {
  3483. $tableHandler = VariableStore::get('authorization.tableHandler');
  3484. if (!$tableHandler) {
  3485. return true;
  3486. }
  3487. return (bool) call_user_func($tableHandler, $operation, $tableName);
  3488. }
  3489. private function isOperationOnColumnAllowed(String $operation, String $tableName, String $columnName): bool
  3490. {
  3491. $columnHandler = VariableStore::get('authorization.columnHandler');
  3492. if (!$columnHandler) {
  3493. return true;
  3494. }
  3495. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  3496. }
  3497. private function setPath(String $tableName) /*: void*/
  3498. {
  3499. $table = $this->reflection->getTable($tableName);
  3500. $type = $table->getType();
  3501. $pk = $table->getPk();
  3502. $pkName = $pk ? $pk->getName() : '';
  3503. foreach ($this->operations as $operation => $method) {
  3504. if (!$pkName && $operation != 'list') {
  3505. continue;
  3506. }
  3507. if ($type != 'table' && $operation != 'list') {
  3508. continue;
  3509. }
  3510. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3511. continue;
  3512. }
  3513. $parameters = [];
  3514. if (in_array($operation, ['list', 'create'])) {
  3515. $path = sprintf('/records/%s', $tableName);
  3516. if ($operation == 'list') {
  3517. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  3518. }
  3519. } else {
  3520. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  3521. if ($operation == 'read') {
  3522. $parameters = ['pk', 'include', 'exclude', 'join'];
  3523. } else {
  3524. $parameters = ['pk'];
  3525. }
  3526. }
  3527. foreach ($parameters as $p => $parameter) {
  3528. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  3529. }
  3530. if (in_array($operation, ['create', 'update', 'increment'])) {
  3531. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  3532. }
  3533. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  3534. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  3535. switch ($operation) {
  3536. case 'list':
  3537. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  3538. break;
  3539. case 'create':
  3540. if ($pk->getType() == 'integer') {
  3541. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  3542. } else {
  3543. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  3544. }
  3545. break;
  3546. case 'read':
  3547. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  3548. break;
  3549. case 'update':
  3550. case 'delete':
  3551. case 'increment':
  3552. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  3553. break;
  3554. }
  3555. }
  3556. }
  3557. private function setComponentSchema(String $tableName, array $references) /*: void*/
  3558. {
  3559. $table = $this->reflection->getTable($tableName);
  3560. $type = $table->getType();
  3561. $pk = $table->getPk();
  3562. $pkName = $pk ? $pk->getName() : '';
  3563. foreach ($this->operations as $operation => $method) {
  3564. if (!$pkName && $operation != 'list') {
  3565. continue;
  3566. }
  3567. if ($type != 'table' && $operation != 'list') {
  3568. continue;
  3569. }
  3570. if ($operation == 'delete') {
  3571. continue;
  3572. }
  3573. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3574. continue;
  3575. }
  3576. if ($operation == 'list') {
  3577. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  3578. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  3579. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  3580. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  3581. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  3582. } else {
  3583. $prefix = "components|schemas|$operation-$tableName";
  3584. }
  3585. $this->openapi->set("$prefix|type", "object");
  3586. foreach ($table->getColumnNames() as $columnName) {
  3587. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  3588. continue;
  3589. }
  3590. $column = $table->getColumn($columnName);
  3591. $properties = $this->types[$column->getType()];
  3592. foreach ($properties as $key => $value) {
  3593. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  3594. }
  3595. if ($column->getPk()) {
  3596. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  3597. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  3598. }
  3599. $fk = $column->getFk();
  3600. if ($fk) {
  3601. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  3602. }
  3603. }
  3604. }
  3605. }
  3606. private function setComponentResponse(String $tableName) /*: void*/
  3607. {
  3608. $table = $this->reflection->getTable($tableName);
  3609. $type = $table->getType();
  3610. $pk = $table->getPk();
  3611. $pkName = $pk ? $pk->getName() : '';
  3612. foreach (['list', 'read'] as $operation) {
  3613. if (!$pkName && $operation != 'list') {
  3614. continue;
  3615. }
  3616. if ($type != 'table' && $operation != 'list') {
  3617. continue;
  3618. }
  3619. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3620. continue;
  3621. }
  3622. if ($operation == 'list') {
  3623. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  3624. } else {
  3625. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  3626. }
  3627. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  3628. }
  3629. }
  3630. private function setComponentRequestBody(String $tableName) /*: void*/
  3631. {
  3632. $table = $this->reflection->getTable($tableName);
  3633. $type = $table->getType();
  3634. $pk = $table->getPk();
  3635. $pkName = $pk ? $pk->getName() : '';
  3636. if ($pkName && $type == 'table') {
  3637. foreach (['create', 'update', 'increment'] as $operation) {
  3638. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3639. continue;
  3640. }
  3641. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  3642. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  3643. }
  3644. }
  3645. }
  3646. private function setComponentParameters() /*: void*/
  3647. {
  3648. $this->openapi->set("components|parameters|pk|name", "id");
  3649. $this->openapi->set("components|parameters|pk|in", "path");
  3650. $this->openapi->set("components|parameters|pk|schema|type", "string");
  3651. $this->openapi->set("components|parameters|pk|description", "primary key value");
  3652. $this->openapi->set("components|parameters|pk|required", true);
  3653. $this->openapi->set("components|parameters|filter|name", "filter");
  3654. $this->openapi->set("components|parameters|filter|in", "query");
  3655. $this->openapi->set("components|parameters|filter|schema|type", "array");
  3656. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  3657. $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");
  3658. $this->openapi->set("components|parameters|filter|required", false);
  3659. $this->openapi->set("components|parameters|include|name", "include");
  3660. $this->openapi->set("components|parameters|include|in", "query");
  3661. $this->openapi->set("components|parameters|include|schema|type", "string");
  3662. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  3663. $this->openapi->set("components|parameters|include|required", false);
  3664. $this->openapi->set("components|parameters|exclude|name", "exclude");
  3665. $this->openapi->set("components|parameters|exclude|in", "query");
  3666. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  3667. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  3668. $this->openapi->set("components|parameters|exclude|required", false);
  3669. $this->openapi->set("components|parameters|order|name", "order");
  3670. $this->openapi->set("components|parameters|order|in", "query");
  3671. $this->openapi->set("components|parameters|order|schema|type", "array");
  3672. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  3673. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  3674. $this->openapi->set("components|parameters|order|required", false);
  3675. $this->openapi->set("components|parameters|size|name", "size");
  3676. $this->openapi->set("components|parameters|size|in", "query");
  3677. $this->openapi->set("components|parameters|size|schema|type", "string");
  3678. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  3679. $this->openapi->set("components|parameters|size|required", false);
  3680. $this->openapi->set("components|parameters|page|name", "page");
  3681. $this->openapi->set("components|parameters|page|in", "query");
  3682. $this->openapi->set("components|parameters|page|schema|type", "string");
  3683. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  3684. $this->openapi->set("components|parameters|page|required", false);
  3685. $this->openapi->set("components|parameters|join|name", "join");
  3686. $this->openapi->set("components|parameters|join|in", "query");
  3687. $this->openapi->set("components|parameters|join|schema|type", "array");
  3688. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  3689. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  3690. $this->openapi->set("components|parameters|join|required", false);
  3691. }
  3692. private function setTag(int $index, String $tableName) /*: void*/
  3693. {
  3694. $this->openapi->set("tags|$index|name", "$tableName");
  3695. $this->openapi->set("tags|$index|description", "$tableName operations");
  3696. }
  3697. }
  3698. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  3699. class OpenApiDefinition implements \JsonSerializable
  3700. {
  3701. private $root;
  3702. public function __construct($base)
  3703. {
  3704. $this->root = $base;
  3705. }
  3706. public function set(String $path, $value) /*: void*/
  3707. {
  3708. $parts = explode('|', trim($path, '|'));
  3709. $current = &$this->root;
  3710. while (count($parts) > 0) {
  3711. $part = array_shift($parts);
  3712. if (!isset($current[$part])) {
  3713. $current[$part] = [];
  3714. }
  3715. $current = &$current[$part];
  3716. }
  3717. $current = $value;
  3718. }
  3719. public function has(String $path): bool
  3720. {
  3721. $parts = explode('|', trim($path, '|'));
  3722. $current = &$this->root;
  3723. while (count($parts) > 0) {
  3724. $part = array_shift($parts);
  3725. if (!isset($current[$part])) {
  3726. return false;
  3727. }
  3728. $current = &$current[$part];
  3729. }
  3730. return true;
  3731. }
  3732. public function jsonSerialize()
  3733. {
  3734. return $this->root;
  3735. }
  3736. }
  3737. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  3738. class OpenApiService
  3739. {
  3740. private $builder;
  3741. public function __construct(ReflectionService $reflection, array $base)
  3742. {
  3743. $this->builder = new OpenApiBuilder($reflection, $base);
  3744. }
  3745. public function get(): OpenApiDefinition
  3746. {
  3747. return $this->builder->build();
  3748. }
  3749. }
  3750. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  3751. class AndCondition extends Condition
  3752. {
  3753. private $conditions;
  3754. public function __construct(Condition $condition1, Condition $condition2)
  3755. {
  3756. $this->conditions = [$condition1, $condition2];
  3757. }
  3758. public function _and(Condition $condition): Condition
  3759. {
  3760. if ($condition instanceof NoCondition) {
  3761. return $this;
  3762. }
  3763. $this->conditions[] = $condition;
  3764. return $this;
  3765. }
  3766. public function getConditions(): array
  3767. {
  3768. return $this->conditions;
  3769. }
  3770. public static function fromArray(array $conditions): Condition
  3771. {
  3772. $condition = new NoCondition();
  3773. foreach ($conditions as $c) {
  3774. $condition = $condition->_and($c);
  3775. }
  3776. return $condition;
  3777. }
  3778. }
  3779. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  3780. class ColumnCondition extends Condition
  3781. {
  3782. private $column;
  3783. private $operator;
  3784. private $value;
  3785. public function __construct(ReflectedColumn $column, String $operator, String $value)
  3786. {
  3787. $this->column = $column;
  3788. $this->operator = $operator;
  3789. $this->value = $value;
  3790. }
  3791. public function getColumn(): ReflectedColumn
  3792. {
  3793. return $this->column;
  3794. }
  3795. public function getOperator(): String
  3796. {
  3797. return $this->operator;
  3798. }
  3799. public function getValue(): String
  3800. {
  3801. return $this->value;
  3802. }
  3803. }
  3804. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  3805. abstract class Condition
  3806. {
  3807. public function _and(Condition $condition): Condition
  3808. {
  3809. if ($condition instanceof NoCondition) {
  3810. return $this;
  3811. }
  3812. return new AndCondition($this, $condition);
  3813. }
  3814. public function _or(Condition $condition): Condition
  3815. {
  3816. if ($condition instanceof NoCondition) {
  3817. return $this;
  3818. }
  3819. return new OrCondition($this, $condition);
  3820. }
  3821. public function _not(): Condition
  3822. {
  3823. return new NotCondition($this);
  3824. }
  3825. public static function fromString(ReflectedTable $table, String $value): Condition
  3826. {
  3827. $condition = new NoCondition();
  3828. $parts = explode(',', $value, 3);
  3829. if (count($parts) < 2) {
  3830. return $condition;
  3831. }
  3832. if (count($parts) < 3) {
  3833. $parts[2] = '';
  3834. }
  3835. $field = $table->getColumn($parts[0]);
  3836. $command = $parts[1];
  3837. $negate = false;
  3838. $spatial = false;
  3839. if (strlen($command) > 2) {
  3840. if (substr($command, 0, 1) == 'n') {
  3841. $negate = true;
  3842. $command = substr($command, 1);
  3843. }
  3844. if (substr($command, 0, 1) == 's') {
  3845. $spatial = true;
  3846. $command = substr($command, 1);
  3847. }
  3848. }
  3849. if ($spatial) {
  3850. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  3851. $condition = new SpatialCondition($field, $command, $parts[2]);
  3852. }
  3853. } else {
  3854. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  3855. $condition = new ColumnCondition($field, $command, $parts[2]);
  3856. }
  3857. }
  3858. if ($negate) {
  3859. $condition = $condition->_not();
  3860. }
  3861. return $condition;
  3862. }
  3863. }
  3864. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  3865. class NoCondition extends Condition
  3866. {
  3867. public function _and(Condition $condition): Condition
  3868. {
  3869. return $condition;
  3870. }
  3871. public function _or(Condition $condition): Condition
  3872. {
  3873. return $condition;
  3874. }
  3875. public function _not(): Condition
  3876. {
  3877. return $this;
  3878. }
  3879. }
  3880. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  3881. class NotCondition extends Condition
  3882. {
  3883. private $condition;
  3884. public function __construct(Condition $condition)
  3885. {
  3886. $this->condition = $condition;
  3887. }
  3888. public function getCondition(): Condition
  3889. {
  3890. return $this->condition;
  3891. }
  3892. }
  3893. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  3894. class OrCondition extends Condition
  3895. {
  3896. private $conditions;
  3897. public function __construct(Condition $condition1, Condition $condition2)
  3898. {
  3899. $this->conditions = [$condition1, $condition2];
  3900. }
  3901. public function _or(Condition $condition): Condition
  3902. {
  3903. if ($condition instanceof NoCondition) {
  3904. return $this;
  3905. }
  3906. $this->conditions[] = $condition;
  3907. return $this;
  3908. }
  3909. public function getConditions(): array
  3910. {
  3911. return $this->conditions;
  3912. }
  3913. public static function fromArray(array $conditions): Condition
  3914. {
  3915. $condition = new NoCondition();
  3916. foreach ($conditions as $c) {
  3917. $condition = $condition->_or($c);
  3918. }
  3919. return $condition;
  3920. }
  3921. }
  3922. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  3923. class SpatialCondition extends ColumnCondition
  3924. {
  3925. }
  3926. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  3927. class ErrorDocument implements \JsonSerializable
  3928. {
  3929. public $code;
  3930. public $message;
  3931. public $details;
  3932. public function __construct(ErrorCode $errorCode, String $argument, $details)
  3933. {
  3934. $this->code = $errorCode->getCode();
  3935. $this->message = $errorCode->getMessage($argument);
  3936. $this->details = $details;
  3937. }
  3938. public function getCode(): int
  3939. {
  3940. return $this->code;
  3941. }
  3942. public function getMessage(): String
  3943. {
  3944. return $this->message;
  3945. }
  3946. public function serialize()
  3947. {
  3948. return [
  3949. 'code' => $this->code,
  3950. 'message' => $this->message,
  3951. 'details' => $this->details,
  3952. ];
  3953. }
  3954. public function jsonSerialize()
  3955. {
  3956. return array_filter($this->serialize());
  3957. }
  3958. }
  3959. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  3960. class ListDocument implements \JsonSerializable
  3961. {
  3962. private $records;
  3963. private $results;
  3964. public function __construct(array $records, int $results)
  3965. {
  3966. $this->records = $records;
  3967. $this->results = $results;
  3968. }
  3969. public function getRecords(): array
  3970. {
  3971. return $this->records;
  3972. }
  3973. public function getResults(): int
  3974. {
  3975. return $this->results;
  3976. }
  3977. public function serialize()
  3978. {
  3979. return [
  3980. 'records' => $this->records,
  3981. 'results' => $this->results,
  3982. ];
  3983. }
  3984. public function jsonSerialize()
  3985. {
  3986. return array_filter($this->serialize(), function ($v) {
  3987. return $v !== 0;
  3988. });
  3989. }
  3990. }
  3991. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  3992. class ColumnIncluder
  3993. {
  3994. private function isMandatory(String $tableName, String $columnName, array $params): bool
  3995. {
  3996. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  3997. }
  3998. private function select(String $tableName, bool $primaryTable, array $params, String $paramName,
  3999. array $columnNames, bool $include): array{
  4000. if (!isset($params[$paramName])) {
  4001. return $columnNames;
  4002. }
  4003. $columns = array();
  4004. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  4005. $columns[$columnName] = true;
  4006. }
  4007. $result = array();
  4008. foreach ($columnNames as $columnName) {
  4009. $match = isset($columns['*.*']);
  4010. if (!$match) {
  4011. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  4012. }
  4013. if ($primaryTable && !$match) {
  4014. $match = isset($columns['*']) || isset($columns[$columnName]);
  4015. }
  4016. if ($match) {
  4017. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  4018. $result[] = $columnName;
  4019. }
  4020. } else {
  4021. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  4022. $result[] = $columnName;
  4023. }
  4024. }
  4025. }
  4026. return $result;
  4027. }
  4028. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  4029. {
  4030. $tableName = $table->getName();
  4031. $results = $table->getColumnNames();
  4032. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  4033. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  4034. return $results;
  4035. }
  4036. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  4037. {
  4038. $results = array();
  4039. $columnNames = $this->getNames($table, $primaryTable, $params);
  4040. foreach ($columnNames as $columnName) {
  4041. if (property_exists($record, $columnName)) {
  4042. $results[$columnName] = $record->$columnName;
  4043. }
  4044. }
  4045. return $results;
  4046. }
  4047. }
  4048. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  4049. class ErrorCode
  4050. {
  4051. private $code;
  4052. private $message;
  4053. private $status;
  4054. const ERROR_NOT_FOUND = 9999;
  4055. const ROUTE_NOT_FOUND = 1000;
  4056. const TABLE_NOT_FOUND = 1001;
  4057. const ARGUMENT_COUNT_MISMATCH = 1002;
  4058. const RECORD_NOT_FOUND = 1003;
  4059. const ORIGIN_FORBIDDEN = 1004;
  4060. const COLUMN_NOT_FOUND = 1005;
  4061. const TABLE_ALREADY_EXISTS = 1006;
  4062. const COLUMN_ALREADY_EXISTS = 1007;
  4063. const HTTP_MESSAGE_NOT_READABLE = 1008;
  4064. const DUPLICATE_KEY_EXCEPTION = 1009;
  4065. const DATA_INTEGRITY_VIOLATION = 1010;
  4066. const AUTHENTICATION_REQUIRED = 1011;
  4067. const AUTHENTICATION_FAILED = 1012;
  4068. const INPUT_VALIDATION_FAILED = 1013;
  4069. const OPERATION_FORBIDDEN = 1014;
  4070. const OPERATION_NOT_SUPPORTED = 1015;
  4071. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  4072. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  4073. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  4074. const PAGINATION_FORBIDDEN = 1019;
  4075. private $values = [
  4076. 9999 => ["%s", Response::INTERNAL_SERVER_ERROR],
  4077. 1000 => ["Route '%s' not found", Response::NOT_FOUND],
  4078. 1001 => ["Table '%s' not found", Response::NOT_FOUND],
  4079. 1002 => ["Argument count mismatch in '%s'", Response::UNPROCESSABLE_ENTITY],
  4080. 1003 => ["Record '%s' not found", Response::NOT_FOUND],
  4081. 1004 => ["Origin '%s' is forbidden", Response::FORBIDDEN],
  4082. 1005 => ["Column '%s' not found", Response::NOT_FOUND],
  4083. 1006 => ["Table '%s' already exists", Response::CONFLICT],
  4084. 1007 => ["Column '%s' already exists", Response::CONFLICT],
  4085. 1008 => ["Cannot read HTTP message", Response::UNPROCESSABLE_ENTITY],
  4086. 1009 => ["Duplicate key exception", Response::CONFLICT],
  4087. 1010 => ["Data integrity violation", Response::CONFLICT],
  4088. 1011 => ["Authentication required", Response::UNAUTHORIZED],
  4089. 1012 => ["Authentication failed for '%s'", Response::FORBIDDEN],
  4090. 1013 => ["Input validation failed for '%s'", Response::UNPROCESSABLE_ENTITY],
  4091. 1014 => ["Operation forbidden", Response::FORBIDDEN],
  4092. 1015 => ["Operation '%s' not supported", Response::METHOD_NOT_ALLOWED],
  4093. 1016 => ["Temporary or permanently blocked", Response::FORBIDDEN],
  4094. 1017 => ["Bad or missing XSRF token", Response::FORBIDDEN],
  4095. 1018 => ["Only AJAX requests allowed for '%s'", Response::FORBIDDEN],
  4096. 1019 => ["Pagination forbidden", Response::FORBIDDEN],
  4097. ];
  4098. public function __construct(int $code)
  4099. {
  4100. if (!isset($this->values[$code])) {
  4101. $code = 9999;
  4102. }
  4103. $this->code = $code;
  4104. $this->message = $this->values[$code][0];
  4105. $this->status = $this->values[$code][1];
  4106. }
  4107. public function getCode(): int
  4108. {
  4109. return $this->code;
  4110. }
  4111. public function getMessage(String $argument): String
  4112. {
  4113. return sprintf($this->message, $argument);
  4114. }
  4115. public function getStatus(): int
  4116. {
  4117. return $this->status;
  4118. }
  4119. }
  4120. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  4121. class FilterInfo
  4122. {
  4123. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  4124. {
  4125. $key = 'filter' . implode('', $path);
  4126. if (isset($params[$key])) {
  4127. foreach ($params[$key] as $filter) {
  4128. $condition = Condition::fromString($table, $filter);
  4129. if (($condition instanceof NoCondition) == false) {
  4130. $conditions->put($path, $condition);
  4131. }
  4132. }
  4133. }
  4134. }
  4135. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  4136. {
  4137. $conditions = new PathTree();
  4138. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  4139. for ($n = ord('0'); $n <= ord('9'); $n++) {
  4140. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  4141. for ($l = ord('a'); $l <= ord('f'); $l++) {
  4142. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  4143. }
  4144. }
  4145. return $conditions;
  4146. }
  4147. private function combinePathTreeOfConditions(PathTree $tree): Condition
  4148. {
  4149. $andConditions = $tree->getValues();
  4150. $and = AndCondition::fromArray($andConditions);
  4151. $orConditions = [];
  4152. foreach ($tree->getKeys() as $p) {
  4153. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  4154. }
  4155. $or = OrCondition::fromArray($orConditions);
  4156. return $and->_and($or);
  4157. }
  4158. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  4159. {
  4160. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  4161. }
  4162. }
  4163. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  4164. class HabtmValues
  4165. {
  4166. public $pkValues;
  4167. public $fkValues;
  4168. public function __construct(array $pkValues, array $fkValues)
  4169. {
  4170. $this->pkValues = $pkValues;
  4171. $this->fkValues = $fkValues;
  4172. }
  4173. }
  4174. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  4175. class OrderingInfo
  4176. {
  4177. public function getColumnOrdering(ReflectedTable $table, array $params): array
  4178. {
  4179. $fields = array();
  4180. if (isset($params['order'])) {
  4181. foreach ($params['order'] as $order) {
  4182. $parts = explode(',', $order, 3);
  4183. $columnName = $parts[0];
  4184. if (!$table->hasColumn($columnName)) {
  4185. continue;
  4186. }
  4187. $ascending = 'ASC';
  4188. if (count($parts) > 1) {
  4189. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  4190. $ascending = 'DESC';
  4191. }
  4192. }
  4193. $fields[] = [$columnName, $ascending];
  4194. }
  4195. }
  4196. if (count($fields) == 0) {
  4197. return $this->getDefaultColumnOrdering($table);
  4198. }
  4199. return $fields;
  4200. }
  4201. public function getDefaultColumnOrdering(ReflectedTable $table): array
  4202. {
  4203. $fields = array();
  4204. $pk = $table->getPk();
  4205. if ($pk) {
  4206. $fields[] = [$pk->getName(), 'ASC'];
  4207. } else {
  4208. foreach ($table->getColumnNames() as $columnName) {
  4209. $fields[] = [$columnName, 'ASC'];
  4210. }
  4211. }
  4212. return $fields;
  4213. }
  4214. }
  4215. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  4216. class PaginationInfo
  4217. {
  4218. public $DEFAULT_PAGE_SIZE = 20;
  4219. public function hasPage(array $params): bool
  4220. {
  4221. return isset($params['page']);
  4222. }
  4223. public function getPageOffset(array $params): int
  4224. {
  4225. $offset = 0;
  4226. $pageSize = $this->getPageSize($params);
  4227. if (isset($params['page'])) {
  4228. foreach ($params['page'] as $page) {
  4229. $parts = explode(',', $page, 2);
  4230. $page = intval($parts[0]) - 1;
  4231. $offset = $page * $pageSize;
  4232. }
  4233. }
  4234. return $offset;
  4235. }
  4236. private function getPageSize(array $params): int
  4237. {
  4238. $pageSize = $this->DEFAULT_PAGE_SIZE;
  4239. if (isset($params['page'])) {
  4240. foreach ($params['page'] as $page) {
  4241. $parts = explode(',', $page, 2);
  4242. if (count($parts) > 1) {
  4243. $pageSize = intval($parts[1]);
  4244. }
  4245. }
  4246. }
  4247. return $pageSize;
  4248. }
  4249. public function getResultSize(array $params): int
  4250. {
  4251. $numberOfRows = -1;
  4252. if (isset($params['size'])) {
  4253. foreach ($params['size'] as $size) {
  4254. $numberOfRows = intval($size);
  4255. }
  4256. }
  4257. return $numberOfRows;
  4258. }
  4259. public function getPageLimit(array $params): int
  4260. {
  4261. $pageLimit = -1;
  4262. if ($this->hasPage($params)) {
  4263. $pageLimit = $this->getPageSize($params);
  4264. }
  4265. $resultSize = $this->getResultSize($params);
  4266. if ($resultSize >= 0) {
  4267. if ($pageLimit >= 0) {
  4268. $pageLimit = min($pageLimit, $resultSize);
  4269. } else {
  4270. $pageLimit = $resultSize;
  4271. }
  4272. }
  4273. return $pageLimit;
  4274. }
  4275. }
  4276. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  4277. class PathTree implements \JsonSerializable
  4278. {
  4279. const WILDCARD = '*';
  4280. private $tree;
  4281. public function __construct( /* object */&$tree = null)
  4282. {
  4283. if (!$tree) {
  4284. $tree = $this->newTree();
  4285. }
  4286. $this->tree = &$tree;
  4287. }
  4288. public function newTree()
  4289. {
  4290. return (object) ['values' => [], 'branches' => (object) []];
  4291. }
  4292. public function getKeys(): array
  4293. {
  4294. $branches = (array) $this->tree->branches;
  4295. return array_keys($branches);
  4296. }
  4297. public function getValues(): array
  4298. {
  4299. return $this->tree->values;
  4300. }
  4301. public function get(String $key): PathTree
  4302. {
  4303. if (!isset($this->tree->branches->$key)) {
  4304. return null;
  4305. }
  4306. return new PathTree($this->tree->branches->$key);
  4307. }
  4308. public function put(array $path, $value)
  4309. {
  4310. $tree = &$this->tree;
  4311. foreach ($path as $key) {
  4312. if (!isset($tree->branches->$key)) {
  4313. $tree->branches->$key = $this->newTree();
  4314. }
  4315. $tree = &$tree->branches->$key;
  4316. }
  4317. $tree->values[] = $value;
  4318. }
  4319. public function match(array $path): array
  4320. {
  4321. $star = self::WILDCARD;
  4322. $tree = &$this->tree;
  4323. foreach ($path as $key) {
  4324. if (isset($tree->branches->$key)) {
  4325. $tree = &$tree->branches->$key;
  4326. } else if (isset($tree->branches->$star)) {
  4327. $tree = &$tree->branches->$star;
  4328. } else {
  4329. return [];
  4330. }
  4331. }
  4332. return $tree->values;
  4333. }
  4334. public static function fromJson( /* object */$tree): PathTree
  4335. {
  4336. return new PathTree($tree);
  4337. }
  4338. public function jsonSerialize()
  4339. {
  4340. return $this->tree;
  4341. }
  4342. }
  4343. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  4344. class RecordService
  4345. {
  4346. private $db;
  4347. private $reflection;
  4348. private $columns;
  4349. private $joiner;
  4350. private $filters;
  4351. private $ordering;
  4352. private $pagination;
  4353. public function __construct(GenericDB $db, ReflectionService $reflection)
  4354. {
  4355. $this->db = $db;
  4356. $this->reflection = $reflection;
  4357. $this->columns = new ColumnIncluder();
  4358. $this->joiner = new RelationJoiner($reflection, $this->columns);
  4359. $this->filters = new FilterInfo();
  4360. $this->ordering = new OrderingInfo();
  4361. $this->pagination = new PaginationInfo();
  4362. }
  4363. private function sanitizeRecord(String $tableName, /* object */ $record, String $id)
  4364. {
  4365. $keyset = array_keys((array) $record);
  4366. foreach ($keyset as $key) {
  4367. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  4368. unset($record->$key);
  4369. }
  4370. }
  4371. if ($id != '') {
  4372. $pk = $this->reflection->getTable($tableName)->getPk();
  4373. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  4374. $field = $this->reflection->getTable($tableName)->getColumn($key);
  4375. if ($field->getName() == $pk->getName()) {
  4376. unset($record->$key);
  4377. }
  4378. }
  4379. }
  4380. }
  4381. public function hasTable(String $table): bool
  4382. {
  4383. return $this->reflection->hasTable($table);
  4384. }
  4385. public function getType(String $table): String
  4386. {
  4387. return $this->reflection->getType($table);
  4388. }
  4389. public function create(String $tableName, /* object */ $record, array $params)
  4390. {
  4391. $this->sanitizeRecord($tableName, $record, '');
  4392. $table = $this->reflection->getTable($tableName);
  4393. $columnValues = $this->columns->getValues($table, true, $record, $params);
  4394. return $this->db->createSingle($table, $columnValues);
  4395. }
  4396. public function read(String $tableName, String $id, array $params) /*: ?object*/
  4397. {
  4398. $table = $this->reflection->getTable($tableName);
  4399. $this->joiner->addMandatoryColumns($table, $params);
  4400. $columnNames = $this->columns->getNames($table, true, $params);
  4401. $record = $this->db->selectSingle($table, $columnNames, $id);
  4402. if ($record == null) {
  4403. return null;
  4404. }
  4405. $records = array($record);
  4406. $this->joiner->addJoins($table, $records, $params, $this->db);
  4407. return $records[0];
  4408. }
  4409. public function update(String $tableName, String $id, /* object */ $record, array $params)
  4410. {
  4411. $this->sanitizeRecord($tableName, $record, $id);
  4412. $table = $this->reflection->getTable($tableName);
  4413. $columnValues = $this->columns->getValues($table, true, $record, $params);
  4414. return $this->db->updateSingle($table, $columnValues, $id);
  4415. }
  4416. public function delete(String $tableName, String $id, array $params)
  4417. {
  4418. $table = $this->reflection->getTable($tableName);
  4419. return $this->db->deleteSingle($table, $id);
  4420. }
  4421. public function increment(String $tableName, String $id, /* object */ $record, array $params)
  4422. {
  4423. $this->sanitizeRecord($tableName, $record, $id);
  4424. $table = $this->reflection->getTable($tableName);
  4425. $columnValues = $this->columns->getValues($table, true, $record, $params);
  4426. return $this->db->incrementSingle($table, $columnValues, $id);
  4427. }
  4428. public function _list(String $tableName, array $params): ListDocument
  4429. {
  4430. $table = $this->reflection->getTable($tableName);
  4431. $this->joiner->addMandatoryColumns($table, $params);
  4432. $columnNames = $this->columns->getNames($table, true, $params);
  4433. $condition = $this->filters->getCombinedConditions($table, $params);
  4434. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  4435. if (!$this->pagination->hasPage($params)) {
  4436. $offset = 0;
  4437. $limit = $this->pagination->getPageLimit($params);
  4438. $count = 0;
  4439. } else {
  4440. $offset = $this->pagination->getPageOffset($params);
  4441. $limit = $this->pagination->getPageLimit($params);
  4442. $count = $this->db->selectCount($table, $condition);
  4443. }
  4444. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  4445. $this->joiner->addJoins($table, $records, $params, $this->db);
  4446. return new ListDocument($records, $count);
  4447. }
  4448. }
  4449. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  4450. class RelationJoiner
  4451. {
  4452. private $reflection;
  4453. private $columns;
  4454. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  4455. {
  4456. $this->reflection = $reflection;
  4457. $this->ordering = new OrderingInfo();
  4458. $this->columns = $columns;
  4459. }
  4460. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  4461. {
  4462. if (!isset($params['join']) || !isset($params['include'])) {
  4463. return;
  4464. }
  4465. $params['mandatory'] = array();
  4466. foreach ($params['join'] as $tableNames) {
  4467. $t1 = $table;
  4468. foreach (explode(',', $tableNames) as $tableName) {
  4469. if (!$this->reflection->hasTable($tableName)) {
  4470. continue;
  4471. }
  4472. $t2 = $this->reflection->getTable($tableName);
  4473. $fks1 = $t1->getFksTo($t2->getName());
  4474. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  4475. if ($t3 != null || count($fks1) > 0) {
  4476. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  4477. }
  4478. foreach ($fks1 as $fk) {
  4479. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  4480. }
  4481. $fks2 = $t2->getFksTo($t1->getName());
  4482. if ($t3 != null || count($fks2) > 0) {
  4483. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  4484. }
  4485. foreach ($fks2 as $fk) {
  4486. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  4487. }
  4488. $t1 = $t2;
  4489. }
  4490. }
  4491. }
  4492. private function getJoinsAsPathTree(array $params): PathTree
  4493. {
  4494. $joins = new PathTree();
  4495. if (isset($params['join'])) {
  4496. foreach ($params['join'] as $tableNames) {
  4497. $path = array();
  4498. foreach (explode(',', $tableNames) as $tableName) {
  4499. $t = $this->reflection->getTable($tableName);
  4500. if ($t != null) {
  4501. $path[] = $t->getName();
  4502. }
  4503. }
  4504. $joins->put($path, true);
  4505. }
  4506. }
  4507. return $joins;
  4508. }
  4509. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  4510. {
  4511. $joins = $this->getJoinsAsPathTree($params);
  4512. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  4513. }
  4514. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  4515. {
  4516. foreach ($this->reflection->getTableNames() as $tableName) {
  4517. $t3 = $this->reflection->getTable($tableName);
  4518. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  4519. return $t3;
  4520. }
  4521. }
  4522. return null;
  4523. }
  4524. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  4525. {
  4526. foreach ($joins->getKeys() as $t2Name) {
  4527. $t2 = $this->reflection->getTable($t2Name);
  4528. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  4529. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  4530. if (!$belongsTo && !$hasMany) {
  4531. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  4532. } else {
  4533. $t3 = null;
  4534. }
  4535. $hasAndBelongsToMany = ($t3 != null);
  4536. $newRecords = array();
  4537. $fkValues = null;
  4538. $pkValues = null;
  4539. $habtmValues = null;
  4540. if ($belongsTo) {
  4541. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  4542. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  4543. }
  4544. if ($hasMany) {
  4545. $pkValues = $this->getPkEmptyValues($t1, $records);
  4546. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  4547. }
  4548. if ($hasAndBelongsToMany) {
  4549. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  4550. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  4551. }
  4552. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  4553. if ($fkValues != null) {
  4554. $this->fillFkValues($t2, $newRecords, $fkValues);
  4555. $this->setFkValues($t1, $t2, $records, $fkValues);
  4556. }
  4557. if ($pkValues != null) {
  4558. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  4559. $this->setPkValues($t1, $t2, $records, $pkValues);
  4560. }
  4561. if ($habtmValues != null) {
  4562. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  4563. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  4564. }
  4565. }
  4566. }
  4567. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  4568. {
  4569. $fkValues = array();
  4570. $fks = $t1->getFksTo($t2->getName());
  4571. foreach ($fks as $fk) {
  4572. $fkName = $fk->getName();
  4573. foreach ($records as $record) {
  4574. if (isset($record[$fkName])) {
  4575. $fkValue = $record[$fkName];
  4576. $fkValues[$fkValue] = null;
  4577. }
  4578. }
  4579. }
  4580. return $fkValues;
  4581. }
  4582. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  4583. {
  4584. $columnNames = $this->columns->getNames($t2, false, $params);
  4585. $fkIds = array_keys($fkValues);
  4586. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  4587. $records[] = $record;
  4588. }
  4589. }
  4590. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  4591. {
  4592. $pkName = $t2->getPk()->getName();
  4593. foreach ($fkRecords as $fkRecord) {
  4594. $pkValue = $fkRecord[$pkName];
  4595. $fkValues[$pkValue] = $fkRecord;
  4596. }
  4597. }
  4598. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  4599. {
  4600. $fks = $t1->getFksTo($t2->getName());
  4601. foreach ($fks as $fk) {
  4602. $fkName = $fk->getName();
  4603. foreach ($records as $i => $record) {
  4604. if (isset($record[$fkName])) {
  4605. $key = $record[$fkName];
  4606. $records[$i][$fkName] = $fkValues[$key];
  4607. }
  4608. }
  4609. }
  4610. }
  4611. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  4612. {
  4613. $pkValues = array();
  4614. $pkName = $t1->getPk()->getName();
  4615. foreach ($records as $record) {
  4616. $key = $record[$pkName];
  4617. $pkValues[$key] = array();
  4618. }
  4619. return $pkValues;
  4620. }
  4621. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  4622. {
  4623. $fks = $t2->getFksTo($t1->getName());
  4624. $columnNames = $this->columns->getNames($t2, false, $params);
  4625. $pkValueKeys = implode(',', array_keys($pkValues));
  4626. $conditions = array();
  4627. foreach ($fks as $fk) {
  4628. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  4629. }
  4630. $condition = OrCondition::fromArray($conditions);
  4631. $columnOrdering = array();
  4632. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  4633. if ($limit != -1) {
  4634. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  4635. }
  4636. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  4637. $records[] = $record;
  4638. }
  4639. }
  4640. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  4641. {
  4642. $fks = $t2->getFksTo($t1->getName());
  4643. foreach ($fks as $fk) {
  4644. $fkName = $fk->getName();
  4645. foreach ($pkRecords as $pkRecord) {
  4646. $key = $pkRecord[$fkName];
  4647. if (isset($pkValues[$key])) {
  4648. $pkValues[$key][] = $pkRecord;
  4649. }
  4650. }
  4651. }
  4652. }
  4653. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  4654. {
  4655. $pkName = $t1->getPk()->getName();
  4656. $t2Name = $t2->getName();
  4657. foreach ($records as $i => $record) {
  4658. $key = $record[$pkName];
  4659. $records[$i][$t2Name] = $pkValues[$key];
  4660. }
  4661. }
  4662. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  4663. {
  4664. $pkValues = $this->getPkEmptyValues($t1, $records);
  4665. $fkValues = array();
  4666. $fk1 = $t3->getFksTo($t1->getName())[0];
  4667. $fk2 = $t3->getFksTo($t2->getName())[0];
  4668. $fk1Name = $fk1->getName();
  4669. $fk2Name = $fk2->getName();
  4670. $columnNames = array($fk1Name, $fk2Name);
  4671. $pkIds = implode(',', array_keys($pkValues));
  4672. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  4673. $columnOrdering = array();
  4674. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  4675. if ($limit != -1) {
  4676. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  4677. }
  4678. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  4679. foreach ($records as $record) {
  4680. $val1 = $record[$fk1Name];
  4681. $val2 = $record[$fk2Name];
  4682. $pkValues[$val1][] = $val2;
  4683. $fkValues[$val2] = null;
  4684. }
  4685. return new HabtmValues($pkValues, $fkValues);
  4686. }
  4687. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  4688. {
  4689. $pkName = $t1->getPk()->getName();
  4690. $t2Name = $t2->getName();
  4691. foreach ($records as $i => $record) {
  4692. $key = $record[$pkName];
  4693. $val = array();
  4694. $fks = $habtmValues->pkValues[$key];
  4695. foreach ($fks as $fk) {
  4696. $val[] = $habtmValues->fkValues[$fk];
  4697. }
  4698. $records[$i][$t2Name] = $val;
  4699. }
  4700. }
  4701. }
  4702. // file: src/Tqdev/PhpCrudApi/Record/RequestUtils.php
  4703. class RequestUtils
  4704. {
  4705. private $reflection;
  4706. public function __construct(ReflectionService $reflection)
  4707. {
  4708. $this->reflection = $reflection;
  4709. }
  4710. public function getOperation(Request $request): String
  4711. {
  4712. $method = $request->getMethod();
  4713. $path = $request->getPathSegment(1);
  4714. $hasPk = $request->getPathSegment(3) != '';
  4715. switch ($path) {
  4716. case 'openapi':
  4717. return 'document';
  4718. case 'columns':
  4719. return $method == 'get' ? 'reflect' : 'remodel';
  4720. case 'records':
  4721. switch ($method) {
  4722. case 'POST':
  4723. return 'create';
  4724. case 'GET':
  4725. return $hasPk ? 'read' : 'list';
  4726. case 'PUT':
  4727. return 'update';
  4728. case 'DELETE':
  4729. return 'delete';
  4730. case 'PATCH':
  4731. return 'increment';
  4732. }
  4733. }
  4734. return 'unknown';
  4735. }
  4736. private function getJoinTables(String $tableName, array $parameters): array
  4737. {
  4738. $uniqueTableNames = array();
  4739. $uniqueTableNames[$tableName] = true;
  4740. if (isset($parameters['join'])) {
  4741. foreach ($parameters['join'] as $parameter) {
  4742. $tableNames = explode(',', trim($parameter));
  4743. foreach ($tableNames as $tableName) {
  4744. $uniqueTableNames[$tableName] = true;
  4745. }
  4746. }
  4747. }
  4748. return array_keys($uniqueTableNames);
  4749. }
  4750. public function getTableNames(Request $request): array
  4751. {
  4752. $path = $request->getPathSegment(1);
  4753. $tableName = $request->getPathSegment(2);
  4754. $allTableNames = $this->reflection->getTableNames();
  4755. switch ($path) {
  4756. case 'openapi':
  4757. return $allTableNames;
  4758. case 'columns':
  4759. return $tableName ? [$tableName] : $allTableNames;
  4760. case 'records':
  4761. return $this->getJoinTables($tableName, $request->getParams());
  4762. }
  4763. return $allTableNames;
  4764. }
  4765. }
  4766. // file: src/Tqdev/PhpCrudApi/Api.php
  4767. class Api
  4768. {
  4769. private $router;
  4770. private $responder;
  4771. private $debug;
  4772. public function __construct(Config $config)
  4773. {
  4774. $db = new GenericDB(
  4775. $config->getDriver(),
  4776. $config->getAddress(),
  4777. $config->getPort(),
  4778. $config->getDatabase(),
  4779. $config->getUsername(),
  4780. $config->getPassword()
  4781. );
  4782. $cache = CacheFactory::create($config);
  4783. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  4784. $responder = new Responder();
  4785. $router = new SimpleRouter($responder, $cache, $config->getCacheTime());
  4786. foreach ($config->getMiddlewares() as $middleware => $properties) {
  4787. switch ($middleware) {
  4788. case 'cors':
  4789. new CorsMiddleware($router, $responder, $properties);
  4790. break;
  4791. case 'firewall':
  4792. new FirewallMiddleware($router, $responder, $properties);
  4793. break;
  4794. case 'basicAuth':
  4795. new BasicAuthMiddleware($router, $responder, $properties);
  4796. break;
  4797. case 'jwtAuth':
  4798. new JwtAuthMiddleware($router, $responder, $properties);
  4799. break;
  4800. case 'validation':
  4801. new ValidationMiddleware($router, $responder, $properties, $reflection);
  4802. break;
  4803. case 'ipAddress':
  4804. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  4805. break;
  4806. case 'sanitation':
  4807. new SanitationMiddleware($router, $responder, $properties, $reflection);
  4808. break;
  4809. case 'multiTenancy':
  4810. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  4811. break;
  4812. case 'authorization':
  4813. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  4814. break;
  4815. case 'xsrf':
  4816. new XsrfMiddleware($router, $responder, $properties);
  4817. break;
  4818. case 'pageLimits':
  4819. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  4820. break;
  4821. case 'joinLimits':
  4822. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  4823. break;
  4824. case 'customization':
  4825. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  4826. break;
  4827. }
  4828. }
  4829. foreach ($config->getControllers() as $controller) {
  4830. switch ($controller) {
  4831. case 'records':
  4832. $records = new RecordService($db, $reflection);
  4833. new RecordController($router, $responder, $records);
  4834. break;
  4835. case 'columns':
  4836. $definition = new DefinitionService($db, $reflection);
  4837. new ColumnController($router, $responder, $reflection, $definition);
  4838. break;
  4839. case 'cache':
  4840. new CacheController($router, $responder, $cache);
  4841. break;
  4842. case 'openapi':
  4843. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  4844. new OpenApiController($router, $responder, $openApi);
  4845. break;
  4846. }
  4847. }
  4848. $this->router = $router;
  4849. $this->responder = $responder;
  4850. $this->debug = $config->getDebug();
  4851. }
  4852. public function handle(Request $request): Response
  4853. {
  4854. $response = null;
  4855. try {
  4856. $response = $this->router->route($request);
  4857. } catch (\Throwable $e) {
  4858. if ($e instanceof \PDOException) {
  4859. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  4860. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  4861. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  4862. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4863. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  4864. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4865. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  4866. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4867. }
  4868. }
  4869. if (!$response) {
  4870. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  4871. }
  4872. if ($this->debug) {
  4873. $response->addHeader('X-Exception-Message', $e->getMessage());
  4874. $response->addHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  4875. }
  4876. }
  4877. return $response;
  4878. }
  4879. }
  4880. // file: src/Tqdev/PhpCrudApi/Config.php
  4881. class Config
  4882. {
  4883. private $values = [
  4884. 'driver' => null,
  4885. 'address' => 'localhost',
  4886. 'port' => null,
  4887. 'username' => null,
  4888. 'password' => null,
  4889. 'database' => null,
  4890. 'middlewares' => 'cors',
  4891. 'controllers' => 'records,openapi',
  4892. 'cacheType' => 'TempFile',
  4893. 'cachePath' => '',
  4894. 'cacheTime' => 10,
  4895. 'debug' => false,
  4896. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  4897. ];
  4898. private function getDefaultDriver(array $values): String
  4899. {
  4900. if (isset($values['driver'])) {
  4901. return $values['driver'];
  4902. }
  4903. return 'mysql';
  4904. }
  4905. private function getDefaultPort(String $driver): int
  4906. {
  4907. switch ($driver) {
  4908. case 'mysql':return 3306;
  4909. case 'pgsql':return 5432;
  4910. case 'sqlsrv':return 1433;
  4911. }
  4912. }
  4913. private function getDefaultAddress(String $driver): String
  4914. {
  4915. switch ($driver) {
  4916. case 'mysql':return 'localhost';
  4917. case 'pgsql':return 'localhost';
  4918. case 'sqlsrv':return 'localhost';
  4919. }
  4920. }
  4921. private function getDriverDefaults(String $driver): array
  4922. {
  4923. return [
  4924. 'driver' => $driver,
  4925. 'address' => $this->getDefaultAddress($driver),
  4926. 'port' => $this->getDefaultPort($driver),
  4927. ];
  4928. }
  4929. public function __construct(array $values)
  4930. {
  4931. $driver = $this->getDefaultDriver($values);
  4932. $defaults = $this->getDriverDefaults($driver);
  4933. $newValues = array_merge($this->values, $defaults, $values);
  4934. $newValues = $this->parseMiddlewares($newValues);
  4935. $diff = array_diff_key($newValues, $this->values);
  4936. if (!empty($diff)) {
  4937. $key = array_keys($diff)[0];
  4938. throw new \Exception("Config has invalid value '$key'");
  4939. }
  4940. $this->values = $newValues;
  4941. }
  4942. private function parseMiddlewares(array $values): array
  4943. {
  4944. $newValues = array();
  4945. $properties = array();
  4946. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  4947. foreach ($middlewares as $middleware) {
  4948. $properties[$middleware] = [];
  4949. }
  4950. foreach ($values as $key => $value) {
  4951. if (strpos($key, '.') === false) {
  4952. $newValues[$key] = $value;
  4953. } else {
  4954. list($middleware, $key2) = explode('.', $key, 2);
  4955. if (isset($properties[$middleware])) {
  4956. $properties[$middleware][$key2] = $value;
  4957. } else {
  4958. throw new \Exception("Config has invalid value '$key'");
  4959. }
  4960. }
  4961. }
  4962. $newValues['middlewares'] = array_reverse($properties, true);
  4963. return $newValues;
  4964. }
  4965. public function getDriver(): String
  4966. {
  4967. return $this->values['driver'];
  4968. }
  4969. public function getAddress(): String
  4970. {
  4971. return $this->values['address'];
  4972. }
  4973. public function getPort(): int
  4974. {
  4975. return $this->values['port'];
  4976. }
  4977. public function getUsername(): String
  4978. {
  4979. return $this->values['username'];
  4980. }
  4981. public function getPassword(): String
  4982. {
  4983. return $this->values['password'];
  4984. }
  4985. public function getDatabase(): String
  4986. {
  4987. return $this->values['database'];
  4988. }
  4989. public function getMiddlewares(): array
  4990. {
  4991. return $this->values['middlewares'];
  4992. }
  4993. public function getControllers(): array
  4994. {
  4995. return array_map('trim', explode(',', $this->values['controllers']));
  4996. }
  4997. public function getCacheType(): String
  4998. {
  4999. return $this->values['cacheType'];
  5000. }
  5001. public function getCachePath(): String
  5002. {
  5003. return $this->values['cachePath'];
  5004. }
  5005. public function getCacheTime(): int
  5006. {
  5007. return $this->values['cacheTime'];
  5008. }
  5009. public function getDebug(): String
  5010. {
  5011. return $this->values['debug'];
  5012. }
  5013. public function getOpenApiBase(): array
  5014. {
  5015. return json_decode($this->values['openApiBase'], true);
  5016. }
  5017. }
  5018. // file: src/Tqdev/PhpCrudApi/Request.php
  5019. class Request
  5020. {
  5021. private $method;
  5022. private $path;
  5023. private $pathSegments;
  5024. private $params;
  5025. private $body;
  5026. private $headers;
  5027. private $highPerformance;
  5028. public function __construct(String $method = null, String $path = null, String $query = null, array $headers = null, String $body = null, bool $highPerformance = true)
  5029. {
  5030. $this->parseMethod($method);
  5031. $this->parsePath($path);
  5032. $this->parseParams($query);
  5033. $this->parseHeaders($headers);
  5034. $this->parseBody($body);
  5035. $this->highPerformance = $highPerformance;
  5036. }
  5037. private function parseMethod(String $method = null)
  5038. {
  5039. if (!$method) {
  5040. if (isset($_SERVER['REQUEST_METHOD'])) {
  5041. $method = $_SERVER['REQUEST_METHOD'];
  5042. } else {
  5043. $method = 'GET';
  5044. }
  5045. }
  5046. $this->method = $method;
  5047. }
  5048. private function parsePath(String $path = null)
  5049. {
  5050. if (!$path) {
  5051. if (isset($_SERVER['PATH_INFO'])) {
  5052. $path = $_SERVER['PATH_INFO'];
  5053. } else {
  5054. $path = '/';
  5055. }
  5056. }
  5057. $this->path = $path;
  5058. $this->pathSegments = explode('/', $path);
  5059. }
  5060. private function parseParams(String $query = null)
  5061. {
  5062. if (!$query) {
  5063. if (isset($_SERVER['QUERY_STRING'])) {
  5064. $query = $_SERVER['QUERY_STRING'];
  5065. } else {
  5066. $query = '';
  5067. }
  5068. }
  5069. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  5070. parse_str($query, $this->params);
  5071. }
  5072. private function parseHeaders(array $headers = null)
  5073. {
  5074. if (!$headers) {
  5075. $headers = array();
  5076. if (!$this->highPerformance) {
  5077. foreach ($_SERVER as $name => $value) {
  5078. if (substr($name, 0, 5) == 'HTTP_') {
  5079. $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
  5080. $headers[$key] = $value;
  5081. }
  5082. }
  5083. }
  5084. }
  5085. $this->headers = $headers;
  5086. }
  5087. private function decodeBody(String $body) /*: ?object*/
  5088. {
  5089. $first = substr($body, 0, 1);
  5090. if ($first == '[' || $first == '{') {
  5091. $object = json_decode($body);
  5092. $causeCode = json_last_error();
  5093. if ($causeCode !== JSON_ERROR_NONE) {
  5094. $object = null;
  5095. }
  5096. } else {
  5097. parse_str($body, $input);
  5098. foreach ($input as $key => $value) {
  5099. if (substr($key, -9) == '__is_null') {
  5100. $input[substr($key, 0, -9)] = null;
  5101. unset($input[$key]);
  5102. }
  5103. }
  5104. $object = (object) $input;
  5105. }
  5106. return $object;
  5107. }
  5108. private function parseBody(String $body = null) /*: void*/
  5109. {
  5110. if (!$body) {
  5111. $body = file_get_contents('php://input');
  5112. }
  5113. $this->body = $this->decodeBody($body);
  5114. }
  5115. public function getMethod(): String
  5116. {
  5117. return $this->method;
  5118. }
  5119. public function getPath(): String
  5120. {
  5121. return $this->path;
  5122. }
  5123. public function getPathSegment(int $part): String
  5124. {
  5125. if ($part < 0 || $part >= count($this->pathSegments)) {
  5126. return '';
  5127. }
  5128. return $this->pathSegments[$part];
  5129. }
  5130. public function getParams(): array
  5131. {
  5132. return $this->params;
  5133. }
  5134. public function setParams(array $params) /*: void*/
  5135. {
  5136. $this->params = $params;
  5137. }
  5138. public function getBody() /*: ?array*/
  5139. {
  5140. return $this->body;
  5141. }
  5142. public function setBody($body) /*: void*/
  5143. {
  5144. $this->body = $body;
  5145. }
  5146. public function addHeader(String $key, String $value)
  5147. {
  5148. $this->headers[$key] = $value;
  5149. }
  5150. public function getHeader(String $key): String
  5151. {
  5152. if (isset($this->headers[$key])) {
  5153. return $this->headers[$key];
  5154. }
  5155. if ($this->highPerformance) {
  5156. $serverKey = 'HTTP_' . strtoupper(str_replace('-', '_', $key));
  5157. if (isset($_SERVER[$serverKey])) {
  5158. return $_SERVER[$serverKey];
  5159. }
  5160. }
  5161. return '';
  5162. }
  5163. public function getHeaders(): array
  5164. {
  5165. return $this->headers;
  5166. }
  5167. public static function fromString(String $request): Request
  5168. {
  5169. $parts = explode("\n\n", trim($request), 2);
  5170. $head = $parts[0];
  5171. $body = isset($parts[1]) ? $parts[1] : null;
  5172. $lines = explode("\n", $head);
  5173. $line = explode(' ', trim(array_shift($lines)), 2);
  5174. $method = $line[0];
  5175. $url = isset($line[1]) ? $line[1] : '';
  5176. $path = parse_url($url, PHP_URL_PATH);
  5177. $query = parse_url($url, PHP_URL_QUERY);
  5178. $headers = array();
  5179. foreach ($lines as $line) {
  5180. list($key, $value) = explode(':', $line, 2);
  5181. $headers[$key] = trim($value);
  5182. }
  5183. return new Request($method, $path, $query, $headers, $body);
  5184. }
  5185. }
  5186. // file: src/Tqdev/PhpCrudApi/Response.php
  5187. class Response
  5188. {
  5189. const OK = 200;
  5190. const UNAUTHORIZED = 401;
  5191. const FORBIDDEN = 403;
  5192. const NOT_FOUND = 404;
  5193. const METHOD_NOT_ALLOWED = 405;
  5194. const CONFLICT = 409;
  5195. const UNPROCESSABLE_ENTITY = 422;
  5196. const INTERNAL_SERVER_ERROR = 500;
  5197. private $status;
  5198. private $headers;
  5199. private $body;
  5200. public function __construct(int $status, $body)
  5201. {
  5202. $this->status = $status;
  5203. $this->headers = array();
  5204. $this->parseBody($body);
  5205. }
  5206. private function parseBody($body)
  5207. {
  5208. if ($body === '') {
  5209. $this->body = '';
  5210. } else {
  5211. $data = json_encode($body, JSON_UNESCAPED_UNICODE);
  5212. $this->addHeader('Content-Type', 'application/json');
  5213. $this->addHeader('Content-Length', strlen($data));
  5214. $this->body = $data;
  5215. }
  5216. }
  5217. public function getStatus(): int
  5218. {
  5219. return $this->status;
  5220. }
  5221. public function getBody(): String
  5222. {
  5223. return $this->body;
  5224. }
  5225. public function addHeader(String $key, String $value)
  5226. {
  5227. $this->headers[$key] = $value;
  5228. }
  5229. public function getHeader(String $key): String
  5230. {
  5231. if (isset($this->headers[$key])) {
  5232. return $this->headers[$key];
  5233. }
  5234. return null;
  5235. }
  5236. public function getHeaders(): array
  5237. {
  5238. return $this->headers;
  5239. }
  5240. public function output()
  5241. {
  5242. http_response_code($this->getStatus());
  5243. foreach ($this->headers as $key => $value) {
  5244. header("$key: $value");
  5245. }
  5246. echo $this->getBody();
  5247. }
  5248. public function __toString(): String
  5249. {
  5250. $str = "$this->status\n";
  5251. foreach ($this->headers as $key => $value) {
  5252. $str .= "$key: $value\n";
  5253. }
  5254. if ($this->body !== '') {
  5255. $str .= "\n";
  5256. $str .= "$this->body\n";
  5257. }
  5258. return $str;
  5259. }
  5260. }
  5261. // file: src/index.php
  5262. $config = new Config([
  5263. 'username' => 'php-crud-api',
  5264. 'password' => 'php-crud-api',
  5265. 'database' => 'php-crud-api',
  5266. ]);
  5267. $request = new Request();
  5268. $api = new Api($config);
  5269. $response = $api->handle($request);
  5270. $response->output();