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.

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