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

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