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.

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