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

api.php 162KB

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