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

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