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

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