api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.php 145KB

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