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

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