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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809
  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. if (count($columnOrdering)==0) {
  1249. return '';
  1250. }
  1251. $results = array();
  1252. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  1253. $column = $table->getColumn($columnName);
  1254. $quotedColumnName = $this->quoteColumnName($column);
  1255. $results[] = $quotedColumnName . ' ' . $ordering;
  1256. }
  1257. return ' ORDER BY '.implode(',', $results);
  1258. }
  1259. public function getSelect(ReflectedTable $table, array $columnNames): String
  1260. {
  1261. $results = array();
  1262. foreach ($columnNames as $columnName) {
  1263. $column = $table->getColumn($columnName);
  1264. $quotedColumnName = $this->quoteColumnName($column);
  1265. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  1266. $results[] = $quotedColumnName;
  1267. }
  1268. return implode(',', $results);
  1269. }
  1270. public function getInsert(ReflectedTable $table, array $columnValues): String
  1271. {
  1272. $columns = array();
  1273. $values = array();
  1274. foreach ($columnValues as $columnName => $columnValue) {
  1275. $column = $table->getColumn($columnName);
  1276. $quotedColumnName = $this->quoteColumnName($column);
  1277. $columns[] = $quotedColumnName;
  1278. $columnValue = $this->converter->convertColumnValue($column);
  1279. $values[] = $columnValue;
  1280. }
  1281. $columnsSql = '(' . implode(',', $columns) . ')';
  1282. $valuesSql = '(' . implode(',', $values) . ')';
  1283. $outputColumn = $this->quoteColumnName($table->getPk());
  1284. switch ($this->driver) {
  1285. case 'mysql':return "$columnsSql VALUES $valuesSql";
  1286. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  1287. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  1288. }
  1289. }
  1290. public function getUpdate(ReflectedTable $table, array $columnValues): String
  1291. {
  1292. $results = array();
  1293. foreach ($columnValues as $columnName => $columnValue) {
  1294. $column = $table->getColumn($columnName);
  1295. $quotedColumnName = $this->quoteColumnName($column);
  1296. $columnValue = $this->converter->convertColumnValue($column);
  1297. $results[] = $quotedColumnName . '=' . $columnValue;
  1298. }
  1299. return implode(',', $results);
  1300. }
  1301. public function getIncrement(ReflectedTable $table, array $columnValues): String
  1302. {
  1303. $results = array();
  1304. foreach ($columnValues as $columnName => $columnValue) {
  1305. if (!is_numeric($columnValue)) {
  1306. continue;
  1307. }
  1308. $column = $table->getColumn($columnName);
  1309. $quotedColumnName = $this->quoteColumnName($column);
  1310. $columnValue = $this->converter->convertColumnValue($column);
  1311. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  1312. }
  1313. return implode(',', $results);
  1314. }
  1315. }
  1316. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  1317. class ConditionsBuilder
  1318. {
  1319. private $driver;
  1320. public function __construct(String $driver)
  1321. {
  1322. $this->driver = $driver;
  1323. }
  1324. private function getConditionSql(Condition $condition, array &$arguments): String
  1325. {
  1326. if ($condition instanceof AndCondition) {
  1327. return $this->getAndConditionSql($condition, $arguments);
  1328. }
  1329. if ($condition instanceof OrCondition) {
  1330. return $this->getOrConditionSql($condition, $arguments);
  1331. }
  1332. if ($condition instanceof NotCondition) {
  1333. return $this->getNotConditionSql($condition, $arguments);
  1334. }
  1335. if ($condition instanceof SpatialCondition) {
  1336. return $this->getSpatialConditionSql($condition, $arguments);
  1337. }
  1338. if ($condition instanceof ColumnCondition) {
  1339. return $this->getColumnConditionSql($condition, $arguments);
  1340. }
  1341. throw new \Exception('Unknown Condition: ' . get_class($condition));
  1342. }
  1343. private function getAndConditionSql(AndCondition $and, array &$arguments): String
  1344. {
  1345. $parts = [];
  1346. foreach ($and->getConditions() as $condition) {
  1347. $parts[] = $this->getConditionSql($condition, $arguments);
  1348. }
  1349. return '(' . implode(' AND ', $parts) . ')';
  1350. }
  1351. private function getOrConditionSql(OrCondition $or, array &$arguments): String
  1352. {
  1353. $parts = [];
  1354. foreach ($or->getConditions() as $condition) {
  1355. $parts[] = $this->getConditionSql($condition, $arguments);
  1356. }
  1357. return '(' . implode(' OR ', $parts) . ')';
  1358. }
  1359. private function getNotConditionSql(NotCondition $not, array &$arguments): String
  1360. {
  1361. $condition = $not->getCondition();
  1362. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  1363. }
  1364. private function quoteColumnName(ReflectedColumn $column): String
  1365. {
  1366. return '"' . $column->getName() . '"';
  1367. }
  1368. private function escapeLikeValue(String $value): String
  1369. {
  1370. return addcslashes($value, '%_');
  1371. }
  1372. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): String
  1373. {
  1374. $column = $this->quoteColumnName($condition->getColumn());
  1375. $operator = $condition->getOperator();
  1376. $value = $condition->getValue();
  1377. switch ($operator) {
  1378. case 'cs':
  1379. $sql = "$column LIKE ?";
  1380. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  1381. break;
  1382. case 'sw':
  1383. $sql = "$column LIKE ?";
  1384. $arguments[] = $this->escapeLikeValue($value) . '%';
  1385. break;
  1386. case 'ew':
  1387. $sql = "$column LIKE ?";
  1388. $arguments[] = '%' . $this->escapeLikeValue($value);
  1389. break;
  1390. case 'eq':
  1391. $sql = "$column = ?";
  1392. $arguments[] = $value;
  1393. break;
  1394. case 'lt':
  1395. $sql = "$column < ?";
  1396. $arguments[] = $value;
  1397. break;
  1398. case 'le':
  1399. $sql = "$column <= ?";
  1400. $arguments[] = $value;
  1401. break;
  1402. case 'ge':
  1403. $sql = "$column >= ?";
  1404. $arguments[] = $value;
  1405. break;
  1406. case 'gt':
  1407. $sql = "$column > ?";
  1408. $arguments[] = $value;
  1409. break;
  1410. case 'bt':
  1411. $parts = explode(',', $value, 2);
  1412. $count = count($parts);
  1413. if ($count == 2) {
  1414. $sql = "($column >= ? AND $column <= ?)";
  1415. $arguments[] = $parts[0];
  1416. $arguments[] = $parts[1];
  1417. } else {
  1418. $sql = "FALSE";
  1419. }
  1420. break;
  1421. case 'in':
  1422. $parts = explode(',', $value);
  1423. $count = count($parts);
  1424. if ($count > 0) {
  1425. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  1426. $sql = "$column IN ($qmarks)";
  1427. for ($i = 0; $i < $count; $i++) {
  1428. $arguments[] = $parts[$i];
  1429. }
  1430. } else {
  1431. $sql = "FALSE";
  1432. }
  1433. break;
  1434. case 'is':
  1435. $sql = "$column IS NULL";
  1436. break;
  1437. }
  1438. return $sql;
  1439. }
  1440. private function getSpatialFunctionName(String $operator): String
  1441. {
  1442. switch ($operator) {
  1443. case 'co':return 'ST_Contains';
  1444. case 'cr':return 'ST_Crosses';
  1445. case 'di':return 'ST_Disjoint';
  1446. case 'eq':return 'ST_Equals';
  1447. case 'in':return 'ST_Intersects';
  1448. case 'ov':return 'ST_Overlaps';
  1449. case 'to':return 'ST_Touches';
  1450. case 'wi':return 'ST_Within';
  1451. case 'ic':return 'ST_IsClosed';
  1452. case 'is':return 'ST_IsSimple';
  1453. case 'iv':return 'ST_IsValid';
  1454. }
  1455. }
  1456. private function hasSpatialArgument(String $operator): bool
  1457. {
  1458. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  1459. }
  1460. private function getSpatialFunctionCall(String $functionName, String $column, bool $hasArgument): String
  1461. {
  1462. switch ($this->driver) {
  1463. case 'mysql':
  1464. case 'pgsql':
  1465. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  1466. return "$functionName($column, $argument)=TRUE";
  1467. case 'sqlsrv':
  1468. $functionName = str_replace('ST_', 'ST', $functionName);
  1469. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  1470. return "$column.$functionName($argument)=1";
  1471. }
  1472. }
  1473. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): String
  1474. {
  1475. $column = $this->quoteColumnName($condition->getColumn());
  1476. $operator = $condition->getOperator();
  1477. $value = $condition->getValue();
  1478. $functionName = $this->getSpatialFunctionName($operator);
  1479. $hasArgument = $this->hasSpatialArgument($operator);
  1480. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  1481. if ($hasArgument) {
  1482. $arguments[] = $value;
  1483. }
  1484. return $sql;
  1485. }
  1486. public function getWhereClause(Condition $condition, array &$arguments): String
  1487. {
  1488. if ($condition instanceof NoCondition) {
  1489. return '';
  1490. }
  1491. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  1492. }
  1493. }
  1494. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  1495. class DataConverter
  1496. {
  1497. private $driver;
  1498. public function __construct(String $driver)
  1499. {
  1500. $this->driver = $driver;
  1501. }
  1502. private function convertRecordValue($conversion, $value)
  1503. {
  1504. switch ($conversion) {
  1505. case 'boolean':
  1506. return $value ? true : false;
  1507. case 'integer':
  1508. return (int) $value;
  1509. }
  1510. return $value;
  1511. }
  1512. private function getRecordValueConversion(ReflectedColumn $column): String
  1513. {
  1514. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  1515. return 'boolean';
  1516. }
  1517. if ($this->driver == 'sqlsrv' && $column->getType() == 'bigint') {
  1518. return 'integer';
  1519. }
  1520. return 'none';
  1521. }
  1522. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  1523. {
  1524. foreach ($columnNames as $columnName) {
  1525. $column = $table->getColumn($columnName);
  1526. $conversion = $this->getRecordValueConversion($column);
  1527. if ($conversion != 'none') {
  1528. foreach ($records as $i => $record) {
  1529. $value = $records[$i][$columnName];
  1530. if ($value === null) {
  1531. continue;
  1532. }
  1533. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  1534. }
  1535. }
  1536. }
  1537. }
  1538. private function convertInputValue($conversion, $value)
  1539. {
  1540. switch ($conversion) {
  1541. case 'base64url_to_base64':
  1542. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  1543. }
  1544. return $value;
  1545. }
  1546. private function getInputValueConversion(ReflectedColumn $column): String
  1547. {
  1548. if ($column->isBinary()) {
  1549. return 'base64url_to_base64';
  1550. }
  1551. return 'none';
  1552. }
  1553. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  1554. {
  1555. $columnNames = array_keys($columnValues);
  1556. foreach ($columnNames as $columnName) {
  1557. $column = $table->getColumn($columnName);
  1558. $conversion = $this->getInputValueConversion($column);
  1559. if ($conversion != 'none') {
  1560. $value = $columnValues[$columnName];
  1561. if ($value !== null) {
  1562. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  1563. }
  1564. }
  1565. }
  1566. }
  1567. }
  1568. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  1569. class GenericDB
  1570. {
  1571. private $driver;
  1572. private $database;
  1573. private $pdo;
  1574. private $reflection;
  1575. private $definition;
  1576. private $conditions;
  1577. private $columns;
  1578. private $converter;
  1579. private function getDsn(String $address, String $port = null, String $database = null): String
  1580. {
  1581. switch ($this->driver) {
  1582. case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  1583. case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  1584. case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
  1585. }
  1586. }
  1587. private function getCommands(): array
  1588. {
  1589. switch ($this->driver) {
  1590. case 'mysql':return [
  1591. 'SET SESSION sql_warnings=1;',
  1592. 'SET NAMES utf8mb4;',
  1593. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  1594. ];
  1595. case 'pgsql':return [
  1596. "SET NAMES 'UTF8';",
  1597. ];
  1598. case 'sqlsrv':return [
  1599. ];
  1600. }
  1601. }
  1602. private function getOptions(): array
  1603. {
  1604. $options = array(
  1605. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  1606. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  1607. );
  1608. switch ($this->driver) {
  1609. case 'mysql':return $options + [
  1610. \PDO::ATTR_EMULATE_PREPARES => false,
  1611. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  1612. \PDO::ATTR_PERSISTENT => true,
  1613. ];
  1614. case 'pgsql':return $options + [
  1615. \PDO::ATTR_EMULATE_PREPARES => false,
  1616. \PDO::ATTR_PERSISTENT => true,
  1617. ];
  1618. case 'sqlsrv':return $options + [
  1619. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  1620. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  1621. ];
  1622. }
  1623. }
  1624. public function __construct(String $driver, String $address, String $port = null, String $database = null, String $username = null, String $password = null)
  1625. {
  1626. $this->driver = $driver;
  1627. $this->database = $database;
  1628. $dsn = $this->getDsn($address, $port, $database);
  1629. $options = $this->getOptions();
  1630. $this->pdo = new \PDO($dsn, $username, $password, $options);
  1631. $commands = $this->getCommands();
  1632. foreach ($commands as $command) {
  1633. $this->pdo->query($command);
  1634. }
  1635. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  1636. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  1637. $this->conditions = new ConditionsBuilder($driver);
  1638. $this->columns = new ColumnsBuilder($driver);
  1639. $this->converter = new DataConverter($driver);
  1640. }
  1641. public function pdo(): \PDO
  1642. {
  1643. return $this->pdo;
  1644. }
  1645. public function reflection(): GenericReflection
  1646. {
  1647. return $this->reflection;
  1648. }
  1649. public function definition(): GenericDefinition
  1650. {
  1651. return $this->definition;
  1652. }
  1653. private function addMiddlewareConditions(String $tableName, Condition $condition): Condition
  1654. {
  1655. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  1656. if ($condition1) {
  1657. $condition = $condition->_and($condition1);
  1658. }
  1659. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  1660. if ($condition2) {
  1661. $condition = $condition->_and($condition2);
  1662. }
  1663. return $condition;
  1664. }
  1665. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  1666. {
  1667. $this->converter->convertColumnValues($table, $columnValues);
  1668. $insertColumns = $this->columns->getInsert($table, $columnValues);
  1669. $tableName = $table->getName();
  1670. $pkName = $table->getPk()->getName();
  1671. $parameters = array_values($columnValues);
  1672. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  1673. $stmt = $this->query($sql, $parameters);
  1674. if (isset($columnValues[$pkName])) {
  1675. return $columnValues[$pkName];
  1676. }
  1677. switch ($this->driver) {
  1678. case 'mysql':
  1679. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  1680. break;
  1681. }
  1682. $pkValue = $stmt->fetchColumn(0);
  1683. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  1684. return (int) $pkValue;
  1685. }
  1686. return $pkValue;
  1687. }
  1688. public function selectSingle(ReflectedTable $table, array $columnNames, String $id) /*: ?array*/
  1689. {
  1690. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1691. $tableName = $table->getName();
  1692. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1693. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1694. $parameters = array();
  1695. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1696. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  1697. $stmt = $this->query($sql, $parameters);
  1698. $record = $stmt->fetch() ?: null;
  1699. if ($record === null) {
  1700. return null;
  1701. }
  1702. $records = array($record);
  1703. $this->converter->convertRecords($table, $columnNames, $records);
  1704. return $records[0];
  1705. }
  1706. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  1707. {
  1708. if (count($ids) == 0) {
  1709. return [];
  1710. }
  1711. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1712. $tableName = $table->getName();
  1713. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  1714. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1715. $parameters = array();
  1716. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1717. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  1718. $stmt = $this->query($sql, $parameters);
  1719. $records = $stmt->fetchAll();
  1720. $this->converter->convertRecords($table, $columnNames, $records);
  1721. return $records;
  1722. }
  1723. public function selectCount(ReflectedTable $table, Condition $condition): int
  1724. {
  1725. $tableName = $table->getName();
  1726. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1727. $parameters = array();
  1728. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1729. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  1730. $stmt = $this->query($sql, $parameters);
  1731. return $stmt->fetchColumn(0);
  1732. }
  1733. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  1734. {
  1735. if ($limit == 0) {
  1736. return array();
  1737. }
  1738. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1739. $tableName = $table->getName();
  1740. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1741. $parameters = array();
  1742. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1743. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  1744. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  1745. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  1746. $stmt = $this->query($sql, $parameters);
  1747. $records = $stmt->fetchAll();
  1748. $this->converter->convertRecords($table, $columnNames, $records);
  1749. return $records;
  1750. }
  1751. public function updateSingle(ReflectedTable $table, array $columnValues, String $id)
  1752. {
  1753. if (count($columnValues) == 0) {
  1754. return 0;
  1755. }
  1756. $this->converter->convertColumnValues($table, $columnValues);
  1757. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  1758. $tableName = $table->getName();
  1759. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1760. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1761. $parameters = array_values($columnValues);
  1762. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1763. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  1764. $stmt = $this->query($sql, $parameters);
  1765. return $stmt->rowCount();
  1766. }
  1767. public function deleteSingle(ReflectedTable $table, String $id)
  1768. {
  1769. $tableName = $table->getName();
  1770. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1771. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1772. $parameters = array();
  1773. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1774. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  1775. $stmt = $this->query($sql, $parameters);
  1776. return $stmt->rowCount();
  1777. }
  1778. public function incrementSingle(ReflectedTable $table, array $columnValues, String $id)
  1779. {
  1780. if (count($columnValues) == 0) {
  1781. return 0;
  1782. }
  1783. $this->converter->convertColumnValues($table, $columnValues);
  1784. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  1785. $tableName = $table->getName();
  1786. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1787. $condition = $this->addMiddlewareConditions($tableName, $condition);
  1788. $parameters = array_values($columnValues);
  1789. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1790. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  1791. $stmt = $this->query($sql, $parameters);
  1792. return $stmt->rowCount();
  1793. }
  1794. private function query(String $sql, array $parameters): \PDOStatement
  1795. {
  1796. $stmt = $this->pdo->prepare($sql);
  1797. $stmt->execute($parameters);
  1798. return $stmt;
  1799. }
  1800. }
  1801. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  1802. class GenericDefinition
  1803. {
  1804. private $pdo;
  1805. private $driver;
  1806. private $database;
  1807. private $typeConverter;
  1808. private $reflection;
  1809. public function __construct(\PDO $pdo, String $driver, String $database)
  1810. {
  1811. $this->pdo = $pdo;
  1812. $this->driver = $driver;
  1813. $this->database = $database;
  1814. $this->typeConverter = new TypeConverter($driver);
  1815. $this->reflection = new GenericReflection($pdo, $driver, $database);
  1816. }
  1817. private function quote(String $identifier): String
  1818. {
  1819. return '"' . str_replace('"', '', $identifier) . '"';
  1820. }
  1821. public function getColumnType(ReflectedColumn $column, bool $update): String
  1822. {
  1823. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  1824. return 'serial';
  1825. }
  1826. $type = $this->typeConverter->fromJdbc($column->getType());
  1827. if ($column->hasPrecision() && $column->hasScale()) {
  1828. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  1829. } else if ($column->hasPrecision()) {
  1830. $size = '(' . $column->getPrecision() . ')';
  1831. } else if ($column->hasLength()) {
  1832. $size = '(' . $column->getLength() . ')';
  1833. } else {
  1834. $size = '';
  1835. }
  1836. $null = $this->getColumnNullType($column, $update);
  1837. $auto = $this->getColumnAutoIncrement($column, $update);
  1838. return $type . $size . $null . $auto;
  1839. }
  1840. private function getPrimaryKey(String $tableName): String
  1841. {
  1842. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  1843. if (count($pks) == 1) {
  1844. return $pks[0];
  1845. }
  1846. return "";
  1847. }
  1848. private function canAutoIncrement(ReflectedColumn $column): bool
  1849. {
  1850. return in_array($column->getType(), ['integer', 'bigint']);
  1851. }
  1852. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): String
  1853. {
  1854. if (!$this->canAutoIncrement($column)) {
  1855. return '';
  1856. }
  1857. switch ($this->driver) {
  1858. case 'mysql':
  1859. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  1860. case 'pgsql':
  1861. return '';
  1862. case 'sqlsrv':
  1863. return ($column->getPk() && !$update) ? ' IDENTITY(1,1)' : '';
  1864. }
  1865. }
  1866. private function getColumnNullType(ReflectedColumn $column, bool $update): String
  1867. {
  1868. if ($this->driver == 'pgsql' && $update) {
  1869. return '';
  1870. }
  1871. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  1872. }
  1873. private function getTableRenameSQL(String $tableName, String $newTableName): String
  1874. {
  1875. $p1 = $this->quote($tableName);
  1876. $p2 = $this->quote($newTableName);
  1877. switch ($this->driver) {
  1878. case 'mysql':
  1879. return "RENAME TABLE $p1 TO $p2";
  1880. case 'pgsql':
  1881. return "ALTER TABLE $p1 RENAME TO $p2";
  1882. case 'sqlsrv':
  1883. return "EXEC sp_rename $p1, $p2";
  1884. }
  1885. }
  1886. private function getColumnRenameSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1887. {
  1888. $p1 = $this->quote($tableName);
  1889. $p2 = $this->quote($columnName);
  1890. $p3 = $this->quote($newColumn->getName());
  1891. switch ($this->driver) {
  1892. case 'mysql':
  1893. $p4 = $this->getColumnType($newColumn, true);
  1894. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1895. case 'pgsql':
  1896. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  1897. case 'sqlsrv':
  1898. $p4 = $this->quote($tableName . '.' . $columnName);
  1899. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  1900. }
  1901. }
  1902. private function getColumnRetypeSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1903. {
  1904. $p1 = $this->quote($tableName);
  1905. $p2 = $this->quote($columnName);
  1906. $p3 = $this->quote($newColumn->getName());
  1907. $p4 = $this->getColumnType($newColumn, true);
  1908. switch ($this->driver) {
  1909. case 'mysql':
  1910. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1911. case 'pgsql':
  1912. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  1913. case 'sqlsrv':
  1914. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  1915. }
  1916. }
  1917. private function getSetColumnNullableSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1918. {
  1919. $p1 = $this->quote($tableName);
  1920. $p2 = $this->quote($columnName);
  1921. $p3 = $this->quote($newColumn->getName());
  1922. $p4 = $this->getColumnType($newColumn, true);
  1923. switch ($this->driver) {
  1924. case 'mysql':
  1925. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1926. case 'pgsql':
  1927. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  1928. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  1929. case 'sqlsrv':
  1930. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  1931. }
  1932. }
  1933. private function getSetColumnPkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1934. {
  1935. $p1 = $this->quote($tableName);
  1936. $p2 = $this->quote($columnName);
  1937. $p3 = $this->quote($tableName . '_pkey');
  1938. switch ($this->driver) {
  1939. case 'mysql':
  1940. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  1941. return "ALTER TABLE $p1 $p4";
  1942. case 'pgsql':
  1943. case 'sqlsrv':
  1944. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  1945. return "ALTER TABLE $p1 $p4";
  1946. }
  1947. }
  1948. private function getSetColumnPkSequenceSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1949. {
  1950. $p1 = $this->quote($tableName);
  1951. $p2 = $this->quote($columnName);
  1952. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1953. switch ($this->driver) {
  1954. case 'mysql':
  1955. return "select 1";
  1956. case 'pgsql':
  1957. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  1958. case 'sqlsrv':
  1959. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  1960. }
  1961. }
  1962. private function getSetColumnPkSequenceStartSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1963. {
  1964. $p1 = $this->quote($tableName);
  1965. $p2 = $this->quote($columnName);
  1966. switch ($this->driver) {
  1967. case 'mysql':
  1968. return "select 1";
  1969. case 'pgsql':
  1970. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1971. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  1972. case 'sqlsrv':
  1973. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1974. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  1975. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  1976. }
  1977. }
  1978. private function getSetColumnPkDefaultSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1979. {
  1980. $p1 = $this->quote($tableName);
  1981. $p2 = $this->quote($columnName);
  1982. switch ($this->driver) {
  1983. case 'mysql':
  1984. $p3 = $this->quote($newColumn->getName());
  1985. $p4 = $this->getColumnType($newColumn, true);
  1986. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1987. case 'pgsql':
  1988. if ($newColumn->getPk()) {
  1989. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1990. $p4 = "SET DEFAULT nextval($p3)";
  1991. } else {
  1992. $p4 = 'DROP DEFAULT';
  1993. }
  1994. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  1995. case 'sqlsrv':
  1996. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1997. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  1998. if ($newColumn->getPk()) {
  1999. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  2000. } else {
  2001. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  2002. }
  2003. }
  2004. }
  2005. private function getAddColumnFkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  2006. {
  2007. $p1 = $this->quote($tableName);
  2008. $p2 = $this->quote($columnName);
  2009. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2010. $p4 = $this->quote($newColumn->getFk());
  2011. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  2012. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  2013. }
  2014. private function getRemoveColumnFkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  2015. {
  2016. $p1 = $this->quote($tableName);
  2017. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2018. switch ($this->driver) {
  2019. case 'mysql':
  2020. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  2021. case 'pgsql':
  2022. case 'sqlsrv':
  2023. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  2024. }
  2025. }
  2026. private function getAddTableSQL(ReflectedTable $newTable): String
  2027. {
  2028. $tableName = $newTable->getName();
  2029. $p1 = $this->quote($tableName);
  2030. $fields = [];
  2031. $constraints = [];
  2032. foreach ($newTable->getColumnNames() as $columnName) {
  2033. $newColumn = $newTable->getColumn($columnName);
  2034. $f1 = $this->quote($columnName);
  2035. $f2 = $this->getColumnType($newColumn, false);
  2036. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2037. $f4 = $this->quote($newColumn->getFk());
  2038. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  2039. $fields[] = "$f1 $f2";
  2040. if ($newColumn->getPk()) {
  2041. $constraints[] = "PRIMARY KEY ($f1)";
  2042. }
  2043. if ($newColumn->getFk()) {
  2044. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  2045. }
  2046. }
  2047. $p2 = implode(',', array_merge($fields, $constraints));
  2048. return "CREATE TABLE $p1 ($p2);";
  2049. }
  2050. private function getAddColumnSQL(String $tableName, ReflectedColumn $newColumn): String
  2051. {
  2052. $p1 = $this->quote($tableName);
  2053. $p2 = $this->quote($newColumn->getName());
  2054. $p3 = $this->getColumnType($newColumn, false);
  2055. switch ($this->driver) {
  2056. case 'mysql':
  2057. case 'pgsql':
  2058. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  2059. case 'sqlsrv':
  2060. return "ALTER TABLE $p1 ADD $p2 $p3";
  2061. }
  2062. }
  2063. private function getRemoveTableSQL(String $tableName): String
  2064. {
  2065. $p1 = $this->quote($tableName);
  2066. switch ($this->driver) {
  2067. case 'mysql':
  2068. case 'pgsql':
  2069. return "DROP TABLE $p1 CASCADE;";
  2070. case 'sqlsrv':
  2071. return "DROP TABLE $p1;";
  2072. }
  2073. }
  2074. private function getRemoveColumnSQL(String $tableName, String $columnName): String
  2075. {
  2076. $p1 = $this->quote($tableName);
  2077. $p2 = $this->quote($columnName);
  2078. switch ($this->driver) {
  2079. case 'mysql':
  2080. case 'pgsql':
  2081. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  2082. case 'sqlsrv':
  2083. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  2084. }
  2085. }
  2086. public function renameTable(String $tableName, String $newTableName)
  2087. {
  2088. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  2089. return $this->query($sql);
  2090. }
  2091. public function renameColumn(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2092. {
  2093. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  2094. return $this->query($sql);
  2095. }
  2096. public function retypeColumn(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2097. {
  2098. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  2099. return $this->query($sql);
  2100. }
  2101. public function setColumnNullable(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2102. {
  2103. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  2104. return $this->query($sql);
  2105. }
  2106. public function addColumnPrimaryKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2107. {
  2108. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  2109. $this->query($sql);
  2110. if ($this->canAutoIncrement($newColumn)) {
  2111. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  2112. $this->query($sql);
  2113. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  2114. $this->query($sql);
  2115. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  2116. $this->query($sql);
  2117. }
  2118. return true;
  2119. }
  2120. public function removeColumnPrimaryKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2121. {
  2122. if ($this->canAutoIncrement($newColumn)) {
  2123. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  2124. $this->query($sql);
  2125. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  2126. $this->query($sql);
  2127. }
  2128. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  2129. $this->query($sql);
  2130. return true;
  2131. }
  2132. public function addColumnForeignKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2133. {
  2134. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  2135. return $this->query($sql);
  2136. }
  2137. public function removeColumnForeignKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2138. {
  2139. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  2140. return $this->query($sql);
  2141. }
  2142. public function addTable(ReflectedTable $newTable)
  2143. {
  2144. $sql = $this->getAddTableSQL($newTable);
  2145. return $this->query($sql);
  2146. }
  2147. public function addColumn(String $tableName, ReflectedColumn $newColumn)
  2148. {
  2149. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  2150. return $this->query($sql);
  2151. }
  2152. public function removeTable(String $tableName)
  2153. {
  2154. $sql = $this->getRemoveTableSQL($tableName);
  2155. return $this->query($sql);
  2156. }
  2157. public function removeColumn(String $tableName, String $columnName)
  2158. {
  2159. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  2160. return $this->query($sql);
  2161. }
  2162. private function query(String $sql): bool
  2163. {
  2164. $stmt = $this->pdo->prepare($sql);
  2165. return $stmt->execute();
  2166. }
  2167. }
  2168. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  2169. class GenericReflection
  2170. {
  2171. private $pdo;
  2172. private $driver;
  2173. private $database;
  2174. private $typeConverter;
  2175. public function __construct(\PDO $pdo, String $driver, String $database)
  2176. {
  2177. $this->pdo = $pdo;
  2178. $this->driver = $driver;
  2179. $this->database = $database;
  2180. $this->typeConverter = new TypeConverter($driver);
  2181. }
  2182. public function getIgnoredTables(): array
  2183. {
  2184. switch ($this->driver) {
  2185. case 'mysql':return [];
  2186. case 'pgsql':return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  2187. case 'sqlsrv':return [];
  2188. }
  2189. }
  2190. private function getTablesSQL(): String
  2191. {
  2192. switch ($this->driver) {
  2193. 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"';
  2194. 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";';
  2195. 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"';
  2196. }
  2197. }
  2198. private function getTableColumnsSQL(): String
  2199. {
  2200. switch ($this->driver) {
  2201. 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" = ?';
  2202. 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;';
  2203. 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 \'\' <> ?';
  2204. }
  2205. }
  2206. private function getTablePrimaryKeysSQL(): String
  2207. {
  2208. switch ($this->driver) {
  2209. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  2210. 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\'';
  2211. 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 \'\' <> ?';
  2212. }
  2213. }
  2214. private function getTableForeignKeysSQL(): String
  2215. {
  2216. switch ($this->driver) {
  2217. 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" = ?';
  2218. 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\'';
  2219. 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 \'\' <> ?';
  2220. }
  2221. }
  2222. public function getDatabaseName(): String
  2223. {
  2224. return $this->database;
  2225. }
  2226. public function getTables(): array
  2227. {
  2228. $sql = $this->getTablesSQL();
  2229. $results = $this->query($sql, [$this->database]);
  2230. foreach ($results as &$result) {
  2231. switch ($this->driver) {
  2232. case 'mysql':
  2233. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  2234. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  2235. break;
  2236. case 'pgsql':
  2237. $map = ['r' => 'table', 'v' => 'view'];
  2238. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  2239. break;
  2240. case 'sqlsrv':
  2241. $map = ['U' => 'table', 'V' => 'view'];
  2242. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  2243. break;
  2244. }
  2245. }
  2246. return $results;
  2247. }
  2248. public function getTableColumns(String $tableName, String $type): array
  2249. {
  2250. $sql = $this->getTableColumnsSQL();
  2251. $results = $this->query($sql, [$tableName, $this->database]);
  2252. if ($type == 'view') {
  2253. foreach ($results as &$result) {
  2254. $result['IS_NULLABLE'] = false;
  2255. }
  2256. }
  2257. return $results;
  2258. }
  2259. public function getTablePrimaryKeys(String $tableName): array
  2260. {
  2261. $sql = $this->getTablePrimaryKeysSQL();
  2262. $results = $this->query($sql, [$tableName, $this->database]);
  2263. $primaryKeys = [];
  2264. foreach ($results as $result) {
  2265. $primaryKeys[] = $result['COLUMN_NAME'];
  2266. }
  2267. return $primaryKeys;
  2268. }
  2269. public function getTableForeignKeys(String $tableName): array
  2270. {
  2271. $sql = $this->getTableForeignKeysSQL();
  2272. $results = $this->query($sql, [$tableName, $this->database]);
  2273. $foreignKeys = [];
  2274. foreach ($results as $result) {
  2275. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  2276. }
  2277. return $foreignKeys;
  2278. }
  2279. public function toJdbcType(String $type, int $size): String
  2280. {
  2281. return $this->typeConverter->toJdbc($type, $size);
  2282. }
  2283. private function query(String $sql, array $parameters): array
  2284. {
  2285. $stmt = $this->pdo->prepare($sql);
  2286. $stmt->execute($parameters);
  2287. return $stmt->fetchAll();
  2288. }
  2289. }
  2290. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  2291. class TypeConverter
  2292. {
  2293. private $driver;
  2294. public function __construct(String $driver)
  2295. {
  2296. $this->driver = $driver;
  2297. }
  2298. private $fromJdbc = [
  2299. 'mysql' => [
  2300. 'clob' => 'longtext',
  2301. 'boolean' => 'bit',
  2302. 'blob' => 'longblob',
  2303. 'timestamp' => 'datetime',
  2304. ],
  2305. 'pgsql' => [
  2306. 'clob' => 'text',
  2307. 'blob' => 'bytea',
  2308. ],
  2309. 'sqlsrv' => [
  2310. 'boolean' => 'bit',
  2311. 'varchar' => 'nvarchar',
  2312. 'clob' => 'ntext',
  2313. 'blob' => 'image',
  2314. ],
  2315. ];
  2316. private $toJdbc = [
  2317. 'simplified' => [
  2318. 'char' => 'varchar',
  2319. 'longvarchar' => 'clob',
  2320. 'nchar' => 'varchar',
  2321. 'nvarchar' => 'varchar',
  2322. 'longnvarchar' => 'clob',
  2323. 'binary' => 'varbinary',
  2324. 'longvarbinary' => 'blob',
  2325. 'tinyint' => 'integer',
  2326. 'smallint' => 'integer',
  2327. 'real' => 'float',
  2328. 'numeric' => 'decimal',
  2329. 'time_with_timezone' => 'time',
  2330. 'timestamp_with_timezone' => 'timestamp',
  2331. ],
  2332. 'mysql' => [
  2333. 'tinyint(1)' => 'boolean',
  2334. 'bit(0)' => 'boolean',
  2335. 'bit(1)' => 'boolean',
  2336. 'tinyblob' => 'blob',
  2337. 'mediumblob' => 'blob',
  2338. 'longblob' => 'blob',
  2339. 'tinytext' => 'clob',
  2340. 'mediumtext' => 'clob',
  2341. 'longtext' => 'clob',
  2342. 'text' => 'clob',
  2343. 'mediumint' => 'integer',
  2344. 'int' => 'integer',
  2345. 'polygon' => 'geometry',
  2346. 'point' => 'geometry',
  2347. 'datetime' => 'timestamp',
  2348. 'year' => 'integer',
  2349. 'enum' => 'varchar',
  2350. 'json' => 'clob',
  2351. ],
  2352. 'pgsql' => [
  2353. 'bigserial' => 'bigint',
  2354. 'bit varying' => 'bit',
  2355. 'box' => 'geometry',
  2356. 'bytea' => 'blob',
  2357. 'character varying' => 'varchar',
  2358. 'character' => 'char',
  2359. 'cidr' => 'varchar',
  2360. 'circle' => 'geometry',
  2361. 'double precision' => 'double',
  2362. 'inet' => 'integer',
  2363. 'json' => 'clob',
  2364. 'jsonb' => 'clob',
  2365. 'line' => 'geometry',
  2366. 'lseg' => 'geometry',
  2367. 'macaddr' => 'varchar',
  2368. 'money' => 'decimal',
  2369. 'path' => 'geometry',
  2370. 'point' => 'geometry',
  2371. 'polygon' => 'geometry',
  2372. 'real' => 'float',
  2373. 'serial' => 'integer',
  2374. 'text' => 'clob',
  2375. 'time without time zone' => 'time',
  2376. 'time with time zone' => 'time_with_timezone',
  2377. 'timestamp without time zone' => 'timestamp',
  2378. 'timestamp with time zone' => 'timestamp_with_timezone',
  2379. 'uuid' => 'char',
  2380. 'xml' => 'clob',
  2381. ],
  2382. 'sqlsrv' => [
  2383. 'varbinary(0)' => 'blob',
  2384. 'bit' => 'boolean',
  2385. 'datetime' => 'timestamp',
  2386. 'datetime2' => 'timestamp',
  2387. 'float' => 'double',
  2388. 'image' => 'blob',
  2389. 'int' => 'integer',
  2390. 'money' => 'decimal',
  2391. 'ntext' => 'clob',
  2392. 'smalldatetime' => 'timestamp',
  2393. 'smallmoney' => 'decimal',
  2394. 'text' => 'clob',
  2395. 'timestamp' => 'binary',
  2396. 'udt' => 'varbinary',
  2397. 'uniqueidentifier' => 'char',
  2398. 'xml' => 'clob',
  2399. ],
  2400. ];
  2401. private $valid = [
  2402. 'bigint' => true,
  2403. 'binary' => true,
  2404. 'bit' => true,
  2405. 'blob' => true,
  2406. 'boolean' => true,
  2407. 'char' => true,
  2408. 'clob' => true,
  2409. 'date' => true,
  2410. 'decimal' => true,
  2411. 'distinct' => true,
  2412. 'double' => true,
  2413. 'float' => true,
  2414. 'integer' => true,
  2415. 'longnvarchar' => true,
  2416. 'longvarbinary' => true,
  2417. 'longvarchar' => true,
  2418. 'nchar' => true,
  2419. 'nclob' => true,
  2420. 'numeric' => true,
  2421. 'nvarchar' => true,
  2422. 'real' => true,
  2423. 'smallint' => true,
  2424. 'time' => true,
  2425. 'time_with_timezone' => true,
  2426. 'timestamp' => true,
  2427. 'timestamp_with_timezone' => true,
  2428. 'tinyint' => true,
  2429. 'varbinary' => true,
  2430. 'varchar' => true,
  2431. 'geometry' => true,
  2432. ];
  2433. public function toJdbc(String $type, int $size): String
  2434. {
  2435. $jdbcType = strtolower($type);
  2436. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  2437. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  2438. }
  2439. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  2440. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  2441. }
  2442. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  2443. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  2444. }
  2445. if (!isset($this->valid[$jdbcType])) {
  2446. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  2447. }
  2448. return $jdbcType;
  2449. }
  2450. public function fromJdbc(String $type): String
  2451. {
  2452. $jdbcType = strtolower($type);
  2453. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  2454. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  2455. }
  2456. return $jdbcType;
  2457. }
  2458. }
  2459. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Handler.php
  2460. interface Handler
  2461. {
  2462. public function handle(Request $request): Response;
  2463. }
  2464. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  2465. abstract class Middleware implements Handler
  2466. {
  2467. protected $next;
  2468. protected $responder;
  2469. private $properties;
  2470. public function __construct(Router $router, Responder $responder, array $properties)
  2471. {
  2472. $router->load($this);
  2473. $this->responder = $responder;
  2474. $this->properties = $properties;
  2475. }
  2476. public function setNext(Handler $handler) /*: void*/
  2477. {
  2478. $this->next = $handler;
  2479. }
  2480. protected function getArrayProperty(String $key, String $default): array
  2481. {
  2482. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  2483. }
  2484. protected function getProperty(String $key, $default)
  2485. {
  2486. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  2487. }
  2488. }
  2489. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  2490. class VariableStore
  2491. {
  2492. static $values = array();
  2493. public static function get(String $key)
  2494. {
  2495. if (isset(self::$values[$key])) {
  2496. return self::$values[$key];
  2497. }
  2498. return null;
  2499. }
  2500. public static function set(String $key, /* object */ $value)
  2501. {
  2502. self::$values[$key] = $value;
  2503. }
  2504. }
  2505. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  2506. interface Router extends Handler
  2507. {
  2508. public function register(String $method, String $path, array $handler);
  2509. public function load(Middleware $middleware);
  2510. public function route(Request $request): Response;
  2511. }
  2512. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  2513. class SimpleRouter implements Router
  2514. {
  2515. private $responder;
  2516. private $cache;
  2517. private $ttl;
  2518. private $registration;
  2519. private $routes;
  2520. private $routeHandlers;
  2521. private $middlewares;
  2522. public function __construct(Responder $responder, Cache $cache, int $ttl)
  2523. {
  2524. $this->responder = $responder;
  2525. $this->cache = $cache;
  2526. $this->ttl = $ttl;
  2527. $this->registration = true;
  2528. $this->routes = $this->loadPathTree();
  2529. $this->routeHandlers = [];
  2530. $this->middlewares = array();
  2531. }
  2532. private function loadPathTree(): PathTree
  2533. {
  2534. $data = $this->cache->get('PathTree');
  2535. if ($data != '') {
  2536. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  2537. $this->registration = false;
  2538. } else {
  2539. $tree = new PathTree();
  2540. }
  2541. return $tree;
  2542. }
  2543. public function register(String $method, String $path, array $handler)
  2544. {
  2545. $routeNumber = count($this->routeHandlers);
  2546. $this->routeHandlers[$routeNumber] = $handler;
  2547. if ($this->registration) {
  2548. $parts = explode('/', trim($path, '/'));
  2549. array_unshift($parts, $method);
  2550. $this->routes->put($parts, $routeNumber);
  2551. }
  2552. }
  2553. public function load(Middleware $middleware) /*: void*/
  2554. {
  2555. if (count($this->middlewares) > 0) {
  2556. $next = $this->middlewares[0];
  2557. } else {
  2558. $next = $this;
  2559. }
  2560. $middleware->setNext($next);
  2561. array_unshift($this->middlewares, $middleware);
  2562. }
  2563. public function route(Request $request): Response
  2564. {
  2565. if ($this->registration) {
  2566. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  2567. $this->cache->set('PathTree', $data, $this->ttl);
  2568. }
  2569. $obj = $this;
  2570. if (count($this->middlewares) > 0) {
  2571. $obj = $this->middlewares[0];
  2572. }
  2573. return $obj->handle($request);
  2574. }
  2575. private function getRouteNumbers(Request $request): array
  2576. {
  2577. $method = strtoupper($request->getMethod());
  2578. $path = explode('/', trim($request->getPath(0), '/'));
  2579. array_unshift($path, $method);
  2580. return $this->routes->match($path);
  2581. }
  2582. public function handle(Request $request): Response
  2583. {
  2584. $routeNumbers = $this->getRouteNumbers($request);
  2585. if (count($routeNumbers) == 0) {
  2586. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getPath());
  2587. }
  2588. return call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  2589. }
  2590. }
  2591. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  2592. class AjaxOnlyMiddleware extends Middleware
  2593. {
  2594. public function handle(Request $request): Response
  2595. {
  2596. $method = $request->getMethod();
  2597. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  2598. if (!in_array($method, $excludeMethods)) {
  2599. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  2600. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  2601. if ($headerValue != $request->getHeader($headerName)) {
  2602. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  2603. }
  2604. }
  2605. return $this->next->handle($request);
  2606. }
  2607. }
  2608. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  2609. class AuthorizationMiddleware extends Middleware
  2610. {
  2611. private $reflection;
  2612. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2613. {
  2614. parent::__construct($router, $responder, $properties);
  2615. $this->reflection = $reflection;
  2616. $this->utils = new RequestUtils($reflection);
  2617. }
  2618. private function handleColumns(String $operation, String $tableName) /*: void*/
  2619. {
  2620. $columnHandler = $this->getProperty('columnHandler', '');
  2621. if ($columnHandler) {
  2622. $table = $this->reflection->getTable($tableName);
  2623. foreach ($table->getColumnNames() as $columnName) {
  2624. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  2625. if (!$allowed) {
  2626. $table->removeColumn($columnName);
  2627. }
  2628. }
  2629. }
  2630. }
  2631. private function handleTable(String $operation, String $tableName) /*: void*/
  2632. {
  2633. if (!$this->reflection->hasTable($tableName)) {
  2634. return;
  2635. }
  2636. $tableHandler = $this->getProperty('tableHandler', '');
  2637. if ($tableHandler) {
  2638. $allowed = call_user_func($tableHandler, $operation, $tableName);
  2639. if (!$allowed) {
  2640. $this->reflection->removeTable($tableName);
  2641. } else {
  2642. $this->handleColumns($operation, $tableName);
  2643. }
  2644. }
  2645. }
  2646. private function handleRecords(String $operation, String $tableName) /*: void*/
  2647. {
  2648. if (!$this->reflection->hasTable($tableName)) {
  2649. return;
  2650. }
  2651. $recordHandler = $this->getProperty('recordHandler', '');
  2652. if ($recordHandler) {
  2653. $query = call_user_func($recordHandler, $operation, $tableName);
  2654. $filters = new FilterInfo();
  2655. $table = $this->reflection->getTable($tableName);
  2656. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  2657. parse_str($query, $params);
  2658. $condition = $filters->getCombinedConditions($table, $params);
  2659. VariableStore::set("authorization.conditions.$tableName", $condition);
  2660. }
  2661. }
  2662. public function handle(Request $request): Response
  2663. {
  2664. $path = $request->getPathSegment(1);
  2665. $operation = $this->utils->getOperation($request);
  2666. $tableNames = $this->utils->getTableNames($request);
  2667. foreach ($tableNames as $tableName) {
  2668. $this->handleTable($operation, $tableName);
  2669. if ($path == 'records') {
  2670. $this->handleRecords($operation, $tableName);
  2671. }
  2672. }
  2673. if ($path == 'openapi') {
  2674. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  2675. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  2676. }
  2677. return $this->next->handle($request);
  2678. }
  2679. }
  2680. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  2681. class BasicAuthMiddleware extends Middleware
  2682. {
  2683. private function hasCorrectPassword(String $username, String $password, array &$passwords): bool
  2684. {
  2685. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  2686. if ($hash && password_verify($password, $hash)) {
  2687. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  2688. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  2689. }
  2690. return true;
  2691. }
  2692. return false;
  2693. }
  2694. private function getValidUsername(String $username, String $password, String $passwordFile): String
  2695. {
  2696. $passwords = $this->readPasswords($passwordFile);
  2697. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  2698. $this->writePasswords($passwordFile, $passwords);
  2699. return $valid ? $username : '';
  2700. }
  2701. private function readPasswords(String $passwordFile): array
  2702. {
  2703. $passwords = [];
  2704. $passwordLines = file($passwordFile);
  2705. foreach ($passwordLines as $passwordLine) {
  2706. if (strpos($passwordLine, ':') !== false) {
  2707. list($username, $hash) = explode(':', trim($passwordLine), 2);
  2708. if (strlen($hash) > 0 && $hash[0] != '$') {
  2709. $hash = password_hash($hash, PASSWORD_DEFAULT);
  2710. }
  2711. $passwords[$username] = $hash;
  2712. }
  2713. }
  2714. return $passwords;
  2715. }
  2716. private function writePasswords(String $passwordFile, array $passwords): bool
  2717. {
  2718. $success = false;
  2719. $passwordFileContents = '';
  2720. foreach ($passwords as $username => $hash) {
  2721. $passwordFileContents .= "$username:$hash\n";
  2722. }
  2723. if (file_get_contents($passwordFile) != $passwordFileContents) {
  2724. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  2725. }
  2726. return $success;
  2727. }
  2728. private function getAuthorizationCredentials(Request $request): String
  2729. {
  2730. if (isset($_SERVER['PHP_AUTH_USER'])) {
  2731. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  2732. }
  2733. $parts = explode(' ', trim($request->getHeader('Authorization')), 2);
  2734. if (count($parts) != 2) {
  2735. return '';
  2736. }
  2737. if ($parts[0] != 'Basic') {
  2738. return '';
  2739. }
  2740. return base64_decode(strtr($parts[1], '-_', '+/'));
  2741. }
  2742. public function handle(Request $request): Response
  2743. {
  2744. if (session_status() == PHP_SESSION_NONE) {
  2745. session_start();
  2746. }
  2747. $credentials = $this->getAuthorizationCredentials($request);
  2748. if ($credentials) {
  2749. list($username, $password) = array('', '');
  2750. if (strpos($credentials, ':') !== false) {
  2751. list($username, $password) = explode(':', $credentials, 2);
  2752. }
  2753. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  2754. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  2755. $_SESSION['username'] = $validUser;
  2756. if (!$validUser) {
  2757. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  2758. }
  2759. if (!headers_sent()) {
  2760. session_regenerate_id();
  2761. }
  2762. }
  2763. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  2764. $authenticationMode = $this->getProperty('mode', 'required');
  2765. if ($authenticationMode == 'required') {
  2766. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  2767. $realm = $this->getProperty('realm', 'Username and password required');
  2768. $response->addHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  2769. return $response;
  2770. }
  2771. }
  2772. return $this->next->handle($request);
  2773. }
  2774. }
  2775. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  2776. class CorsMiddleware extends Middleware
  2777. {
  2778. private function isOriginAllowed(String $origin, String $allowedOrigins): bool
  2779. {
  2780. $found = false;
  2781. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  2782. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  2783. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  2784. if (preg_match($regex, $origin)) {
  2785. $found = true;
  2786. break;
  2787. }
  2788. }
  2789. return $found;
  2790. }
  2791. public function handle(Request $request): Response
  2792. {
  2793. $method = $request->getMethod();
  2794. $origin = $request->getHeader('Origin');
  2795. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  2796. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  2797. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  2798. } elseif ($method == 'OPTIONS') {
  2799. $response = new Response(Response::OK, '');
  2800. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  2801. if ($allowHeaders) {
  2802. $response->addHeader('Access-Control-Allow-Headers', $allowHeaders);
  2803. }
  2804. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  2805. if ($allowMethods) {
  2806. $response->addHeader('Access-Control-Allow-Methods', $allowMethods);
  2807. }
  2808. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  2809. if ($allowCredentials) {
  2810. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  2811. }
  2812. $maxAge = $this->getProperty('maxAge', '1728000');
  2813. if ($maxAge) {
  2814. $response->addHeader('Access-Control-Max-Age', $maxAge);
  2815. }
  2816. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  2817. if ($exposeHeaders) {
  2818. $response->addHeader('Access-Control-Expose-Headers', $exposeHeaders);
  2819. }
  2820. } else {
  2821. $response = $this->next->handle($request);
  2822. }
  2823. if ($origin) {
  2824. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  2825. if ($allowCredentials) {
  2826. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  2827. }
  2828. $response->addHeader('Access-Control-Allow-Origin', $origin);
  2829. }
  2830. return $response;
  2831. }
  2832. }
  2833. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  2834. class CustomizationMiddleware extends Middleware
  2835. {
  2836. private $reflection;
  2837. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2838. {
  2839. parent::__construct($router, $responder, $properties);
  2840. $this->reflection = $reflection;
  2841. $this->utils = new RequestUtils($reflection);
  2842. }
  2843. public function handle(Request $request): Response
  2844. {
  2845. $operation = $this->utils->getOperation($request);
  2846. $tableName = $request->getPathSegment(2);
  2847. $beforeHandler = $this->getProperty('beforeHandler', '');
  2848. $environment = (object) array();
  2849. if ($beforeHandler !== '') {
  2850. call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  2851. }
  2852. $response = $this->next->handle($request);
  2853. $afterHandler = $this->getProperty('afterHandler', '');
  2854. if ($afterHandler !== '') {
  2855. call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  2856. }
  2857. return $response;
  2858. }
  2859. }
  2860. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  2861. class FirewallMiddleware extends Middleware
  2862. {
  2863. private function ipMatch(String $ip, String $cidr): bool
  2864. {
  2865. if (strpos($cidr, '/') !== false) {
  2866. list($subnet, $mask) = explode('/', trim($cidr));
  2867. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  2868. return true;
  2869. }
  2870. } else {
  2871. if (ip2long($ip) == ip2long($cidr)) {
  2872. return true;
  2873. }
  2874. }
  2875. return false;
  2876. }
  2877. private function isIpAllowed(String $ipAddress, String $allowedIpAddresses): bool
  2878. {
  2879. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  2880. if ($this->ipMatch($ipAddress, $allowedIp)) {
  2881. return true;
  2882. }
  2883. }
  2884. return false;
  2885. }
  2886. public function handle(Request $request): Response
  2887. {
  2888. $reverseProxy = $this->getProperty('reverseProxy', '');
  2889. if ($reverseProxy) {
  2890. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  2891. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  2892. $ipAddress = $_SERVER['REMOTE_ADDR'];
  2893. } else {
  2894. $ipAddress = '127.0.0.1';
  2895. }
  2896. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  2897. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  2898. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  2899. } else {
  2900. $response = $this->next->handle($request);
  2901. }
  2902. return $response;
  2903. }
  2904. }
  2905. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  2906. class JoinLimitsMiddleware extends Middleware
  2907. {
  2908. private $reflection;
  2909. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2910. {
  2911. parent::__construct($router, $responder, $properties);
  2912. $this->reflection = $reflection;
  2913. $this->utils = new RequestUtils($reflection);
  2914. }
  2915. public function handle(Request $request): Response
  2916. {
  2917. $operation = $this->utils->getOperation($request);
  2918. $params = $request->getParams();
  2919. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  2920. $maxDepth = (int) $this->getProperty('depth', '3');
  2921. $maxTables = (int) $this->getProperty('tables', '10');
  2922. $maxRecords = (int) $this->getProperty('records', '1000');
  2923. $tableCount = 0;
  2924. $joinPaths = array();
  2925. for ($i = 0; $i < count($params['join']); $i++) {
  2926. $joinPath = array();
  2927. $tables = explode(',', $params['join'][$i]);
  2928. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  2929. array_push($joinPath, $tables[$depth]);
  2930. $tableCount += 1;
  2931. if ($tableCount == $maxTables) {
  2932. break;
  2933. }
  2934. }
  2935. array_push($joinPaths, implode(',', $joinPath));
  2936. if ($tableCount == $maxTables) {
  2937. break;
  2938. }
  2939. }
  2940. $params['join'] = $joinPaths;
  2941. $request->setParams($params);
  2942. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  2943. }
  2944. return $this->next->handle($request);
  2945. }
  2946. }
  2947. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  2948. class JwtAuthMiddleware extends Middleware
  2949. {
  2950. private function getVerifiedClaims(String $token, int $time, int $leeway, int $ttl, String $secret, array $requirements): array
  2951. {
  2952. $algorithms = array(
  2953. 'HS256' => 'sha256',
  2954. 'HS384' => 'sha384',
  2955. 'HS512' => 'sha512',
  2956. 'RS256' => 'sha256',
  2957. 'RS384' => 'sha384',
  2958. 'RS512' => 'sha512',
  2959. );
  2960. $token = explode('.', $token);
  2961. if (count($token) < 3) {
  2962. return array();
  2963. }
  2964. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  2965. if (!$secret) {
  2966. return array();
  2967. }
  2968. if ($header['typ'] != 'JWT') {
  2969. return array();
  2970. }
  2971. $algorithm = $header['alg'];
  2972. if (!isset($algorithms[$algorithm])) {
  2973. return array();
  2974. }
  2975. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  2976. return array();
  2977. }
  2978. $hmac = $algorithms[$algorithm];
  2979. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  2980. $data = "$token[0].$token[1]";
  2981. switch ($algorithm[0]) {
  2982. case 'H':
  2983. $hash = hash_hmac($hmac, $data, $secret, true);
  2984. if (function_exists('hash_equals')) {
  2985. $equals = hash_equals($signature, $hash);
  2986. } else {
  2987. $equals = $signature == $hash;
  2988. }
  2989. if (!$equals) {
  2990. return array();
  2991. }
  2992. break;
  2993. case 'R':
  2994. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  2995. if (!$equals) {
  2996. return array();
  2997. }
  2998. break;
  2999. }
  3000. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  3001. if (!$claims) {
  3002. return array();
  3003. }
  3004. foreach ($requirements as $field => $values) {
  3005. if (!empty($values)) {
  3006. if ($field != 'alg') {
  3007. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  3008. return array();
  3009. }
  3010. }
  3011. }
  3012. }
  3013. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  3014. return array();
  3015. }
  3016. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  3017. return array();
  3018. }
  3019. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  3020. return array();
  3021. }
  3022. if (isset($claims['iat']) && !isset($claims['exp'])) {
  3023. if ($time - $leeway > $claims['iat'] + $ttl) {
  3024. return array();
  3025. }
  3026. }
  3027. return $claims;
  3028. }
  3029. private function getClaims(String $token): array
  3030. {
  3031. $time = (int) $this->getProperty('time', time());
  3032. $leeway = (int) $this->getProperty('leeway', '5');
  3033. $ttl = (int) $this->getProperty('ttl', '30');
  3034. $secret = $this->getProperty('secret', '');
  3035. $requirements = array(
  3036. 'alg' => $this->getArrayProperty('algorithms', ''),
  3037. 'aud' => $this->getArrayProperty('audiences', ''),
  3038. 'iss' => $this->getArrayProperty('issuers', ''),
  3039. );
  3040. if (!$secret) {
  3041. return array();
  3042. }
  3043. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  3044. }
  3045. private function getAuthorizationToken(Request $request): String
  3046. {
  3047. $header = $this->getProperty('header', 'X-Authorization');
  3048. $parts = explode(' ', trim($request->getHeader($header)), 2);
  3049. if (count($parts) != 2) {
  3050. return '';
  3051. }
  3052. if ($parts[0] != 'Bearer') {
  3053. return '';
  3054. }
  3055. return $parts[1];
  3056. }
  3057. public function handle(Request $request): Response
  3058. {
  3059. if (session_status() == PHP_SESSION_NONE) {
  3060. session_start();
  3061. }
  3062. $token = $this->getAuthorizationToken($request);
  3063. if ($token) {
  3064. $claims = $this->getClaims($token);
  3065. $_SESSION['claims'] = $claims;
  3066. if (empty($claims)) {
  3067. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  3068. }
  3069. if (!headers_sent()) {
  3070. session_regenerate_id();
  3071. }
  3072. }
  3073. if (empty($_SESSION['claims'])) {
  3074. $authenticationMode = $this->getProperty('mode', 'required');
  3075. if ($authenticationMode == 'required') {
  3076. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  3077. }
  3078. }
  3079. return $this->next->handle($request);
  3080. }
  3081. }
  3082. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  3083. class MultiTenancyMiddleware extends Middleware
  3084. {
  3085. private $reflection;
  3086. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3087. {
  3088. parent::__construct($router, $responder, $properties);
  3089. $this->reflection = $reflection;
  3090. $this->utils = new RequestUtils($reflection);
  3091. }
  3092. private function getCondition(String $tableName, array $pairs): Condition
  3093. {
  3094. $condition = new NoCondition();
  3095. $table = $this->reflection->getTable($tableName);
  3096. foreach ($pairs as $k => $v) {
  3097. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  3098. }
  3099. return $condition;
  3100. }
  3101. private function getPairs($handler, String $operation, String $tableName): array
  3102. {
  3103. $result = array();
  3104. $pairs = call_user_func($handler, $operation, $tableName);
  3105. $table = $this->reflection->getTable($tableName);
  3106. foreach ($pairs as $k => $v) {
  3107. if ($table->hasColumn($k)) {
  3108. $result[$k] = $v;
  3109. }
  3110. }
  3111. return $result;
  3112. }
  3113. private function handleRecord(Request $request, String $operation, array $pairs) /*: void*/
  3114. {
  3115. $record = $request->getBody();
  3116. if ($record === null) {
  3117. return;
  3118. }
  3119. $multi = is_array($record);
  3120. $records = $multi ? $record : [$record];
  3121. foreach ($records as &$record) {
  3122. foreach ($pairs as $column => $value) {
  3123. if ($operation == 'create') {
  3124. $record->$column = $value;
  3125. } else {
  3126. if (isset($record->$column)) {
  3127. unset($record->$column);
  3128. }
  3129. }
  3130. }
  3131. }
  3132. $request->setBody($multi ? $records : $records[0]);
  3133. }
  3134. public function handle(Request $request): Response
  3135. {
  3136. $handler = $this->getProperty('handler', '');
  3137. if ($handler !== '') {
  3138. $path = $request->getPathSegment(1);
  3139. if ($path == 'records') {
  3140. $operation = $this->utils->getOperation($request);
  3141. $tableNames = $this->utils->getTableNames($request);
  3142. foreach ($tableNames as $i => $tableName) {
  3143. if (!$this->reflection->hasTable($tableName)) {
  3144. continue;
  3145. }
  3146. $pairs = $this->getPairs($handler, $operation, $tableName);
  3147. if ($i == 0) {
  3148. if (in_array($operation, ['create', 'update', 'increment'])) {
  3149. $this->handleRecord($request, $operation, $pairs);
  3150. }
  3151. }
  3152. $condition = $this->getCondition($tableName, $pairs);
  3153. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  3154. }
  3155. }
  3156. }
  3157. return $this->next->handle($request);
  3158. }
  3159. }
  3160. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  3161. class PageLimitsMiddleware extends Middleware
  3162. {
  3163. private $reflection;
  3164. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3165. {
  3166. parent::__construct($router, $responder, $properties);
  3167. $this->reflection = $reflection;
  3168. $this->utils = new RequestUtils($reflection);
  3169. }
  3170. public function handle(Request $request): Response
  3171. {
  3172. $operation = $this->utils->getOperation($request);
  3173. if ($operation == 'list') {
  3174. $params = $request->getParams();
  3175. $maxPage = (int) $this->getProperty('pages', '100');
  3176. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  3177. if (strpos($params['page'][0], ',') === false) {
  3178. $page = $params['page'][0];
  3179. } else {
  3180. list($page, $size) = explode(',', $params['page'][0], 2);
  3181. }
  3182. if ($page > $maxPage) {
  3183. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  3184. }
  3185. }
  3186. $maxSize = (int) $this->getProperty('records', '1000');
  3187. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  3188. $params['size'] = array($maxSize);
  3189. } else {
  3190. $params['size'] = array(min($params['size'][0], $maxSize));
  3191. }
  3192. $request->setParams($params);
  3193. }
  3194. return $this->next->handle($request);
  3195. }
  3196. }
  3197. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  3198. class SanitationMiddleware extends Middleware
  3199. {
  3200. private $reflection;
  3201. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3202. {
  3203. parent::__construct($router, $responder, $properties);
  3204. $this->reflection = $reflection;
  3205. $this->utils = new RequestUtils($reflection);
  3206. }
  3207. private function callHandler($handler, $record, String $operation, ReflectedTable $table) /*: object */
  3208. {
  3209. $context = (array) $record;
  3210. $tableName = $table->getName();
  3211. foreach ($context as $columnName => &$value) {
  3212. if ($table->hasColumn($columnName)) {
  3213. $column = $table->getColumn($columnName);
  3214. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  3215. }
  3216. }
  3217. return (object) $context;
  3218. }
  3219. public function handle(Request $request): Response
  3220. {
  3221. $operation = $this->utils->getOperation($request);
  3222. if (in_array($operation, ['create', 'update', 'increment'])) {
  3223. $tableName = $request->getPathSegment(2);
  3224. if ($this->reflection->hasTable($tableName)) {
  3225. $record = $request->getBody();
  3226. if ($record !== null) {
  3227. $handler = $this->getProperty('handler', '');
  3228. if ($handler !== '') {
  3229. $table = $this->reflection->getTable($tableName);
  3230. if (is_array($record)) {
  3231. foreach ($record as &$r) {
  3232. $r = $this->callHandler($handler, $r, $operation, $table);
  3233. }
  3234. } else {
  3235. $record = $this->callHandler($handler, $record, $operation, $table);
  3236. }
  3237. $request->setBody($record);
  3238. }
  3239. }
  3240. }
  3241. }
  3242. return $this->next->handle($request);
  3243. }
  3244. }
  3245. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  3246. class ValidationMiddleware extends Middleware
  3247. {
  3248. private $reflection;
  3249. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  3250. {
  3251. parent::__construct($router, $responder, $properties);
  3252. $this->reflection = $reflection;
  3253. $this->utils = new RequestUtils($reflection);
  3254. }
  3255. private function callHandler($handler, $record, String $operation, ReflectedTable $table) /*: Response?*/
  3256. {
  3257. $context = (array) $record;
  3258. $details = array();
  3259. $tableName = $table->getName();
  3260. foreach ($context as $columnName => $value) {
  3261. if ($table->hasColumn($columnName)) {
  3262. $column = $table->getColumn($columnName);
  3263. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  3264. if ($valid !== true && $valid !== '') {
  3265. $details[$columnName] = $valid;
  3266. }
  3267. }
  3268. }
  3269. if (count($details) > 0) {
  3270. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  3271. }
  3272. return null;
  3273. }
  3274. public function handle(Request $request): Response
  3275. {
  3276. $operation = $this->utils->getOperation($request);
  3277. if (in_array($operation, ['create', 'update', 'increment'])) {
  3278. $tableName = $request->getPathSegment(2);
  3279. if ($this->reflection->hasTable($tableName)) {
  3280. $record = $request->getBody();
  3281. if ($record !== null) {
  3282. $handler = $this->getProperty('handler', '');
  3283. if ($handler !== '') {
  3284. $table = $this->reflection->getTable($tableName);
  3285. if (is_array($record)) {
  3286. foreach ($record as $r) {
  3287. $response = $this->callHandler($handler, $r, $operation, $table);
  3288. if ($response !== null) {
  3289. return $response;
  3290. }
  3291. }
  3292. } else {
  3293. $response = $this->callHandler($handler, $record, $operation, $table);
  3294. if ($response !== null) {
  3295. return $response;
  3296. }
  3297. }
  3298. }
  3299. }
  3300. }
  3301. }
  3302. return $this->next->handle($request);
  3303. }
  3304. }
  3305. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  3306. class XsrfMiddleware extends Middleware
  3307. {
  3308. private function getToken(): String
  3309. {
  3310. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  3311. if (isset($_COOKIE[$cookieName])) {
  3312. $token = $_COOKIE[$cookieName];
  3313. } else {
  3314. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  3315. $token = bin2hex(random_bytes(8));
  3316. if (!headers_sent()) {
  3317. setcookie($cookieName, $token, 0, '', '', $secure);
  3318. }
  3319. }
  3320. return $token;
  3321. }
  3322. public function handle(Request $request): Response
  3323. {
  3324. $token = $this->getToken();
  3325. $method = $request->getMethod();
  3326. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  3327. if (!in_array($method, $excludeMethods)) {
  3328. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  3329. if ($token != $request->getHeader($headerName)) {
  3330. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  3331. }
  3332. }
  3333. return $this->next->handle($request);
  3334. }
  3335. }
  3336. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  3337. class OpenApiBuilder
  3338. {
  3339. private $openapi;
  3340. private $reflection;
  3341. private $operations = [
  3342. 'list' => 'get',
  3343. 'create' => 'post',
  3344. 'read' => 'get',
  3345. 'update' => 'put',
  3346. 'delete' => 'delete',
  3347. 'increment' => 'patch',
  3348. ];
  3349. private $types = [
  3350. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  3351. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  3352. 'varchar' => ['type' => 'string'],
  3353. 'clob' => ['type' => 'string'],
  3354. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  3355. 'blob' => ['type' => 'string', 'format' => 'byte'],
  3356. 'decimal' => ['type' => 'string'],
  3357. 'float' => ['type' => 'number', 'format' => 'float'],
  3358. 'double' => ['type' => 'number', 'format' => 'double'],
  3359. 'date' => ['type' => 'string', 'format' => 'date'],
  3360. 'time' => ['type' => 'string', 'format' => 'date-time'],
  3361. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  3362. 'geometry' => ['type' => 'string'],
  3363. 'boolean' => ['type' => 'boolean'],
  3364. ];
  3365. public function __construct(ReflectionService $reflection, $base)
  3366. {
  3367. $this->reflection = $reflection;
  3368. $this->openapi = new OpenApiDefinition($base);
  3369. }
  3370. private function getServerUrl(): String
  3371. {
  3372. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  3373. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  3374. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  3375. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  3376. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  3377. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  3378. }
  3379. public function build(): OpenApiDefinition
  3380. {
  3381. $this->openapi->set("openapi", "3.0.0");
  3382. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  3383. $this->openapi->set("servers|0|url", $this->getServerUrl());
  3384. }
  3385. $tableNames = $this->reflection->getTableNames();
  3386. foreach ($tableNames as $tableName) {
  3387. $this->setPath($tableName);
  3388. }
  3389. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  3390. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  3391. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  3392. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  3393. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  3394. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  3395. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  3396. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  3397. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  3398. foreach ($tableNames as $tableName) {
  3399. $this->setComponentSchema($tableName);
  3400. $this->setComponentResponse($tableName);
  3401. $this->setComponentRequestBody($tableName);
  3402. }
  3403. $this->setComponentParameters();
  3404. foreach ($tableNames as $index => $tableName) {
  3405. $this->setTag($index, $tableName);
  3406. }
  3407. return $this->openapi;
  3408. }
  3409. private function isOperationOnTableAllowed(String $operation, String $tableName): bool
  3410. {
  3411. $tableHandler = VariableStore::get('authorization.tableHandler');
  3412. if (!$tableHandler) {
  3413. return true;
  3414. }
  3415. return (bool) call_user_func($tableHandler, $operation, $tableName);
  3416. }
  3417. private function isOperationOnColumnAllowed(String $operation, String $tableName, String $columnName): bool
  3418. {
  3419. $columnHandler = VariableStore::get('authorization.columnHandler');
  3420. if (!$columnHandler) {
  3421. return true;
  3422. }
  3423. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  3424. }
  3425. private function setPath(String $tableName) /*: void*/
  3426. {
  3427. $table = $this->reflection->getTable($tableName);
  3428. $type = $table->getType();
  3429. $pk = $table->getPk();
  3430. $pkName = $pk ? $pk->getName() : '';
  3431. foreach ($this->operations as $operation => $method) {
  3432. if (!$pkName && $operation != 'list') {
  3433. continue;
  3434. }
  3435. if ($type != 'table' && $operation != 'list') {
  3436. continue;
  3437. }
  3438. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3439. continue;
  3440. }
  3441. $parameters = [];
  3442. if (in_array($operation, ['list', 'create'])) {
  3443. $path = sprintf('/records/%s', $tableName);
  3444. if ($operation == 'list') {
  3445. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  3446. }
  3447. } else {
  3448. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  3449. if ($operation == 'read') {
  3450. $parameters = ['pk', 'include', 'exclude', 'join'];
  3451. } else {
  3452. $parameters = ['pk'];
  3453. }
  3454. }
  3455. foreach ($parameters as $p => $parameter) {
  3456. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  3457. }
  3458. if (in_array($operation, ['create', 'update', 'increment'])) {
  3459. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  3460. }
  3461. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  3462. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  3463. switch ($operation) {
  3464. case 'list':
  3465. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  3466. break;
  3467. case 'create':
  3468. if ($pk->getType() == 'integer') {
  3469. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  3470. } else {
  3471. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  3472. }
  3473. break;
  3474. case 'read':
  3475. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  3476. break;
  3477. case 'update':
  3478. case 'delete':
  3479. case 'increment':
  3480. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  3481. break;
  3482. }
  3483. }
  3484. }
  3485. private function setComponentSchema(String $tableName) /*: void*/
  3486. {
  3487. $table = $this->reflection->getTable($tableName);
  3488. $type = $table->getType();
  3489. $pk = $table->getPk();
  3490. $pkName = $pk ? $pk->getName() : '';
  3491. foreach ($this->operations as $operation => $method) {
  3492. if (!$pkName && $operation != 'list') {
  3493. continue;
  3494. }
  3495. if ($type != 'table' && $operation != 'list') {
  3496. continue;
  3497. }
  3498. if ($operation == 'delete') {
  3499. continue;
  3500. }
  3501. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3502. continue;
  3503. }
  3504. if ($operation == 'list') {
  3505. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  3506. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  3507. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  3508. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  3509. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  3510. } else {
  3511. $prefix = "components|schemas|$operation-$tableName";
  3512. }
  3513. $this->openapi->set("$prefix|type", "object");
  3514. foreach ($table->getColumnNames() as $columnName) {
  3515. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  3516. continue;
  3517. }
  3518. $column = $table->getColumn($columnName);
  3519. $properties = $this->types[$column->getType()];
  3520. foreach ($properties as $key => $value) {
  3521. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  3522. }
  3523. }
  3524. }
  3525. }
  3526. private function setComponentResponse(String $tableName) /*: void*/
  3527. {
  3528. $table = $this->reflection->getTable($tableName);
  3529. $type = $table->getType();
  3530. $pk = $table->getPk();
  3531. $pkName = $pk ? $pk->getName() : '';
  3532. foreach (['list', 'read'] as $operation) {
  3533. if (!$pkName && $operation != 'list') {
  3534. continue;
  3535. }
  3536. if ($type != 'table' && $operation != 'list') {
  3537. continue;
  3538. }
  3539. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3540. continue;
  3541. }
  3542. if ($operation == 'list') {
  3543. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  3544. } else {
  3545. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  3546. }
  3547. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  3548. }
  3549. }
  3550. private function setComponentRequestBody(String $tableName) /*: void*/
  3551. {
  3552. $table = $this->reflection->getTable($tableName);
  3553. $type = $table->getType();
  3554. $pk = $table->getPk();
  3555. $pkName = $pk ? $pk->getName() : '';
  3556. if ($pkName && $type == 'table') {
  3557. foreach (['create', 'update', 'increment'] as $operation) {
  3558. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3559. continue;
  3560. }
  3561. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  3562. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  3563. }
  3564. }
  3565. }
  3566. private function setComponentParameters() /*: void*/
  3567. {
  3568. $this->openapi->set("components|parameters|pk|name", "id");
  3569. $this->openapi->set("components|parameters|pk|in", "path");
  3570. $this->openapi->set("components|parameters|pk|schema|type", "string");
  3571. $this->openapi->set("components|parameters|pk|description", "primary key value");
  3572. $this->openapi->set("components|parameters|pk|required", true);
  3573. $this->openapi->set("components|parameters|filter|name", "filter");
  3574. $this->openapi->set("components|parameters|filter|in", "query");
  3575. $this->openapi->set("components|parameters|filter|schema|type", "array");
  3576. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  3577. $this->openapi->set("components|parameters|filter|description", "Filters to be applied. Each filter consists of a column, an operator and a value (comma separated). Example: id,eq,1");
  3578. $this->openapi->set("components|parameters|filter|required", false);
  3579. $this->openapi->set("components|parameters|include|name", "include");
  3580. $this->openapi->set("components|parameters|include|in", "query");
  3581. $this->openapi->set("components|parameters|include|schema|type", "string");
  3582. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  3583. $this->openapi->set("components|parameters|include|required", false);
  3584. $this->openapi->set("components|parameters|exclude|name", "exclude");
  3585. $this->openapi->set("components|parameters|exclude|in", "query");
  3586. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  3587. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  3588. $this->openapi->set("components|parameters|exclude|required", false);
  3589. $this->openapi->set("components|parameters|order|name", "order");
  3590. $this->openapi->set("components|parameters|order|in", "query");
  3591. $this->openapi->set("components|parameters|order|schema|type", "array");
  3592. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  3593. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  3594. $this->openapi->set("components|parameters|order|required", false);
  3595. $this->openapi->set("components|parameters|size|name", "size");
  3596. $this->openapi->set("components|parameters|size|in", "query");
  3597. $this->openapi->set("components|parameters|size|schema|type", "string");
  3598. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  3599. $this->openapi->set("components|parameters|size|required", false);
  3600. $this->openapi->set("components|parameters|page|name", "page");
  3601. $this->openapi->set("components|parameters|page|in", "query");
  3602. $this->openapi->set("components|parameters|page|schema|type", "string");
  3603. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  3604. $this->openapi->set("components|parameters|page|required", false);
  3605. $this->openapi->set("components|parameters|join|name", "join");
  3606. $this->openapi->set("components|parameters|join|in", "query");
  3607. $this->openapi->set("components|parameters|join|schema|type", "array");
  3608. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  3609. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  3610. $this->openapi->set("components|parameters|join|required", false);
  3611. }
  3612. private function setTag(int $index, String $tableName) /*: void*/
  3613. {
  3614. $this->openapi->set("tags|$index|name", "$tableName");
  3615. $this->openapi->set("tags|$index|description", "$tableName operations");
  3616. }
  3617. }
  3618. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  3619. class OpenApiDefinition implements \JsonSerializable
  3620. {
  3621. private $root;
  3622. public function __construct($base)
  3623. {
  3624. $this->root = $base;
  3625. }
  3626. public function set(String $path, $value) /*: void*/
  3627. {
  3628. $parts = explode('|', trim($path, '|'));
  3629. $current = &$this->root;
  3630. while (count($parts) > 0) {
  3631. $part = array_shift($parts);
  3632. if (!isset($current[$part])) {
  3633. $current[$part] = [];
  3634. }
  3635. $current = &$current[$part];
  3636. }
  3637. $current = $value;
  3638. }
  3639. public function has(String $path): bool
  3640. {
  3641. $parts = explode('|', trim($path, '|'));
  3642. $current = &$this->root;
  3643. while (count($parts) > 0) {
  3644. $part = array_shift($parts);
  3645. if (!isset($current[$part])) {
  3646. return false;
  3647. }
  3648. $current = &$current[$part];
  3649. }
  3650. return true;
  3651. }
  3652. public function jsonSerialize()
  3653. {
  3654. return $this->root;
  3655. }
  3656. }
  3657. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  3658. class OpenApiService
  3659. {
  3660. private $builder;
  3661. public function __construct(ReflectionService $reflection, array $base)
  3662. {
  3663. $this->builder = new OpenApiBuilder($reflection, $base);
  3664. }
  3665. public function get(): OpenApiDefinition
  3666. {
  3667. return $this->builder->build();
  3668. }
  3669. }
  3670. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  3671. class AndCondition extends Condition
  3672. {
  3673. private $conditions;
  3674. public function __construct(Condition $condition1, Condition $condition2)
  3675. {
  3676. $this->conditions = [$condition1, $condition2];
  3677. }
  3678. public function _and(Condition $condition): Condition
  3679. {
  3680. if ($condition instanceof NoCondition) {
  3681. return $this;
  3682. }
  3683. $this->conditions[] = $condition;
  3684. return $this;
  3685. }
  3686. public function getConditions(): array
  3687. {
  3688. return $this->conditions;
  3689. }
  3690. public static function fromArray(array $conditions): Condition
  3691. {
  3692. $condition = new NoCondition();
  3693. foreach ($conditions as $c) {
  3694. $condition = $condition->_and($c);
  3695. }
  3696. return $condition;
  3697. }
  3698. }
  3699. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  3700. class ColumnCondition extends Condition
  3701. {
  3702. private $column;
  3703. private $operator;
  3704. private $value;
  3705. public function __construct(ReflectedColumn $column, String $operator, String $value)
  3706. {
  3707. $this->column = $column;
  3708. $this->operator = $operator;
  3709. $this->value = $value;
  3710. }
  3711. public function getColumn(): ReflectedColumn
  3712. {
  3713. return $this->column;
  3714. }
  3715. public function getOperator(): String
  3716. {
  3717. return $this->operator;
  3718. }
  3719. public function getValue(): String
  3720. {
  3721. return $this->value;
  3722. }
  3723. }
  3724. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  3725. abstract class Condition
  3726. {
  3727. public function _and(Condition $condition): Condition
  3728. {
  3729. if ($condition instanceof NoCondition) {
  3730. return $this;
  3731. }
  3732. return new AndCondition($this, $condition);
  3733. }
  3734. public function _or(Condition $condition): Condition
  3735. {
  3736. if ($condition instanceof NoCondition) {
  3737. return $this;
  3738. }
  3739. return new OrCondition($this, $condition);
  3740. }
  3741. public function _not(): Condition
  3742. {
  3743. return new NotCondition($this);
  3744. }
  3745. public static function fromString(ReflectedTable $table, String $value): Condition
  3746. {
  3747. $condition = new NoCondition();
  3748. $parts = explode(',', $value, 3);
  3749. if (count($parts) < 2) {
  3750. return $condition;
  3751. }
  3752. if (count($parts) < 3) {
  3753. $parts[2] = '';
  3754. }
  3755. $field = $table->getColumn($parts[0]);
  3756. $command = $parts[1];
  3757. $negate = false;
  3758. $spatial = false;
  3759. if (strlen($command) > 2) {
  3760. if (substr($command, 0, 1) == 'n') {
  3761. $negate = true;
  3762. $command = substr($command, 1);
  3763. }
  3764. if (substr($command, 0, 1) == 's') {
  3765. $spatial = true;
  3766. $command = substr($command, 1);
  3767. }
  3768. }
  3769. if ($spatial) {
  3770. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  3771. $condition = new SpatialCondition($field, $command, $parts[2]);
  3772. }
  3773. } else {
  3774. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  3775. $condition = new ColumnCondition($field, $command, $parts[2]);
  3776. }
  3777. }
  3778. if ($negate) {
  3779. $condition = $condition->_not();
  3780. }
  3781. return $condition;
  3782. }
  3783. }
  3784. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  3785. class NoCondition extends Condition
  3786. {
  3787. public function _and(Condition $condition): Condition
  3788. {
  3789. return $condition;
  3790. }
  3791. public function _or(Condition $condition): Condition
  3792. {
  3793. return $condition;
  3794. }
  3795. public function _not(): Condition
  3796. {
  3797. return $this;
  3798. }
  3799. }
  3800. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  3801. class NotCondition extends Condition
  3802. {
  3803. private $condition;
  3804. public function __construct(Condition $condition)
  3805. {
  3806. $this->condition = $condition;
  3807. }
  3808. public function getCondition(): Condition
  3809. {
  3810. return $this->condition;
  3811. }
  3812. }
  3813. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  3814. class OrCondition extends Condition
  3815. {
  3816. private $conditions;
  3817. public function __construct(Condition $condition1, Condition $condition2)
  3818. {
  3819. $this->conditions = [$condition1, $condition2];
  3820. }
  3821. public function _or(Condition $condition): Condition
  3822. {
  3823. if ($condition instanceof NoCondition) {
  3824. return $this;
  3825. }
  3826. $this->conditions[] = $condition;
  3827. return $this;
  3828. }
  3829. public function getConditions(): array
  3830. {
  3831. return $this->conditions;
  3832. }
  3833. public static function fromArray(array $conditions): Condition
  3834. {
  3835. $condition = new NoCondition();
  3836. foreach ($conditions as $c) {
  3837. $condition = $condition->_or($c);
  3838. }
  3839. return $condition;
  3840. }
  3841. }
  3842. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  3843. class SpatialCondition extends ColumnCondition
  3844. {
  3845. }
  3846. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  3847. class ErrorDocument implements \JsonSerializable
  3848. {
  3849. public $code;
  3850. public $message;
  3851. public $details;
  3852. public function __construct(ErrorCode $errorCode, String $argument, $details)
  3853. {
  3854. $this->code = $errorCode->getCode();
  3855. $this->message = $errorCode->getMessage($argument);
  3856. $this->details = $details;
  3857. }
  3858. public function getCode(): int
  3859. {
  3860. return $this->code;
  3861. }
  3862. public function getMessage(): String
  3863. {
  3864. return $this->message;
  3865. }
  3866. public function serialize()
  3867. {
  3868. return [
  3869. 'code' => $this->code,
  3870. 'message' => $this->message,
  3871. 'details' => $this->details,
  3872. ];
  3873. }
  3874. public function jsonSerialize()
  3875. {
  3876. return array_filter($this->serialize());
  3877. }
  3878. }
  3879. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  3880. class ListDocument implements \JsonSerializable
  3881. {
  3882. private $records;
  3883. private $results;
  3884. public function __construct(array $records, int $results)
  3885. {
  3886. $this->records = $records;
  3887. $this->results = $results;
  3888. }
  3889. public function getRecords(): array
  3890. {
  3891. return $this->records;
  3892. }
  3893. public function getResults(): int
  3894. {
  3895. return $this->results;
  3896. }
  3897. public function serialize()
  3898. {
  3899. return [
  3900. 'records' => $this->records,
  3901. 'results' => $this->results,
  3902. ];
  3903. }
  3904. public function jsonSerialize()
  3905. {
  3906. return array_filter($this->serialize(), function ($v) {
  3907. return $v !== 0;
  3908. });
  3909. }
  3910. }
  3911. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  3912. class ColumnIncluder
  3913. {
  3914. private function isMandatory(String $tableName, String $columnName, array $params): bool
  3915. {
  3916. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  3917. }
  3918. private function select(String $tableName, bool $primaryTable, array $params, String $paramName,
  3919. array $columnNames, bool $include): array{
  3920. if (!isset($params[$paramName])) {
  3921. return $columnNames;
  3922. }
  3923. $columns = array();
  3924. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  3925. $columns[$columnName] = true;
  3926. }
  3927. $result = array();
  3928. foreach ($columnNames as $columnName) {
  3929. $match = isset($columns['*.*']);
  3930. if (!$match) {
  3931. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  3932. }
  3933. if ($primaryTable && !$match) {
  3934. $match = isset($columns['*']) || isset($columns[$columnName]);
  3935. }
  3936. if ($match) {
  3937. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  3938. $result[] = $columnName;
  3939. }
  3940. } else {
  3941. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  3942. $result[] = $columnName;
  3943. }
  3944. }
  3945. }
  3946. return $result;
  3947. }
  3948. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  3949. {
  3950. $tableName = $table->getName();
  3951. $results = $table->getColumnNames();
  3952. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  3953. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  3954. return $results;
  3955. }
  3956. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  3957. {
  3958. $results = array();
  3959. $columnNames = $this->getNames($table, $primaryTable, $params);
  3960. foreach ($columnNames as $columnName) {
  3961. if (property_exists($record, $columnName)) {
  3962. $results[$columnName] = $record->$columnName;
  3963. }
  3964. }
  3965. return $results;
  3966. }
  3967. }
  3968. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  3969. class ErrorCode
  3970. {
  3971. private $code;
  3972. private $message;
  3973. private $status;
  3974. const ERROR_NOT_FOUND = 9999;
  3975. const ROUTE_NOT_FOUND = 1000;
  3976. const TABLE_NOT_FOUND = 1001;
  3977. const ARGUMENT_COUNT_MISMATCH = 1002;
  3978. const RECORD_NOT_FOUND = 1003;
  3979. const ORIGIN_FORBIDDEN = 1004;
  3980. const COLUMN_NOT_FOUND = 1005;
  3981. const TABLE_ALREADY_EXISTS = 1006;
  3982. const COLUMN_ALREADY_EXISTS = 1007;
  3983. const HTTP_MESSAGE_NOT_READABLE = 1008;
  3984. const DUPLICATE_KEY_EXCEPTION = 1009;
  3985. const DATA_INTEGRITY_VIOLATION = 1010;
  3986. const AUTHENTICATION_REQUIRED = 1011;
  3987. const AUTHENTICATION_FAILED = 1012;
  3988. const INPUT_VALIDATION_FAILED = 1013;
  3989. const OPERATION_FORBIDDEN = 1014;
  3990. const OPERATION_NOT_SUPPORTED = 1015;
  3991. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  3992. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  3993. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  3994. const PAGINATION_FORBIDDEN = 1019;
  3995. private $values = [
  3996. 9999 => ["%s", Response::INTERNAL_SERVER_ERROR],
  3997. 1000 => ["Route '%s' not found", Response::NOT_FOUND],
  3998. 1001 => ["Table '%s' not found", Response::NOT_FOUND],
  3999. 1002 => ["Argument count mismatch in '%s'", Response::UNPROCESSABLE_ENTITY],
  4000. 1003 => ["Record '%s' not found", Response::NOT_FOUND],
  4001. 1004 => ["Origin '%s' is forbidden", Response::FORBIDDEN],
  4002. 1005 => ["Column '%s' not found", Response::NOT_FOUND],
  4003. 1006 => ["Table '%s' already exists", Response::CONFLICT],
  4004. 1007 => ["Column '%s' already exists", Response::CONFLICT],
  4005. 1008 => ["Cannot read HTTP message", Response::UNPROCESSABLE_ENTITY],
  4006. 1009 => ["Duplicate key exception", Response::CONFLICT],
  4007. 1010 => ["Data integrity violation", Response::CONFLICT],
  4008. 1011 => ["Authentication required", Response::UNAUTHORIZED],
  4009. 1012 => ["Authentication failed for '%s'", Response::FORBIDDEN],
  4010. 1013 => ["Input validation failed for '%s'", Response::UNPROCESSABLE_ENTITY],
  4011. 1014 => ["Operation forbidden", Response::FORBIDDEN],
  4012. 1015 => ["Operation '%s' not supported", Response::METHOD_NOT_ALLOWED],
  4013. 1016 => ["Temporary or permanently blocked", Response::FORBIDDEN],
  4014. 1017 => ["Bad or missing XSRF token", Response::FORBIDDEN],
  4015. 1018 => ["Only AJAX requests allowed for '%s'", Response::FORBIDDEN],
  4016. 1019 => ["Pagination forbidden", Response::FORBIDDEN],
  4017. ];
  4018. public function __construct(int $code)
  4019. {
  4020. if (!isset($this->values[$code])) {
  4021. $code = 9999;
  4022. }
  4023. $this->code = $code;
  4024. $this->message = $this->values[$code][0];
  4025. $this->status = $this->values[$code][1];
  4026. }
  4027. public function getCode(): int
  4028. {
  4029. return $this->code;
  4030. }
  4031. public function getMessage(String $argument): String
  4032. {
  4033. return sprintf($this->message, $argument);
  4034. }
  4035. public function getStatus(): int
  4036. {
  4037. return $this->status;
  4038. }
  4039. }
  4040. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  4041. class FilterInfo
  4042. {
  4043. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  4044. {
  4045. $key = 'filter' . implode('', $path);
  4046. if (isset($params[$key])) {
  4047. foreach ($params[$key] as $filter) {
  4048. $condition = Condition::fromString($table, $filter);
  4049. if (($condition instanceof NoCondition) == false) {
  4050. $conditions->put($path, $condition);
  4051. }
  4052. }
  4053. }
  4054. }
  4055. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  4056. {
  4057. $conditions = new PathTree();
  4058. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  4059. for ($n = ord('0'); $n <= ord('9'); $n++) {
  4060. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  4061. for ($l = ord('a'); $l <= ord('f'); $l++) {
  4062. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  4063. }
  4064. }
  4065. return $conditions;
  4066. }
  4067. private function combinePathTreeOfConditions(PathTree $tree): Condition
  4068. {
  4069. $andConditions = $tree->getValues();
  4070. $and = AndCondition::fromArray($andConditions);
  4071. $orConditions = [];
  4072. foreach ($tree->getKeys() as $p) {
  4073. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  4074. }
  4075. $or = OrCondition::fromArray($orConditions);
  4076. return $and->_and($or);
  4077. }
  4078. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  4079. {
  4080. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  4081. }
  4082. }
  4083. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  4084. class HabtmValues
  4085. {
  4086. public $pkValues;
  4087. public $fkValues;
  4088. public function __construct(array $pkValues, array $fkValues)
  4089. {
  4090. $this->pkValues = $pkValues;
  4091. $this->fkValues = $fkValues;
  4092. }
  4093. }
  4094. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  4095. class OrderingInfo
  4096. {
  4097. public function getColumnOrdering(ReflectedTable $table, array $params): array
  4098. {
  4099. $fields = array();
  4100. if (isset($params['order'])) {
  4101. foreach ($params['order'] as $order) {
  4102. $parts = explode(',', $order, 3);
  4103. $columnName = $parts[0];
  4104. if (!$table->hasColumn($columnName)) {
  4105. continue;
  4106. }
  4107. $ascending = 'ASC';
  4108. if (count($parts) > 1) {
  4109. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  4110. $ascending = 'DESC';
  4111. }
  4112. }
  4113. $fields[] = [$columnName, $ascending];
  4114. }
  4115. }
  4116. if (count($fields) == 0) {
  4117. return $this->getDefaultColumnOrdering($table);
  4118. }
  4119. return $fields;
  4120. }
  4121. public function getDefaultColumnOrdering(ReflectedTable $table): array
  4122. {
  4123. $fields = array();
  4124. $pk = $table->getPk();
  4125. if ($pk) {
  4126. $fields[] = [$pk->getName(), 'ASC'];
  4127. } else {
  4128. foreach ($table->getColumnNames() as $columnName) {
  4129. $fields[] = [$columnName, 'ASC'];
  4130. }
  4131. }
  4132. return $fields;
  4133. }
  4134. }
  4135. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  4136. class PaginationInfo
  4137. {
  4138. public $DEFAULT_PAGE_SIZE = 20;
  4139. public function hasPage(array $params): bool
  4140. {
  4141. return isset($params['page']);
  4142. }
  4143. public function getPageOffset(array $params): int
  4144. {
  4145. $offset = 0;
  4146. $pageSize = $this->getPageSize($params);
  4147. if (isset($params['page'])) {
  4148. foreach ($params['page'] as $page) {
  4149. $parts = explode(',', $page, 2);
  4150. $page = intval($parts[0]) - 1;
  4151. $offset = $page * $pageSize;
  4152. }
  4153. }
  4154. return $offset;
  4155. }
  4156. private function getPageSize(array $params): int
  4157. {
  4158. $pageSize = $this->DEFAULT_PAGE_SIZE;
  4159. if (isset($params['page'])) {
  4160. foreach ($params['page'] as $page) {
  4161. $parts = explode(',', $page, 2);
  4162. if (count($parts) > 1) {
  4163. $pageSize = intval($parts[1]);
  4164. }
  4165. }
  4166. }
  4167. return $pageSize;
  4168. }
  4169. public function getResultSize(array $params): int
  4170. {
  4171. $numberOfRows = -1;
  4172. if (isset($params['size'])) {
  4173. foreach ($params['size'] as $size) {
  4174. $numberOfRows = intval($size);
  4175. }
  4176. }
  4177. return $numberOfRows;
  4178. }
  4179. public function getPageLimit(array $params): int
  4180. {
  4181. $pageLimit = -1;
  4182. if ($this->hasPage($params)) {
  4183. $pageLimit = $this->getPageSize($params);
  4184. }
  4185. $resultSize = $this->getResultSize($params);
  4186. if ($resultSize >= 0) {
  4187. if ($pageLimit >= 0) {
  4188. $pageLimit = min($pageLimit, $resultSize);
  4189. } else {
  4190. $pageLimit = $resultSize;
  4191. }
  4192. }
  4193. return $pageLimit;
  4194. }
  4195. }
  4196. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  4197. class PathTree implements \JsonSerializable
  4198. {
  4199. const WILDCARD = '*';
  4200. private $tree;
  4201. public function __construct( /* object */&$tree = null)
  4202. {
  4203. if (!$tree) {
  4204. $tree = $this->newTree();
  4205. }
  4206. $this->tree = &$tree;
  4207. }
  4208. public function newTree()
  4209. {
  4210. return (object) ['values' => [], 'branches' => (object) []];
  4211. }
  4212. public function getKeys(): array
  4213. {
  4214. $branches = (array) $this->tree->branches;
  4215. return array_keys($branches);
  4216. }
  4217. public function getValues(): array
  4218. {
  4219. return $this->tree->values;
  4220. }
  4221. public function get(String $key): PathTree
  4222. {
  4223. if (!isset($this->tree->branches->$key)) {
  4224. return null;
  4225. }
  4226. return new PathTree($this->tree->branches->$key);
  4227. }
  4228. public function put(array $path, $value)
  4229. {
  4230. $tree = &$this->tree;
  4231. foreach ($path as $key) {
  4232. if (!isset($tree->branches->$key)) {
  4233. $tree->branches->$key = $this->newTree();
  4234. }
  4235. $tree = &$tree->branches->$key;
  4236. }
  4237. $tree->values[] = $value;
  4238. }
  4239. public function match(array $path): array
  4240. {
  4241. $star = self::WILDCARD;
  4242. $tree = &$this->tree;
  4243. foreach ($path as $key) {
  4244. if (isset($tree->branches->$key)) {
  4245. $tree = &$tree->branches->$key;
  4246. } else if (isset($tree->branches->$star)) {
  4247. $tree = &$tree->branches->$star;
  4248. } else {
  4249. return [];
  4250. }
  4251. }
  4252. return $tree->values;
  4253. }
  4254. public static function fromJson( /* object */$tree): PathTree
  4255. {
  4256. return new PathTree($tree);
  4257. }
  4258. public function jsonSerialize()
  4259. {
  4260. return $this->tree;
  4261. }
  4262. }
  4263. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  4264. class RecordService
  4265. {
  4266. private $db;
  4267. private $reflection;
  4268. private $columns;
  4269. private $joiner;
  4270. private $filters;
  4271. private $ordering;
  4272. private $pagination;
  4273. public function __construct(GenericDB $db, ReflectionService $reflection)
  4274. {
  4275. $this->db = $db;
  4276. $this->reflection = $reflection;
  4277. $this->columns = new ColumnIncluder();
  4278. $this->joiner = new RelationJoiner($reflection, $this->columns);
  4279. $this->filters = new FilterInfo();
  4280. $this->ordering = new OrderingInfo();
  4281. $this->pagination = new PaginationInfo();
  4282. }
  4283. private function sanitizeRecord(String $tableName, /* object */ $record, String $id)
  4284. {
  4285. $keyset = array_keys((array) $record);
  4286. foreach ($keyset as $key) {
  4287. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  4288. unset($record->$key);
  4289. }
  4290. }
  4291. if ($id != '') {
  4292. $pk = $this->reflection->getTable($tableName)->getPk();
  4293. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  4294. $field = $this->reflection->getTable($tableName)->getColumn($key);
  4295. if ($field->getName() == $pk->getName()) {
  4296. unset($record->$key);
  4297. }
  4298. }
  4299. }
  4300. }
  4301. public function hasTable(String $table): bool
  4302. {
  4303. return $this->reflection->hasTable($table);
  4304. }
  4305. public function getType(String $table): String
  4306. {
  4307. return $this->reflection->getType($table);
  4308. }
  4309. public function create(String $tableName, /* object */ $record, array $params)
  4310. {
  4311. $this->sanitizeRecord($tableName, $record, '');
  4312. $table = $this->reflection->getTable($tableName);
  4313. $columnValues = $this->columns->getValues($table, true, $record, $params);
  4314. return $this->db->createSingle($table, $columnValues);
  4315. }
  4316. public function read(String $tableName, String $id, array $params) /*: ?object*/
  4317. {
  4318. $table = $this->reflection->getTable($tableName);
  4319. $this->joiner->addMandatoryColumns($table, $params);
  4320. $columnNames = $this->columns->getNames($table, true, $params);
  4321. $record = $this->db->selectSingle($table, $columnNames, $id);
  4322. if ($record == null) {
  4323. return null;
  4324. }
  4325. $records = array($record);
  4326. $this->joiner->addJoins($table, $records, $params, $this->db);
  4327. return $records[0];
  4328. }
  4329. public function update(String $tableName, String $id, /* object */ $record, array $params)
  4330. {
  4331. $this->sanitizeRecord($tableName, $record, $id);
  4332. $table = $this->reflection->getTable($tableName);
  4333. $columnValues = $this->columns->getValues($table, true, $record, $params);
  4334. return $this->db->updateSingle($table, $columnValues, $id);
  4335. }
  4336. public function delete(String $tableName, String $id, array $params)
  4337. {
  4338. $table = $this->reflection->getTable($tableName);
  4339. return $this->db->deleteSingle($table, $id);
  4340. }
  4341. public function increment(String $tableName, String $id, /* object */ $record, array $params)
  4342. {
  4343. $this->sanitizeRecord($tableName, $record, $id);
  4344. $table = $this->reflection->getTable($tableName);
  4345. $columnValues = $this->columns->getValues($table, true, $record, $params);
  4346. return $this->db->incrementSingle($table, $columnValues, $id);
  4347. }
  4348. public function _list(String $tableName, array $params): ListDocument
  4349. {
  4350. $table = $this->reflection->getTable($tableName);
  4351. $this->joiner->addMandatoryColumns($table, $params);
  4352. $columnNames = $this->columns->getNames($table, true, $params);
  4353. $condition = $this->filters->getCombinedConditions($table, $params);
  4354. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  4355. if (!$this->pagination->hasPage($params)) {
  4356. $offset = 0;
  4357. $limit = $this->pagination->getPageLimit($params);
  4358. $count = 0;
  4359. } else {
  4360. $offset = $this->pagination->getPageOffset($params);
  4361. $limit = $this->pagination->getPageLimit($params);
  4362. $count = $this->db->selectCount($table, $condition);
  4363. }
  4364. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  4365. $this->joiner->addJoins($table, $records, $params, $this->db);
  4366. return new ListDocument($records, $count);
  4367. }
  4368. }
  4369. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  4370. class RelationJoiner
  4371. {
  4372. private $reflection;
  4373. private $columns;
  4374. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  4375. {
  4376. $this->reflection = $reflection;
  4377. $this->ordering = new OrderingInfo();
  4378. $this->columns = $columns;
  4379. }
  4380. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  4381. {
  4382. if (!isset($params['join']) || !isset($params['include'])) {
  4383. return;
  4384. }
  4385. $params['mandatory'] = array();
  4386. foreach ($params['join'] as $tableNames) {
  4387. $t1 = $table;
  4388. foreach (explode(',', $tableNames) as $tableName) {
  4389. if (!$this->reflection->hasTable($tableName)) {
  4390. continue;
  4391. }
  4392. $t2 = $this->reflection->getTable($tableName);
  4393. $fks1 = $t1->getFksTo($t2->getName());
  4394. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  4395. if ($t3 != null || count($fks1) > 0) {
  4396. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  4397. }
  4398. foreach ($fks1 as $fk) {
  4399. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  4400. }
  4401. $fks2 = $t2->getFksTo($t1->getName());
  4402. if ($t3 != null || count($fks2) > 0) {
  4403. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  4404. }
  4405. foreach ($fks2 as $fk) {
  4406. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  4407. }
  4408. $t1 = $t2;
  4409. }
  4410. }
  4411. }
  4412. private function getJoinsAsPathTree(array $params): PathTree
  4413. {
  4414. $joins = new PathTree();
  4415. if (isset($params['join'])) {
  4416. foreach ($params['join'] as $tableNames) {
  4417. $path = array();
  4418. foreach (explode(',', $tableNames) as $tableName) {
  4419. $t = $this->reflection->getTable($tableName);
  4420. if ($t != null) {
  4421. $path[] = $t->getName();
  4422. }
  4423. }
  4424. $joins->put($path, true);
  4425. }
  4426. }
  4427. return $joins;
  4428. }
  4429. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  4430. {
  4431. $joins = $this->getJoinsAsPathTree($params);
  4432. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  4433. }
  4434. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  4435. {
  4436. foreach ($this->reflection->getTableNames() as $tableName) {
  4437. $t3 = $this->reflection->getTable($tableName);
  4438. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  4439. return $t3;
  4440. }
  4441. }
  4442. return null;
  4443. }
  4444. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  4445. {
  4446. foreach ($joins->getKeys() as $t2Name) {
  4447. $t2 = $this->reflection->getTable($t2Name);
  4448. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  4449. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  4450. if (!$belongsTo && !$hasMany) {
  4451. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  4452. } else {
  4453. $t3 = null;
  4454. }
  4455. $hasAndBelongsToMany = ($t3 != null);
  4456. $newRecords = array();
  4457. $fkValues = null;
  4458. $pkValues = null;
  4459. $habtmValues = null;
  4460. if ($belongsTo) {
  4461. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  4462. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  4463. }
  4464. if ($hasMany) {
  4465. $pkValues = $this->getPkEmptyValues($t1, $records);
  4466. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  4467. }
  4468. if ($hasAndBelongsToMany) {
  4469. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  4470. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  4471. }
  4472. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  4473. if ($fkValues != null) {
  4474. $this->fillFkValues($t2, $newRecords, $fkValues);
  4475. $this->setFkValues($t1, $t2, $records, $fkValues);
  4476. }
  4477. if ($pkValues != null) {
  4478. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  4479. $this->setPkValues($t1, $t2, $records, $pkValues);
  4480. }
  4481. if ($habtmValues != null) {
  4482. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  4483. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  4484. }
  4485. }
  4486. }
  4487. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  4488. {
  4489. $fkValues = array();
  4490. $fks = $t1->getFksTo($t2->getName());
  4491. foreach ($fks as $fk) {
  4492. $fkName = $fk->getName();
  4493. foreach ($records as $record) {
  4494. if (isset($record[$fkName])) {
  4495. $fkValue = $record[$fkName];
  4496. $fkValues[$fkValue] = null;
  4497. }
  4498. }
  4499. }
  4500. return $fkValues;
  4501. }
  4502. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  4503. {
  4504. $columnNames = $this->columns->getNames($t2, false, $params);
  4505. $fkIds = array_keys($fkValues);
  4506. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  4507. $records[] = $record;
  4508. }
  4509. }
  4510. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  4511. {
  4512. $pkName = $t2->getPk()->getName();
  4513. foreach ($fkRecords as $fkRecord) {
  4514. $pkValue = $fkRecord[$pkName];
  4515. $fkValues[$pkValue] = $fkRecord;
  4516. }
  4517. }
  4518. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  4519. {
  4520. $fks = $t1->getFksTo($t2->getName());
  4521. foreach ($fks as $fk) {
  4522. $fkName = $fk->getName();
  4523. foreach ($records as $i => $record) {
  4524. if (isset($record[$fkName])) {
  4525. $key = $record[$fkName];
  4526. $records[$i][$fkName] = $fkValues[$key];
  4527. }
  4528. }
  4529. }
  4530. }
  4531. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  4532. {
  4533. $pkValues = array();
  4534. $pkName = $t1->getPk()->getName();
  4535. foreach ($records as $record) {
  4536. $key = $record[$pkName];
  4537. $pkValues[$key] = array();
  4538. }
  4539. return $pkValues;
  4540. }
  4541. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  4542. {
  4543. $fks = $t2->getFksTo($t1->getName());
  4544. $columnNames = $this->columns->getNames($t2, false, $params);
  4545. $pkValueKeys = implode(',', array_keys($pkValues));
  4546. $conditions = array();
  4547. foreach ($fks as $fk) {
  4548. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  4549. }
  4550. $condition = OrCondition::fromArray($conditions);
  4551. $columnOrdering = array();
  4552. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  4553. if ($limit != -1) {
  4554. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  4555. }
  4556. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  4557. $records[] = $record;
  4558. }
  4559. }
  4560. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  4561. {
  4562. $fks = $t2->getFksTo($t1->getName());
  4563. foreach ($fks as $fk) {
  4564. $fkName = $fk->getName();
  4565. foreach ($pkRecords as $pkRecord) {
  4566. $key = $pkRecord[$fkName];
  4567. if (isset($pkValues[$key])) {
  4568. $pkValues[$key][] = $pkRecord;
  4569. }
  4570. }
  4571. }
  4572. }
  4573. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  4574. {
  4575. $pkName = $t1->getPk()->getName();
  4576. $t2Name = $t2->getName();
  4577. foreach ($records as $i => $record) {
  4578. $key = $record[$pkName];
  4579. $records[$i][$t2Name] = $pkValues[$key];
  4580. }
  4581. }
  4582. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  4583. {
  4584. $pkValues = $this->getPkEmptyValues($t1, $records);
  4585. $fkValues = array();
  4586. $fk1 = $t3->getFksTo($t1->getName())[0];
  4587. $fk2 = $t3->getFksTo($t2->getName())[0];
  4588. $fk1Name = $fk1->getName();
  4589. $fk2Name = $fk2->getName();
  4590. $columnNames = array($fk1Name, $fk2Name);
  4591. $pkIds = implode(',', array_keys($pkValues));
  4592. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  4593. $columnOrdering = array();
  4594. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  4595. if ($limit != -1) {
  4596. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  4597. }
  4598. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  4599. foreach ($records as $record) {
  4600. $val1 = $record[$fk1Name];
  4601. $val2 = $record[$fk2Name];
  4602. $pkValues[$val1][] = $val2;
  4603. $fkValues[$val2] = null;
  4604. }
  4605. return new HabtmValues($pkValues, $fkValues);
  4606. }
  4607. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  4608. {
  4609. $pkName = $t1->getPk()->getName();
  4610. $t2Name = $t2->getName();
  4611. foreach ($records as $i => $record) {
  4612. $key = $record[$pkName];
  4613. $val = array();
  4614. $fks = $habtmValues->pkValues[$key];
  4615. foreach ($fks as $fk) {
  4616. $val[] = $habtmValues->fkValues[$fk];
  4617. }
  4618. $records[$i][$t2Name] = $val;
  4619. }
  4620. }
  4621. }
  4622. // file: src/Tqdev/PhpCrudApi/Record/RequestUtils.php
  4623. class RequestUtils
  4624. {
  4625. private $reflection;
  4626. public function __construct(ReflectionService $reflection)
  4627. {
  4628. $this->reflection = $reflection;
  4629. }
  4630. public function getOperation(Request $request): String
  4631. {
  4632. $method = $request->getMethod();
  4633. $path = $request->getPathSegment(1);
  4634. $hasPk = $request->getPathSegment(3) != '';
  4635. switch ($path) {
  4636. case 'openapi':
  4637. return 'document';
  4638. case 'columns':
  4639. return $method == 'get' ? 'reflect' : 'remodel';
  4640. case 'records':
  4641. switch ($method) {
  4642. case 'POST':
  4643. return 'create';
  4644. case 'GET':
  4645. return $hasPk ? 'read' : 'list';
  4646. case 'PUT':
  4647. return 'update';
  4648. case 'DELETE':
  4649. return 'delete';
  4650. case 'PATCH':
  4651. return 'increment';
  4652. }
  4653. }
  4654. return 'unknown';
  4655. }
  4656. private function getJoinTables(String $tableName, array $parameters): array
  4657. {
  4658. $uniqueTableNames = array();
  4659. $uniqueTableNames[$tableName] = true;
  4660. if (isset($parameters['join'])) {
  4661. foreach ($parameters['join'] as $parameter) {
  4662. $tableNames = explode(',', trim($parameter));
  4663. foreach ($tableNames as $tableName) {
  4664. $uniqueTableNames[$tableName] = true;
  4665. }
  4666. }
  4667. }
  4668. return array_keys($uniqueTableNames);
  4669. }
  4670. public function getTableNames(Request $request): array
  4671. {
  4672. $path = $request->getPathSegment(1);
  4673. $tableName = $request->getPathSegment(2);
  4674. $allTableNames = $this->reflection->getTableNames();
  4675. switch ($path) {
  4676. case 'openapi':
  4677. return $allTableNames;
  4678. case 'columns':
  4679. return $tableName ? [$tableName] : $allTableNames;
  4680. case 'records':
  4681. return $this->getJoinTables($tableName, $request->getParams());
  4682. }
  4683. return $allTableNames;
  4684. }
  4685. }
  4686. // file: src/Tqdev/PhpCrudApi/Api.php
  4687. class Api
  4688. {
  4689. private $router;
  4690. private $responder;
  4691. private $debug;
  4692. public function __construct(Config $config)
  4693. {
  4694. $db = new GenericDB(
  4695. $config->getDriver(),
  4696. $config->getAddress(),
  4697. $config->getPort(),
  4698. $config->getDatabase(),
  4699. $config->getUsername(),
  4700. $config->getPassword()
  4701. );
  4702. $cache = CacheFactory::create($config);
  4703. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  4704. $responder = new Responder();
  4705. $router = new SimpleRouter($responder, $cache, $config->getCacheTime());
  4706. foreach ($config->getMiddlewares() as $middleware => $properties) {
  4707. switch ($middleware) {
  4708. case 'cors':
  4709. new CorsMiddleware($router, $responder, $properties);
  4710. break;
  4711. case 'firewall':
  4712. new FirewallMiddleware($router, $responder, $properties);
  4713. break;
  4714. case 'basicAuth':
  4715. new BasicAuthMiddleware($router, $responder, $properties);
  4716. break;
  4717. case 'jwtAuth':
  4718. new JwtAuthMiddleware($router, $responder, $properties);
  4719. break;
  4720. case 'validation':
  4721. new ValidationMiddleware($router, $responder, $properties, $reflection);
  4722. break;
  4723. case 'sanitation':
  4724. new SanitationMiddleware($router, $responder, $properties, $reflection);
  4725. break;
  4726. case 'multiTenancy':
  4727. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  4728. break;
  4729. case 'authorization':
  4730. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  4731. break;
  4732. case 'xsrf':
  4733. new XsrfMiddleware($router, $responder, $properties);
  4734. break;
  4735. case 'pageLimits':
  4736. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  4737. break;
  4738. case 'joinLimits':
  4739. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  4740. break;
  4741. case 'customization':
  4742. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  4743. break;
  4744. }
  4745. }
  4746. foreach ($config->getControllers() as $controller) {
  4747. switch ($controller) {
  4748. case 'records':
  4749. $records = new RecordService($db, $reflection);
  4750. new RecordController($router, $responder, $records);
  4751. break;
  4752. case 'columns':
  4753. $definition = new DefinitionService($db, $reflection);
  4754. new ColumnController($router, $responder, $reflection, $definition);
  4755. break;
  4756. case 'cache':
  4757. new CacheController($router, $responder, $cache);
  4758. break;
  4759. case 'openapi':
  4760. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  4761. new OpenApiController($router, $responder, $openApi);
  4762. break;
  4763. }
  4764. }
  4765. $this->router = $router;
  4766. $this->responder = $responder;
  4767. $this->debug = $config->getDebug();
  4768. }
  4769. public function handle(Request $request): Response
  4770. {
  4771. $response = null;
  4772. try {
  4773. $response = $this->router->route($request);
  4774. } catch (\Throwable $e) {
  4775. if ($e instanceof \PDOException) {
  4776. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  4777. return $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  4778. }
  4779. if (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  4780. return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4781. }
  4782. if (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  4783. return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4784. }
  4785. if (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  4786. return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4787. }
  4788. }
  4789. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  4790. if ($this->debug) {
  4791. $response->addHeader('X-Debug-Info', 'Exception in ' . $e->getFile() . ' on line ' . $e->getLine());
  4792. }
  4793. }
  4794. return $response;
  4795. }
  4796. }
  4797. // file: src/Tqdev/PhpCrudApi/Config.php
  4798. class Config
  4799. {
  4800. private $values = [
  4801. 'driver' => null,
  4802. 'address' => 'localhost',
  4803. 'port' => null,
  4804. 'username' => null,
  4805. 'password' => null,
  4806. 'database' => null,
  4807. 'middlewares' => 'cors',
  4808. 'controllers' => 'records,openapi',
  4809. 'cacheType' => 'TempFile',
  4810. 'cachePath' => '',
  4811. 'cacheTime' => 10,
  4812. 'debug' => false,
  4813. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  4814. ];
  4815. private function getDefaultDriver(array $values): String
  4816. {
  4817. if (isset($values['driver'])) {
  4818. return $values['driver'];
  4819. }
  4820. return 'mysql';
  4821. }
  4822. private function getDefaultPort(String $driver): int
  4823. {
  4824. switch ($driver) {
  4825. case 'mysql':return 3306;
  4826. case 'pgsql':return 5432;
  4827. case 'sqlsrv':return 1433;
  4828. }
  4829. }
  4830. private function getDefaultAddress(String $driver): String
  4831. {
  4832. switch ($driver) {
  4833. case 'mysql':return 'localhost';
  4834. case 'pgsql':return 'localhost';
  4835. case 'sqlsrv':return 'localhost';
  4836. }
  4837. }
  4838. private function getDriverDefaults(String $driver): array
  4839. {
  4840. return [
  4841. 'driver' => $driver,
  4842. 'address' => $this->getDefaultAddress($driver),
  4843. 'port' => $this->getDefaultPort($driver),
  4844. ];
  4845. }
  4846. public function __construct(array $values)
  4847. {
  4848. $driver = $this->getDefaultDriver($values);
  4849. $defaults = $this->getDriverDefaults($driver);
  4850. $newValues = array_merge($this->values, $defaults, $values);
  4851. $newValues = $this->parseMiddlewares($newValues);
  4852. $diff = array_diff_key($newValues, $this->values);
  4853. if (!empty($diff)) {
  4854. $key = array_keys($diff)[0];
  4855. throw new \Exception("Config has invalid value '$key'");
  4856. }
  4857. $this->values = $newValues;
  4858. }
  4859. private function parseMiddlewares(array $values): array
  4860. {
  4861. $newValues = array();
  4862. $properties = array();
  4863. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  4864. foreach ($middlewares as $middleware) {
  4865. $properties[$middleware] = [];
  4866. }
  4867. foreach ($values as $key => $value) {
  4868. if (strpos($key, '.') === false) {
  4869. $newValues[$key] = $value;
  4870. } else {
  4871. list($middleware, $key2) = explode('.', $key, 2);
  4872. if (isset($properties[$middleware])) {
  4873. $properties[$middleware][$key2] = $value;
  4874. } else {
  4875. throw new \Exception("Config has invalid value '$key'");
  4876. }
  4877. }
  4878. }
  4879. $newValues['middlewares'] = array_reverse($properties, true);
  4880. return $newValues;
  4881. }
  4882. public function getDriver(): String
  4883. {
  4884. return $this->values['driver'];
  4885. }
  4886. public function getAddress(): String
  4887. {
  4888. return $this->values['address'];
  4889. }
  4890. public function getPort(): int
  4891. {
  4892. return $this->values['port'];
  4893. }
  4894. public function getUsername(): String
  4895. {
  4896. return $this->values['username'];
  4897. }
  4898. public function getPassword(): String
  4899. {
  4900. return $this->values['password'];
  4901. }
  4902. public function getDatabase(): String
  4903. {
  4904. return $this->values['database'];
  4905. }
  4906. public function getMiddlewares(): array
  4907. {
  4908. return $this->values['middlewares'];
  4909. }
  4910. public function getControllers(): array
  4911. {
  4912. return array_map('trim', explode(',', $this->values['controllers']));
  4913. }
  4914. public function getCacheType(): String
  4915. {
  4916. return $this->values['cacheType'];
  4917. }
  4918. public function getCachePath(): String
  4919. {
  4920. return $this->values['cachePath'];
  4921. }
  4922. public function getCacheTime(): int
  4923. {
  4924. return $this->values['cacheTime'];
  4925. }
  4926. public function getDebug(): String
  4927. {
  4928. return $this->values['debug'];
  4929. }
  4930. public function getOpenApiBase(): array
  4931. {
  4932. return json_decode($this->values['openApiBase'], true);
  4933. }
  4934. }
  4935. // file: src/Tqdev/PhpCrudApi/Request.php
  4936. class Request
  4937. {
  4938. private $method;
  4939. private $path;
  4940. private $pathSegments;
  4941. private $params;
  4942. private $body;
  4943. private $headers;
  4944. private $highPerformance;
  4945. public function __construct(String $method = null, String $path = null, String $query = null, array $headers = null, String $body = null, bool $highPerformance = true)
  4946. {
  4947. $this->parseMethod($method);
  4948. $this->parsePath($path);
  4949. $this->parseParams($query);
  4950. $this->parseHeaders($headers);
  4951. $this->parseBody($body);
  4952. $this->highPerformance = $highPerformance;
  4953. }
  4954. private function parseMethod(String $method = null)
  4955. {
  4956. if (!$method) {
  4957. if (isset($_SERVER['REQUEST_METHOD'])) {
  4958. $method = $_SERVER['REQUEST_METHOD'];
  4959. } else {
  4960. $method = 'GET';
  4961. }
  4962. }
  4963. $this->method = $method;
  4964. }
  4965. private function parsePath(String $path = null)
  4966. {
  4967. if (!$path) {
  4968. if (isset($_SERVER['PATH_INFO'])) {
  4969. $path = $_SERVER['PATH_INFO'];
  4970. } else {
  4971. $path = '/';
  4972. }
  4973. }
  4974. $this->path = $path;
  4975. $this->pathSegments = explode('/', $path);
  4976. }
  4977. private function parseParams(String $query = null)
  4978. {
  4979. if (!$query) {
  4980. if (isset($_SERVER['QUERY_STRING'])) {
  4981. $query = $_SERVER['QUERY_STRING'];
  4982. } else {
  4983. $query = '';
  4984. }
  4985. }
  4986. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  4987. parse_str($query, $this->params);
  4988. }
  4989. private function parseHeaders(array $headers = null)
  4990. {
  4991. if (!$headers) {
  4992. $headers = array();
  4993. if (!$this->highPerformance) {
  4994. foreach ($_SERVER as $name => $value) {
  4995. if (substr($name, 0, 5) == 'HTTP_') {
  4996. $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
  4997. $headers[$key] = $value;
  4998. }
  4999. }
  5000. }
  5001. }
  5002. $this->headers = $headers;
  5003. }
  5004. private function decodeBody(String $body) /*: ?object*/
  5005. {
  5006. $first = substr($body, 0, 1);
  5007. if ($first == '[' || $first == '{') {
  5008. $object = json_decode($body);
  5009. $causeCode = json_last_error();
  5010. if ($causeCode !== JSON_ERROR_NONE) {
  5011. $object = null;
  5012. }
  5013. } else {
  5014. parse_str($body, $input);
  5015. foreach ($input as $key => $value) {
  5016. if (substr($key, -9) == '__is_null') {
  5017. $input[substr($key, 0, -9)] = null;
  5018. unset($input[$key]);
  5019. }
  5020. }
  5021. $object = (object) $input;
  5022. }
  5023. return $object;
  5024. }
  5025. private function parseBody(String $body = null) /*: void*/
  5026. {
  5027. if (!$body) {
  5028. $body = file_get_contents('php://input');
  5029. }
  5030. $this->body = $this->decodeBody($body);
  5031. }
  5032. public function getMethod(): String
  5033. {
  5034. return $this->method;
  5035. }
  5036. public function getPath(): String
  5037. {
  5038. return $this->path;
  5039. }
  5040. public function getPathSegment(int $part): String
  5041. {
  5042. if ($part < 0 || $part >= count($this->pathSegments)) {
  5043. return '';
  5044. }
  5045. return $this->pathSegments[$part];
  5046. }
  5047. public function getParams(): array
  5048. {
  5049. return $this->params;
  5050. }
  5051. public function setParams(array $params) /*: void*/
  5052. {
  5053. $this->params = $params;
  5054. }
  5055. public function getBody() /*: ?array*/
  5056. {
  5057. return $this->body;
  5058. }
  5059. public function setBody($body) /*: void*/
  5060. {
  5061. $this->body = $body;
  5062. }
  5063. public function addHeader(String $key, String $value)
  5064. {
  5065. $this->headers[$key] = $value;
  5066. }
  5067. public function getHeader(String $key): String
  5068. {
  5069. if (isset($this->headers[$key])) {
  5070. return $this->headers[$key];
  5071. }
  5072. if ($this->highPerformance) {
  5073. $serverKey = 'HTTP_' . strtoupper(str_replace('-', '_', $key));
  5074. if (isset($_SERVER[$serverKey])) {
  5075. return $_SERVER[$serverKey];
  5076. }
  5077. }
  5078. return '';
  5079. }
  5080. public function getHeaders(): array
  5081. {
  5082. return $this->headers;
  5083. }
  5084. public static function fromString(String $request): Request
  5085. {
  5086. $parts = explode("\n\n", trim($request), 2);
  5087. $head = $parts[0];
  5088. $body = isset($parts[1]) ? $parts[1] : null;
  5089. $lines = explode("\n", $head);
  5090. $line = explode(' ', trim(array_shift($lines)), 2);
  5091. $method = $line[0];
  5092. $url = isset($line[1]) ? $line[1] : '';
  5093. $path = parse_url($url, PHP_URL_PATH);
  5094. $query = parse_url($url, PHP_URL_QUERY);
  5095. $headers = array();
  5096. foreach ($lines as $line) {
  5097. list($key, $value) = explode(':', $line, 2);
  5098. $headers[$key] = trim($value);
  5099. }
  5100. return new Request($method, $path, $query, $headers, $body);
  5101. }
  5102. }
  5103. // file: src/Tqdev/PhpCrudApi/Response.php
  5104. class Response
  5105. {
  5106. const OK = 200;
  5107. const UNAUTHORIZED = 401;
  5108. const FORBIDDEN = 403;
  5109. const NOT_FOUND = 404;
  5110. const METHOD_NOT_ALLOWED = 405;
  5111. const CONFLICT = 409;
  5112. const UNPROCESSABLE_ENTITY = 422;
  5113. const INTERNAL_SERVER_ERROR = 500;
  5114. private $status;
  5115. private $headers;
  5116. private $body;
  5117. public function __construct(int $status, $body)
  5118. {
  5119. $this->status = $status;
  5120. $this->headers = array();
  5121. $this->parseBody($body);
  5122. }
  5123. private function parseBody($body)
  5124. {
  5125. if ($body === '') {
  5126. $this->body = '';
  5127. } else {
  5128. $data = json_encode($body, JSON_UNESCAPED_UNICODE);
  5129. $this->addHeader('Content-Type', 'application/json');
  5130. $this->addHeader('Content-Length', strlen($data));
  5131. $this->body = $data;
  5132. }
  5133. }
  5134. public function getStatus(): int
  5135. {
  5136. return $this->status;
  5137. }
  5138. public function getBody(): String
  5139. {
  5140. return $this->body;
  5141. }
  5142. public function addHeader(String $key, String $value)
  5143. {
  5144. $this->headers[$key] = $value;
  5145. }
  5146. public function getHeader(String $key): String
  5147. {
  5148. if (isset($this->headers[$key])) {
  5149. return $this->headers[$key];
  5150. }
  5151. return null;
  5152. }
  5153. public function getHeaders(): array
  5154. {
  5155. return $this->headers;
  5156. }
  5157. public function output()
  5158. {
  5159. http_response_code($this->getStatus());
  5160. foreach ($this->headers as $key => $value) {
  5161. header("$key: $value");
  5162. }
  5163. echo $this->getBody();
  5164. }
  5165. public function __toString(): String
  5166. {
  5167. $str = "$this->status\n";
  5168. foreach ($this->headers as $key => $value) {
  5169. $str .= "$key: $value\n";
  5170. }
  5171. if ($this->body !== '') {
  5172. $str .= "\n";
  5173. $str .= "$this->body\n";
  5174. }
  5175. return $str;
  5176. }
  5177. }
  5178. // file: src/index.php
  5179. $config = new Config([
  5180. 'username' => 'php-crud-api',
  5181. 'password' => 'php-crud-api',
  5182. 'database' => 'php-crud-api',
  5183. ]);
  5184. $request = new Request();
  5185. $api = new Api($config);
  5186. $response = $api->handle($request);
  5187. $response->output();