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

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