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

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