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

api.php 253KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739
  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. * Dependencies:
  8. * - vendor/psr/*: PHP-FIG
  9. * https://github.com/php-fig
  10. * - vendor/nyholm/*: Tobias Nyholm
  11. * https://github.com/Nyholm
  12. **/
  13. namespace Tqdev\PhpCrudApi;
  14. // file: vendor/psr/http-factory/src/RequestFactoryInterface.php
  15. interface RequestFactoryInterface
  16. {
  17. public function createRequest(string $method, $uri): RequestInterface;
  18. }
  19. // file: vendor/psr/http-factory/src/ResponseFactoryInterface.php
  20. interface ResponseFactoryInterface
  21. {
  22. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface;
  23. }
  24. // file: vendor/psr/http-factory/src/ServerRequestFactoryInterface.php
  25. interface ServerRequestFactoryInterface
  26. {
  27. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface;
  28. }
  29. // file: vendor/psr/http-factory/src/StreamFactoryInterface.php
  30. interface StreamFactoryInterface
  31. {
  32. public function createStream(string $content = ''): StreamInterface;
  33. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface;
  34. public function createStreamFromResource($resource): StreamInterface;
  35. }
  36. // file: vendor/psr/http-factory/src/UploadedFileFactoryInterface.php
  37. interface UploadedFileFactoryInterface
  38. {
  39. public function createUploadedFile(
  40. StreamInterface $stream,
  41. int $size = null,
  42. int $error = \UPLOAD_ERR_OK,
  43. string $clientFilename = null,
  44. string $clientMediaType = null
  45. ): UploadedFileInterface;
  46. }
  47. // file: vendor/psr/http-factory/src/UriFactoryInterface.php
  48. interface UriFactoryInterface
  49. {
  50. public function createUri(string $uri = ''): UriInterface;
  51. }
  52. // file: vendor/psr/http-message/src/MessageInterface.php
  53. interface MessageInterface
  54. {
  55. public function getProtocolVersion();
  56. public function withProtocolVersion($version);
  57. public function getHeaders();
  58. public function hasHeader($name);
  59. public function getHeader($name);
  60. public function getHeaderLine($name);
  61. public function withHeader($name, $value);
  62. public function withAddedHeader($name, $value);
  63. public function withoutHeader($name);
  64. public function getBody();
  65. public function withBody(StreamInterface $body);
  66. }
  67. // file: vendor/psr/http-message/src/RequestInterface.php
  68. interface RequestInterface extends MessageInterface
  69. {
  70. public function getRequestTarget();
  71. public function withRequestTarget($requestTarget);
  72. public function getMethod();
  73. public function withMethod($method);
  74. public function getUri();
  75. public function withUri(UriInterface $uri, $preserveHost = false);
  76. }
  77. // file: vendor/psr/http-message/src/ResponseInterface.php
  78. interface ResponseInterface extends MessageInterface
  79. {
  80. public function getStatusCode();
  81. public function withStatus($code, $reasonPhrase = '');
  82. public function getReasonPhrase();
  83. }
  84. // file: vendor/psr/http-message/src/ServerRequestInterface.php
  85. interface ServerRequestInterface extends RequestInterface
  86. {
  87. public function getServerParams();
  88. public function getCookieParams();
  89. public function withCookieParams(array $cookies);
  90. public function getQueryParams();
  91. public function withQueryParams(array $query);
  92. public function getUploadedFiles();
  93. public function withUploadedFiles(array $uploadedFiles);
  94. public function getParsedBody();
  95. public function withParsedBody($data);
  96. public function getAttributes();
  97. public function getAttribute($name, $default = null);
  98. public function withAttribute($name, $value);
  99. public function withoutAttribute($name);
  100. }
  101. // file: vendor/psr/http-message/src/StreamInterface.php
  102. interface StreamInterface
  103. {
  104. public function __toString();
  105. public function close();
  106. public function detach();
  107. public function getSize();
  108. public function tell();
  109. public function eof();
  110. public function isSeekable();
  111. public function seek($offset, $whence = SEEK_SET);
  112. public function rewind();
  113. public function isWritable();
  114. public function write($string);
  115. public function isReadable();
  116. public function read($length);
  117. public function getContents();
  118. public function getMetadata($key = null);
  119. }
  120. // file: vendor/psr/http-message/src/UploadedFileInterface.php
  121. interface UploadedFileInterface
  122. {
  123. public function getStream();
  124. public function moveTo($targetPath);
  125. public function getSize();
  126. public function getError();
  127. public function getClientFilename();
  128. public function getClientMediaType();
  129. }
  130. // file: vendor/psr/http-message/src/UriInterface.php
  131. interface UriInterface
  132. {
  133. public function getScheme();
  134. public function getAuthority();
  135. public function getUserInfo();
  136. public function getHost();
  137. public function getPort();
  138. public function getPath();
  139. public function getQuery();
  140. public function getFragment();
  141. public function withScheme($scheme);
  142. public function withUserInfo($user, $password = null);
  143. public function withHost($host);
  144. public function withPort($port);
  145. public function withPath($path);
  146. public function withQuery($query);
  147. public function withFragment($fragment);
  148. public function __toString();
  149. }
  150. // file: vendor/psr/http-server-handler/src/RequestHandlerInterface.php
  151. interface RequestHandlerInterface
  152. {
  153. public function handle(ServerRequestInterface $request): ResponseInterface;
  154. }
  155. // file: vendor/psr/http-server-middleware/src/MiddlewareInterface.php
  156. interface MiddlewareInterface
  157. {
  158. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
  159. }
  160. // file: vendor/nyholm/psr7/src/Factory/Psr17Factory.php
  161. final class Psr17Factory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
  162. {
  163. public function createRequest(string $method, $uri): RequestInterface
  164. {
  165. return new Request($method, $uri);
  166. }
  167. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface
  168. {
  169. return new Response($code, [], null, '1.1', $reasonPhrase);
  170. }
  171. public function createStream(string $content = ''): StreamInterface
  172. {
  173. return Stream::create($content);
  174. }
  175. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
  176. {
  177. $resource = @\fopen($filename, $mode);
  178. if (false === $resource) {
  179. if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'])) {
  180. throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.');
  181. }
  182. throw new \RuntimeException('The file ' . $filename . ' cannot be opened.');
  183. }
  184. return Stream::create($resource);
  185. }
  186. public function createStreamFromResource($resource): StreamInterface
  187. {
  188. return Stream::create($resource);
  189. }
  190. public function createUploadedFile(StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null): UploadedFileInterface
  191. {
  192. if (null === $size) {
  193. $size = $stream->getSize();
  194. }
  195. return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);
  196. }
  197. public function createUri(string $uri = ''): UriInterface
  198. {
  199. return new Uri($uri);
  200. }
  201. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  202. {
  203. return new ServerRequest($method, $uri, [], null, '1.1', $serverParams);
  204. }
  205. }
  206. // file: vendor/nyholm/psr7/src/MessageTrait.php
  207. trait MessageTrait
  208. {
  209. private $headers = [];
  210. private $headerNames = [];
  211. private $protocol = '1.1';
  212. private $stream;
  213. public function getProtocolVersion(): string
  214. {
  215. return $this->protocol;
  216. }
  217. public function withProtocolVersion($version): self
  218. {
  219. if ($this->protocol === $version) {
  220. return $this;
  221. }
  222. $new = clone $this;
  223. $new->protocol = $version;
  224. return $new;
  225. }
  226. public function getHeaders(): array
  227. {
  228. return $this->headers;
  229. }
  230. public function hasHeader($header): bool
  231. {
  232. return isset($this->headerNames[\strtolower($header)]);
  233. }
  234. public function getHeader($header): array
  235. {
  236. $header = \strtolower($header);
  237. if (!isset($this->headerNames[$header])) {
  238. return [];
  239. }
  240. $header = $this->headerNames[$header];
  241. return $this->headers[$header];
  242. }
  243. public function getHeaderLine($header): string
  244. {
  245. return \implode(', ', $this->getHeader($header));
  246. }
  247. public function withHeader($header, $value): self
  248. {
  249. $value = $this->validateAndTrimHeader($header, $value);
  250. $normalized = \strtolower($header);
  251. $new = clone $this;
  252. if (isset($new->headerNames[$normalized])) {
  253. unset($new->headers[$new->headerNames[$normalized]]);
  254. }
  255. $new->headerNames[$normalized] = $header;
  256. $new->headers[$header] = $value;
  257. return $new;
  258. }
  259. public function withAddedHeader($header, $value): self
  260. {
  261. if (!\is_string($header) || '' === $header) {
  262. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  263. }
  264. $new = clone $this;
  265. $new->setHeaders([$header => $value]);
  266. return $new;
  267. }
  268. public function withoutHeader($header): self
  269. {
  270. $normalized = \strtolower($header);
  271. if (!isset($this->headerNames[$normalized])) {
  272. return $this;
  273. }
  274. $header = $this->headerNames[$normalized];
  275. $new = clone $this;
  276. unset($new->headers[$header], $new->headerNames[$normalized]);
  277. return $new;
  278. }
  279. public function getBody(): StreamInterface
  280. {
  281. if (null === $this->stream) {
  282. $this->stream = Stream::create('');
  283. }
  284. return $this->stream;
  285. }
  286. public function withBody(StreamInterface $body): self
  287. {
  288. if ($body === $this->stream) {
  289. return $this;
  290. }
  291. $new = clone $this;
  292. $new->stream = $body;
  293. return $new;
  294. }
  295. private function setHeaders(array $headers) /*:void*/
  296. {
  297. foreach ($headers as $header => $value) {
  298. $value = $this->validateAndTrimHeader($header, $value);
  299. $normalized = \strtolower($header);
  300. if (isset($this->headerNames[$normalized])) {
  301. $header = $this->headerNames[$normalized];
  302. $this->headers[$header] = \array_merge($this->headers[$header], $value);
  303. } else {
  304. $this->headerNames[$normalized] = $header;
  305. $this->headers[$header] = $value;
  306. }
  307. }
  308. }
  309. private function validateAndTrimHeader($header, $values): array
  310. {
  311. if (!\is_string($header) || 1 !== \preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@", $header)) {
  312. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  313. }
  314. if (!\is_array($values)) {
  315. if ((!\is_numeric($values) && !\is_string($values)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $values)) {
  316. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  317. }
  318. return [\trim((string) $values, " \t")];
  319. }
  320. if (empty($values)) {
  321. throw new \InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
  322. }
  323. $returnValues = [];
  324. foreach ($values as $v) {
  325. if ((!\is_numeric($v) && !\is_string($v)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $v)) {
  326. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  327. }
  328. $returnValues[] = \trim((string) $v, " \t");
  329. }
  330. return $returnValues;
  331. }
  332. }
  333. // file: vendor/nyholm/psr7/src/Request.php
  334. final class Request implements RequestInterface
  335. {
  336. use MessageTrait;
  337. use RequestTrait;
  338. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
  339. {
  340. if (!($uri instanceof UriInterface)) {
  341. $uri = new Uri($uri);
  342. }
  343. $this->method = $method;
  344. $this->uri = $uri;
  345. $this->setHeaders($headers);
  346. $this->protocol = $version;
  347. if (!$this->hasHeader('Host')) {
  348. $this->updateHostFromUri();
  349. }
  350. if ('' !== $body && null !== $body) {
  351. $this->stream = Stream::create($body);
  352. }
  353. }
  354. }
  355. // file: vendor/nyholm/psr7/src/RequestTrait.php
  356. trait RequestTrait
  357. {
  358. private $method;
  359. private $requestTarget;
  360. private $uri;
  361. public function getRequestTarget(): string
  362. {
  363. if (null !== $this->requestTarget) {
  364. return $this->requestTarget;
  365. }
  366. if ('' === $target = $this->uri->getPath()) {
  367. $target = '/';
  368. }
  369. if ('' !== $this->uri->getQuery()) {
  370. $target .= '?' . $this->uri->getQuery();
  371. }
  372. return $target;
  373. }
  374. public function withRequestTarget($requestTarget): self
  375. {
  376. if (\preg_match('#\s#', $requestTarget)) {
  377. throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
  378. }
  379. $new = clone $this;
  380. $new->requestTarget = $requestTarget;
  381. return $new;
  382. }
  383. public function getMethod(): string
  384. {
  385. return $this->method;
  386. }
  387. public function withMethod($method): self
  388. {
  389. if (!\is_string($method)) {
  390. throw new \InvalidArgumentException('Method must be a string');
  391. }
  392. $new = clone $this;
  393. $new->method = $method;
  394. return $new;
  395. }
  396. public function getUri(): UriInterface
  397. {
  398. return $this->uri;
  399. }
  400. public function withUri(UriInterface $uri, $preserveHost = false): self
  401. {
  402. if ($uri === $this->uri) {
  403. return $this;
  404. }
  405. $new = clone $this;
  406. $new->uri = $uri;
  407. if (!$preserveHost || !$this->hasHeader('Host')) {
  408. $new->updateHostFromUri();
  409. }
  410. return $new;
  411. }
  412. private function updateHostFromUri() /*:void*/
  413. {
  414. if ('' === $host = $this->uri->getHost()) {
  415. return;
  416. }
  417. if (null !== ($port = $this->uri->getPort())) {
  418. $host .= ':' . $port;
  419. }
  420. if (isset($this->headerNames['host'])) {
  421. $header = $this->headerNames['host'];
  422. } else {
  423. $this->headerNames['host'] = $header = 'Host';
  424. }
  425. $this->headers = [$header => [$host]] + $this->headers;
  426. }
  427. }
  428. // file: vendor/nyholm/psr7/src/Response.php
  429. final class Response implements ResponseInterface
  430. {
  431. use MessageTrait;
  432. /*private*/ const PHRASES = [
  433. 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing',
  434. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported',
  435. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect',
  436. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons',
  437. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 511 => 'Network Authentication Required',
  438. ];
  439. private $reasonPhrase = '';
  440. private $statusCode;
  441. public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
  442. {
  443. if ('' !== $body && null !== $body) {
  444. $this->stream = Stream::create($body);
  445. }
  446. $this->statusCode = $status;
  447. $this->setHeaders($headers);
  448. if (null === $reason && isset(self::PHRASES[$this->statusCode])) {
  449. $this->reasonPhrase = self::PHRASES[$status];
  450. } else {
  451. $this->reasonPhrase = $reason;
  452. }
  453. $this->protocol = $version;
  454. }
  455. public function getStatusCode(): int
  456. {
  457. return $this->statusCode;
  458. }
  459. public function getReasonPhrase(): string
  460. {
  461. return $this->reasonPhrase;
  462. }
  463. public function withStatus($code, $reasonPhrase = ''): self
  464. {
  465. if (!\is_int($code) && !\is_string($code)) {
  466. throw new \InvalidArgumentException('Status code has to be an integer');
  467. }
  468. $code = (int) $code;
  469. if ($code < 100 || $code > 599) {
  470. throw new \InvalidArgumentException('Status code has to be an integer between 100 and 599');
  471. }
  472. $new = clone $this;
  473. $new->statusCode = $code;
  474. if ((null === $reasonPhrase || '' === $reasonPhrase) && isset(self::PHRASES[$new->statusCode])) {
  475. $reasonPhrase = self::PHRASES[$new->statusCode];
  476. }
  477. $new->reasonPhrase = $reasonPhrase;
  478. return $new;
  479. }
  480. }
  481. // file: vendor/nyholm/psr7/src/ServerRequest.php
  482. final class ServerRequest implements ServerRequestInterface
  483. {
  484. use MessageTrait;
  485. use RequestTrait;
  486. private $attributes = [];
  487. private $cookieParams = [];
  488. private $parsedBody;
  489. private $queryParams = [];
  490. private $serverParams;
  491. private $uploadedFiles = [];
  492. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
  493. {
  494. $this->serverParams = $serverParams;
  495. if (!($uri instanceof UriInterface)) {
  496. $uri = new Uri($uri);
  497. }
  498. $this->method = $method;
  499. $this->uri = $uri;
  500. $this->setHeaders($headers);
  501. $this->protocol = $version;
  502. if (!$this->hasHeader('Host')) {
  503. $this->updateHostFromUri();
  504. }
  505. if ('' !== $body && null !== $body) {
  506. $this->stream = Stream::create($body);
  507. }
  508. }
  509. public function getServerParams(): array
  510. {
  511. return $this->serverParams;
  512. }
  513. public function getUploadedFiles(): array
  514. {
  515. return $this->uploadedFiles;
  516. }
  517. public function withUploadedFiles(array $uploadedFiles)
  518. {
  519. $new = clone $this;
  520. $new->uploadedFiles = $uploadedFiles;
  521. return $new;
  522. }
  523. public function getCookieParams(): array
  524. {
  525. return $this->cookieParams;
  526. }
  527. public function withCookieParams(array $cookies)
  528. {
  529. $new = clone $this;
  530. $new->cookieParams = $cookies;
  531. return $new;
  532. }
  533. public function getQueryParams(): array
  534. {
  535. return $this->queryParams;
  536. }
  537. public function withQueryParams(array $query)
  538. {
  539. $new = clone $this;
  540. $new->queryParams = $query;
  541. return $new;
  542. }
  543. public function getParsedBody()
  544. {
  545. return $this->parsedBody;
  546. }
  547. public function withParsedBody($data)
  548. {
  549. if (!\is_array($data) && !\is_object($data) && null !== $data) {
  550. throw new \InvalidArgumentException('First parameter to withParsedBody MUST be object, array or null');
  551. }
  552. $new = clone $this;
  553. $new->parsedBody = $data;
  554. return $new;
  555. }
  556. public function getAttributes(): array
  557. {
  558. return $this->attributes;
  559. }
  560. public function getAttribute($attribute, $default = null)
  561. {
  562. if (false === \array_key_exists($attribute, $this->attributes)) {
  563. return $default;
  564. }
  565. return $this->attributes[$attribute];
  566. }
  567. public function withAttribute($attribute, $value): self
  568. {
  569. $new = clone $this;
  570. $new->attributes[$attribute] = $value;
  571. return $new;
  572. }
  573. public function withoutAttribute($attribute): self
  574. {
  575. if (false === \array_key_exists($attribute, $this->attributes)) {
  576. return $this;
  577. }
  578. $new = clone $this;
  579. unset($new->attributes[$attribute]);
  580. return $new;
  581. }
  582. }
  583. // file: vendor/nyholm/psr7/src/Stream.php
  584. final class Stream implements StreamInterface
  585. {
  586. private $stream;
  587. private $seekable;
  588. private $readable;
  589. private $writable;
  590. private $uri;
  591. private $size;
  592. /*private*/ const READ_WRITE_HASH = [
  593. 'read' => [
  594. 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
  595. 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
  596. 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
  597. 'x+t' => true, 'c+t' => true, 'a+' => true,
  598. ],
  599. 'write' => [
  600. 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
  601. 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
  602. 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
  603. 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
  604. ],
  605. ];
  606. private function __construct()
  607. {
  608. }
  609. public static function create($body = ''): StreamInterface
  610. {
  611. if ($body instanceof StreamInterface) {
  612. return $body;
  613. }
  614. if (\is_string($body)) {
  615. $resource = \fopen('php://temp', 'rw+');
  616. \fwrite($resource, $body);
  617. $body = $resource;
  618. }
  619. if (\is_resource($body)) {
  620. $new = new self();
  621. $new->stream = $body;
  622. $meta = \stream_get_meta_data($new->stream);
  623. $new->seekable = $meta['seekable'];
  624. $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]);
  625. $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]);
  626. $new->uri = $new->getMetadata('uri');
  627. return $new;
  628. }
  629. throw new \InvalidArgumentException('First argument to Stream::create() must be a string, resource or StreamInterface.');
  630. }
  631. public function __destruct()
  632. {
  633. $this->close();
  634. }
  635. public function __toString(): string
  636. {
  637. try {
  638. if ($this->isSeekable()) {
  639. $this->seek(0);
  640. }
  641. return $this->getContents();
  642. } catch (\Exception $e) {
  643. return '';
  644. }
  645. }
  646. public function close() /*:void*/
  647. {
  648. if (isset($this->stream)) {
  649. if (\is_resource($this->stream)) {
  650. \fclose($this->stream);
  651. }
  652. $this->detach();
  653. }
  654. }
  655. public function detach()
  656. {
  657. if (!isset($this->stream)) {
  658. return null;
  659. }
  660. $result = $this->stream;
  661. unset($this->stream);
  662. $this->size = $this->uri = null;
  663. $this->readable = $this->writable = $this->seekable = false;
  664. return $result;
  665. }
  666. public function getSize() /*:?int*/
  667. {
  668. if (null !== $this->size) {
  669. return $this->size;
  670. }
  671. if (!isset($this->stream)) {
  672. return null;
  673. }
  674. if ($this->uri) {
  675. \clearstatcache(true, $this->uri);
  676. }
  677. $stats = \fstat($this->stream);
  678. if (isset($stats['size'])) {
  679. $this->size = $stats['size'];
  680. return $this->size;
  681. }
  682. return null;
  683. }
  684. public function tell(): int
  685. {
  686. if (false === $result = \ftell($this->stream)) {
  687. throw new \RuntimeException('Unable to determine stream position');
  688. }
  689. return $result;
  690. }
  691. public function eof(): bool
  692. {
  693. return !$this->stream || \feof($this->stream);
  694. }
  695. public function isSeekable(): bool
  696. {
  697. return $this->seekable;
  698. }
  699. public function seek($offset, $whence = \SEEK_SET) /*:void*/
  700. {
  701. if (!$this->seekable) {
  702. throw new \RuntimeException('Stream is not seekable');
  703. }
  704. if (-1 === \fseek($this->stream, $offset, $whence)) {
  705. throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, true));
  706. }
  707. }
  708. public function rewind() /*:void*/
  709. {
  710. $this->seek(0);
  711. }
  712. public function isWritable(): bool
  713. {
  714. return $this->writable;
  715. }
  716. public function write($string): int
  717. {
  718. if (!$this->writable) {
  719. throw new \RuntimeException('Cannot write to a non-writable stream');
  720. }
  721. $this->size = null;
  722. if (false === $result = \fwrite($this->stream, $string)) {
  723. throw new \RuntimeException('Unable to write to stream');
  724. }
  725. return $result;
  726. }
  727. public function isReadable(): bool
  728. {
  729. return $this->readable;
  730. }
  731. public function read($length): string
  732. {
  733. if (!$this->readable) {
  734. throw new \RuntimeException('Cannot read from non-readable stream');
  735. }
  736. return \fread($this->stream, $length);
  737. }
  738. public function getContents(): string
  739. {
  740. if (!isset($this->stream)) {
  741. throw new \RuntimeException('Unable to read stream contents');
  742. }
  743. if (false === $contents = \stream_get_contents($this->stream)) {
  744. throw new \RuntimeException('Unable to read stream contents');
  745. }
  746. return $contents;
  747. }
  748. public function getMetadata($key = null)
  749. {
  750. if (!isset($this->stream)) {
  751. return $key ? null : [];
  752. }
  753. $meta = \stream_get_meta_data($this->stream);
  754. if (null === $key) {
  755. return $meta;
  756. }
  757. return $meta[$key] ?? null;
  758. }
  759. }
  760. // file: vendor/nyholm/psr7/src/UploadedFile.php
  761. final class UploadedFile implements UploadedFileInterface
  762. {
  763. /*private*/ const ERRORS = [
  764. \UPLOAD_ERR_OK => 1,
  765. \UPLOAD_ERR_INI_SIZE => 1,
  766. \UPLOAD_ERR_FORM_SIZE => 1,
  767. \UPLOAD_ERR_PARTIAL => 1,
  768. \UPLOAD_ERR_NO_FILE => 1,
  769. \UPLOAD_ERR_NO_TMP_DIR => 1,
  770. \UPLOAD_ERR_CANT_WRITE => 1,
  771. \UPLOAD_ERR_EXTENSION => 1,
  772. ];
  773. private $clientFilename;
  774. private $clientMediaType;
  775. private $error;
  776. private $file;
  777. private $moved = false;
  778. private $size;
  779. private $stream;
  780. public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
  781. {
  782. if (false === \is_int($errorStatus) || !isset(self::ERRORS[$errorStatus])) {
  783. throw new \InvalidArgumentException('Upload file error status must be an integer value and one of the "UPLOAD_ERR_*" constants.');
  784. }
  785. if (false === \is_int($size)) {
  786. throw new \InvalidArgumentException('Upload file size must be an integer');
  787. }
  788. if (null !== $clientFilename && !\is_string($clientFilename)) {
  789. throw new \InvalidArgumentException('Upload file client filename must be a string or null');
  790. }
  791. if (null !== $clientMediaType && !\is_string($clientMediaType)) {
  792. throw new \InvalidArgumentException('Upload file client media type must be a string or null');
  793. }
  794. $this->error = $errorStatus;
  795. $this->size = $size;
  796. $this->clientFilename = $clientFilename;
  797. $this->clientMediaType = $clientMediaType;
  798. if (\UPLOAD_ERR_OK === $this->error) {
  799. if (\is_string($streamOrFile)) {
  800. $this->file = $streamOrFile;
  801. } elseif (\is_resource($streamOrFile)) {
  802. $this->stream = Stream::create($streamOrFile);
  803. } elseif ($streamOrFile instanceof StreamInterface) {
  804. $this->stream = $streamOrFile;
  805. } else {
  806. throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile');
  807. }
  808. }
  809. }
  810. private function validateActive() /*:void*/
  811. {
  812. if (\UPLOAD_ERR_OK !== $this->error) {
  813. throw new \RuntimeException('Cannot retrieve stream due to upload error');
  814. }
  815. if ($this->moved) {
  816. throw new \RuntimeException('Cannot retrieve stream after it has already been moved');
  817. }
  818. }
  819. public function getStream(): StreamInterface
  820. {
  821. $this->validateActive();
  822. if ($this->stream instanceof StreamInterface) {
  823. return $this->stream;
  824. }
  825. $resource = \fopen($this->file, 'r');
  826. return Stream::create($resource);
  827. }
  828. public function moveTo($targetPath) /*:void*/
  829. {
  830. $this->validateActive();
  831. if (!\is_string($targetPath) || '' === $targetPath) {
  832. throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
  833. }
  834. if (null !== $this->file) {
  835. $this->moved = 'cli' === \PHP_SAPI ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath);
  836. } else {
  837. $stream = $this->getStream();
  838. if ($stream->isSeekable()) {
  839. $stream->rewind();
  840. }
  841. $dest = Stream::create(\fopen($targetPath, 'w'));
  842. while (!$stream->eof()) {
  843. if (!$dest->write($stream->read(1048576))) {
  844. break;
  845. }
  846. }
  847. $this->moved = true;
  848. }
  849. if (false === $this->moved) {
  850. throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath));
  851. }
  852. }
  853. public function getSize(): int
  854. {
  855. return $this->size;
  856. }
  857. public function getError(): int
  858. {
  859. return $this->error;
  860. }
  861. public function getClientFilename() /*:?string*/
  862. {
  863. return $this->clientFilename;
  864. }
  865. public function getClientMediaType() /*:?string*/
  866. {
  867. return $this->clientMediaType;
  868. }
  869. }
  870. // file: vendor/nyholm/psr7/src/Uri.php
  871. final class Uri implements UriInterface
  872. {
  873. /*private*/ const SCHEMES = ['http' => 80, 'https' => 443];
  874. /*private*/ const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  875. /*private*/ const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  876. private $scheme = '';
  877. private $userInfo = '';
  878. private $host = '';
  879. private $port;
  880. private $path = '';
  881. private $query = '';
  882. private $fragment = '';
  883. public function __construct(string $uri = '')
  884. {
  885. if ('' !== $uri) {
  886. if (false === $parts = \parse_url($uri)) {
  887. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  888. }
  889. $this->scheme = isset($parts['scheme']) ? \strtolower($parts['scheme']) : '';
  890. $this->userInfo = $parts['user'] ?? '';
  891. $this->host = isset($parts['host']) ? \strtolower($parts['host']) : '';
  892. $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
  893. $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
  894. $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : '';
  895. $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : '';
  896. if (isset($parts['pass'])) {
  897. $this->userInfo .= ':' . $parts['pass'];
  898. }
  899. }
  900. }
  901. public function __toString(): string
  902. {
  903. return self::createUriString($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment);
  904. }
  905. public function getScheme(): string
  906. {
  907. return $this->scheme;
  908. }
  909. public function getAuthority(): string
  910. {
  911. if ('' === $this->host) {
  912. return '';
  913. }
  914. $authority = $this->host;
  915. if ('' !== $this->userInfo) {
  916. $authority = $this->userInfo . '@' . $authority;
  917. }
  918. if (null !== $this->port) {
  919. $authority .= ':' . $this->port;
  920. }
  921. return $authority;
  922. }
  923. public function getUserInfo(): string
  924. {
  925. return $this->userInfo;
  926. }
  927. public function getHost(): string
  928. {
  929. return $this->host;
  930. }
  931. public function getPort() /*:?int*/
  932. {
  933. return $this->port;
  934. }
  935. public function getPath(): string
  936. {
  937. return $this->path;
  938. }
  939. public function getQuery(): string
  940. {
  941. return $this->query;
  942. }
  943. public function getFragment(): string
  944. {
  945. return $this->fragment;
  946. }
  947. public function withScheme($scheme): self
  948. {
  949. if (!\is_string($scheme)) {
  950. throw new \InvalidArgumentException('Scheme must be a string');
  951. }
  952. if ($this->scheme === $scheme = \strtolower($scheme)) {
  953. return $this;
  954. }
  955. $new = clone $this;
  956. $new->scheme = $scheme;
  957. $new->port = $new->filterPort($new->port);
  958. return $new;
  959. }
  960. public function withUserInfo($user, $password = null): self
  961. {
  962. $info = $user;
  963. if (null !== $password && '' !== $password) {
  964. $info .= ':' . $password;
  965. }
  966. if ($this->userInfo === $info) {
  967. return $this;
  968. }
  969. $new = clone $this;
  970. $new->userInfo = $info;
  971. return $new;
  972. }
  973. public function withHost($host): self
  974. {
  975. if (!\is_string($host)) {
  976. throw new \InvalidArgumentException('Host must be a string');
  977. }
  978. if ($this->host === $host = \strtolower($host)) {
  979. return $this;
  980. }
  981. $new = clone $this;
  982. $new->host = $host;
  983. return $new;
  984. }
  985. public function withPort($port): self
  986. {
  987. if ($this->port === $port = $this->filterPort($port)) {
  988. return $this;
  989. }
  990. $new = clone $this;
  991. $new->port = $port;
  992. return $new;
  993. }
  994. public function withPath($path): self
  995. {
  996. if ($this->path === $path = $this->filterPath($path)) {
  997. return $this;
  998. }
  999. $new = clone $this;
  1000. $new->path = $path;
  1001. return $new;
  1002. }
  1003. public function withQuery($query): self
  1004. {
  1005. if ($this->query === $query = $this->filterQueryAndFragment($query)) {
  1006. return $this;
  1007. }
  1008. $new = clone $this;
  1009. $new->query = $query;
  1010. return $new;
  1011. }
  1012. public function withFragment($fragment): self
  1013. {
  1014. if ($this->fragment === $fragment = $this->filterQueryAndFragment($fragment)) {
  1015. return $this;
  1016. }
  1017. $new = clone $this;
  1018. $new->fragment = $fragment;
  1019. return $new;
  1020. }
  1021. private static function createUriString(string $scheme, string $authority, string $path, string $query, string $fragment): string
  1022. {
  1023. $uri = '';
  1024. if ('' !== $scheme) {
  1025. $uri .= $scheme . ':';
  1026. }
  1027. if ('' !== $authority) {
  1028. $uri .= '//' . $authority;
  1029. }
  1030. if ('' !== $path) {
  1031. if ('/' !== $path[0]) {
  1032. if ('' !== $authority) {
  1033. $path = '/' . $path;
  1034. }
  1035. } elseif (isset($path[1]) && '/' === $path[1]) {
  1036. if ('' === $authority) {
  1037. $path = '/' . \ltrim($path, '/');
  1038. }
  1039. }
  1040. $uri .= $path;
  1041. }
  1042. if ('' !== $query) {
  1043. $uri .= '?' . $query;
  1044. }
  1045. if ('' !== $fragment) {
  1046. $uri .= '#' . $fragment;
  1047. }
  1048. return $uri;
  1049. }
  1050. private static function isNonStandardPort(string $scheme, int $port): bool
  1051. {
  1052. return !isset(self::SCHEMES[$scheme]) || $port !== self::SCHEMES[$scheme];
  1053. }
  1054. private function filterPort($port) /*:?int*/
  1055. {
  1056. if (null === $port) {
  1057. return null;
  1058. }
  1059. $port = (int) $port;
  1060. if (1 > $port || 0xffff < $port) {
  1061. throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 1 and 65535', $port));
  1062. }
  1063. return self::isNonStandardPort($this->scheme, $port) ? $port : null;
  1064. }
  1065. private function filterPath($path): string
  1066. {
  1067. if (!\is_string($path)) {
  1068. throw new \InvalidArgumentException('Path must be a string');
  1069. }
  1070. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $path);
  1071. }
  1072. private function filterQueryAndFragment($str): string
  1073. {
  1074. if (!\is_string($str)) {
  1075. throw new \InvalidArgumentException('Query and fragment must be a string');
  1076. }
  1077. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $str);
  1078. }
  1079. private static function rawurlencodeMatchZero(array $match): string
  1080. {
  1081. return \rawurlencode($match[0]);
  1082. }
  1083. }
  1084. // file: vendor/nyholm/psr7-server/src/ServerRequestCreator.php
  1085. final class ServerRequestCreator implements ServerRequestCreatorInterface
  1086. {
  1087. private $serverRequestFactory;
  1088. private $uriFactory;
  1089. private $uploadedFileFactory;
  1090. private $streamFactory;
  1091. public function __construct(
  1092. ServerRequestFactoryInterface $serverRequestFactory,
  1093. UriFactoryInterface $uriFactory,
  1094. UploadedFileFactoryInterface $uploadedFileFactory,
  1095. StreamFactoryInterface $streamFactory
  1096. ) {
  1097. $this->serverRequestFactory = $serverRequestFactory;
  1098. $this->uriFactory = $uriFactory;
  1099. $this->uploadedFileFactory = $uploadedFileFactory;
  1100. $this->streamFactory = $streamFactory;
  1101. }
  1102. public function fromGlobals(): ServerRequestInterface
  1103. {
  1104. $server = $_SERVER;
  1105. if (false === isset($server['REQUEST_METHOD'])) {
  1106. $server['REQUEST_METHOD'] = 'GET';
  1107. }
  1108. $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
  1109. return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $_POST, $_FILES, fopen('php://input', 'r') ?: null);
  1110. }
  1111. public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
  1112. {
  1113. $method = $this->getMethodFromEnv($server);
  1114. $uri = $this->getUriFromEnvWithHTTP($server);
  1115. $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
  1116. $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
  1117. foreach ($headers as $name => $value) {
  1118. $serverRequest = $serverRequest->withAddedHeader($name, $value);
  1119. }
  1120. $serverRequest = $serverRequest
  1121. ->withProtocolVersion($protocol)
  1122. ->withCookieParams($cookie)
  1123. ->withQueryParams($get)
  1124. ->withParsedBody($post)
  1125. ->withUploadedFiles($this->normalizeFiles($files));
  1126. if (null === $body) {
  1127. return $serverRequest;
  1128. }
  1129. if (\is_resource($body)) {
  1130. $body = $this->streamFactory->createStreamFromResource($body);
  1131. } elseif (\is_string($body)) {
  1132. $body = $this->streamFactory->createStream($body);
  1133. } elseif (!$body instanceof StreamInterface) {
  1134. throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
  1135. }
  1136. return $serverRequest->withBody($body);
  1137. }
  1138. public static function getHeadersFromServer(array $server): array
  1139. {
  1140. $headers = [];
  1141. foreach ($server as $key => $value) {
  1142. if (0 === \strpos($key, 'REDIRECT_')) {
  1143. $key = \substr($key, 9);
  1144. if (\array_key_exists($key, $server)) {
  1145. continue;
  1146. }
  1147. }
  1148. if ($value && 0 === \strpos($key, 'HTTP_')) {
  1149. $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
  1150. $headers[$name] = $value;
  1151. continue;
  1152. }
  1153. if ($value && 0 === \strpos($key, 'CONTENT_')) {
  1154. $name = 'content-'.\strtolower(\substr($key, 8));
  1155. $headers[$name] = $value;
  1156. continue;
  1157. }
  1158. }
  1159. return $headers;
  1160. }
  1161. private function getMethodFromEnv(array $environment): string
  1162. {
  1163. if (false === isset($environment['REQUEST_METHOD'])) {
  1164. throw new \InvalidArgumentException('Cannot determine HTTP method');
  1165. }
  1166. return $environment['REQUEST_METHOD'];
  1167. }
  1168. private function getUriFromEnvWithHTTP(array $environment): UriInterface
  1169. {
  1170. $uri = $this->createUriFromArray($environment);
  1171. if (empty($uri->getScheme())) {
  1172. $uri = $uri->withScheme('http');
  1173. }
  1174. return $uri;
  1175. }
  1176. private function normalizeFiles(array $files): array
  1177. {
  1178. $normalized = [];
  1179. foreach ($files as $key => $value) {
  1180. if ($value instanceof UploadedFileInterface) {
  1181. $normalized[$key] = $value;
  1182. } elseif (\is_array($value) && isset($value['tmp_name'])) {
  1183. $normalized[$key] = $this->createUploadedFileFromSpec($value);
  1184. } elseif (\is_array($value)) {
  1185. $normalized[$key] = $this->normalizeFiles($value);
  1186. } else {
  1187. throw new \InvalidArgumentException('Invalid value in files specification');
  1188. }
  1189. }
  1190. return $normalized;
  1191. }
  1192. private function createUploadedFileFromSpec(array $value)
  1193. {
  1194. if (\is_array($value['tmp_name'])) {
  1195. return $this->normalizeNestedFileSpec($value);
  1196. }
  1197. try {
  1198. $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
  1199. } catch (\RuntimeException $e) {
  1200. $stream = $this->streamFactory->createStream();
  1201. }
  1202. return $this->uploadedFileFactory->createUploadedFile(
  1203. $stream,
  1204. (int) $value['size'],
  1205. (int) $value['error'],
  1206. $value['name'],
  1207. $value['type']
  1208. );
  1209. }
  1210. private function normalizeNestedFileSpec(array $files = []): array
  1211. {
  1212. $normalizedFiles = [];
  1213. foreach (\array_keys($files['tmp_name']) as $key) {
  1214. $spec = [
  1215. 'tmp_name' => $files['tmp_name'][$key],
  1216. 'size' => $files['size'][$key],
  1217. 'error' => $files['error'][$key],
  1218. 'name' => $files['name'][$key],
  1219. 'type' => $files['type'][$key],
  1220. ];
  1221. $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
  1222. }
  1223. return $normalizedFiles;
  1224. }
  1225. private function createUriFromArray(array $server): UriInterface
  1226. {
  1227. $uri = $this->uriFactory->createUri('');
  1228. if (isset($server['REQUEST_SCHEME'])) {
  1229. $uri = $uri->withScheme($server['REQUEST_SCHEME']);
  1230. } elseif (isset($server['HTTPS'])) {
  1231. $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
  1232. }
  1233. if (isset($server['HTTP_HOST'])) {
  1234. $uri = $uri->withHost($server['HTTP_HOST']);
  1235. } elseif (isset($server['SERVER_NAME'])) {
  1236. $uri = $uri->withHost($server['SERVER_NAME']);
  1237. }
  1238. if (isset($server['SERVER_PORT'])) {
  1239. $uri = $uri->withPort($server['SERVER_PORT']);
  1240. }
  1241. if (isset($server['REQUEST_URI'])) {
  1242. $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
  1243. }
  1244. if (isset($server['QUERY_STRING'])) {
  1245. $uri = $uri->withQuery($server['QUERY_STRING']);
  1246. }
  1247. return $uri;
  1248. }
  1249. }
  1250. // file: vendor/nyholm/psr7-server/src/ServerRequestCreatorInterface.php
  1251. interface ServerRequestCreatorInterface
  1252. {
  1253. public function fromGlobals(): ServerRequestInterface;
  1254. public function fromArrays(
  1255. array $server,
  1256. array $headers = [],
  1257. array $cookie = [],
  1258. array $get = [],
  1259. array $post = [],
  1260. array $files = [],
  1261. $body = null
  1262. ): ServerRequestInterface;
  1263. public static function getHeadersFromServer(array $server): array;
  1264. }
  1265. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  1266. interface Cache
  1267. {
  1268. public function set(string $key, string $value, int $ttl = 0): bool;
  1269. public function get(string $key): string;
  1270. public function clear(): bool;
  1271. }
  1272. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  1273. class CacheFactory
  1274. {
  1275. const PREFIX = 'phpcrudapi-%s-%s-%s-';
  1276. private static function getPrefix(Config $config): string
  1277. {
  1278. $driver = $config->getDriver();
  1279. $database = $config->getDatabase();
  1280. $filehash = substr(md5(__FILE__), 0, 8);
  1281. return sprintf(self::PREFIX, $driver, $database, $filehash);
  1282. }
  1283. public static function create(Config $config): Cache
  1284. {
  1285. switch ($config->getCacheType()) {
  1286. case 'TempFile':
  1287. $cache = new TempFileCache(self::getPrefix($config), $config->getCachePath());
  1288. break;
  1289. case 'Redis':
  1290. $cache = new RedisCache(self::getPrefix($config), $config->getCachePath());
  1291. break;
  1292. case 'Memcache':
  1293. $cache = new MemcacheCache(self::getPrefix($config), $config->getCachePath());
  1294. break;
  1295. case 'Memcached':
  1296. $cache = new MemcachedCache(self::getPrefix($config), $config->getCachePath());
  1297. break;
  1298. default:
  1299. $cache = new NoCache();
  1300. }
  1301. return $cache;
  1302. }
  1303. }
  1304. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  1305. class MemcacheCache implements Cache
  1306. {
  1307. protected $prefix;
  1308. protected $memcache;
  1309. public function __construct(string $prefix, string $config)
  1310. {
  1311. $this->prefix = $prefix;
  1312. if ($config == '') {
  1313. $address = 'localhost';
  1314. $port = 11211;
  1315. } elseif (strpos($config, ':') === false) {
  1316. $address = $config;
  1317. $port = 11211;
  1318. } else {
  1319. list($address, $port) = explode(':', $config);
  1320. }
  1321. $this->memcache = $this->create();
  1322. $this->memcache->addServer($address, $port);
  1323. }
  1324. protected function create() /*: \Memcache*/
  1325. {
  1326. return new \Memcache();
  1327. }
  1328. public function set(string $key, string $value, int $ttl = 0): bool
  1329. {
  1330. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  1331. }
  1332. public function get(string $key): string
  1333. {
  1334. return $this->memcache->get($this->prefix . $key) ?: '';
  1335. }
  1336. public function clear(): bool
  1337. {
  1338. return $this->memcache->flush();
  1339. }
  1340. }
  1341. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  1342. class MemcachedCache extends MemcacheCache
  1343. {
  1344. protected function create() /*: \Memcached*/
  1345. {
  1346. return new \Memcached();
  1347. }
  1348. public function set(string $key, string $value, int $ttl = 0): bool
  1349. {
  1350. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  1351. }
  1352. }
  1353. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  1354. class NoCache implements Cache
  1355. {
  1356. public function __construct()
  1357. {
  1358. }
  1359. public function set(string $key, string $value, int $ttl = 0): bool
  1360. {
  1361. return true;
  1362. }
  1363. public function get(string $key): string
  1364. {
  1365. return '';
  1366. }
  1367. public function clear(): bool
  1368. {
  1369. return true;
  1370. }
  1371. }
  1372. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  1373. class RedisCache implements Cache
  1374. {
  1375. protected $prefix;
  1376. protected $redis;
  1377. public function __construct(string $prefix, string $config)
  1378. {
  1379. $this->prefix = $prefix;
  1380. if ($config == '') {
  1381. $config = '127.0.0.1';
  1382. }
  1383. $params = explode(':', $config, 6);
  1384. if (isset($params[3])) {
  1385. $params[3] = null;
  1386. }
  1387. $this->redis = new \Redis();
  1388. call_user_func_array(array($this->redis, 'pconnect'), $params);
  1389. }
  1390. public function set(string $key, string $value, int $ttl = 0): bool
  1391. {
  1392. return $this->redis->set($this->prefix . $key, $value, $ttl);
  1393. }
  1394. public function get(string $key): string
  1395. {
  1396. return $this->redis->get($this->prefix . $key) ?: '';
  1397. }
  1398. public function clear(): bool
  1399. {
  1400. return $this->redis->flushDb();
  1401. }
  1402. }
  1403. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  1404. class TempFileCache implements Cache
  1405. {
  1406. const SUFFIX = 'cache';
  1407. private $path;
  1408. private $segments;
  1409. public function __construct(string $prefix, string $config)
  1410. {
  1411. $this->segments = [];
  1412. $s = DIRECTORY_SEPARATOR;
  1413. $ps = PATH_SEPARATOR;
  1414. if ($config == '') {
  1415. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  1416. } elseif (strpos($config, $ps) === false) {
  1417. $this->path = $config;
  1418. } else {
  1419. list($path, $segments) = explode($ps, $config);
  1420. $this->path = $path;
  1421. $this->segments = explode(',', $segments);
  1422. }
  1423. if (file_exists($this->path) && is_dir($this->path)) {
  1424. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  1425. }
  1426. }
  1427. private function getFileName(string $key): string
  1428. {
  1429. $s = DIRECTORY_SEPARATOR;
  1430. $md5 = md5($key);
  1431. $filename = rtrim($this->path, $s) . $s;
  1432. $i = 0;
  1433. foreach ($this->segments as $segment) {
  1434. $filename .= substr($md5, $i, $segment) . $s;
  1435. $i += $segment;
  1436. }
  1437. $filename .= substr($md5, $i);
  1438. return $filename;
  1439. }
  1440. public function set(string $key, string $value, int $ttl = 0): bool
  1441. {
  1442. $filename = $this->getFileName($key);
  1443. $dirname = dirname($filename);
  1444. if (!file_exists($dirname)) {
  1445. if (!mkdir($dirname, 0755, true)) {
  1446. return false;
  1447. }
  1448. }
  1449. $string = $ttl . '|' . $value;
  1450. return $this->filePutContents($filename, $string) !== false;
  1451. }
  1452. private function filePutContents($filename, $string)
  1453. {
  1454. return file_put_contents($filename, $string, LOCK_EX);
  1455. }
  1456. private function fileGetContents($filename)
  1457. {
  1458. $file = fopen($filename, 'rb');
  1459. if ($file === false) {
  1460. return false;
  1461. }
  1462. $lock = flock($file, LOCK_SH);
  1463. if (!$lock) {
  1464. fclose($file);
  1465. return false;
  1466. }
  1467. $string = '';
  1468. while (!feof($file)) {
  1469. $string .= fread($file, 8192);
  1470. }
  1471. flock($file, LOCK_UN);
  1472. fclose($file);
  1473. return $string;
  1474. }
  1475. private function getString($filename): string
  1476. {
  1477. $data = $this->fileGetContents($filename);
  1478. if ($data === false) {
  1479. return '';
  1480. }
  1481. list($ttl, $string) = explode('|', $data, 2);
  1482. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  1483. return '';
  1484. }
  1485. return $string;
  1486. }
  1487. public function get(string $key): string
  1488. {
  1489. $filename = $this->getFileName($key);
  1490. if (!file_exists($filename)) {
  1491. return '';
  1492. }
  1493. $string = $this->getString($filename);
  1494. if ($string == null) {
  1495. return '';
  1496. }
  1497. return $string;
  1498. }
  1499. private function clean(string $path, array $segments, int $len, bool $all) /*: void*/
  1500. {
  1501. $entries = scandir($path);
  1502. foreach ($entries as $entry) {
  1503. if ($entry === '.' || $entry === '..') {
  1504. continue;
  1505. }
  1506. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  1507. if (count($segments) == 0) {
  1508. if (strlen($entry) != $len) {
  1509. continue;
  1510. }
  1511. if (is_file($filename)) {
  1512. if ($all || $this->getString($filename) == null) {
  1513. unlink($filename);
  1514. }
  1515. }
  1516. } else {
  1517. if (strlen($entry) != $segments[0]) {
  1518. continue;
  1519. }
  1520. if (is_dir($filename)) {
  1521. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  1522. rmdir($filename);
  1523. }
  1524. }
  1525. }
  1526. }
  1527. public function clear(): bool
  1528. {
  1529. if (!file_exists($this->path) || !is_dir($this->path)) {
  1530. return false;
  1531. }
  1532. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  1533. return true;
  1534. }
  1535. }
  1536. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  1537. class ReflectedColumn implements \JsonSerializable
  1538. {
  1539. const DEFAULT_LENGTH = 255;
  1540. const DEFAULT_PRECISION = 19;
  1541. const DEFAULT_SCALE = 4;
  1542. private $name;
  1543. private $type;
  1544. private $length;
  1545. private $precision;
  1546. private $scale;
  1547. private $nullable;
  1548. private $pk;
  1549. private $fk;
  1550. public function __construct(string $name, string $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, string $fk)
  1551. {
  1552. $this->name = $name;
  1553. $this->type = $type;
  1554. $this->length = $length;
  1555. $this->precision = $precision;
  1556. $this->scale = $scale;
  1557. $this->nullable = $nullable;
  1558. $this->pk = $pk;
  1559. $this->fk = $fk;
  1560. $this->sanitize();
  1561. }
  1562. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  1563. {
  1564. $name = $columnResult['COLUMN_NAME'];
  1565. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  1566. $type = $reflection->toJdbcType($columnResult['DATA_TYPE'], $length);
  1567. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  1568. $scale = (int) $columnResult['NUMERIC_SCALE'];
  1569. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  1570. $pk = false;
  1571. $fk = '';
  1572. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  1573. }
  1574. public static function fromJson( /* object */$json): ReflectedColumn
  1575. {
  1576. $name = $json->name;
  1577. $type = $json->type;
  1578. $length = isset($json->length) ? $json->length : 0;
  1579. $precision = isset($json->precision) ? $json->precision : 0;
  1580. $scale = isset($json->scale) ? $json->scale : 0;
  1581. $nullable = isset($json->nullable) ? $json->nullable : false;
  1582. $pk = isset($json->pk) ? $json->pk : false;
  1583. $fk = isset($json->fk) ? $json->fk : '';
  1584. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  1585. }
  1586. private function sanitize()
  1587. {
  1588. $this->length = $this->hasLength() ? $this->getLength() : 0;
  1589. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  1590. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  1591. }
  1592. public function getName(): string
  1593. {
  1594. return $this->name;
  1595. }
  1596. public function getNullable(): bool
  1597. {
  1598. return $this->nullable;
  1599. }
  1600. public function getType(): string
  1601. {
  1602. return $this->type;
  1603. }
  1604. public function getLength(): int
  1605. {
  1606. return $this->length ?: self::DEFAULT_LENGTH;
  1607. }
  1608. public function getPrecision(): int
  1609. {
  1610. return $this->precision ?: self::DEFAULT_PRECISION;
  1611. }
  1612. public function getScale(): int
  1613. {
  1614. return $this->scale ?: self::DEFAULT_SCALE;
  1615. }
  1616. public function hasLength(): bool
  1617. {
  1618. return in_array($this->type, ['varchar', 'varbinary']);
  1619. }
  1620. public function hasPrecision(): bool
  1621. {
  1622. return $this->type == 'decimal';
  1623. }
  1624. public function hasScale(): bool
  1625. {
  1626. return $this->type == 'decimal';
  1627. }
  1628. public function isBinary(): bool
  1629. {
  1630. return in_array($this->type, ['blob', 'varbinary']);
  1631. }
  1632. public function isBoolean(): bool
  1633. {
  1634. return $this->type == 'boolean';
  1635. }
  1636. public function isGeometry(): bool
  1637. {
  1638. return $this->type == 'geometry';
  1639. }
  1640. public function isInteger(): bool
  1641. {
  1642. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  1643. }
  1644. public function setPk($value) /*: void*/
  1645. {
  1646. $this->pk = $value;
  1647. }
  1648. public function getPk(): bool
  1649. {
  1650. return $this->pk;
  1651. }
  1652. public function setFk($value) /*: void*/
  1653. {
  1654. $this->fk = $value;
  1655. }
  1656. public function getFk(): string
  1657. {
  1658. return $this->fk;
  1659. }
  1660. public function serialize()
  1661. {
  1662. return [
  1663. 'name' => $this->name,
  1664. 'type' => $this->type,
  1665. 'length' => $this->length,
  1666. 'precision' => $this->precision,
  1667. 'scale' => $this->scale,
  1668. 'nullable' => $this->nullable,
  1669. 'pk' => $this->pk,
  1670. 'fk' => $this->fk,
  1671. ];
  1672. }
  1673. public function jsonSerialize()
  1674. {
  1675. return array_filter($this->serialize());
  1676. }
  1677. }
  1678. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  1679. class ReflectedDatabase implements \JsonSerializable
  1680. {
  1681. private $tableTypes;
  1682. public function __construct(array $tableTypes)
  1683. {
  1684. $this->tableTypes = $tableTypes;
  1685. }
  1686. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  1687. {
  1688. $tableTypes = [];
  1689. foreach ($reflection->getTables() as $table) {
  1690. $tableName = $table['TABLE_NAME'];
  1691. $tableType = $table['TABLE_TYPE'];
  1692. if (in_array($tableName, $reflection->getIgnoredTables())) {
  1693. continue;
  1694. }
  1695. $tableTypes[$tableName] = $tableType;
  1696. }
  1697. return new ReflectedDatabase($tableTypes);
  1698. }
  1699. public static function fromJson( /* object */$json): ReflectedDatabase
  1700. {
  1701. $tableTypes = (array) $json->tables;
  1702. return new ReflectedDatabase($tableTypes);
  1703. }
  1704. public function hasTable(string $tableName): bool
  1705. {
  1706. return isset($this->tableTypes[$tableName]);
  1707. }
  1708. public function getType(string $tableName): string
  1709. {
  1710. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  1711. }
  1712. public function getTableNames(): array
  1713. {
  1714. return array_keys($this->tableTypes);
  1715. }
  1716. public function removeTable(string $tableName): bool
  1717. {
  1718. if (!isset($this->tableTypes[$tableName])) {
  1719. return false;
  1720. }
  1721. unset($this->tableTypes[$tableName]);
  1722. return true;
  1723. }
  1724. public function serialize()
  1725. {
  1726. return [
  1727. 'tables' => $this->tableTypes,
  1728. ];
  1729. }
  1730. public function jsonSerialize()
  1731. {
  1732. return $this->serialize();
  1733. }
  1734. }
  1735. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  1736. class ReflectedTable implements \JsonSerializable
  1737. {
  1738. private $name;
  1739. private $type;
  1740. private $columns;
  1741. private $pk;
  1742. private $fks;
  1743. public function __construct(string $name, string $type, array $columns)
  1744. {
  1745. $this->name = $name;
  1746. $this->type = $type;
  1747. $this->columns = [];
  1748. foreach ($columns as $column) {
  1749. $columnName = $column->getName();
  1750. $this->columns[$columnName] = $column;
  1751. }
  1752. $this->pk = null;
  1753. foreach ($columns as $column) {
  1754. if ($column->getPk() == true) {
  1755. $this->pk = $column;
  1756. }
  1757. }
  1758. $this->fks = [];
  1759. foreach ($columns as $column) {
  1760. $columnName = $column->getName();
  1761. $referencedTableName = $column->getFk();
  1762. if ($referencedTableName != '') {
  1763. $this->fks[$columnName] = $referencedTableName;
  1764. }
  1765. }
  1766. }
  1767. public static function fromReflection(GenericReflection $reflection, string $name, string $type): ReflectedTable
  1768. {
  1769. $columns = [];
  1770. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  1771. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  1772. $columns[$column->getName()] = $column;
  1773. }
  1774. $columnNames = $reflection->getTablePrimaryKeys($name);
  1775. if (count($columnNames) == 1) {
  1776. $columnName = $columnNames[0];
  1777. if (isset($columns[$columnName])) {
  1778. $pk = $columns[$columnName];
  1779. $pk->setPk(true);
  1780. }
  1781. }
  1782. $fks = $reflection->getTableForeignKeys($name);
  1783. foreach ($fks as $columnName => $table) {
  1784. $columns[$columnName]->setFk($table);
  1785. }
  1786. return new ReflectedTable($name, $type, array_values($columns));
  1787. }
  1788. public static function fromJson( /* object */$json): ReflectedTable
  1789. {
  1790. $name = $json->name;
  1791. $type = $json->type;
  1792. $columns = [];
  1793. if (isset($json->columns) && is_array($json->columns)) {
  1794. foreach ($json->columns as $column) {
  1795. $columns[] = ReflectedColumn::fromJson($column);
  1796. }
  1797. }
  1798. return new ReflectedTable($name, $type, $columns);
  1799. }
  1800. public function hasColumn(string $columnName): bool
  1801. {
  1802. return isset($this->columns[$columnName]);
  1803. }
  1804. public function hasPk(): bool
  1805. {
  1806. return $this->pk != null;
  1807. }
  1808. public function getPk() /*: ?ReflectedColumn */
  1809. {
  1810. return $this->pk;
  1811. }
  1812. public function getName(): string
  1813. {
  1814. return $this->name;
  1815. }
  1816. public function getType(): string
  1817. {
  1818. return $this->type;
  1819. }
  1820. public function getColumnNames(): array
  1821. {
  1822. return array_keys($this->columns);
  1823. }
  1824. public function getColumn($columnName): ReflectedColumn
  1825. {
  1826. return $this->columns[$columnName];
  1827. }
  1828. public function getFksTo(string $tableName): array
  1829. {
  1830. $columns = array();
  1831. foreach ($this->fks as $columnName => $referencedTableName) {
  1832. if ($tableName == $referencedTableName) {
  1833. $columns[] = $this->columns[$columnName];
  1834. }
  1835. }
  1836. return $columns;
  1837. }
  1838. public function removeColumn(string $columnName): bool
  1839. {
  1840. if (!isset($this->columns[$columnName])) {
  1841. return false;
  1842. }
  1843. unset($this->columns[$columnName]);
  1844. return true;
  1845. }
  1846. public function serialize()
  1847. {
  1848. return [
  1849. 'name' => $this->name,
  1850. 'type' => $this->type,
  1851. 'columns' => array_values($this->columns),
  1852. ];
  1853. }
  1854. public function jsonSerialize()
  1855. {
  1856. return $this->serialize();
  1857. }
  1858. }
  1859. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  1860. class DefinitionService
  1861. {
  1862. private $db;
  1863. private $reflection;
  1864. public function __construct(GenericDB $db, ReflectionService $reflection)
  1865. {
  1866. $this->db = $db;
  1867. $this->reflection = $reflection;
  1868. }
  1869. public function updateTable(string $tableName, /* object */ $changes): bool
  1870. {
  1871. $table = $this->reflection->getTable($tableName);
  1872. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  1873. if ($table->getName() != $newTable->getName()) {
  1874. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  1875. return false;
  1876. }
  1877. }
  1878. return true;
  1879. }
  1880. public function updateColumn(string $tableName, string $columnName, /* object */ $changes): bool
  1881. {
  1882. $table = $this->reflection->getTable($tableName);
  1883. $column = $table->getColumn($columnName);
  1884. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  1885. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  1886. $oldColumn = $table->getPk();
  1887. if ($oldColumn->getName() != $columnName) {
  1888. $oldColumn->setPk(false);
  1889. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  1890. return false;
  1891. }
  1892. }
  1893. }
  1894. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  1895. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  1896. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  1897. return false;
  1898. }
  1899. }
  1900. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  1901. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  1902. return false;
  1903. }
  1904. }
  1905. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  1906. $newColumn->setPk(false);
  1907. $newColumn->setFk('');
  1908. if ($newColumn->getName() != $column->getName()) {
  1909. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  1910. return false;
  1911. }
  1912. }
  1913. if ($newColumn->getType() != $column->getType() ||
  1914. $newColumn->getLength() != $column->getLength() ||
  1915. $newColumn->getPrecision() != $column->getPrecision() ||
  1916. $newColumn->getScale() != $column->getScale()
  1917. ) {
  1918. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  1919. return false;
  1920. }
  1921. }
  1922. if ($newColumn->getNullable() != $column->getNullable()) {
  1923. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  1924. return false;
  1925. }
  1926. }
  1927. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  1928. if ($newColumn->getFk()) {
  1929. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  1930. return false;
  1931. }
  1932. }
  1933. if ($newColumn->getPk()) {
  1934. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  1935. return false;
  1936. }
  1937. }
  1938. return true;
  1939. }
  1940. public function addTable( /* object */$definition)
  1941. {
  1942. $newTable = ReflectedTable::fromJson($definition);
  1943. if (!$this->db->definition()->addTable($newTable)) {
  1944. return false;
  1945. }
  1946. return true;
  1947. }
  1948. public function addColumn(string $tableName, /* object */ $definition)
  1949. {
  1950. $newColumn = ReflectedColumn::fromJson($definition);
  1951. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  1952. return false;
  1953. }
  1954. if ($newColumn->getFk()) {
  1955. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  1956. return false;
  1957. }
  1958. }
  1959. if ($newColumn->getPk()) {
  1960. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  1961. return false;
  1962. }
  1963. }
  1964. return true;
  1965. }
  1966. public function removeTable(string $tableName)
  1967. {
  1968. if (!$this->db->definition()->removeTable($tableName)) {
  1969. return false;
  1970. }
  1971. return true;
  1972. }
  1973. public function removeColumn(string $tableName, string $columnName)
  1974. {
  1975. $table = $this->reflection->getTable($tableName);
  1976. $newColumn = $table->getColumn($columnName);
  1977. if ($newColumn->getPk()) {
  1978. $newColumn->setPk(false);
  1979. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  1980. return false;
  1981. }
  1982. }
  1983. if ($newColumn->getFk()) {
  1984. $newColumn->setFk("");
  1985. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  1986. return false;
  1987. }
  1988. }
  1989. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  1990. return false;
  1991. }
  1992. return true;
  1993. }
  1994. }
  1995. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  1996. class ReflectionService
  1997. {
  1998. private $db;
  1999. private $cache;
  2000. private $ttl;
  2001. private $database;
  2002. private $tables;
  2003. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  2004. {
  2005. $this->db = $db;
  2006. $this->cache = $cache;
  2007. $this->ttl = $ttl;
  2008. $this->database = $this->loadDatabase(true);
  2009. $this->tables = [];
  2010. }
  2011. private function loadDatabase(bool $useCache): ReflectedDatabase
  2012. {
  2013. $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
  2014. if ($data != '') {
  2015. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  2016. } else {
  2017. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  2018. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  2019. $this->cache->set('ReflectedDatabase', $data, $this->ttl);
  2020. }
  2021. return $database;
  2022. }
  2023. private function loadTable(string $tableName, bool $useCache): ReflectedTable
  2024. {
  2025. $data = $useCache ? $this->cache->get("ReflectedTable($tableName)") : '';
  2026. if ($data != '') {
  2027. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  2028. } else {
  2029. $tableType = $this->database->getType($tableName);
  2030. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  2031. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  2032. $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
  2033. }
  2034. return $table;
  2035. }
  2036. public function refreshTables()
  2037. {
  2038. $this->database = $this->loadDatabase(false);
  2039. }
  2040. public function refreshTable(string $tableName)
  2041. {
  2042. $this->tables[$tableName] = $this->loadTable($tableName, false);
  2043. }
  2044. public function hasTable(string $tableName): bool
  2045. {
  2046. return $this->database->hasTable($tableName);
  2047. }
  2048. public function getType(string $tableName): string
  2049. {
  2050. return $this->database->getType($tableName);
  2051. }
  2052. public function getTable(string $tableName): ReflectedTable
  2053. {
  2054. if (!isset($this->tables[$tableName])) {
  2055. $this->tables[$tableName] = $this->loadTable($tableName, true);
  2056. }
  2057. return $this->tables[$tableName];
  2058. }
  2059. public function getTableNames(): array
  2060. {
  2061. return $this->database->getTableNames();
  2062. }
  2063. public function getDatabaseName(): string
  2064. {
  2065. return $this->database->getName();
  2066. }
  2067. public function removeTable(string $tableName): bool
  2068. {
  2069. unset($this->tables[$tableName]);
  2070. return $this->database->removeTable($tableName);
  2071. }
  2072. }
  2073. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  2074. class CacheController
  2075. {
  2076. private $cache;
  2077. private $responder;
  2078. public function __construct(Router $router, Responder $responder, Cache $cache)
  2079. {
  2080. $router->register('GET', '/cache/clear', array($this, 'clear'));
  2081. $this->cache = $cache;
  2082. $this->responder = $responder;
  2083. }
  2084. public function clear(ServerRequestInterface $request): ResponseInterface
  2085. {
  2086. return $this->responder->success($this->cache->clear());
  2087. }
  2088. }
  2089. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  2090. class ColumnController
  2091. {
  2092. private $responder;
  2093. private $reflection;
  2094. private $definition;
  2095. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  2096. {
  2097. $router->register('GET', '/columns', array($this, 'getDatabase'));
  2098. $router->register('GET', '/columns/*', array($this, 'getTable'));
  2099. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  2100. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  2101. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  2102. $router->register('POST', '/columns', array($this, 'addTable'));
  2103. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  2104. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  2105. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  2106. $this->responder = $responder;
  2107. $this->reflection = $reflection;
  2108. $this->definition = $definition;
  2109. }
  2110. public function getDatabase(ServerRequestInterface $request): ResponseInterface
  2111. {
  2112. $tables = [];
  2113. foreach ($this->reflection->getTableNames() as $table) {
  2114. $tables[] = $this->reflection->getTable($table);
  2115. }
  2116. $database = ['tables' => $tables];
  2117. return $this->responder->success($database);
  2118. }
  2119. public function getTable(ServerRequestInterface $request): ResponseInterface
  2120. {
  2121. $tableName = RequestUtils::getPathSegment($request, 2);
  2122. if (!$this->reflection->hasTable($tableName)) {
  2123. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2124. }
  2125. $table = $this->reflection->getTable($tableName);
  2126. return $this->responder->success($table);
  2127. }
  2128. public function getColumn(ServerRequestInterface $request): ResponseInterface
  2129. {
  2130. $tableName = RequestUtils::getPathSegment($request, 2);
  2131. $columnName = RequestUtils::getPathSegment($request, 3);
  2132. if (!$this->reflection->hasTable($tableName)) {
  2133. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2134. }
  2135. $table = $this->reflection->getTable($tableName);
  2136. if (!$table->hasColumn($columnName)) {
  2137. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  2138. }
  2139. $column = $table->getColumn($columnName);
  2140. return $this->responder->success($column);
  2141. }
  2142. public function updateTable(ServerRequestInterface $request): ResponseInterface
  2143. {
  2144. $tableName = RequestUtils::getPathSegment($request, 2);
  2145. if (!$this->reflection->hasTable($tableName)) {
  2146. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2147. }
  2148. $success = $this->definition->updateTable($tableName, $request->getParsedBody());
  2149. if ($success) {
  2150. $this->reflection->refreshTables();
  2151. }
  2152. return $this->responder->success($success);
  2153. }
  2154. public function updateColumn(ServerRequestInterface $request): ResponseInterface
  2155. {
  2156. $tableName = RequestUtils::getPathSegment($request, 2);
  2157. $columnName = RequestUtils::getPathSegment($request, 3);
  2158. if (!$this->reflection->hasTable($tableName)) {
  2159. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2160. }
  2161. $table = $this->reflection->getTable($tableName);
  2162. if (!$table->hasColumn($columnName)) {
  2163. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  2164. }
  2165. $success = $this->definition->updateColumn($tableName, $columnName, $request->getParsedBody());
  2166. if ($success) {
  2167. $this->reflection->refreshTable($tableName);
  2168. }
  2169. return $this->responder->success($success);
  2170. }
  2171. public function addTable(ServerRequestInterface $request): ResponseInterface
  2172. {
  2173. $tableName = $request->getParsedBody()->name;
  2174. if ($this->reflection->hasTable($tableName)) {
  2175. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  2176. }
  2177. $success = $this->definition->addTable($request->getParsedBody());
  2178. if ($success) {
  2179. $this->reflection->refreshTables();
  2180. }
  2181. return $this->responder->success($success);
  2182. }
  2183. public function addColumn(ServerRequestInterface $request): ResponseInterface
  2184. {
  2185. $tableName = RequestUtils::getPathSegment($request, 2);
  2186. if (!$this->reflection->hasTable($tableName)) {
  2187. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2188. }
  2189. $columnName = $request->getParsedBody()->name;
  2190. $table = $this->reflection->getTable($tableName);
  2191. if ($table->hasColumn($columnName)) {
  2192. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  2193. }
  2194. $success = $this->definition->addColumn($tableName, $request->getParsedBody());
  2195. if ($success) {
  2196. $this->reflection->refreshTable($tableName);
  2197. }
  2198. return $this->responder->success($success);
  2199. }
  2200. public function removeTable(ServerRequestInterface $request): ResponseInterface
  2201. {
  2202. $tableName = RequestUtils::getPathSegment($request, 2);
  2203. if (!$this->reflection->hasTable($tableName)) {
  2204. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2205. }
  2206. $success = $this->definition->removeTable($tableName);
  2207. if ($success) {
  2208. $this->reflection->refreshTables();
  2209. }
  2210. return $this->responder->success($success);
  2211. }
  2212. public function removeColumn(ServerRequestInterface $request): ResponseInterface
  2213. {
  2214. $tableName = RequestUtils::getPathSegment($request, 2);
  2215. $columnName = RequestUtils::getPathSegment($request, 3);
  2216. if (!$this->reflection->hasTable($tableName)) {
  2217. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  2218. }
  2219. $table = $this->reflection->getTable($tableName);
  2220. if (!$table->hasColumn($columnName)) {
  2221. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  2222. }
  2223. $success = $this->definition->removeColumn($tableName, $columnName);
  2224. if ($success) {
  2225. $this->reflection->refreshTable($tableName);
  2226. }
  2227. return $this->responder->success($success);
  2228. }
  2229. }
  2230. // file: src/Tqdev/PhpCrudApi/Controller/GeoJsonController.php
  2231. class GeoJsonController
  2232. {
  2233. private $service;
  2234. private $responder;
  2235. private $geoJsonConverter;
  2236. public function __construct(Router $router, Responder $responder, GeoJsonService $service)
  2237. {
  2238. $router->register('GET', '/geojson/*', array($this, '_list'));
  2239. $router->register('GET', '/geojson/*/*', array($this, 'read'));
  2240. $this->service = $service;
  2241. $this->responder = $responder;
  2242. }
  2243. public function _list(ServerRequestInterface $request): ResponseInterface
  2244. {
  2245. $table = RequestUtils::getPathSegment($request, 2);
  2246. $params = RequestUtils::getParams($request);
  2247. if (!$this->service->hasTable($table)) {
  2248. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2249. }
  2250. return $this->responder->success($this->service->_list($table, $params));
  2251. }
  2252. public function read(ServerRequestInterface $request): ResponseInterface
  2253. {
  2254. $table = RequestUtils::getPathSegment($request, 2);
  2255. if (!$this->service->hasTable($table)) {
  2256. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2257. }
  2258. if ($this->service->getType($table) != 'table') {
  2259. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2260. }
  2261. $id = RequestUtils::getPathSegment($request, 3);
  2262. $params = RequestUtils::getParams($request);
  2263. if (strpos($id, ',') !== false) {
  2264. $ids = explode(',', $id);
  2265. $result = [];
  2266. for ($i = 0; $i < count($ids); $i++) {
  2267. array_push($result, $this->service->read($table, $ids[$i], $params));
  2268. }
  2269. return $this->responder->success($result);
  2270. } else {
  2271. $response = $this->service->read($table, $id, $params);
  2272. if ($response === null) {
  2273. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  2274. }
  2275. return $this->responder->success($response);
  2276. }
  2277. }
  2278. }
  2279. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  2280. class OpenApiController
  2281. {
  2282. private $openApi;
  2283. private $responder;
  2284. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  2285. {
  2286. $router->register('GET', '/openapi', array($this, 'openapi'));
  2287. $this->openApi = $openApi;
  2288. $this->responder = $responder;
  2289. }
  2290. public function openapi(ServerRequestInterface $request): ResponseInterface
  2291. {
  2292. return $this->responder->success($this->openApi->get());
  2293. }
  2294. }
  2295. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  2296. class RecordController
  2297. {
  2298. private $service;
  2299. private $responder;
  2300. public function __construct(Router $router, Responder $responder, RecordService $service)
  2301. {
  2302. $router->register('GET', '/records/*', array($this, '_list'));
  2303. $router->register('POST', '/records/*', array($this, 'create'));
  2304. $router->register('GET', '/records/*/*', array($this, 'read'));
  2305. $router->register('PUT', '/records/*/*', array($this, 'update'));
  2306. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  2307. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  2308. $this->service = $service;
  2309. $this->responder = $responder;
  2310. }
  2311. public function _list(ServerRequestInterface $request): ResponseInterface
  2312. {
  2313. $table = RequestUtils::getPathSegment($request, 2);
  2314. $params = RequestUtils::getParams($request);
  2315. if (!$this->service->hasTable($table)) {
  2316. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2317. }
  2318. return $this->responder->success($this->service->_list($table, $params));
  2319. }
  2320. public function read(ServerRequestInterface $request): ResponseInterface
  2321. {
  2322. $table = RequestUtils::getPathSegment($request, 2);
  2323. if (!$this->service->hasTable($table)) {
  2324. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2325. }
  2326. if ($this->service->getType($table) != 'table') {
  2327. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2328. }
  2329. $id = RequestUtils::getPathSegment($request, 3);
  2330. $params = RequestUtils::getParams($request);
  2331. if (strpos($id, ',') !== false) {
  2332. $ids = explode(',', $id);
  2333. $result = [];
  2334. for ($i = 0; $i < count($ids); $i++) {
  2335. array_push($result, $this->service->read($table, $ids[$i], $params));
  2336. }
  2337. return $this->responder->success($result);
  2338. } else {
  2339. $response = $this->service->read($table, $id, $params);
  2340. if ($response === null) {
  2341. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  2342. }
  2343. return $this->responder->success($response);
  2344. }
  2345. }
  2346. public function create(ServerRequestInterface $request): ResponseInterface
  2347. {
  2348. $table = RequestUtils::getPathSegment($request, 2);
  2349. if (!$this->service->hasTable($table)) {
  2350. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2351. }
  2352. if ($this->service->getType($table) != 'table') {
  2353. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2354. }
  2355. $record = $request->getParsedBody();
  2356. if ($record === null) {
  2357. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  2358. }
  2359. $params = RequestUtils::getParams($request);
  2360. if (is_array($record)) {
  2361. $result = array();
  2362. foreach ($record as $r) {
  2363. $result[] = $this->service->create($table, $r, $params);
  2364. }
  2365. return $this->responder->success($result);
  2366. } else {
  2367. return $this->responder->success($this->service->create($table, $record, $params));
  2368. }
  2369. }
  2370. public function update(ServerRequestInterface $request): ResponseInterface
  2371. {
  2372. $table = RequestUtils::getPathSegment($request, 2);
  2373. if (!$this->service->hasTable($table)) {
  2374. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2375. }
  2376. if ($this->service->getType($table) != 'table') {
  2377. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2378. }
  2379. $id = RequestUtils::getPathSegment($request, 3);
  2380. $params = RequestUtils::getParams($request);
  2381. $record = $request->getParsedBody();
  2382. if ($record === null) {
  2383. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  2384. }
  2385. $ids = explode(',', $id);
  2386. if (is_array($record)) {
  2387. if (count($ids) != count($record)) {
  2388. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2389. }
  2390. $result = array();
  2391. for ($i = 0; $i < count($ids); $i++) {
  2392. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  2393. }
  2394. return $this->responder->success($result);
  2395. } else {
  2396. if (count($ids) != 1) {
  2397. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2398. }
  2399. return $this->responder->success($this->service->update($table, $id, $record, $params));
  2400. }
  2401. }
  2402. public function delete(ServerRequestInterface $request): ResponseInterface
  2403. {
  2404. $table = RequestUtils::getPathSegment($request, 2);
  2405. if (!$this->service->hasTable($table)) {
  2406. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2407. }
  2408. if ($this->service->getType($table) != 'table') {
  2409. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2410. }
  2411. $id = RequestUtils::getPathSegment($request, 3);
  2412. $params = RequestUtils::getParams($request);
  2413. $ids = explode(',', $id);
  2414. if (count($ids) > 1) {
  2415. $result = array();
  2416. for ($i = 0; $i < count($ids); $i++) {
  2417. $result[] = $this->service->delete($table, $ids[$i], $params);
  2418. }
  2419. return $this->responder->success($result);
  2420. } else {
  2421. return $this->responder->success($this->service->delete($table, $id, $params));
  2422. }
  2423. }
  2424. public function increment(ServerRequestInterface $request): ResponseInterface
  2425. {
  2426. $table = RequestUtils::getPathSegment($request, 2);
  2427. if (!$this->service->hasTable($table)) {
  2428. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  2429. }
  2430. if ($this->service->getType($table) != 'table') {
  2431. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  2432. }
  2433. $id = RequestUtils::getPathSegment($request, 3);
  2434. $record = $request->getParsedBody();
  2435. if ($record === null) {
  2436. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  2437. }
  2438. $params = RequestUtils::getParams($request);
  2439. $ids = explode(',', $id);
  2440. if (is_array($record)) {
  2441. if (count($ids) != count($record)) {
  2442. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2443. }
  2444. $result = array();
  2445. for ($i = 0; $i < count($ids); $i++) {
  2446. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  2447. }
  2448. return $this->responder->success($result);
  2449. } else {
  2450. if (count($ids) != 1) {
  2451. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  2452. }
  2453. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  2454. }
  2455. }
  2456. }
  2457. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  2458. class Responder
  2459. {
  2460. public function error(int $error, string $argument, $details = null): ResponseInterface
  2461. {
  2462. $errorCode = new ErrorCode($error);
  2463. $status = $errorCode->getStatus();
  2464. $document = new ErrorDocument($errorCode, $argument, $details);
  2465. return ResponseFactory::fromObject($status, $document);
  2466. }
  2467. public function success($result): ResponseInterface
  2468. {
  2469. return ResponseFactory::fromObject(ResponseFactory::OK, $result);
  2470. }
  2471. }
  2472. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  2473. class ColumnConverter
  2474. {
  2475. private $driver;
  2476. public function __construct(string $driver)
  2477. {
  2478. $this->driver = $driver;
  2479. }
  2480. public function convertColumnValue(ReflectedColumn $column): string
  2481. {
  2482. if ($column->isBinary()) {
  2483. switch ($this->driver) {
  2484. case 'mysql':
  2485. return "FROM_BASE64(?)";
  2486. case 'pgsql':
  2487. return "decode(?, 'base64')";
  2488. case 'sqlsrv':
  2489. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  2490. }
  2491. }
  2492. if ($column->isGeometry()) {
  2493. switch ($this->driver) {
  2494. case 'mysql':
  2495. case 'pgsql':
  2496. return "ST_GeomFromText(?)";
  2497. case 'sqlsrv':
  2498. return "geometry::STGeomFromText(?,0)";
  2499. }
  2500. }
  2501. return '?';
  2502. }
  2503. public function convertColumnName(ReflectedColumn $column, $value): string
  2504. {
  2505. if ($column->isBinary()) {
  2506. switch ($this->driver) {
  2507. case 'mysql':
  2508. return "TO_BASE64($value) as $value";
  2509. case 'pgsql':
  2510. return "encode($value::bytea, 'base64') as $value";
  2511. case 'sqlsrv':
  2512. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  2513. }
  2514. }
  2515. if ($column->isGeometry()) {
  2516. switch ($this->driver) {
  2517. case 'mysql':
  2518. case 'pgsql':
  2519. return "ST_AsText($value) as $value";
  2520. case 'sqlsrv':
  2521. return "REPLACE($value.STAsText(),' (','(') as $value";
  2522. }
  2523. }
  2524. return $value;
  2525. }
  2526. }
  2527. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  2528. class ColumnsBuilder
  2529. {
  2530. private $driver;
  2531. private $converter;
  2532. public function __construct(string $driver)
  2533. {
  2534. $this->driver = $driver;
  2535. $this->converter = new ColumnConverter($driver);
  2536. }
  2537. public function getOffsetLimit(int $offset, int $limit): string
  2538. {
  2539. if ($limit < 0 || $offset < 0) {
  2540. return '';
  2541. }
  2542. switch ($this->driver) {
  2543. case 'mysql':return " LIMIT $offset, $limit";
  2544. case 'pgsql':return " LIMIT $limit OFFSET $offset";
  2545. case 'sqlsrv':return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  2546. }
  2547. }
  2548. private function quoteColumnName(ReflectedColumn $column): string
  2549. {
  2550. return '"' . $column->getName() . '"';
  2551. }
  2552. public function getOrderBy(ReflectedTable $table, array $columnOrdering): string
  2553. {
  2554. if (count($columnOrdering) == 0) {
  2555. return '';
  2556. }
  2557. $results = array();
  2558. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  2559. $column = $table->getColumn($columnName);
  2560. $quotedColumnName = $this->quoteColumnName($column);
  2561. $results[] = $quotedColumnName . ' ' . $ordering;
  2562. }
  2563. return ' ORDER BY ' . implode(',', $results);
  2564. }
  2565. public function getSelect(ReflectedTable $table, array $columnNames): string
  2566. {
  2567. $results = array();
  2568. foreach ($columnNames as $columnName) {
  2569. $column = $table->getColumn($columnName);
  2570. $quotedColumnName = $this->quoteColumnName($column);
  2571. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  2572. $results[] = $quotedColumnName;
  2573. }
  2574. return implode(',', $results);
  2575. }
  2576. public function getInsert(ReflectedTable $table, array $columnValues): string
  2577. {
  2578. $columns = array();
  2579. $values = array();
  2580. foreach ($columnValues as $columnName => $columnValue) {
  2581. $column = $table->getColumn($columnName);
  2582. $quotedColumnName = $this->quoteColumnName($column);
  2583. $columns[] = $quotedColumnName;
  2584. $columnValue = $this->converter->convertColumnValue($column);
  2585. $values[] = $columnValue;
  2586. }
  2587. $columnsSql = '(' . implode(',', $columns) . ')';
  2588. $valuesSql = '(' . implode(',', $values) . ')';
  2589. $outputColumn = $this->quoteColumnName($table->getPk());
  2590. switch ($this->driver) {
  2591. case 'mysql':return "$columnsSql VALUES $valuesSql";
  2592. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  2593. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  2594. }
  2595. }
  2596. public function getUpdate(ReflectedTable $table, array $columnValues): string
  2597. {
  2598. $results = array();
  2599. foreach ($columnValues as $columnName => $columnValue) {
  2600. $column = $table->getColumn($columnName);
  2601. $quotedColumnName = $this->quoteColumnName($column);
  2602. $columnValue = $this->converter->convertColumnValue($column);
  2603. $results[] = $quotedColumnName . '=' . $columnValue;
  2604. }
  2605. return implode(',', $results);
  2606. }
  2607. public function getIncrement(ReflectedTable $table, array $columnValues): string
  2608. {
  2609. $results = array();
  2610. foreach ($columnValues as $columnName => $columnValue) {
  2611. if (!is_numeric($columnValue)) {
  2612. continue;
  2613. }
  2614. $column = $table->getColumn($columnName);
  2615. $quotedColumnName = $this->quoteColumnName($column);
  2616. $columnValue = $this->converter->convertColumnValue($column);
  2617. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  2618. }
  2619. return implode(',', $results);
  2620. }
  2621. }
  2622. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  2623. class ConditionsBuilder
  2624. {
  2625. private $driver;
  2626. public function __construct(string $driver)
  2627. {
  2628. $this->driver = $driver;
  2629. }
  2630. private function getConditionSql(Condition $condition, array &$arguments): string
  2631. {
  2632. if ($condition instanceof AndCondition) {
  2633. return $this->getAndConditionSql($condition, $arguments);
  2634. }
  2635. if ($condition instanceof OrCondition) {
  2636. return $this->getOrConditionSql($condition, $arguments);
  2637. }
  2638. if ($condition instanceof NotCondition) {
  2639. return $this->getNotConditionSql($condition, $arguments);
  2640. }
  2641. if ($condition instanceof SpatialCondition) {
  2642. return $this->getSpatialConditionSql($condition, $arguments);
  2643. }
  2644. if ($condition instanceof ColumnCondition) {
  2645. return $this->getColumnConditionSql($condition, $arguments);
  2646. }
  2647. throw new \Exception('Unknown Condition: ' . get_class($condition));
  2648. }
  2649. private function getAndConditionSql(AndCondition $and, array &$arguments): string
  2650. {
  2651. $parts = [];
  2652. foreach ($and->getConditions() as $condition) {
  2653. $parts[] = $this->getConditionSql($condition, $arguments);
  2654. }
  2655. return '(' . implode(' AND ', $parts) . ')';
  2656. }
  2657. private function getOrConditionSql(OrCondition $or, array &$arguments): string
  2658. {
  2659. $parts = [];
  2660. foreach ($or->getConditions() as $condition) {
  2661. $parts[] = $this->getConditionSql($condition, $arguments);
  2662. }
  2663. return '(' . implode(' OR ', $parts) . ')';
  2664. }
  2665. private function getNotConditionSql(NotCondition $not, array &$arguments): string
  2666. {
  2667. $condition = $not->getCondition();
  2668. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  2669. }
  2670. private function quoteColumnName(ReflectedColumn $column): string
  2671. {
  2672. return '"' . $column->getName() . '"';
  2673. }
  2674. private function escapeLikeValue(string $value): string
  2675. {
  2676. return addcslashes($value, '%_');
  2677. }
  2678. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): string
  2679. {
  2680. $column = $this->quoteColumnName($condition->getColumn());
  2681. $operator = $condition->getOperator();
  2682. $value = $condition->getValue();
  2683. switch ($operator) {
  2684. case 'cs':
  2685. $sql = "$column LIKE ?";
  2686. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  2687. break;
  2688. case 'sw':
  2689. $sql = "$column LIKE ?";
  2690. $arguments[] = $this->escapeLikeValue($value) . '%';
  2691. break;
  2692. case 'ew':
  2693. $sql = "$column LIKE ?";
  2694. $arguments[] = '%' . $this->escapeLikeValue($value);
  2695. break;
  2696. case 'eq':
  2697. $sql = "$column = ?";
  2698. $arguments[] = $value;
  2699. break;
  2700. case 'lt':
  2701. $sql = "$column < ?";
  2702. $arguments[] = $value;
  2703. break;
  2704. case 'le':
  2705. $sql = "$column <= ?";
  2706. $arguments[] = $value;
  2707. break;
  2708. case 'ge':
  2709. $sql = "$column >= ?";
  2710. $arguments[] = $value;
  2711. break;
  2712. case 'gt':
  2713. $sql = "$column > ?";
  2714. $arguments[] = $value;
  2715. break;
  2716. case 'bt':
  2717. $parts = explode(',', $value, 2);
  2718. $count = count($parts);
  2719. if ($count == 2) {
  2720. $sql = "($column >= ? AND $column <= ?)";
  2721. $arguments[] = $parts[0];
  2722. $arguments[] = $parts[1];
  2723. } else {
  2724. $sql = "FALSE";
  2725. }
  2726. break;
  2727. case 'in':
  2728. $parts = explode(',', $value);
  2729. $count = count($parts);
  2730. if ($count > 0) {
  2731. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  2732. $sql = "$column IN ($qmarks)";
  2733. for ($i = 0; $i < $count; $i++) {
  2734. $arguments[] = $parts[$i];
  2735. }
  2736. } else {
  2737. $sql = "FALSE";
  2738. }
  2739. break;
  2740. case 'is':
  2741. $sql = "$column IS NULL";
  2742. break;
  2743. }
  2744. return $sql;
  2745. }
  2746. private function getSpatialFunctionName(string $operator): string
  2747. {
  2748. switch ($operator) {
  2749. case 'co':return 'ST_Contains';
  2750. case 'cr':return 'ST_Crosses';
  2751. case 'di':return 'ST_Disjoint';
  2752. case 'eq':return 'ST_Equals';
  2753. case 'in':return 'ST_Intersects';
  2754. case 'ov':return 'ST_Overlaps';
  2755. case 'to':return 'ST_Touches';
  2756. case 'wi':return 'ST_Within';
  2757. case 'ic':return 'ST_IsClosed';
  2758. case 'is':return 'ST_IsSimple';
  2759. case 'iv':return 'ST_IsValid';
  2760. }
  2761. }
  2762. private function hasSpatialArgument(string $operator): bool
  2763. {
  2764. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  2765. }
  2766. private function getSpatialFunctionCall(string $functionName, string $column, bool $hasArgument): string
  2767. {
  2768. switch ($this->driver) {
  2769. case 'mysql':
  2770. case 'pgsql':
  2771. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  2772. return "$functionName($column, $argument)=TRUE";
  2773. case 'sqlsrv':
  2774. $functionName = str_replace('ST_', 'ST', $functionName);
  2775. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  2776. return "$column.$functionName($argument)=1";
  2777. }
  2778. }
  2779. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): string
  2780. {
  2781. $column = $this->quoteColumnName($condition->getColumn());
  2782. $operator = $condition->getOperator();
  2783. $value = $condition->getValue();
  2784. $functionName = $this->getSpatialFunctionName($operator);
  2785. $hasArgument = $this->hasSpatialArgument($operator);
  2786. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  2787. if ($hasArgument) {
  2788. $arguments[] = $value;
  2789. }
  2790. return $sql;
  2791. }
  2792. public function getWhereClause(Condition $condition, array &$arguments): string
  2793. {
  2794. if ($condition instanceof NoCondition) {
  2795. return '';
  2796. }
  2797. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  2798. }
  2799. }
  2800. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  2801. class DataConverter
  2802. {
  2803. private $driver;
  2804. public function __construct(string $driver)
  2805. {
  2806. $this->driver = $driver;
  2807. }
  2808. private function convertRecordValue($conversion, $value)
  2809. {
  2810. switch ($conversion) {
  2811. case 'boolean':
  2812. return $value ? true : false;
  2813. case 'integer':
  2814. return (int) $value;
  2815. }
  2816. return $value;
  2817. }
  2818. private function getRecordValueConversion(ReflectedColumn $column): string
  2819. {
  2820. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  2821. return 'boolean';
  2822. }
  2823. if ($this->driver == 'sqlsrv' && $column->getType() == 'bigint') {
  2824. return 'integer';
  2825. }
  2826. return 'none';
  2827. }
  2828. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  2829. {
  2830. foreach ($columnNames as $columnName) {
  2831. $column = $table->getColumn($columnName);
  2832. $conversion = $this->getRecordValueConversion($column);
  2833. if ($conversion != 'none') {
  2834. foreach ($records as $i => $record) {
  2835. $value = $records[$i][$columnName];
  2836. if ($value === null) {
  2837. continue;
  2838. }
  2839. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  2840. }
  2841. }
  2842. }
  2843. }
  2844. private function convertInputValue($conversion, $value)
  2845. {
  2846. switch ($conversion) {
  2847. case 'base64url_to_base64':
  2848. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  2849. }
  2850. return $value;
  2851. }
  2852. private function getInputValueConversion(ReflectedColumn $column): string
  2853. {
  2854. if ($column->isBinary()) {
  2855. return 'base64url_to_base64';
  2856. }
  2857. return 'none';
  2858. }
  2859. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  2860. {
  2861. $columnNames = array_keys($columnValues);
  2862. foreach ($columnNames as $columnName) {
  2863. $column = $table->getColumn($columnName);
  2864. $conversion = $this->getInputValueConversion($column);
  2865. if ($conversion != 'none') {
  2866. $value = $columnValues[$columnName];
  2867. if ($value !== null) {
  2868. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  2869. }
  2870. }
  2871. }
  2872. }
  2873. }
  2874. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  2875. class GenericDB
  2876. {
  2877. private $driver;
  2878. private $database;
  2879. private $pdo;
  2880. private $reflection;
  2881. private $definition;
  2882. private $conditions;
  2883. private $columns;
  2884. private $converter;
  2885. private function getDsn(string $address, int $port, string $database): string
  2886. {
  2887. switch ($this->driver) {
  2888. case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  2889. case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  2890. case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
  2891. }
  2892. }
  2893. private function getCommands(): array
  2894. {
  2895. switch ($this->driver) {
  2896. case 'mysql':return [
  2897. 'SET SESSION sql_warnings=1;',
  2898. 'SET NAMES utf8mb4;',
  2899. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  2900. ];
  2901. case 'pgsql':return [
  2902. "SET NAMES 'UTF8';",
  2903. ];
  2904. case 'sqlsrv':return [
  2905. ];
  2906. }
  2907. }
  2908. private function getOptions(): array
  2909. {
  2910. $options = array(
  2911. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  2912. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  2913. );
  2914. switch ($this->driver) {
  2915. case 'mysql':return $options + [
  2916. \PDO::ATTR_EMULATE_PREPARES => false,
  2917. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  2918. \PDO::ATTR_PERSISTENT => true,
  2919. ];
  2920. case 'pgsql':return $options + [
  2921. \PDO::ATTR_EMULATE_PREPARES => false,
  2922. \PDO::ATTR_PERSISTENT => true,
  2923. ];
  2924. case 'sqlsrv':return $options + [
  2925. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  2926. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  2927. ];
  2928. }
  2929. }
  2930. public function __construct(string $driver, string $address, int $port, string $database, string $username, string $password)
  2931. {
  2932. $this->driver = $driver;
  2933. $this->database = $database;
  2934. $dsn = $this->getDsn($address, $port, $database);
  2935. $options = $this->getOptions();
  2936. $this->pdo = new \PDO($dsn, $username, $password, $options);
  2937. $commands = $this->getCommands();
  2938. foreach ($commands as $command) {
  2939. $this->pdo->query($command);
  2940. }
  2941. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  2942. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  2943. $this->conditions = new ConditionsBuilder($driver);
  2944. $this->columns = new ColumnsBuilder($driver);
  2945. $this->converter = new DataConverter($driver);
  2946. }
  2947. public function pdo(): \PDO
  2948. {
  2949. return $this->pdo;
  2950. }
  2951. public function reflection(): GenericReflection
  2952. {
  2953. return $this->reflection;
  2954. }
  2955. public function definition(): GenericDefinition
  2956. {
  2957. return $this->definition;
  2958. }
  2959. private function addMiddlewareConditions(string $tableName, Condition $condition): Condition
  2960. {
  2961. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  2962. if ($condition1) {
  2963. $condition = $condition->_and($condition1);
  2964. }
  2965. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  2966. if ($condition2) {
  2967. $condition = $condition->_and($condition2);
  2968. }
  2969. return $condition;
  2970. }
  2971. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  2972. {
  2973. $this->converter->convertColumnValues($table, $columnValues);
  2974. $insertColumns = $this->columns->getInsert($table, $columnValues);
  2975. $tableName = $table->getName();
  2976. $pkName = $table->getPk()->getName();
  2977. $parameters = array_values($columnValues);
  2978. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  2979. $stmt = $this->query($sql, $parameters);
  2980. if (isset($columnValues[$pkName])) {
  2981. return $columnValues[$pkName];
  2982. }
  2983. switch ($this->driver) {
  2984. case 'mysql':
  2985. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  2986. break;
  2987. }
  2988. $pkValue = $stmt->fetchColumn(0);
  2989. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  2990. return (int) $pkValue;
  2991. }
  2992. return $pkValue;
  2993. }
  2994. public function selectSingle(ReflectedTable $table, array $columnNames, string $id) /*: ?array*/
  2995. {
  2996. $selectColumns = $this->columns->getSelect($table, $columnNames);
  2997. $tableName = $table->getName();
  2998. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  2999. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3000. $parameters = array();
  3001. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3002. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  3003. $stmt = $this->query($sql, $parameters);
  3004. $record = $stmt->fetch() ?: null;
  3005. if ($record === null) {
  3006. return null;
  3007. }
  3008. $records = array($record);
  3009. $this->converter->convertRecords($table, $columnNames, $records);
  3010. return $records[0];
  3011. }
  3012. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  3013. {
  3014. if (count($ids) == 0) {
  3015. return [];
  3016. }
  3017. $selectColumns = $this->columns->getSelect($table, $columnNames);
  3018. $tableName = $table->getName();
  3019. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  3020. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3021. $parameters = array();
  3022. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3023. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  3024. $stmt = $this->query($sql, $parameters);
  3025. $records = $stmt->fetchAll();
  3026. $this->converter->convertRecords($table, $columnNames, $records);
  3027. return $records;
  3028. }
  3029. public function selectCount(ReflectedTable $table, Condition $condition): int
  3030. {
  3031. $tableName = $table->getName();
  3032. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3033. $parameters = array();
  3034. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3035. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  3036. $stmt = $this->query($sql, $parameters);
  3037. return $stmt->fetchColumn(0);
  3038. }
  3039. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  3040. {
  3041. if ($limit == 0) {
  3042. return array();
  3043. }
  3044. $selectColumns = $this->columns->getSelect($table, $columnNames);
  3045. $tableName = $table->getName();
  3046. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3047. $parameters = array();
  3048. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3049. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  3050. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  3051. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  3052. $stmt = $this->query($sql, $parameters);
  3053. $records = $stmt->fetchAll();
  3054. $this->converter->convertRecords($table, $columnNames, $records);
  3055. return $records;
  3056. }
  3057. public function updateSingle(ReflectedTable $table, array $columnValues, string $id)
  3058. {
  3059. if (count($columnValues) == 0) {
  3060. return 0;
  3061. }
  3062. $this->converter->convertColumnValues($table, $columnValues);
  3063. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  3064. $tableName = $table->getName();
  3065. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  3066. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3067. $parameters = array_values($columnValues);
  3068. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3069. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  3070. $stmt = $this->query($sql, $parameters);
  3071. return $stmt->rowCount();
  3072. }
  3073. public function deleteSingle(ReflectedTable $table, string $id)
  3074. {
  3075. $tableName = $table->getName();
  3076. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  3077. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3078. $parameters = array();
  3079. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3080. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  3081. $stmt = $this->query($sql, $parameters);
  3082. return $stmt->rowCount();
  3083. }
  3084. public function incrementSingle(ReflectedTable $table, array $columnValues, string $id)
  3085. {
  3086. if (count($columnValues) == 0) {
  3087. return 0;
  3088. }
  3089. $this->converter->convertColumnValues($table, $columnValues);
  3090. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  3091. $tableName = $table->getName();
  3092. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  3093. $condition = $this->addMiddlewareConditions($tableName, $condition);
  3094. $parameters = array_values($columnValues);
  3095. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  3096. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  3097. $stmt = $this->query($sql, $parameters);
  3098. return $stmt->rowCount();
  3099. }
  3100. private function query(string $sql, array $parameters): \PDOStatement
  3101. {
  3102. $stmt = $this->pdo->prepare($sql);
  3103. $stmt->execute($parameters);
  3104. return $stmt;
  3105. }
  3106. }
  3107. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  3108. class GenericDefinition
  3109. {
  3110. private $pdo;
  3111. private $driver;
  3112. private $database;
  3113. private $typeConverter;
  3114. private $reflection;
  3115. public function __construct(\PDO $pdo, string $driver, string $database)
  3116. {
  3117. $this->pdo = $pdo;
  3118. $this->driver = $driver;
  3119. $this->database = $database;
  3120. $this->typeConverter = new TypeConverter($driver);
  3121. $this->reflection = new GenericReflection($pdo, $driver, $database);
  3122. }
  3123. private function quote(string $identifier): string
  3124. {
  3125. return '"' . str_replace('"', '', $identifier) . '"';
  3126. }
  3127. public function getColumnType(ReflectedColumn $column, bool $update): string
  3128. {
  3129. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  3130. return 'serial';
  3131. }
  3132. $type = $this->typeConverter->fromJdbc($column->getType());
  3133. if ($column->hasPrecision() && $column->hasScale()) {
  3134. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  3135. } else if ($column->hasPrecision()) {
  3136. $size = '(' . $column->getPrecision() . ')';
  3137. } else if ($column->hasLength()) {
  3138. $size = '(' . $column->getLength() . ')';
  3139. } else {
  3140. $size = '';
  3141. }
  3142. $null = $this->getColumnNullType($column, $update);
  3143. $auto = $this->getColumnAutoIncrement($column, $update);
  3144. return $type . $size . $null . $auto;
  3145. }
  3146. private function getPrimaryKey(string $tableName): string
  3147. {
  3148. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  3149. if (count($pks) == 1) {
  3150. return $pks[0];
  3151. }
  3152. return "";
  3153. }
  3154. private function canAutoIncrement(ReflectedColumn $column): bool
  3155. {
  3156. return in_array($column->getType(), ['integer', 'bigint']);
  3157. }
  3158. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): string
  3159. {
  3160. if (!$this->canAutoIncrement($column)) {
  3161. return '';
  3162. }
  3163. switch ($this->driver) {
  3164. case 'mysql':
  3165. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  3166. case 'pgsql':
  3167. case 'sqlsrv':
  3168. return '';
  3169. }
  3170. }
  3171. private function getColumnNullType(ReflectedColumn $column, bool $update): string
  3172. {
  3173. if ($this->driver == 'pgsql' && $update) {
  3174. return '';
  3175. }
  3176. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  3177. }
  3178. private function getTableRenameSQL(string $tableName, string $newTableName): string
  3179. {
  3180. $p1 = $this->quote($tableName);
  3181. $p2 = $this->quote($newTableName);
  3182. switch ($this->driver) {
  3183. case 'mysql':
  3184. return "RENAME TABLE $p1 TO $p2";
  3185. case 'pgsql':
  3186. return "ALTER TABLE $p1 RENAME TO $p2";
  3187. case 'sqlsrv':
  3188. return "EXEC sp_rename $p1, $p2";
  3189. }
  3190. }
  3191. private function getColumnRenameSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3192. {
  3193. $p1 = $this->quote($tableName);
  3194. $p2 = $this->quote($columnName);
  3195. $p3 = $this->quote($newColumn->getName());
  3196. switch ($this->driver) {
  3197. case 'mysql':
  3198. $p4 = $this->getColumnType($newColumn, true);
  3199. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3200. case 'pgsql':
  3201. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  3202. case 'sqlsrv':
  3203. $p4 = $this->quote($tableName . '.' . $columnName);
  3204. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  3205. }
  3206. }
  3207. private function getColumnRetypeSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3208. {
  3209. $p1 = $this->quote($tableName);
  3210. $p2 = $this->quote($columnName);
  3211. $p3 = $this->quote($newColumn->getName());
  3212. $p4 = $this->getColumnType($newColumn, true);
  3213. switch ($this->driver) {
  3214. case 'mysql':
  3215. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3216. case 'pgsql':
  3217. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  3218. case 'sqlsrv':
  3219. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  3220. }
  3221. }
  3222. private function getSetColumnNullableSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3223. {
  3224. $p1 = $this->quote($tableName);
  3225. $p2 = $this->quote($columnName);
  3226. $p3 = $this->quote($newColumn->getName());
  3227. $p4 = $this->getColumnType($newColumn, true);
  3228. switch ($this->driver) {
  3229. case 'mysql':
  3230. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3231. case 'pgsql':
  3232. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  3233. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  3234. case 'sqlsrv':
  3235. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  3236. }
  3237. }
  3238. private function getSetColumnPkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3239. {
  3240. $p1 = $this->quote($tableName);
  3241. $p2 = $this->quote($columnName);
  3242. $p3 = $this->quote($tableName . '_pkey');
  3243. switch ($this->driver) {
  3244. case 'mysql':
  3245. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  3246. return "ALTER TABLE $p1 $p4";
  3247. case 'pgsql':
  3248. case 'sqlsrv':
  3249. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  3250. return "ALTER TABLE $p1 $p4";
  3251. }
  3252. }
  3253. private function getSetColumnPkSequenceSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3254. {
  3255. $p1 = $this->quote($tableName);
  3256. $p2 = $this->quote($columnName);
  3257. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  3258. switch ($this->driver) {
  3259. case 'mysql':
  3260. return "select 1";
  3261. case 'pgsql':
  3262. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  3263. case 'sqlsrv':
  3264. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  3265. }
  3266. }
  3267. private function getSetColumnPkSequenceStartSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3268. {
  3269. $p1 = $this->quote($tableName);
  3270. $p2 = $this->quote($columnName);
  3271. switch ($this->driver) {
  3272. case 'mysql':
  3273. return "select 1";
  3274. case 'pgsql':
  3275. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  3276. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  3277. case 'sqlsrv':
  3278. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  3279. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  3280. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  3281. }
  3282. }
  3283. private function getSetColumnPkDefaultSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3284. {
  3285. $p1 = $this->quote($tableName);
  3286. $p2 = $this->quote($columnName);
  3287. switch ($this->driver) {
  3288. case 'mysql':
  3289. $p3 = $this->quote($newColumn->getName());
  3290. $p4 = $this->getColumnType($newColumn, true);
  3291. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  3292. case 'pgsql':
  3293. if ($newColumn->getPk()) {
  3294. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  3295. $p4 = "SET DEFAULT nextval($p3)";
  3296. } else {
  3297. $p4 = 'DROP DEFAULT';
  3298. }
  3299. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  3300. case 'sqlsrv':
  3301. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  3302. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  3303. if ($newColumn->getPk()) {
  3304. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  3305. } else {
  3306. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  3307. }
  3308. }
  3309. }
  3310. private function getAddColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3311. {
  3312. $p1 = $this->quote($tableName);
  3313. $p2 = $this->quote($columnName);
  3314. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  3315. $p4 = $this->quote($newColumn->getFk());
  3316. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  3317. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  3318. }
  3319. private function getRemoveColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  3320. {
  3321. $p1 = $this->quote($tableName);
  3322. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  3323. switch ($this->driver) {
  3324. case 'mysql':
  3325. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  3326. case 'pgsql':
  3327. case 'sqlsrv':
  3328. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  3329. }
  3330. }
  3331. private function getAddTableSQL(ReflectedTable $newTable): string
  3332. {
  3333. $tableName = $newTable->getName();
  3334. $p1 = $this->quote($tableName);
  3335. $fields = [];
  3336. $constraints = [];
  3337. foreach ($newTable->getColumnNames() as $columnName) {
  3338. $pkColumn = $this->getPrimaryKey($tableName);
  3339. $newColumn = $newTable->getColumn($columnName);
  3340. $f1 = $this->quote($columnName);
  3341. $f2 = $this->getColumnType($newColumn, false);
  3342. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  3343. $f4 = $this->quote($newColumn->getFk());
  3344. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  3345. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  3346. $fields[] = "$f1 $f2";
  3347. if ($newColumn->getPk()) {
  3348. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  3349. }
  3350. if ($newColumn->getFk()) {
  3351. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  3352. }
  3353. }
  3354. $p2 = implode(',', array_merge($fields, $constraints));
  3355. return "CREATE TABLE $p1 ($p2);";
  3356. }
  3357. private function getAddColumnSQL(string $tableName, ReflectedColumn $newColumn): string
  3358. {
  3359. $p1 = $this->quote($tableName);
  3360. $p2 = $this->quote($newColumn->getName());
  3361. $p3 = $this->getColumnType($newColumn, false);
  3362. switch ($this->driver) {
  3363. case 'mysql':
  3364. case 'pgsql':
  3365. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  3366. case 'sqlsrv':
  3367. return "ALTER TABLE $p1 ADD $p2 $p3";
  3368. }
  3369. }
  3370. private function getRemoveTableSQL(string $tableName): string
  3371. {
  3372. $p1 = $this->quote($tableName);
  3373. switch ($this->driver) {
  3374. case 'mysql':
  3375. case 'pgsql':
  3376. return "DROP TABLE $p1 CASCADE;";
  3377. case 'sqlsrv':
  3378. return "DROP TABLE $p1;";
  3379. }
  3380. }
  3381. private function getRemoveColumnSQL(string $tableName, string $columnName): string
  3382. {
  3383. $p1 = $this->quote($tableName);
  3384. $p2 = $this->quote($columnName);
  3385. switch ($this->driver) {
  3386. case 'mysql':
  3387. case 'pgsql':
  3388. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  3389. case 'sqlsrv':
  3390. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  3391. }
  3392. }
  3393. public function renameTable(string $tableName, string $newTableName)
  3394. {
  3395. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  3396. return $this->query($sql);
  3397. }
  3398. public function renameColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3399. {
  3400. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  3401. return $this->query($sql);
  3402. }
  3403. public function retypeColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3404. {
  3405. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  3406. return $this->query($sql);
  3407. }
  3408. public function setColumnNullable(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3409. {
  3410. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  3411. return $this->query($sql);
  3412. }
  3413. public function addColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3414. {
  3415. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  3416. $this->query($sql);
  3417. if ($this->canAutoIncrement($newColumn)) {
  3418. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  3419. $this->query($sql);
  3420. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  3421. $this->query($sql);
  3422. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  3423. $this->query($sql);
  3424. }
  3425. return true;
  3426. }
  3427. public function removeColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3428. {
  3429. if ($this->canAutoIncrement($newColumn)) {
  3430. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  3431. $this->query($sql);
  3432. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  3433. $this->query($sql);
  3434. }
  3435. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  3436. $this->query($sql);
  3437. return true;
  3438. }
  3439. public function addColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3440. {
  3441. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  3442. return $this->query($sql);
  3443. }
  3444. public function removeColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  3445. {
  3446. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  3447. return $this->query($sql);
  3448. }
  3449. public function addTable(ReflectedTable $newTable)
  3450. {
  3451. $sql = $this->getAddTableSQL($newTable);
  3452. return $this->query($sql);
  3453. }
  3454. public function addColumn(string $tableName, ReflectedColumn $newColumn)
  3455. {
  3456. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  3457. return $this->query($sql);
  3458. }
  3459. public function removeTable(string $tableName)
  3460. {
  3461. $sql = $this->getRemoveTableSQL($tableName);
  3462. return $this->query($sql);
  3463. }
  3464. public function removeColumn(string $tableName, string $columnName)
  3465. {
  3466. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  3467. return $this->query($sql);
  3468. }
  3469. private function query(string $sql): bool
  3470. {
  3471. $stmt = $this->pdo->prepare($sql);
  3472. return $stmt->execute();
  3473. }
  3474. }
  3475. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  3476. class GenericReflection
  3477. {
  3478. private $pdo;
  3479. private $driver;
  3480. private $database;
  3481. private $typeConverter;
  3482. public function __construct(\PDO $pdo, string $driver, string $database)
  3483. {
  3484. $this->pdo = $pdo;
  3485. $this->driver = $driver;
  3486. $this->database = $database;
  3487. $this->typeConverter = new TypeConverter($driver);
  3488. }
  3489. public function getIgnoredTables(): array
  3490. {
  3491. switch ($this->driver) {
  3492. case 'mysql':return [];
  3493. case 'pgsql':return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  3494. case 'sqlsrv':return [];
  3495. }
  3496. }
  3497. private function getTablesSQL(): string
  3498. {
  3499. switch ($this->driver) {
  3500. 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"';
  3501. 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";';
  3502. 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"';
  3503. }
  3504. }
  3505. private function getTableColumnsSQL(): string
  3506. {
  3507. switch ($this->driver) {
  3508. 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" = ?';
  3509. 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;';
  3510. 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 \'\' <> ?';
  3511. }
  3512. }
  3513. private function getTablePrimaryKeysSQL(): string
  3514. {
  3515. switch ($this->driver) {
  3516. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  3517. 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\'';
  3518. 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 \'\' <> ?';
  3519. }
  3520. }
  3521. private function getTableForeignKeysSQL(): string
  3522. {
  3523. switch ($this->driver) {
  3524. 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" = ?';
  3525. 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\'';
  3526. 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 \'\' <> ?';
  3527. }
  3528. }
  3529. public function getDatabaseName(): string
  3530. {
  3531. return $this->database;
  3532. }
  3533. public function getTables(): array
  3534. {
  3535. $sql = $this->getTablesSQL();
  3536. $results = $this->query($sql, [$this->database]);
  3537. foreach ($results as &$result) {
  3538. switch ($this->driver) {
  3539. case 'mysql':
  3540. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  3541. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  3542. break;
  3543. case 'pgsql':
  3544. $map = ['r' => 'table', 'v' => 'view'];
  3545. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  3546. break;
  3547. case 'sqlsrv':
  3548. $map = ['U' => 'table', 'V' => 'view'];
  3549. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  3550. break;
  3551. }
  3552. }
  3553. return $results;
  3554. }
  3555. public function getTableColumns(string $tableName, string $type): array
  3556. {
  3557. $sql = $this->getTableColumnsSQL();
  3558. $results = $this->query($sql, [$tableName, $this->database]);
  3559. if ($type == 'view') {
  3560. foreach ($results as &$result) {
  3561. $result['IS_NULLABLE'] = false;
  3562. }
  3563. }
  3564. return $results;
  3565. }
  3566. public function getTablePrimaryKeys(string $tableName): array
  3567. {
  3568. $sql = $this->getTablePrimaryKeysSQL();
  3569. $results = $this->query($sql, [$tableName, $this->database]);
  3570. $primaryKeys = [];
  3571. foreach ($results as $result) {
  3572. $primaryKeys[] = $result['COLUMN_NAME'];
  3573. }
  3574. return $primaryKeys;
  3575. }
  3576. public function getTableForeignKeys(string $tableName): array
  3577. {
  3578. $sql = $this->getTableForeignKeysSQL();
  3579. $results = $this->query($sql, [$tableName, $this->database]);
  3580. $foreignKeys = [];
  3581. foreach ($results as $result) {
  3582. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  3583. }
  3584. return $foreignKeys;
  3585. }
  3586. public function toJdbcType(string $type, int $size): string
  3587. {
  3588. return $this->typeConverter->toJdbc($type, $size);
  3589. }
  3590. private function query(string $sql, array $parameters): array
  3591. {
  3592. $stmt = $this->pdo->prepare($sql);
  3593. $stmt->execute($parameters);
  3594. return $stmt->fetchAll();
  3595. }
  3596. }
  3597. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  3598. class TypeConverter
  3599. {
  3600. private $driver;
  3601. public function __construct(string $driver)
  3602. {
  3603. $this->driver = $driver;
  3604. }
  3605. private $fromJdbc = [
  3606. 'mysql' => [
  3607. 'clob' => 'longtext',
  3608. 'boolean' => 'bit',
  3609. 'blob' => 'longblob',
  3610. 'timestamp' => 'datetime',
  3611. ],
  3612. 'pgsql' => [
  3613. 'clob' => 'text',
  3614. 'blob' => 'bytea',
  3615. ],
  3616. 'sqlsrv' => [
  3617. 'boolean' => 'bit',
  3618. 'varchar' => 'nvarchar',
  3619. 'clob' => 'ntext',
  3620. 'blob' => 'image',
  3621. ],
  3622. ];
  3623. private $toJdbc = [
  3624. 'simplified' => [
  3625. 'char' => 'varchar',
  3626. 'longvarchar' => 'clob',
  3627. 'nchar' => 'varchar',
  3628. 'nvarchar' => 'varchar',
  3629. 'longnvarchar' => 'clob',
  3630. 'binary' => 'varbinary',
  3631. 'longvarbinary' => 'blob',
  3632. 'tinyint' => 'integer',
  3633. 'smallint' => 'integer',
  3634. 'real' => 'float',
  3635. 'numeric' => 'decimal',
  3636. 'time_with_timezone' => 'time',
  3637. 'timestamp_with_timezone' => 'timestamp',
  3638. ],
  3639. 'mysql' => [
  3640. 'bit' => 'boolean',
  3641. 'tinyblob' => 'blob',
  3642. 'mediumblob' => 'blob',
  3643. 'longblob' => 'blob',
  3644. 'tinytext' => 'clob',
  3645. 'mediumtext' => 'clob',
  3646. 'longtext' => 'clob',
  3647. 'text' => 'clob',
  3648. 'mediumint' => 'integer',
  3649. 'int' => 'integer',
  3650. 'polygon' => 'geometry',
  3651. 'point' => 'geometry',
  3652. 'datetime' => 'timestamp',
  3653. 'year' => 'integer',
  3654. 'enum' => 'varchar',
  3655. 'json' => 'clob',
  3656. ],
  3657. 'pgsql' => [
  3658. 'bigserial' => 'bigint',
  3659. 'bit varying' => 'bit',
  3660. 'box' => 'geometry',
  3661. 'bytea' => 'blob',
  3662. 'character varying' => 'varchar',
  3663. 'character' => 'char',
  3664. 'cidr' => 'varchar',
  3665. 'circle' => 'geometry',
  3666. 'double precision' => 'double',
  3667. 'inet' => 'integer',
  3668. 'json' => 'clob',
  3669. 'jsonb' => 'clob',
  3670. 'line' => 'geometry',
  3671. 'lseg' => 'geometry',
  3672. 'macaddr' => 'varchar',
  3673. 'money' => 'decimal',
  3674. 'path' => 'geometry',
  3675. 'point' => 'geometry',
  3676. 'polygon' => 'geometry',
  3677. 'real' => 'float',
  3678. 'serial' => 'integer',
  3679. 'text' => 'clob',
  3680. 'time without time zone' => 'time',
  3681. 'time with time zone' => 'time_with_timezone',
  3682. 'timestamp without time zone' => 'timestamp',
  3683. 'timestamp with time zone' => 'timestamp_with_timezone',
  3684. 'uuid' => 'char',
  3685. 'xml' => 'clob',
  3686. ],
  3687. 'sqlsrv' => [
  3688. 'varbinary(0)' => 'blob',
  3689. 'bit' => 'boolean',
  3690. 'datetime' => 'timestamp',
  3691. 'datetime2' => 'timestamp',
  3692. 'float' => 'double',
  3693. 'image' => 'blob',
  3694. 'int' => 'integer',
  3695. 'money' => 'decimal',
  3696. 'ntext' => 'clob',
  3697. 'smalldatetime' => 'timestamp',
  3698. 'smallmoney' => 'decimal',
  3699. 'text' => 'clob',
  3700. 'timestamp' => 'binary',
  3701. 'udt' => 'varbinary',
  3702. 'uniqueidentifier' => 'char',
  3703. 'xml' => 'clob',
  3704. ],
  3705. ];
  3706. private $valid = [
  3707. 'bigint' => true,
  3708. 'binary' => true,
  3709. 'bit' => true,
  3710. 'blob' => true,
  3711. 'boolean' => true,
  3712. 'char' => true,
  3713. 'clob' => true,
  3714. 'date' => true,
  3715. 'decimal' => true,
  3716. 'distinct' => true,
  3717. 'double' => true,
  3718. 'float' => true,
  3719. 'integer' => true,
  3720. 'longnvarchar' => true,
  3721. 'longvarbinary' => true,
  3722. 'longvarchar' => true,
  3723. 'nchar' => true,
  3724. 'nclob' => true,
  3725. 'numeric' => true,
  3726. 'nvarchar' => true,
  3727. 'real' => true,
  3728. 'smallint' => true,
  3729. 'time' => true,
  3730. 'time_with_timezone' => true,
  3731. 'timestamp' => true,
  3732. 'timestamp_with_timezone' => true,
  3733. 'tinyint' => true,
  3734. 'varbinary' => true,
  3735. 'varchar' => true,
  3736. 'geometry' => true,
  3737. ];
  3738. public function toJdbc(string $type, int $size): string
  3739. {
  3740. $jdbcType = strtolower($type);
  3741. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  3742. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  3743. }
  3744. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  3745. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  3746. }
  3747. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  3748. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  3749. }
  3750. if (!isset($this->valid[$jdbcType])) {
  3751. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  3752. }
  3753. return $jdbcType;
  3754. }
  3755. public function fromJdbc(string $type): string
  3756. {
  3757. $jdbcType = strtolower($type);
  3758. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  3759. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  3760. }
  3761. return $jdbcType;
  3762. }
  3763. }
  3764. // file: src/Tqdev/PhpCrudApi/GeoJson/Feature.php
  3765. class Feature implements \JsonSerializable
  3766. {
  3767. private $properties;
  3768. private $geometry;
  3769. public function __construct(array $properties, /*?Geometry*/ $geometry)
  3770. {
  3771. $this->properties = $properties;
  3772. $this->geometry = $geometry;
  3773. }
  3774. public function serialize()
  3775. {
  3776. return [
  3777. 'type' => 'Feature',
  3778. 'properties' => $this->properties,
  3779. 'geometry' => $this->geometry,
  3780. ];
  3781. }
  3782. public function jsonSerialize()
  3783. {
  3784. return $this->serialize();
  3785. }
  3786. }
  3787. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  3788. class FeatureCollection implements \JsonSerializable
  3789. {
  3790. private $features;
  3791. private $results;
  3792. public function __construct(array $features, int $results)
  3793. {
  3794. $this->features = $features;
  3795. $this->results = $results;
  3796. }
  3797. public function serialize()
  3798. {
  3799. return [
  3800. 'type' => 'FeatureCollection',
  3801. 'features' => $this->features,
  3802. 'results' => $this->results,
  3803. ];
  3804. }
  3805. public function jsonSerialize()
  3806. {
  3807. return array_filter($this->serialize(), function ($v) {
  3808. return $v !== 0;
  3809. });
  3810. }
  3811. }
  3812. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  3813. class GeoJsonService
  3814. {
  3815. private $reflection;
  3816. private $records;
  3817. public function __construct(ReflectionService $reflection, RecordService $records)
  3818. {
  3819. $this->reflection = $reflection;
  3820. $this->records = $records;
  3821. }
  3822. public function hasTable(string $table): bool
  3823. {
  3824. return $this->reflection->hasTable($table);
  3825. }
  3826. public function getType(string $table): string
  3827. {
  3828. return $this->reflection->getType($table);
  3829. }
  3830. private function getGeometryColumnName(string $tableName, array &$params): string
  3831. {
  3832. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  3833. $table = $this->reflection->getTable($tableName);
  3834. $geometryColumnName = '';
  3835. foreach ($table->getColumnNames() as $columnName) {
  3836. if ($geometryParam && $geometryParam != $columnName) {
  3837. continue;
  3838. }
  3839. $column = $table->getColumn($columnName);
  3840. if ($column->isGeometry()) {
  3841. $geometryColumnName = $columnName;
  3842. break;
  3843. }
  3844. }
  3845. if ($geometryColumnName) {
  3846. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  3847. }
  3848. return $geometryColumnName;
  3849. }
  3850. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  3851. {
  3852. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  3853. if ($boundingBox) {
  3854. $c = explode(',', $boundingBox);
  3855. if (!isset($params['filter'])) {
  3856. $params['filter'] = array();
  3857. }
  3858. $params['filter'][] = "$geometryColumnName,sin,POLYGON(($c[0] $c[1],$c[2] $c[1],$c[2] $c[3],$c[0] $c[3],$c[0] $c[1]))";
  3859. }
  3860. }
  3861. private function convertRecordToFeature( /*object*/$record, string $geometryColumnName)
  3862. {
  3863. $geometry = null;
  3864. if (isset($record[$geometryColumnName])) {
  3865. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  3866. }
  3867. $properties = array_diff_key($record, [$geometryColumnName => true]);
  3868. return new Feature($properties, $geometry);
  3869. }
  3870. public function _list(string $tableName, array $params): FeatureCollection
  3871. {
  3872. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  3873. $this->setBoudingBoxFilter($geometryColumnName, $params);
  3874. $records = $this->records->_list($tableName, $params);
  3875. $features = array();
  3876. foreach ($records->getRecords() as $record) {
  3877. $features[] = $this->convertRecordToFeature($record, $geometryColumnName);
  3878. }
  3879. return new FeatureCollection($features, $records->getResults());
  3880. }
  3881. public function read(string $tableName, string $id, array $params): Feature
  3882. {
  3883. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  3884. $this->setBoudingBoxFilter($geometryColumnName, $params);
  3885. $record = $this->records->read($tableName, $id, $params);
  3886. return $this->convertRecordToFeature($record, $geometryColumnName);
  3887. }
  3888. }
  3889. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  3890. class Geometry implements \JsonSerializable
  3891. {
  3892. private $type;
  3893. private $geometry;
  3894. public static $types = [
  3895. "Point",
  3896. "MultiPoint",
  3897. "LineString",
  3898. "MultiLineString",
  3899. "Polygon",
  3900. "MultiPolygon",
  3901. ];
  3902. public function __construct(string $type, array $coordinates)
  3903. {
  3904. $this->type = $type;
  3905. $this->coordinates = $coordinates;
  3906. }
  3907. public static function fromWkt(string $wkt): Geometry
  3908. {
  3909. $bracket = strpos($wkt, '(');
  3910. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  3911. $supported = false;
  3912. foreach (Geometry::$types as $typeName) {
  3913. if (strtoupper($typeName) == $type) {
  3914. $type = $typeName;
  3915. $supported = true;
  3916. }
  3917. }
  3918. if (!$supported) {
  3919. throw new \Exception('Geometry type not supported: ' . $type);
  3920. }
  3921. $coordinates = substr($wkt, $bracket);
  3922. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  3923. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  3924. }
  3925. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  3926. $json = $coordinates;
  3927. $coordinates = json_decode($coordinates);
  3928. if (!$coordinates) {
  3929. throw new \Exception('Could not decode WKT: ' . $wkt);
  3930. }
  3931. return new Geometry($type, $coordinates);
  3932. }
  3933. public function serialize()
  3934. {
  3935. return [
  3936. 'type' => $this->type,
  3937. 'coordinates' => $this->coordinates,
  3938. ];
  3939. }
  3940. public function jsonSerialize()
  3941. {
  3942. return $this->serialize();
  3943. }
  3944. }
  3945. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  3946. abstract class Middleware implements MiddlewareInterface
  3947. {
  3948. protected $next;
  3949. protected $responder;
  3950. private $properties;
  3951. public function __construct(Router $router, Responder $responder, array $properties)
  3952. {
  3953. $router->load($this);
  3954. $this->responder = $responder;
  3955. $this->properties = $properties;
  3956. }
  3957. protected function getArrayProperty(string $key, string $default): array
  3958. {
  3959. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  3960. }
  3961. protected function getProperty(string $key, $default)
  3962. {
  3963. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  3964. }
  3965. }
  3966. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  3967. class VariableStore
  3968. {
  3969. static $values = array();
  3970. public static function get(string $key)
  3971. {
  3972. if (isset(self::$values[$key])) {
  3973. return self::$values[$key];
  3974. }
  3975. return null;
  3976. }
  3977. public static function set(string $key, /* object */ $value)
  3978. {
  3979. self::$values[$key] = $value;
  3980. }
  3981. }
  3982. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  3983. interface Router extends RequestHandlerInterface
  3984. {
  3985. public function register(string $method, string $path, array $handler);
  3986. public function load(Middleware $middleware);
  3987. public function route(ServerRequestInterface $request): ResponseInterface;
  3988. }
  3989. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  3990. class SimpleRouter implements Router
  3991. {
  3992. private $basePath;
  3993. private $responder;
  3994. private $cache;
  3995. private $ttl;
  3996. private $debug;
  3997. private $registration;
  3998. private $routes;
  3999. private $routeHandlers;
  4000. private $middlewares;
  4001. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  4002. {
  4003. $this->basePath = $basePath;
  4004. $this->responder = $responder;
  4005. $this->cache = $cache;
  4006. $this->ttl = $ttl;
  4007. $this->debug = $debug;
  4008. $this->registration = true;
  4009. $this->routes = $this->loadPathTree();
  4010. $this->routeHandlers = [];
  4011. $this->middlewares = array();
  4012. }
  4013. private function loadPathTree(): PathTree
  4014. {
  4015. $data = $this->cache->get('PathTree');
  4016. if ($data != '') {
  4017. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  4018. $this->registration = false;
  4019. } else {
  4020. $tree = new PathTree();
  4021. }
  4022. return $tree;
  4023. }
  4024. public function register(string $method, string $path, array $handler)
  4025. {
  4026. $routeNumber = count($this->routeHandlers);
  4027. $this->routeHandlers[$routeNumber] = $handler;
  4028. if ($this->registration) {
  4029. $parts = explode('/', trim($path, '/'));
  4030. array_unshift($parts, $method);
  4031. $this->routes->put($parts, $routeNumber);
  4032. }
  4033. }
  4034. public function load(Middleware $middleware) /*: void*/
  4035. {
  4036. array_push($this->middlewares, $middleware);
  4037. }
  4038. public function route(ServerRequestInterface $request): ResponseInterface
  4039. {
  4040. if ($this->registration) {
  4041. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  4042. $this->cache->set('PathTree', $data, $this->ttl);
  4043. }
  4044. return $this->handle($request);
  4045. }
  4046. private function getRouteNumbers(ServerRequestInterface $request): array
  4047. {
  4048. $method = strtoupper($request->getMethod());
  4049. $path = array();
  4050. $segment = $method;
  4051. for ($i = 1; $segment; $i++) {
  4052. array_push($path, $segment);
  4053. $segment = RequestUtils::getPathSegment($request, $i);
  4054. }
  4055. return $this->routes->match($path);
  4056. }
  4057. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  4058. {
  4059. if ($this->basePath) {
  4060. $path = $request->getUri()->getPath();
  4061. $basePath = rtrim($this->basePath, '/');
  4062. if (substr($path, 0, strlen($basePath)) == $basePath) {
  4063. $path = substr($path, strlen($basePath));
  4064. $request = $request->withUri($request->getUri()->withPath($path));
  4065. }
  4066. } elseif (isset($_SERVER['PATH_INFO'])) {
  4067. $path = $_SERVER['PATH_INFO'];
  4068. $request = $request->withUri($request->getUri()->withPath($path));
  4069. }
  4070. return $request;
  4071. }
  4072. public function handle(ServerRequestInterface $request): ResponseInterface
  4073. {
  4074. $request = $this->removeBasePath($request);
  4075. if (count($this->middlewares)) {
  4076. $handler = array_pop($this->middlewares);
  4077. return $handler->process($request, $this);
  4078. }
  4079. $routeNumbers = $this->getRouteNumbers($request);
  4080. if (count($routeNumbers) == 0) {
  4081. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  4082. }
  4083. try {
  4084. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  4085. } catch (\PDOException $e) {
  4086. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  4087. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  4088. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  4089. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4090. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  4091. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4092. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  4093. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4094. } else {
  4095. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  4096. }
  4097. if ($this->debug) {
  4098. $response = ResponseUtils::addExceptionHeaders($response, $e);
  4099. }
  4100. }
  4101. return $response;
  4102. }
  4103. }
  4104. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  4105. class AjaxOnlyMiddleware extends Middleware
  4106. {
  4107. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4108. {
  4109. $method = $request->getMethod();
  4110. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  4111. if (!in_array($method, $excludeMethods)) {
  4112. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  4113. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  4114. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  4115. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  4116. }
  4117. }
  4118. return $next->handle($request);
  4119. }
  4120. }
  4121. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  4122. class AuthorizationMiddleware extends Middleware
  4123. {
  4124. private $reflection;
  4125. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4126. {
  4127. parent::__construct($router, $responder, $properties);
  4128. $this->reflection = $reflection;
  4129. }
  4130. private function handleColumns(string $operation, string $tableName) /*: void*/
  4131. {
  4132. $columnHandler = $this->getProperty('columnHandler', '');
  4133. if ($columnHandler) {
  4134. $table = $this->reflection->getTable($tableName);
  4135. foreach ($table->getColumnNames() as $columnName) {
  4136. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  4137. if (!$allowed) {
  4138. $table->removeColumn($columnName);
  4139. }
  4140. }
  4141. }
  4142. }
  4143. private function handleTable(string $operation, string $tableName) /*: void*/
  4144. {
  4145. if (!$this->reflection->hasTable($tableName)) {
  4146. return;
  4147. }
  4148. $tableHandler = $this->getProperty('tableHandler', '');
  4149. if ($tableHandler) {
  4150. $allowed = call_user_func($tableHandler, $operation, $tableName);
  4151. if (!$allowed) {
  4152. $this->reflection->removeTable($tableName);
  4153. } else {
  4154. $this->handleColumns($operation, $tableName);
  4155. }
  4156. }
  4157. }
  4158. private function handleRecords(string $operation, string $tableName) /*: void*/
  4159. {
  4160. if (!$this->reflection->hasTable($tableName)) {
  4161. return;
  4162. }
  4163. $recordHandler = $this->getProperty('recordHandler', '');
  4164. if ($recordHandler) {
  4165. $query = call_user_func($recordHandler, $operation, $tableName);
  4166. $filters = new FilterInfo();
  4167. $table = $this->reflection->getTable($tableName);
  4168. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  4169. parse_str($query, $params);
  4170. $condition = $filters->getCombinedConditions($table, $params);
  4171. VariableStore::set("authorization.conditions.$tableName", $condition);
  4172. }
  4173. }
  4174. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4175. {
  4176. $path = RequestUtils::getPathSegment($request, 1);
  4177. $operation = RequestUtils::getOperation($request);
  4178. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  4179. foreach ($tableNames as $tableName) {
  4180. $this->handleTable($operation, $tableName);
  4181. if ($path == 'records') {
  4182. $this->handleRecords($operation, $tableName);
  4183. }
  4184. }
  4185. if ($path == 'openapi') {
  4186. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  4187. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  4188. }
  4189. return $next->handle($request);
  4190. }
  4191. }
  4192. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  4193. class BasicAuthMiddleware extends Middleware
  4194. {
  4195. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  4196. {
  4197. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  4198. if ($hash && password_verify($password, $hash)) {
  4199. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  4200. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  4201. }
  4202. return true;
  4203. }
  4204. return false;
  4205. }
  4206. private function getValidUsername(string $username, string $password, string $passwordFile): string
  4207. {
  4208. $passwords = $this->readPasswords($passwordFile);
  4209. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  4210. $this->writePasswords($passwordFile, $passwords);
  4211. return $valid ? $username : '';
  4212. }
  4213. private function readPasswords(string $passwordFile): array
  4214. {
  4215. $passwords = [];
  4216. $passwordLines = file($passwordFile);
  4217. foreach ($passwordLines as $passwordLine) {
  4218. if (strpos($passwordLine, ':') !== false) {
  4219. list($username, $hash) = explode(':', trim($passwordLine), 2);
  4220. if (strlen($hash) > 0 && $hash[0] != '$') {
  4221. $hash = password_hash($hash, PASSWORD_DEFAULT);
  4222. }
  4223. $passwords[$username] = $hash;
  4224. }
  4225. }
  4226. return $passwords;
  4227. }
  4228. private function writePasswords(string $passwordFile, array $passwords): bool
  4229. {
  4230. $success = false;
  4231. $passwordFileContents = '';
  4232. foreach ($passwords as $username => $hash) {
  4233. $passwordFileContents .= "$username:$hash\n";
  4234. }
  4235. if (file_get_contents($passwordFile) != $passwordFileContents) {
  4236. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  4237. }
  4238. return $success;
  4239. }
  4240. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  4241. {
  4242. if (isset($_SERVER['PHP_AUTH_USER'])) {
  4243. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  4244. }
  4245. $header = RequestUtils::getHeader($request, 'Authorization');
  4246. $parts = explode(' ', trim($header), 2);
  4247. if (count($parts) != 2) {
  4248. return '';
  4249. }
  4250. if ($parts[0] != 'Basic') {
  4251. return '';
  4252. }
  4253. return base64_decode(strtr($parts[1], '-_', '+/'));
  4254. }
  4255. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4256. {
  4257. if (session_status() == PHP_SESSION_NONE) {
  4258. session_start();
  4259. }
  4260. $credentials = $this->getAuthorizationCredentials($request);
  4261. if ($credentials) {
  4262. list($username, $password) = array('', '');
  4263. if (strpos($credentials, ':') !== false) {
  4264. list($username, $password) = explode(':', $credentials, 2);
  4265. }
  4266. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  4267. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  4268. $_SESSION['username'] = $validUser;
  4269. if (!$validUser) {
  4270. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  4271. }
  4272. if (!headers_sent()) {
  4273. session_regenerate_id();
  4274. }
  4275. }
  4276. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  4277. $authenticationMode = $this->getProperty('mode', 'required');
  4278. if ($authenticationMode == 'required') {
  4279. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4280. $realm = $this->getProperty('realm', 'Username and password required');
  4281. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  4282. return $response;
  4283. }
  4284. }
  4285. return $next->handle($request);
  4286. }
  4287. }
  4288. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  4289. class CorsMiddleware extends Middleware
  4290. {
  4291. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  4292. {
  4293. $found = false;
  4294. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  4295. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  4296. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  4297. if (preg_match($regex, $origin)) {
  4298. $found = true;
  4299. break;
  4300. }
  4301. }
  4302. return $found;
  4303. }
  4304. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4305. {
  4306. $method = $request->getMethod();
  4307. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  4308. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  4309. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  4310. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  4311. } elseif ($method == 'OPTIONS') {
  4312. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  4313. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  4314. if ($allowHeaders) {
  4315. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  4316. }
  4317. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  4318. if ($allowMethods) {
  4319. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  4320. }
  4321. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  4322. if ($allowCredentials) {
  4323. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  4324. }
  4325. $maxAge = $this->getProperty('maxAge', '1728000');
  4326. if ($maxAge) {
  4327. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  4328. }
  4329. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  4330. if ($exposeHeaders) {
  4331. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  4332. }
  4333. } else {
  4334. $response = $next->handle($request);
  4335. }
  4336. if ($origin) {
  4337. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  4338. if ($allowCredentials) {
  4339. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  4340. }
  4341. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  4342. }
  4343. return $response;
  4344. }
  4345. }
  4346. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  4347. class CustomizationMiddleware extends Middleware
  4348. {
  4349. private $reflection;
  4350. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4351. {
  4352. parent::__construct($router, $responder, $properties);
  4353. $this->reflection = $reflection;
  4354. }
  4355. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4356. {
  4357. $operation = RequestUtils::getOperation($request);
  4358. $tableName = RequestUtils::getPathSegment($request, 2);
  4359. $beforeHandler = $this->getProperty('beforeHandler', '');
  4360. $environment = (object) array();
  4361. if ($beforeHandler !== '') {
  4362. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  4363. $request = $result ?: $request;
  4364. }
  4365. $response = $next->handle($request);
  4366. $afterHandler = $this->getProperty('afterHandler', '');
  4367. if ($afterHandler !== '') {
  4368. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  4369. $response = $result ?: $response;
  4370. }
  4371. return $response;
  4372. }
  4373. }
  4374. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  4375. class FirewallMiddleware extends Middleware
  4376. {
  4377. private function ipMatch(string $ip, string $cidr): bool
  4378. {
  4379. if (strpos($cidr, '/') !== false) {
  4380. list($subnet, $mask) = explode('/', trim($cidr));
  4381. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  4382. return true;
  4383. }
  4384. } else {
  4385. if (ip2long($ip) == ip2long($cidr)) {
  4386. return true;
  4387. }
  4388. }
  4389. return false;
  4390. }
  4391. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  4392. {
  4393. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  4394. if ($this->ipMatch($ipAddress, $allowedIp)) {
  4395. return true;
  4396. }
  4397. }
  4398. return false;
  4399. }
  4400. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4401. {
  4402. $reverseProxy = $this->getProperty('reverseProxy', '');
  4403. if ($reverseProxy) {
  4404. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  4405. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  4406. $ipAddress = $_SERVER['REMOTE_ADDR'];
  4407. } else {
  4408. $ipAddress = '127.0.0.1';
  4409. }
  4410. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  4411. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  4412. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  4413. } else {
  4414. $response = $next->handle($request);
  4415. }
  4416. return $response;
  4417. }
  4418. }
  4419. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  4420. class IpAddressMiddleware extends Middleware
  4421. {
  4422. private $reflection;
  4423. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4424. {
  4425. parent::__construct($router, $responder, $properties);
  4426. $this->reflection = $reflection;
  4427. }
  4428. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  4429. {
  4430. $context = (array) $record;
  4431. $columnNames = $this->getProperty('columns', '');
  4432. if ($columnNames) {
  4433. foreach (explode(',', $columnNames) as $columnName) {
  4434. if ($table->hasColumn($columnName)) {
  4435. if ($operation == 'create') {
  4436. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  4437. } else {
  4438. unset($context[$columnName]);
  4439. }
  4440. }
  4441. }
  4442. }
  4443. return (object) $context;
  4444. }
  4445. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4446. {
  4447. $operation = RequestUtils::getOperation($request);
  4448. if (in_array($operation, ['create', 'update', 'increment'])) {
  4449. $tableNames = $this->getProperty('tables', '');
  4450. $tableName = RequestUtils::getPathSegment($request, 2);
  4451. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  4452. if ($this->reflection->hasTable($tableName)) {
  4453. $record = $request->getParsedBody();
  4454. if ($record !== null) {
  4455. $table = $this->reflection->getTable($tableName);
  4456. if (is_array($record)) {
  4457. foreach ($record as &$r) {
  4458. $r = $this->callHandler($r, $operation, $table);
  4459. }
  4460. } else {
  4461. $record = $this->callHandler($record, $operation, $table);
  4462. }
  4463. $request = $request->withParsedBody($record);
  4464. }
  4465. }
  4466. }
  4467. }
  4468. return $next->handle($request);
  4469. }
  4470. }
  4471. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  4472. class JoinLimitsMiddleware extends Middleware
  4473. {
  4474. private $reflection;
  4475. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4476. {
  4477. parent::__construct($router, $responder, $properties);
  4478. $this->reflection = $reflection;
  4479. }
  4480. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4481. {
  4482. $operation = RequestUtils::getOperation($request);
  4483. $params = RequestUtils::getParams($request);
  4484. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  4485. $maxDepth = (int) $this->getProperty('depth', '3');
  4486. $maxTables = (int) $this->getProperty('tables', '10');
  4487. $maxRecords = (int) $this->getProperty('records', '1000');
  4488. $tableCount = 0;
  4489. $joinPaths = array();
  4490. for ($i = 0; $i < count($params['join']); $i++) {
  4491. $joinPath = array();
  4492. $tables = explode(',', $params['join'][$i]);
  4493. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  4494. array_push($joinPath, $tables[$depth]);
  4495. $tableCount += 1;
  4496. if ($tableCount == $maxTables) {
  4497. break;
  4498. }
  4499. }
  4500. array_push($joinPaths, implode(',', $joinPath));
  4501. if ($tableCount == $maxTables) {
  4502. break;
  4503. }
  4504. }
  4505. $params['join'] = $joinPaths;
  4506. $request = RequestUtils::setParams($request, $params);
  4507. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  4508. }
  4509. return $next->handle($request);
  4510. }
  4511. }
  4512. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  4513. class JwtAuthMiddleware extends Middleware
  4514. {
  4515. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, string $secret, array $requirements): array
  4516. {
  4517. $algorithms = array(
  4518. 'HS256' => 'sha256',
  4519. 'HS384' => 'sha384',
  4520. 'HS512' => 'sha512',
  4521. 'RS256' => 'sha256',
  4522. 'RS384' => 'sha384',
  4523. 'RS512' => 'sha512',
  4524. );
  4525. $token = explode('.', $token);
  4526. if (count($token) < 3) {
  4527. return array();
  4528. }
  4529. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  4530. if (!$secret) {
  4531. return array();
  4532. }
  4533. if ($header['typ'] != 'JWT') {
  4534. return array();
  4535. }
  4536. $algorithm = $header['alg'];
  4537. if (!isset($algorithms[$algorithm])) {
  4538. return array();
  4539. }
  4540. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  4541. return array();
  4542. }
  4543. $hmac = $algorithms[$algorithm];
  4544. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  4545. $data = "$token[0].$token[1]";
  4546. switch ($algorithm[0]) {
  4547. case 'H':
  4548. $hash = hash_hmac($hmac, $data, $secret, true);
  4549. if (function_exists('hash_equals')) {
  4550. $equals = hash_equals($signature, $hash);
  4551. } else {
  4552. $equals = $signature == $hash;
  4553. }
  4554. if (!$equals) {
  4555. return array();
  4556. }
  4557. break;
  4558. case 'R':
  4559. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  4560. if (!$equals) {
  4561. return array();
  4562. }
  4563. break;
  4564. }
  4565. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  4566. if (!$claims) {
  4567. return array();
  4568. }
  4569. foreach ($requirements as $field => $values) {
  4570. if (!empty($values)) {
  4571. if ($field != 'alg') {
  4572. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  4573. return array();
  4574. }
  4575. }
  4576. }
  4577. }
  4578. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  4579. return array();
  4580. }
  4581. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  4582. return array();
  4583. }
  4584. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  4585. return array();
  4586. }
  4587. if (isset($claims['iat']) && !isset($claims['exp'])) {
  4588. if ($time - $leeway > $claims['iat'] + $ttl) {
  4589. return array();
  4590. }
  4591. }
  4592. return $claims;
  4593. }
  4594. private function getClaims(string $token): array
  4595. {
  4596. $time = (int) $this->getProperty('time', time());
  4597. $leeway = (int) $this->getProperty('leeway', '5');
  4598. $ttl = (int) $this->getProperty('ttl', '30');
  4599. $secret = $this->getProperty('secret', '');
  4600. $requirements = array(
  4601. 'alg' => $this->getArrayProperty('algorithms', ''),
  4602. 'aud' => $this->getArrayProperty('audiences', ''),
  4603. 'iss' => $this->getArrayProperty('issuers', ''),
  4604. );
  4605. if (!$secret) {
  4606. return array();
  4607. }
  4608. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  4609. }
  4610. private function getAuthorizationToken(ServerRequestInterface $request): string
  4611. {
  4612. $headerName = $this->getProperty('header', 'X-Authorization');
  4613. $headerValue = RequestUtils::getHeader($request, $headerName);
  4614. $parts = explode(' ', trim($headerValue), 2);
  4615. if (count($parts) != 2) {
  4616. return '';
  4617. }
  4618. if ($parts[0] != 'Bearer') {
  4619. return '';
  4620. }
  4621. return $parts[1];
  4622. }
  4623. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4624. {
  4625. if (session_status() == PHP_SESSION_NONE) {
  4626. session_start();
  4627. }
  4628. $token = $this->getAuthorizationToken($request);
  4629. if ($token) {
  4630. $claims = $this->getClaims($token);
  4631. $_SESSION['claims'] = $claims;
  4632. if (empty($claims)) {
  4633. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  4634. }
  4635. if (!headers_sent()) {
  4636. session_regenerate_id();
  4637. }
  4638. }
  4639. if (empty($_SESSION['claims'])) {
  4640. $authenticationMode = $this->getProperty('mode', 'required');
  4641. if ($authenticationMode == 'required') {
  4642. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  4643. }
  4644. }
  4645. return $next->handle($request);
  4646. }
  4647. }
  4648. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  4649. class MultiTenancyMiddleware extends Middleware
  4650. {
  4651. private $reflection;
  4652. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4653. {
  4654. parent::__construct($router, $responder, $properties);
  4655. $this->reflection = $reflection;
  4656. }
  4657. private function getCondition(string $tableName, array $pairs): Condition
  4658. {
  4659. $condition = new NoCondition();
  4660. $table = $this->reflection->getTable($tableName);
  4661. foreach ($pairs as $k => $v) {
  4662. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  4663. }
  4664. return $condition;
  4665. }
  4666. private function getPairs($handler, string $operation, string $tableName): array
  4667. {
  4668. $result = array();
  4669. $pairs = call_user_func($handler, $operation, $tableName);
  4670. $table = $this->reflection->getTable($tableName);
  4671. foreach ($pairs as $k => $v) {
  4672. if ($table->hasColumn($k)) {
  4673. $result[$k] = $v;
  4674. }
  4675. }
  4676. return $result;
  4677. }
  4678. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  4679. {
  4680. $record = $request->getParsedBody();
  4681. if ($record === null) {
  4682. return $request;
  4683. }
  4684. $multi = is_array($record);
  4685. $records = $multi ? $record : [$record];
  4686. foreach ($records as &$record) {
  4687. foreach ($pairs as $column => $value) {
  4688. if ($operation == 'create') {
  4689. $record->$column = $value;
  4690. } else {
  4691. if (isset($record->$column)) {
  4692. unset($record->$column);
  4693. }
  4694. }
  4695. }
  4696. }
  4697. return $request->withParsedBody($multi ? $records : $records[0]);
  4698. }
  4699. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4700. {
  4701. $handler = $this->getProperty('handler', '');
  4702. if ($handler !== '') {
  4703. $path = RequestUtils::getPathSegment($request, 1);
  4704. if ($path == 'records') {
  4705. $operation = RequestUtils::getOperation($request);
  4706. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  4707. foreach ($tableNames as $i => $tableName) {
  4708. if (!$this->reflection->hasTable($tableName)) {
  4709. continue;
  4710. }
  4711. $pairs = $this->getPairs($handler, $operation, $tableName);
  4712. if ($i == 0) {
  4713. if (in_array($operation, ['create', 'update', 'increment'])) {
  4714. $request = $this->handleRecord($request, $operation, $pairs);
  4715. }
  4716. }
  4717. $condition = $this->getCondition($tableName, $pairs);
  4718. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  4719. }
  4720. }
  4721. }
  4722. return $next->handle($request);
  4723. }
  4724. }
  4725. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  4726. class PageLimitsMiddleware extends Middleware
  4727. {
  4728. private $reflection;
  4729. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4730. {
  4731. parent::__construct($router, $responder, $properties);
  4732. $this->reflection = $reflection;
  4733. }
  4734. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4735. {
  4736. $operation = RequestUtils::getOperation($request);
  4737. if ($operation == 'list') {
  4738. $params = RequestUtils::getParams($request);
  4739. $maxPage = (int) $this->getProperty('pages', '100');
  4740. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  4741. if (strpos($params['page'][0], ',') === false) {
  4742. $page = $params['page'][0];
  4743. } else {
  4744. list($page, $size) = explode(',', $params['page'][0], 2);
  4745. }
  4746. if ($page > $maxPage) {
  4747. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  4748. }
  4749. }
  4750. $maxSize = (int) $this->getProperty('records', '1000');
  4751. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  4752. $params['size'] = array($maxSize);
  4753. } else {
  4754. $params['size'] = array(min($params['size'][0], $maxSize));
  4755. }
  4756. $request = RequestUtils::setParams($request, $params);
  4757. }
  4758. return $next->handle($request);
  4759. }
  4760. }
  4761. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  4762. class SanitationMiddleware extends Middleware
  4763. {
  4764. private $reflection;
  4765. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4766. {
  4767. parent::__construct($router, $responder, $properties);
  4768. $this->reflection = $reflection;
  4769. }
  4770. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  4771. {
  4772. $context = (array) $record;
  4773. $tableName = $table->getName();
  4774. foreach ($context as $columnName => &$value) {
  4775. if ($table->hasColumn($columnName)) {
  4776. $column = $table->getColumn($columnName);
  4777. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  4778. }
  4779. }
  4780. return (object) $context;
  4781. }
  4782. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4783. {
  4784. $operation = RequestUtils::getOperation($request);
  4785. if (in_array($operation, ['create', 'update', 'increment'])) {
  4786. $tableName = RequestUtils::getPathSegment($request, 2);
  4787. if ($this->reflection->hasTable($tableName)) {
  4788. $record = $request->getParsedBody();
  4789. if ($record !== null) {
  4790. $handler = $this->getProperty('handler', '');
  4791. if ($handler !== '') {
  4792. $table = $this->reflection->getTable($tableName);
  4793. if (is_array($record)) {
  4794. foreach ($record as &$r) {
  4795. $r = $this->callHandler($handler, $r, $operation, $table);
  4796. }
  4797. } else {
  4798. $record = $this->callHandler($handler, $record, $operation, $table);
  4799. }
  4800. $request = $request->withParsedBody($record);
  4801. }
  4802. }
  4803. }
  4804. }
  4805. return $next->handle($request);
  4806. }
  4807. }
  4808. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  4809. class ValidationMiddleware extends Middleware
  4810. {
  4811. private $reflection;
  4812. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  4813. {
  4814. parent::__construct($router, $responder, $properties);
  4815. $this->reflection = $reflection;
  4816. }
  4817. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  4818. {
  4819. $context = (array) $record;
  4820. $details = array();
  4821. $tableName = $table->getName();
  4822. foreach ($context as $columnName => $value) {
  4823. if ($table->hasColumn($columnName)) {
  4824. $column = $table->getColumn($columnName);
  4825. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  4826. if ($valid !== true && $valid !== '') {
  4827. $details[$columnName] = $valid;
  4828. }
  4829. }
  4830. }
  4831. if (count($details) > 0) {
  4832. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  4833. }
  4834. return null;
  4835. }
  4836. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4837. {
  4838. $operation = RequestUtils::getOperation($request);
  4839. if (in_array($operation, ['create', 'update', 'increment'])) {
  4840. $tableName = RequestUtils::getPathSegment($request, 2);
  4841. if ($this->reflection->hasTable($tableName)) {
  4842. $record = $request->getParsedBody();
  4843. if ($record !== null) {
  4844. $handler = $this->getProperty('handler', '');
  4845. if ($handler !== '') {
  4846. $table = $this->reflection->getTable($tableName);
  4847. if (is_array($record)) {
  4848. foreach ($record as $r) {
  4849. $response = $this->callHandler($handler, $r, $operation, $table);
  4850. if ($response !== null) {
  4851. return $response;
  4852. }
  4853. }
  4854. } else {
  4855. $response = $this->callHandler($handler, $record, $operation, $table);
  4856. if ($response !== null) {
  4857. return $response;
  4858. }
  4859. }
  4860. }
  4861. }
  4862. }
  4863. }
  4864. return $next->handle($request);
  4865. }
  4866. }
  4867. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  4868. class XsrfMiddleware extends Middleware
  4869. {
  4870. private function getToken(): string
  4871. {
  4872. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  4873. if (isset($_COOKIE[$cookieName])) {
  4874. $token = $_COOKIE[$cookieName];
  4875. } else {
  4876. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  4877. $token = bin2hex(random_bytes(8));
  4878. if (!headers_sent()) {
  4879. setcookie($cookieName, $token, 0, '', '', $secure);
  4880. }
  4881. }
  4882. return $token;
  4883. }
  4884. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  4885. {
  4886. $token = $this->getToken();
  4887. $method = $request->getMethod();
  4888. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  4889. if (!in_array($method, $excludeMethods)) {
  4890. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  4891. if ($token != $request->getHeader($headerName)) {
  4892. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  4893. }
  4894. }
  4895. return $next->handle($request);
  4896. }
  4897. }
  4898. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  4899. class OpenApiBuilder
  4900. {
  4901. private $openapi;
  4902. private $reflection;
  4903. private $operations = [
  4904. 'list' => 'get',
  4905. 'create' => 'post',
  4906. 'read' => 'get',
  4907. 'update' => 'put',
  4908. 'delete' => 'delete',
  4909. 'increment' => 'patch',
  4910. ];
  4911. private $types = [
  4912. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  4913. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  4914. 'varchar' => ['type' => 'string'],
  4915. 'clob' => ['type' => 'string'],
  4916. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  4917. 'blob' => ['type' => 'string', 'format' => 'byte'],
  4918. 'decimal' => ['type' => 'string'],
  4919. 'float' => ['type' => 'number', 'format' => 'float'],
  4920. 'double' => ['type' => 'number', 'format' => 'double'],
  4921. 'date' => ['type' => 'string', 'format' => 'date'],
  4922. 'time' => ['type' => 'string', 'format' => 'date-time'],
  4923. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  4924. 'geometry' => ['type' => 'string'],
  4925. 'boolean' => ['type' => 'boolean'],
  4926. ];
  4927. public function __construct(ReflectionService $reflection, $base)
  4928. {
  4929. $this->reflection = $reflection;
  4930. $this->openapi = new OpenApiDefinition($base);
  4931. }
  4932. private function getServerUrl(): string
  4933. {
  4934. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  4935. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  4936. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  4937. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  4938. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  4939. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  4940. }
  4941. private function getAllTableReferences(): array
  4942. {
  4943. $tableReferences = array();
  4944. foreach ($this->reflection->getTableNames() as $tableName) {
  4945. $table = $this->reflection->getTable($tableName);
  4946. foreach ($table->getColumnNames() as $columnName) {
  4947. $column = $table->getColumn($columnName);
  4948. $referencedTableName = $column->getFk();
  4949. if ($referencedTableName) {
  4950. if (!isset($tableReferences[$referencedTableName])) {
  4951. $tableReferences[$referencedTableName] = array();
  4952. }
  4953. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  4954. }
  4955. }
  4956. }
  4957. return $tableReferences;
  4958. }
  4959. public function build(): OpenApiDefinition
  4960. {
  4961. $this->openapi->set("openapi", "3.0.0");
  4962. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  4963. $this->openapi->set("servers|0|url", $this->getServerUrl());
  4964. }
  4965. $tableNames = $this->reflection->getTableNames();
  4966. foreach ($tableNames as $tableName) {
  4967. $this->setPath($tableName);
  4968. }
  4969. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  4970. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  4971. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  4972. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  4973. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  4974. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  4975. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  4976. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  4977. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  4978. $tableReferences = $this->getAllTableReferences();
  4979. foreach ($tableNames as $tableName) {
  4980. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  4981. $this->setComponentSchema($tableName, $references);
  4982. $this->setComponentResponse($tableName);
  4983. $this->setComponentRequestBody($tableName);
  4984. }
  4985. $this->setComponentParameters();
  4986. foreach ($tableNames as $index => $tableName) {
  4987. $this->setTag($index, $tableName);
  4988. }
  4989. return $this->openapi;
  4990. }
  4991. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  4992. {
  4993. $tableHandler = VariableStore::get('authorization.tableHandler');
  4994. if (!$tableHandler) {
  4995. return true;
  4996. }
  4997. return (bool) call_user_func($tableHandler, $operation, $tableName);
  4998. }
  4999. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  5000. {
  5001. $columnHandler = VariableStore::get('authorization.columnHandler');
  5002. if (!$columnHandler) {
  5003. return true;
  5004. }
  5005. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  5006. }
  5007. private function setPath(string $tableName) /*: void*/
  5008. {
  5009. $table = $this->reflection->getTable($tableName);
  5010. $type = $table->getType();
  5011. $pk = $table->getPk();
  5012. $pkName = $pk ? $pk->getName() : '';
  5013. foreach ($this->operations as $operation => $method) {
  5014. if (!$pkName && $operation != 'list') {
  5015. continue;
  5016. }
  5017. if ($type != 'table' && $operation != 'list') {
  5018. continue;
  5019. }
  5020. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5021. continue;
  5022. }
  5023. $parameters = [];
  5024. if (in_array($operation, ['list', 'create'])) {
  5025. $path = sprintf('/records/%s', $tableName);
  5026. if ($operation == 'list') {
  5027. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  5028. }
  5029. } else {
  5030. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  5031. if ($operation == 'read') {
  5032. $parameters = ['pk', 'include', 'exclude', 'join'];
  5033. } else {
  5034. $parameters = ['pk'];
  5035. }
  5036. }
  5037. foreach ($parameters as $p => $parameter) {
  5038. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  5039. }
  5040. if (in_array($operation, ['create', 'update', 'increment'])) {
  5041. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  5042. }
  5043. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  5044. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  5045. switch ($operation) {
  5046. case 'list':
  5047. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  5048. break;
  5049. case 'create':
  5050. if ($pk->getType() == 'integer') {
  5051. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  5052. } else {
  5053. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  5054. }
  5055. break;
  5056. case 'read':
  5057. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  5058. break;
  5059. case 'update':
  5060. case 'delete':
  5061. case 'increment':
  5062. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  5063. break;
  5064. }
  5065. }
  5066. }
  5067. private function setComponentSchema(string $tableName, array $references) /*: void*/
  5068. {
  5069. $table = $this->reflection->getTable($tableName);
  5070. $type = $table->getType();
  5071. $pk = $table->getPk();
  5072. $pkName = $pk ? $pk->getName() : '';
  5073. foreach ($this->operations as $operation => $method) {
  5074. if (!$pkName && $operation != 'list') {
  5075. continue;
  5076. }
  5077. if ($type != 'table' && $operation != 'list') {
  5078. continue;
  5079. }
  5080. if ($operation == 'delete') {
  5081. continue;
  5082. }
  5083. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5084. continue;
  5085. }
  5086. if ($operation == 'list') {
  5087. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  5088. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  5089. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  5090. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  5091. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  5092. } else {
  5093. $prefix = "components|schemas|$operation-$tableName";
  5094. }
  5095. $this->openapi->set("$prefix|type", "object");
  5096. foreach ($table->getColumnNames() as $columnName) {
  5097. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  5098. continue;
  5099. }
  5100. $column = $table->getColumn($columnName);
  5101. $properties = $this->types[$column->getType()];
  5102. foreach ($properties as $key => $value) {
  5103. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  5104. }
  5105. if ($column->getPk()) {
  5106. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  5107. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  5108. }
  5109. $fk = $column->getFk();
  5110. if ($fk) {
  5111. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  5112. }
  5113. }
  5114. }
  5115. }
  5116. private function setComponentResponse(string $tableName) /*: void*/
  5117. {
  5118. $table = $this->reflection->getTable($tableName);
  5119. $type = $table->getType();
  5120. $pk = $table->getPk();
  5121. $pkName = $pk ? $pk->getName() : '';
  5122. foreach (['list', 'read'] as $operation) {
  5123. if (!$pkName && $operation != 'list') {
  5124. continue;
  5125. }
  5126. if ($type != 'table' && $operation != 'list') {
  5127. continue;
  5128. }
  5129. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5130. continue;
  5131. }
  5132. if ($operation == 'list') {
  5133. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  5134. } else {
  5135. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  5136. }
  5137. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  5138. }
  5139. }
  5140. private function setComponentRequestBody(string $tableName) /*: void*/
  5141. {
  5142. $table = $this->reflection->getTable($tableName);
  5143. $type = $table->getType();
  5144. $pk = $table->getPk();
  5145. $pkName = $pk ? $pk->getName() : '';
  5146. if ($pkName && $type == 'table') {
  5147. foreach (['create', 'update', 'increment'] as $operation) {
  5148. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  5149. continue;
  5150. }
  5151. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  5152. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  5153. }
  5154. }
  5155. }
  5156. private function setComponentParameters() /*: void*/
  5157. {
  5158. $this->openapi->set("components|parameters|pk|name", "id");
  5159. $this->openapi->set("components|parameters|pk|in", "path");
  5160. $this->openapi->set("components|parameters|pk|schema|type", "string");
  5161. $this->openapi->set("components|parameters|pk|description", "primary key value");
  5162. $this->openapi->set("components|parameters|pk|required", true);
  5163. $this->openapi->set("components|parameters|filter|name", "filter");
  5164. $this->openapi->set("components|parameters|filter|in", "query");
  5165. $this->openapi->set("components|parameters|filter|schema|type", "array");
  5166. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  5167. $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");
  5168. $this->openapi->set("components|parameters|filter|required", false);
  5169. $this->openapi->set("components|parameters|include|name", "include");
  5170. $this->openapi->set("components|parameters|include|in", "query");
  5171. $this->openapi->set("components|parameters|include|schema|type", "string");
  5172. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  5173. $this->openapi->set("components|parameters|include|required", false);
  5174. $this->openapi->set("components|parameters|exclude|name", "exclude");
  5175. $this->openapi->set("components|parameters|exclude|in", "query");
  5176. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  5177. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  5178. $this->openapi->set("components|parameters|exclude|required", false);
  5179. $this->openapi->set("components|parameters|order|name", "order");
  5180. $this->openapi->set("components|parameters|order|in", "query");
  5181. $this->openapi->set("components|parameters|order|schema|type", "array");
  5182. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  5183. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  5184. $this->openapi->set("components|parameters|order|required", false);
  5185. $this->openapi->set("components|parameters|size|name", "size");
  5186. $this->openapi->set("components|parameters|size|in", "query");
  5187. $this->openapi->set("components|parameters|size|schema|type", "string");
  5188. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  5189. $this->openapi->set("components|parameters|size|required", false);
  5190. $this->openapi->set("components|parameters|page|name", "page");
  5191. $this->openapi->set("components|parameters|page|in", "query");
  5192. $this->openapi->set("components|parameters|page|schema|type", "string");
  5193. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  5194. $this->openapi->set("components|parameters|page|required", false);
  5195. $this->openapi->set("components|parameters|join|name", "join");
  5196. $this->openapi->set("components|parameters|join|in", "query");
  5197. $this->openapi->set("components|parameters|join|schema|type", "array");
  5198. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  5199. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  5200. $this->openapi->set("components|parameters|join|required", false);
  5201. }
  5202. private function setTag(int $index, string $tableName) /*: void*/
  5203. {
  5204. $this->openapi->set("tags|$index|name", "$tableName");
  5205. $this->openapi->set("tags|$index|description", "$tableName operations");
  5206. }
  5207. }
  5208. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  5209. class OpenApiDefinition implements \JsonSerializable
  5210. {
  5211. private $root;
  5212. public function __construct($base)
  5213. {
  5214. $this->root = $base;
  5215. }
  5216. public function set(string $path, $value) /*: void*/
  5217. {
  5218. $parts = explode('|', trim($path, '|'));
  5219. $current = &$this->root;
  5220. while (count($parts) > 0) {
  5221. $part = array_shift($parts);
  5222. if (!isset($current[$part])) {
  5223. $current[$part] = [];
  5224. }
  5225. $current = &$current[$part];
  5226. }
  5227. $current = $value;
  5228. }
  5229. public function has(string $path): bool
  5230. {
  5231. $parts = explode('|', trim($path, '|'));
  5232. $current = &$this->root;
  5233. while (count($parts) > 0) {
  5234. $part = array_shift($parts);
  5235. if (!isset($current[$part])) {
  5236. return false;
  5237. }
  5238. $current = &$current[$part];
  5239. }
  5240. return true;
  5241. }
  5242. public function jsonSerialize()
  5243. {
  5244. return $this->root;
  5245. }
  5246. }
  5247. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  5248. class OpenApiService
  5249. {
  5250. private $builder;
  5251. public function __construct(ReflectionService $reflection, array $base)
  5252. {
  5253. $this->builder = new OpenApiBuilder($reflection, $base);
  5254. }
  5255. public function get(): OpenApiDefinition
  5256. {
  5257. return $this->builder->build();
  5258. }
  5259. }
  5260. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  5261. class AndCondition extends Condition
  5262. {
  5263. private $conditions;
  5264. public function __construct(Condition $condition1, Condition $condition2)
  5265. {
  5266. $this->conditions = [$condition1, $condition2];
  5267. }
  5268. public function _and(Condition $condition): Condition
  5269. {
  5270. if ($condition instanceof NoCondition) {
  5271. return $this;
  5272. }
  5273. $this->conditions[] = $condition;
  5274. return $this;
  5275. }
  5276. public function getConditions(): array
  5277. {
  5278. return $this->conditions;
  5279. }
  5280. public static function fromArray(array $conditions): Condition
  5281. {
  5282. $condition = new NoCondition();
  5283. foreach ($conditions as $c) {
  5284. $condition = $condition->_and($c);
  5285. }
  5286. return $condition;
  5287. }
  5288. }
  5289. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  5290. class ColumnCondition extends Condition
  5291. {
  5292. private $column;
  5293. private $operator;
  5294. private $value;
  5295. public function __construct(ReflectedColumn $column, string $operator, string $value)
  5296. {
  5297. $this->column = $column;
  5298. $this->operator = $operator;
  5299. $this->value = $value;
  5300. }
  5301. public function getColumn(): ReflectedColumn
  5302. {
  5303. return $this->column;
  5304. }
  5305. public function getOperator(): string
  5306. {
  5307. return $this->operator;
  5308. }
  5309. public function getValue(): string
  5310. {
  5311. return $this->value;
  5312. }
  5313. }
  5314. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  5315. abstract class Condition
  5316. {
  5317. public function _and(Condition $condition): Condition
  5318. {
  5319. if ($condition instanceof NoCondition) {
  5320. return $this;
  5321. }
  5322. return new AndCondition($this, $condition);
  5323. }
  5324. public function _or(Condition $condition): Condition
  5325. {
  5326. if ($condition instanceof NoCondition) {
  5327. return $this;
  5328. }
  5329. return new OrCondition($this, $condition);
  5330. }
  5331. public function _not(): Condition
  5332. {
  5333. return new NotCondition($this);
  5334. }
  5335. public static function fromString(ReflectedTable $table, string $value): Condition
  5336. {
  5337. $condition = new NoCondition();
  5338. $parts = explode(',', $value, 3);
  5339. if (count($parts) < 2) {
  5340. return $condition;
  5341. }
  5342. if (count($parts) < 3) {
  5343. $parts[2] = '';
  5344. }
  5345. $field = $table->getColumn($parts[0]);
  5346. $command = $parts[1];
  5347. $negate = false;
  5348. $spatial = false;
  5349. if (strlen($command) > 2) {
  5350. if (substr($command, 0, 1) == 'n') {
  5351. $negate = true;
  5352. $command = substr($command, 1);
  5353. }
  5354. if (substr($command, 0, 1) == 's') {
  5355. $spatial = true;
  5356. $command = substr($command, 1);
  5357. }
  5358. }
  5359. if ($spatial) {
  5360. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  5361. $condition = new SpatialCondition($field, $command, $parts[2]);
  5362. }
  5363. } else {
  5364. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  5365. $condition = new ColumnCondition($field, $command, $parts[2]);
  5366. }
  5367. }
  5368. if ($negate) {
  5369. $condition = $condition->_not();
  5370. }
  5371. return $condition;
  5372. }
  5373. }
  5374. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  5375. class NoCondition extends Condition
  5376. {
  5377. public function _and(Condition $condition): Condition
  5378. {
  5379. return $condition;
  5380. }
  5381. public function _or(Condition $condition): Condition
  5382. {
  5383. return $condition;
  5384. }
  5385. public function _not(): Condition
  5386. {
  5387. return $this;
  5388. }
  5389. }
  5390. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  5391. class NotCondition extends Condition
  5392. {
  5393. private $condition;
  5394. public function __construct(Condition $condition)
  5395. {
  5396. $this->condition = $condition;
  5397. }
  5398. public function getCondition(): Condition
  5399. {
  5400. return $this->condition;
  5401. }
  5402. }
  5403. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  5404. class OrCondition extends Condition
  5405. {
  5406. private $conditions;
  5407. public function __construct(Condition $condition1, Condition $condition2)
  5408. {
  5409. $this->conditions = [$condition1, $condition2];
  5410. }
  5411. public function _or(Condition $condition): Condition
  5412. {
  5413. if ($condition instanceof NoCondition) {
  5414. return $this;
  5415. }
  5416. $this->conditions[] = $condition;
  5417. return $this;
  5418. }
  5419. public function getConditions(): array
  5420. {
  5421. return $this->conditions;
  5422. }
  5423. public static function fromArray(array $conditions): Condition
  5424. {
  5425. $condition = new NoCondition();
  5426. foreach ($conditions as $c) {
  5427. $condition = $condition->_or($c);
  5428. }
  5429. return $condition;
  5430. }
  5431. }
  5432. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  5433. class SpatialCondition extends ColumnCondition
  5434. {
  5435. }
  5436. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  5437. class ErrorDocument implements \JsonSerializable
  5438. {
  5439. public $code;
  5440. public $message;
  5441. public $details;
  5442. public function __construct(ErrorCode $errorCode, string $argument, $details)
  5443. {
  5444. $this->code = $errorCode->getCode();
  5445. $this->message = $errorCode->getMessage($argument);
  5446. $this->details = $details;
  5447. }
  5448. public function getCode(): int
  5449. {
  5450. return $this->code;
  5451. }
  5452. public function getMessage(): string
  5453. {
  5454. return $this->message;
  5455. }
  5456. public function serialize()
  5457. {
  5458. return [
  5459. 'code' => $this->code,
  5460. 'message' => $this->message,
  5461. 'details' => $this->details,
  5462. ];
  5463. }
  5464. public function jsonSerialize()
  5465. {
  5466. return array_filter($this->serialize());
  5467. }
  5468. }
  5469. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  5470. class ListDocument implements \JsonSerializable
  5471. {
  5472. private $records;
  5473. private $results;
  5474. public function __construct(array $records, int $results)
  5475. {
  5476. $this->records = $records;
  5477. $this->results = $results;
  5478. }
  5479. public function getRecords(): array
  5480. {
  5481. return $this->records;
  5482. }
  5483. public function getResults(): int
  5484. {
  5485. return $this->results;
  5486. }
  5487. public function serialize()
  5488. {
  5489. return [
  5490. 'records' => $this->records,
  5491. 'results' => $this->results,
  5492. ];
  5493. }
  5494. public function jsonSerialize()
  5495. {
  5496. return array_filter($this->serialize(), function ($v) {
  5497. return $v !== 0;
  5498. });
  5499. }
  5500. }
  5501. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  5502. class ColumnIncluder
  5503. {
  5504. private function isMandatory(string $tableName, string $columnName, array $params): bool
  5505. {
  5506. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  5507. }
  5508. private function select(string $tableName, bool $primaryTable, array $params, string $paramName,
  5509. array $columnNames, bool $include): array{
  5510. if (!isset($params[$paramName])) {
  5511. return $columnNames;
  5512. }
  5513. $columns = array();
  5514. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  5515. $columns[$columnName] = true;
  5516. }
  5517. $result = array();
  5518. foreach ($columnNames as $columnName) {
  5519. $match = isset($columns['*.*']);
  5520. if (!$match) {
  5521. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  5522. }
  5523. if ($primaryTable && !$match) {
  5524. $match = isset($columns['*']) || isset($columns[$columnName]);
  5525. }
  5526. if ($match) {
  5527. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  5528. $result[] = $columnName;
  5529. }
  5530. } else {
  5531. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  5532. $result[] = $columnName;
  5533. }
  5534. }
  5535. }
  5536. return $result;
  5537. }
  5538. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  5539. {
  5540. $tableName = $table->getName();
  5541. $results = $table->getColumnNames();
  5542. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  5543. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  5544. return $results;
  5545. }
  5546. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  5547. {
  5548. $results = array();
  5549. $columnNames = $this->getNames($table, $primaryTable, $params);
  5550. foreach ($columnNames as $columnName) {
  5551. if (property_exists($record, $columnName)) {
  5552. $results[$columnName] = $record->$columnName;
  5553. }
  5554. }
  5555. return $results;
  5556. }
  5557. }
  5558. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  5559. class ErrorCode
  5560. {
  5561. private $code;
  5562. private $message;
  5563. private $status;
  5564. const ERROR_NOT_FOUND = 9999;
  5565. const ROUTE_NOT_FOUND = 1000;
  5566. const TABLE_NOT_FOUND = 1001;
  5567. const ARGUMENT_COUNT_MISMATCH = 1002;
  5568. const RECORD_NOT_FOUND = 1003;
  5569. const ORIGIN_FORBIDDEN = 1004;
  5570. const COLUMN_NOT_FOUND = 1005;
  5571. const TABLE_ALREADY_EXISTS = 1006;
  5572. const COLUMN_ALREADY_EXISTS = 1007;
  5573. const HTTP_MESSAGE_NOT_READABLE = 1008;
  5574. const DUPLICATE_KEY_EXCEPTION = 1009;
  5575. const DATA_INTEGRITY_VIOLATION = 1010;
  5576. const AUTHENTICATION_REQUIRED = 1011;
  5577. const AUTHENTICATION_FAILED = 1012;
  5578. const INPUT_VALIDATION_FAILED = 1013;
  5579. const OPERATION_FORBIDDEN = 1014;
  5580. const OPERATION_NOT_SUPPORTED = 1015;
  5581. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  5582. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  5583. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  5584. const PAGINATION_FORBIDDEN = 1019;
  5585. private $values = [
  5586. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  5587. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  5588. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  5589. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  5590. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  5591. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  5592. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  5593. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  5594. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  5595. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  5596. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  5597. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  5598. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  5599. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  5600. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  5601. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  5602. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  5603. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  5604. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  5605. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  5606. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  5607. ];
  5608. public function __construct(int $code)
  5609. {
  5610. if (!isset($this->values[$code])) {
  5611. $code = 9999;
  5612. }
  5613. $this->code = $code;
  5614. $this->message = $this->values[$code][0];
  5615. $this->status = $this->values[$code][1];
  5616. }
  5617. public function getCode(): int
  5618. {
  5619. return $this->code;
  5620. }
  5621. public function getMessage(string $argument): string
  5622. {
  5623. return sprintf($this->message, $argument);
  5624. }
  5625. public function getStatus(): int
  5626. {
  5627. return $this->status;
  5628. }
  5629. }
  5630. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  5631. class FilterInfo
  5632. {
  5633. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  5634. {
  5635. $key = 'filter' . implode('', $path);
  5636. if (isset($params[$key])) {
  5637. foreach ($params[$key] as $filter) {
  5638. $condition = Condition::fromString($table, $filter);
  5639. if (($condition instanceof NoCondition) == false) {
  5640. $conditions->put($path, $condition);
  5641. }
  5642. }
  5643. }
  5644. }
  5645. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  5646. {
  5647. $conditions = new PathTree();
  5648. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  5649. for ($n = ord('0'); $n <= ord('9'); $n++) {
  5650. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  5651. for ($l = ord('a'); $l <= ord('f'); $l++) {
  5652. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  5653. }
  5654. }
  5655. return $conditions;
  5656. }
  5657. private function combinePathTreeOfConditions(PathTree $tree): Condition
  5658. {
  5659. $andConditions = $tree->getValues();
  5660. $and = AndCondition::fromArray($andConditions);
  5661. $orConditions = [];
  5662. foreach ($tree->getKeys() as $p) {
  5663. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  5664. }
  5665. $or = OrCondition::fromArray($orConditions);
  5666. return $and->_and($or);
  5667. }
  5668. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  5669. {
  5670. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  5671. }
  5672. }
  5673. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  5674. class HabtmValues
  5675. {
  5676. public $pkValues;
  5677. public $fkValues;
  5678. public function __construct(array $pkValues, array $fkValues)
  5679. {
  5680. $this->pkValues = $pkValues;
  5681. $this->fkValues = $fkValues;
  5682. }
  5683. }
  5684. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  5685. class OrderingInfo
  5686. {
  5687. public function getColumnOrdering(ReflectedTable $table, array $params): array
  5688. {
  5689. $fields = array();
  5690. if (isset($params['order'])) {
  5691. foreach ($params['order'] as $order) {
  5692. $parts = explode(',', $order, 3);
  5693. $columnName = $parts[0];
  5694. if (!$table->hasColumn($columnName)) {
  5695. continue;
  5696. }
  5697. $ascending = 'ASC';
  5698. if (count($parts) > 1) {
  5699. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  5700. $ascending = 'DESC';
  5701. }
  5702. }
  5703. $fields[] = [$columnName, $ascending];
  5704. }
  5705. }
  5706. if (count($fields) == 0) {
  5707. return $this->getDefaultColumnOrdering($table);
  5708. }
  5709. return $fields;
  5710. }
  5711. public function getDefaultColumnOrdering(ReflectedTable $table): array
  5712. {
  5713. $fields = array();
  5714. $pk = $table->getPk();
  5715. if ($pk) {
  5716. $fields[] = [$pk->getName(), 'ASC'];
  5717. } else {
  5718. foreach ($table->getColumnNames() as $columnName) {
  5719. $fields[] = [$columnName, 'ASC'];
  5720. }
  5721. }
  5722. return $fields;
  5723. }
  5724. }
  5725. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  5726. class PaginationInfo
  5727. {
  5728. public $DEFAULT_PAGE_SIZE = 20;
  5729. public function hasPage(array $params): bool
  5730. {
  5731. return isset($params['page']);
  5732. }
  5733. public function getPageOffset(array $params): int
  5734. {
  5735. $offset = 0;
  5736. $pageSize = $this->getPageSize($params);
  5737. if (isset($params['page'])) {
  5738. foreach ($params['page'] as $page) {
  5739. $parts = explode(',', $page, 2);
  5740. $page = intval($parts[0]) - 1;
  5741. $offset = $page * $pageSize;
  5742. }
  5743. }
  5744. return $offset;
  5745. }
  5746. private function getPageSize(array $params): int
  5747. {
  5748. $pageSize = $this->DEFAULT_PAGE_SIZE;
  5749. if (isset($params['page'])) {
  5750. foreach ($params['page'] as $page) {
  5751. $parts = explode(',', $page, 2);
  5752. if (count($parts) > 1) {
  5753. $pageSize = intval($parts[1]);
  5754. }
  5755. }
  5756. }
  5757. return $pageSize;
  5758. }
  5759. public function getResultSize(array $params): int
  5760. {
  5761. $numberOfRows = -1;
  5762. if (isset($params['size'])) {
  5763. foreach ($params['size'] as $size) {
  5764. $numberOfRows = intval($size);
  5765. }
  5766. }
  5767. return $numberOfRows;
  5768. }
  5769. public function getPageLimit(array $params): int
  5770. {
  5771. $pageLimit = -1;
  5772. if ($this->hasPage($params)) {
  5773. $pageLimit = $this->getPageSize($params);
  5774. }
  5775. $resultSize = $this->getResultSize($params);
  5776. if ($resultSize >= 0) {
  5777. if ($pageLimit >= 0) {
  5778. $pageLimit = min($pageLimit, $resultSize);
  5779. } else {
  5780. $pageLimit = $resultSize;
  5781. }
  5782. }
  5783. return $pageLimit;
  5784. }
  5785. }
  5786. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  5787. class PathTree implements \JsonSerializable
  5788. {
  5789. const WILDCARD = '*';
  5790. private $tree;
  5791. public function __construct( /* object */&$tree = null)
  5792. {
  5793. if (!$tree) {
  5794. $tree = $this->newTree();
  5795. }
  5796. $this->tree = &$tree;
  5797. }
  5798. public function newTree()
  5799. {
  5800. return (object) ['values' => [], 'branches' => (object) []];
  5801. }
  5802. public function getKeys(): array
  5803. {
  5804. $branches = (array) $this->tree->branches;
  5805. return array_keys($branches);
  5806. }
  5807. public function getValues(): array
  5808. {
  5809. return $this->tree->values;
  5810. }
  5811. public function get(string $key): PathTree
  5812. {
  5813. if (!isset($this->tree->branches->$key)) {
  5814. return null;
  5815. }
  5816. return new PathTree($this->tree->branches->$key);
  5817. }
  5818. public function put(array $path, $value)
  5819. {
  5820. $tree = &$this->tree;
  5821. foreach ($path as $key) {
  5822. if (!isset($tree->branches->$key)) {
  5823. $tree->branches->$key = $this->newTree();
  5824. }
  5825. $tree = &$tree->branches->$key;
  5826. }
  5827. $tree->values[] = $value;
  5828. }
  5829. public function match(array $path): array
  5830. {
  5831. $star = self::WILDCARD;
  5832. $tree = &$this->tree;
  5833. foreach ($path as $key) {
  5834. if (isset($tree->branches->$key)) {
  5835. $tree = &$tree->branches->$key;
  5836. } else if (isset($tree->branches->$star)) {
  5837. $tree = &$tree->branches->$star;
  5838. } else {
  5839. return [];
  5840. }
  5841. }
  5842. return $tree->values;
  5843. }
  5844. public static function fromJson( /* object */$tree): PathTree
  5845. {
  5846. return new PathTree($tree);
  5847. }
  5848. public function jsonSerialize()
  5849. {
  5850. return $this->tree;
  5851. }
  5852. }
  5853. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  5854. class RecordService
  5855. {
  5856. private $db;
  5857. private $reflection;
  5858. private $columns;
  5859. private $joiner;
  5860. private $filters;
  5861. private $ordering;
  5862. private $pagination;
  5863. public function __construct(GenericDB $db, ReflectionService $reflection)
  5864. {
  5865. $this->db = $db;
  5866. $this->reflection = $reflection;
  5867. $this->columns = new ColumnIncluder();
  5868. $this->joiner = new RelationJoiner($reflection, $this->columns);
  5869. $this->filters = new FilterInfo();
  5870. $this->ordering = new OrderingInfo();
  5871. $this->pagination = new PaginationInfo();
  5872. }
  5873. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  5874. {
  5875. $keyset = array_keys((array) $record);
  5876. foreach ($keyset as $key) {
  5877. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  5878. unset($record->$key);
  5879. }
  5880. }
  5881. if ($id != '') {
  5882. $pk = $this->reflection->getTable($tableName)->getPk();
  5883. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  5884. $field = $this->reflection->getTable($tableName)->getColumn($key);
  5885. if ($field->getName() == $pk->getName()) {
  5886. unset($record->$key);
  5887. }
  5888. }
  5889. }
  5890. }
  5891. public function hasTable(string $table): bool
  5892. {
  5893. return $this->reflection->hasTable($table);
  5894. }
  5895. public function getType(string $table): string
  5896. {
  5897. return $this->reflection->getType($table);
  5898. }
  5899. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  5900. {
  5901. $this->sanitizeRecord($tableName, $record, '');
  5902. $table = $this->reflection->getTable($tableName);
  5903. $columnValues = $this->columns->getValues($table, true, $record, $params);
  5904. return $this->db->createSingle($table, $columnValues);
  5905. }
  5906. public function read(string $tableName, string $id, array $params) /*: ?object*/
  5907. {
  5908. $table = $this->reflection->getTable($tableName);
  5909. $this->joiner->addMandatoryColumns($table, $params);
  5910. $columnNames = $this->columns->getNames($table, true, $params);
  5911. $record = $this->db->selectSingle($table, $columnNames, $id);
  5912. if ($record == null) {
  5913. return null;
  5914. }
  5915. $records = array($record);
  5916. $this->joiner->addJoins($table, $records, $params, $this->db);
  5917. return $records[0];
  5918. }
  5919. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  5920. {
  5921. $this->sanitizeRecord($tableName, $record, $id);
  5922. $table = $this->reflection->getTable($tableName);
  5923. $columnValues = $this->columns->getValues($table, true, $record, $params);
  5924. return $this->db->updateSingle($table, $columnValues, $id);
  5925. }
  5926. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  5927. {
  5928. $table = $this->reflection->getTable($tableName);
  5929. return $this->db->deleteSingle($table, $id);
  5930. }
  5931. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  5932. {
  5933. $this->sanitizeRecord($tableName, $record, $id);
  5934. $table = $this->reflection->getTable($tableName);
  5935. $columnValues = $this->columns->getValues($table, true, $record, $params);
  5936. return $this->db->incrementSingle($table, $columnValues, $id);
  5937. }
  5938. public function _list(string $tableName, array $params): ListDocument
  5939. {
  5940. $table = $this->reflection->getTable($tableName);
  5941. $this->joiner->addMandatoryColumns($table, $params);
  5942. $columnNames = $this->columns->getNames($table, true, $params);
  5943. $condition = $this->filters->getCombinedConditions($table, $params);
  5944. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  5945. if (!$this->pagination->hasPage($params)) {
  5946. $offset = 0;
  5947. $limit = $this->pagination->getPageLimit($params);
  5948. $count = 0;
  5949. } else {
  5950. $offset = $this->pagination->getPageOffset($params);
  5951. $limit = $this->pagination->getPageLimit($params);
  5952. $count = $this->db->selectCount($table, $condition);
  5953. }
  5954. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  5955. $this->joiner->addJoins($table, $records, $params, $this->db);
  5956. return new ListDocument($records, $count);
  5957. }
  5958. }
  5959. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  5960. class RelationJoiner
  5961. {
  5962. private $reflection;
  5963. private $columns;
  5964. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  5965. {
  5966. $this->reflection = $reflection;
  5967. $this->ordering = new OrderingInfo();
  5968. $this->columns = $columns;
  5969. }
  5970. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  5971. {
  5972. if (!isset($params['join']) || !isset($params['include'])) {
  5973. return;
  5974. }
  5975. $params['mandatory'] = array();
  5976. foreach ($params['join'] as $tableNames) {
  5977. $t1 = $table;
  5978. foreach (explode(',', $tableNames) as $tableName) {
  5979. if (!$this->reflection->hasTable($tableName)) {
  5980. continue;
  5981. }
  5982. $t2 = $this->reflection->getTable($tableName);
  5983. $fks1 = $t1->getFksTo($t2->getName());
  5984. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  5985. if ($t3 != null || count($fks1) > 0) {
  5986. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  5987. }
  5988. foreach ($fks1 as $fk) {
  5989. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  5990. }
  5991. $fks2 = $t2->getFksTo($t1->getName());
  5992. if ($t3 != null || count($fks2) > 0) {
  5993. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  5994. }
  5995. foreach ($fks2 as $fk) {
  5996. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  5997. }
  5998. $t1 = $t2;
  5999. }
  6000. }
  6001. }
  6002. private function getJoinsAsPathTree(array $params): PathTree
  6003. {
  6004. $joins = new PathTree();
  6005. if (isset($params['join'])) {
  6006. foreach ($params['join'] as $tableNames) {
  6007. $path = array();
  6008. foreach (explode(',', $tableNames) as $tableName) {
  6009. $t = $this->reflection->getTable($tableName);
  6010. if ($t != null) {
  6011. $path[] = $t->getName();
  6012. }
  6013. }
  6014. $joins->put($path, true);
  6015. }
  6016. }
  6017. return $joins;
  6018. }
  6019. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  6020. {
  6021. $joins = $this->getJoinsAsPathTree($params);
  6022. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  6023. }
  6024. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  6025. {
  6026. foreach ($this->reflection->getTableNames() as $tableName) {
  6027. $t3 = $this->reflection->getTable($tableName);
  6028. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  6029. return $t3;
  6030. }
  6031. }
  6032. return null;
  6033. }
  6034. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  6035. {
  6036. foreach ($joins->getKeys() as $t2Name) {
  6037. $t2 = $this->reflection->getTable($t2Name);
  6038. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  6039. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  6040. if (!$belongsTo && !$hasMany) {
  6041. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  6042. } else {
  6043. $t3 = null;
  6044. }
  6045. $hasAndBelongsToMany = ($t3 != null);
  6046. $newRecords = array();
  6047. $fkValues = null;
  6048. $pkValues = null;
  6049. $habtmValues = null;
  6050. if ($belongsTo) {
  6051. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  6052. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  6053. }
  6054. if ($hasMany) {
  6055. $pkValues = $this->getPkEmptyValues($t1, $records);
  6056. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  6057. }
  6058. if ($hasAndBelongsToMany) {
  6059. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  6060. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  6061. }
  6062. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  6063. if ($fkValues != null) {
  6064. $this->fillFkValues($t2, $newRecords, $fkValues);
  6065. $this->setFkValues($t1, $t2, $records, $fkValues);
  6066. }
  6067. if ($pkValues != null) {
  6068. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  6069. $this->setPkValues($t1, $t2, $records, $pkValues);
  6070. }
  6071. if ($habtmValues != null) {
  6072. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  6073. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  6074. }
  6075. }
  6076. }
  6077. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  6078. {
  6079. $fkValues = array();
  6080. $fks = $t1->getFksTo($t2->getName());
  6081. foreach ($fks as $fk) {
  6082. $fkName = $fk->getName();
  6083. foreach ($records as $record) {
  6084. if (isset($record[$fkName])) {
  6085. $fkValue = $record[$fkName];
  6086. $fkValues[$fkValue] = null;
  6087. }
  6088. }
  6089. }
  6090. return $fkValues;
  6091. }
  6092. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  6093. {
  6094. $columnNames = $this->columns->getNames($t2, false, $params);
  6095. $fkIds = array_keys($fkValues);
  6096. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  6097. $records[] = $record;
  6098. }
  6099. }
  6100. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  6101. {
  6102. $pkName = $t2->getPk()->getName();
  6103. foreach ($fkRecords as $fkRecord) {
  6104. $pkValue = $fkRecord[$pkName];
  6105. $fkValues[$pkValue] = $fkRecord;
  6106. }
  6107. }
  6108. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  6109. {
  6110. $fks = $t1->getFksTo($t2->getName());
  6111. foreach ($fks as $fk) {
  6112. $fkName = $fk->getName();
  6113. foreach ($records as $i => $record) {
  6114. if (isset($record[$fkName])) {
  6115. $key = $record[$fkName];
  6116. $records[$i][$fkName] = $fkValues[$key];
  6117. }
  6118. }
  6119. }
  6120. }
  6121. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  6122. {
  6123. $pkValues = array();
  6124. $pkName = $t1->getPk()->getName();
  6125. foreach ($records as $record) {
  6126. $key = $record[$pkName];
  6127. $pkValues[$key] = array();
  6128. }
  6129. return $pkValues;
  6130. }
  6131. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  6132. {
  6133. $fks = $t2->getFksTo($t1->getName());
  6134. $columnNames = $this->columns->getNames($t2, false, $params);
  6135. $pkValueKeys = implode(',', array_keys($pkValues));
  6136. $conditions = array();
  6137. foreach ($fks as $fk) {
  6138. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  6139. }
  6140. $condition = OrCondition::fromArray($conditions);
  6141. $columnOrdering = array();
  6142. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  6143. if ($limit != -1) {
  6144. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  6145. }
  6146. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  6147. $records[] = $record;
  6148. }
  6149. }
  6150. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  6151. {
  6152. $fks = $t2->getFksTo($t1->getName());
  6153. foreach ($fks as $fk) {
  6154. $fkName = $fk->getName();
  6155. foreach ($pkRecords as $pkRecord) {
  6156. $key = $pkRecord[$fkName];
  6157. if (isset($pkValues[$key])) {
  6158. $pkValues[$key][] = $pkRecord;
  6159. }
  6160. }
  6161. }
  6162. }
  6163. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  6164. {
  6165. $pkName = $t1->getPk()->getName();
  6166. $t2Name = $t2->getName();
  6167. foreach ($records as $i => $record) {
  6168. $key = $record[$pkName];
  6169. $records[$i][$t2Name] = $pkValues[$key];
  6170. }
  6171. }
  6172. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  6173. {
  6174. $pkValues = $this->getPkEmptyValues($t1, $records);
  6175. $fkValues = array();
  6176. $fk1 = $t3->getFksTo($t1->getName())[0];
  6177. $fk2 = $t3->getFksTo($t2->getName())[0];
  6178. $fk1Name = $fk1->getName();
  6179. $fk2Name = $fk2->getName();
  6180. $columnNames = array($fk1Name, $fk2Name);
  6181. $pkIds = implode(',', array_keys($pkValues));
  6182. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  6183. $columnOrdering = array();
  6184. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  6185. if ($limit != -1) {
  6186. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  6187. }
  6188. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  6189. foreach ($records as $record) {
  6190. $val1 = $record[$fk1Name];
  6191. $val2 = $record[$fk2Name];
  6192. $pkValues[$val1][] = $val2;
  6193. $fkValues[$val2] = null;
  6194. }
  6195. return new HabtmValues($pkValues, $fkValues);
  6196. }
  6197. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  6198. {
  6199. $pkName = $t1->getPk()->getName();
  6200. $t2Name = $t2->getName();
  6201. foreach ($records as $i => $record) {
  6202. $key = $record[$pkName];
  6203. $val = array();
  6204. $fks = $habtmValues->pkValues[$key];
  6205. foreach ($fks as $fk) {
  6206. $val[] = $habtmValues->fkValues[$fk];
  6207. }
  6208. $records[$i][$t2Name] = $val;
  6209. }
  6210. }
  6211. }
  6212. // file: src/Tqdev/PhpCrudApi/Api.php
  6213. class Api implements RequestHandlerInterface
  6214. {
  6215. private $router;
  6216. private $responder;
  6217. private $debug;
  6218. public function __construct(Config $config)
  6219. {
  6220. $db = new GenericDB(
  6221. $config->getDriver(),
  6222. $config->getAddress(),
  6223. $config->getPort(),
  6224. $config->getDatabase(),
  6225. $config->getUsername(),
  6226. $config->getPassword()
  6227. );
  6228. $cache = CacheFactory::create($config);
  6229. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  6230. $responder = new Responder();
  6231. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  6232. foreach ($config->getMiddlewares() as $middleware => $properties) {
  6233. switch ($middleware) {
  6234. case 'cors':
  6235. new CorsMiddleware($router, $responder, $properties);
  6236. break;
  6237. case 'firewall':
  6238. new FirewallMiddleware($router, $responder, $properties);
  6239. break;
  6240. case 'basicAuth':
  6241. new BasicAuthMiddleware($router, $responder, $properties);
  6242. break;
  6243. case 'jwtAuth':
  6244. new JwtAuthMiddleware($router, $responder, $properties);
  6245. break;
  6246. case 'validation':
  6247. new ValidationMiddleware($router, $responder, $properties, $reflection);
  6248. break;
  6249. case 'ipAddress':
  6250. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  6251. break;
  6252. case 'sanitation':
  6253. new SanitationMiddleware($router, $responder, $properties, $reflection);
  6254. break;
  6255. case 'multiTenancy':
  6256. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  6257. break;
  6258. case 'authorization':
  6259. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  6260. break;
  6261. case 'xsrf':
  6262. new XsrfMiddleware($router, $responder, $properties);
  6263. break;
  6264. case 'pageLimits':
  6265. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  6266. break;
  6267. case 'joinLimits':
  6268. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  6269. break;
  6270. case 'customization':
  6271. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  6272. break;
  6273. }
  6274. }
  6275. foreach ($config->getControllers() as $controller) {
  6276. switch ($controller) {
  6277. case 'records':
  6278. $records = new RecordService($db, $reflection);
  6279. new RecordController($router, $responder, $records);
  6280. break;
  6281. case 'columns':
  6282. $definition = new DefinitionService($db, $reflection);
  6283. new ColumnController($router, $responder, $reflection, $definition);
  6284. break;
  6285. case 'cache':
  6286. new CacheController($router, $responder, $cache);
  6287. break;
  6288. case 'openapi':
  6289. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  6290. new OpenApiController($router, $responder, $openApi);
  6291. break;
  6292. case 'geojson':
  6293. $records = new RecordService($db, $reflection);
  6294. $geoJson = new GeoJsonService($reflection, $records);
  6295. new GeoJsonController($router, $responder, $geoJson);
  6296. break;
  6297. }
  6298. }
  6299. $this->router = $router;
  6300. $this->responder = $responder;
  6301. $this->debug = $config->getDebug();
  6302. }
  6303. public function handle(ServerRequestInterface $request): ResponseInterface
  6304. {
  6305. $response = null;
  6306. try {
  6307. $response = $this->router->route($request);
  6308. } catch (\Throwable $e) {
  6309. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  6310. if ($this->debug) {
  6311. $response = ResponseUtils::addExceptionHeaders($response, $e);
  6312. }
  6313. }
  6314. return $response;
  6315. }
  6316. }
  6317. // file: src/Tqdev/PhpCrudApi/Config.php
  6318. class Config
  6319. {
  6320. private $values = [
  6321. 'driver' => null,
  6322. 'address' => 'localhost',
  6323. 'port' => null,
  6324. 'username' => null,
  6325. 'password' => null,
  6326. 'database' => null,
  6327. 'middlewares' => 'cors',
  6328. 'controllers' => 'records,openapi',
  6329. 'cacheType' => 'TempFile',
  6330. 'cachePath' => '',
  6331. 'cacheTime' => 10,
  6332. 'debug' => false,
  6333. 'basePath' => '',
  6334. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  6335. ];
  6336. private function getDefaultDriver(array $values): string
  6337. {
  6338. if (isset($values['driver'])) {
  6339. return $values['driver'];
  6340. }
  6341. return 'mysql';
  6342. }
  6343. private function getDefaultPort(string $driver): int
  6344. {
  6345. switch ($driver) {
  6346. case 'mysql':return 3306;
  6347. case 'pgsql':return 5432;
  6348. case 'sqlsrv':return 1433;
  6349. }
  6350. }
  6351. private function getDefaultAddress(string $driver): string
  6352. {
  6353. switch ($driver) {
  6354. case 'mysql':return 'localhost';
  6355. case 'pgsql':return 'localhost';
  6356. case 'sqlsrv':return 'localhost';
  6357. }
  6358. }
  6359. private function getDriverDefaults(string $driver): array
  6360. {
  6361. return [
  6362. 'driver' => $driver,
  6363. 'address' => $this->getDefaultAddress($driver),
  6364. 'port' => $this->getDefaultPort($driver),
  6365. ];
  6366. }
  6367. public function __construct(array $values)
  6368. {
  6369. $driver = $this->getDefaultDriver($values);
  6370. $defaults = $this->getDriverDefaults($driver);
  6371. $newValues = array_merge($this->values, $defaults, $values);
  6372. $newValues = $this->parseMiddlewares($newValues);
  6373. $diff = array_diff_key($newValues, $this->values);
  6374. if (!empty($diff)) {
  6375. $key = array_keys($diff)[0];
  6376. throw new \Exception("Config has invalid value '$key'");
  6377. }
  6378. $this->values = $newValues;
  6379. }
  6380. private function parseMiddlewares(array $values): array
  6381. {
  6382. $newValues = array();
  6383. $properties = array();
  6384. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  6385. foreach ($middlewares as $middleware) {
  6386. $properties[$middleware] = [];
  6387. }
  6388. foreach ($values as $key => $value) {
  6389. if (strpos($key, '.') === false) {
  6390. $newValues[$key] = $value;
  6391. } else {
  6392. list($middleware, $key2) = explode('.', $key, 2);
  6393. if (isset($properties[$middleware])) {
  6394. $properties[$middleware][$key2] = $value;
  6395. } else {
  6396. throw new \Exception("Config has invalid value '$key'");
  6397. }
  6398. }
  6399. }
  6400. $newValues['middlewares'] = array_reverse($properties, true);
  6401. return $newValues;
  6402. }
  6403. public function getDriver(): string
  6404. {
  6405. return $this->values['driver'];
  6406. }
  6407. public function getAddress(): string
  6408. {
  6409. return $this->values['address'];
  6410. }
  6411. public function getPort(): int
  6412. {
  6413. return $this->values['port'];
  6414. }
  6415. public function getUsername(): string
  6416. {
  6417. return $this->values['username'];
  6418. }
  6419. public function getPassword(): string
  6420. {
  6421. return $this->values['password'];
  6422. }
  6423. public function getDatabase(): string
  6424. {
  6425. return $this->values['database'];
  6426. }
  6427. public function getMiddlewares(): array
  6428. {
  6429. return $this->values['middlewares'];
  6430. }
  6431. public function getControllers(): array
  6432. {
  6433. return array_map('trim', explode(',', $this->values['controllers']));
  6434. }
  6435. public function getCacheType(): string
  6436. {
  6437. return $this->values['cacheType'];
  6438. }
  6439. public function getCachePath(): string
  6440. {
  6441. return $this->values['cachePath'];
  6442. }
  6443. public function getCacheTime(): int
  6444. {
  6445. return $this->values['cacheTime'];
  6446. }
  6447. public function getDebug(): bool
  6448. {
  6449. return $this->values['debug'];
  6450. }
  6451. public function getBasePath(): string
  6452. {
  6453. return $this->values['basePath'];
  6454. }
  6455. public function getOpenApiBase(): array
  6456. {
  6457. return json_decode($this->values['openApiBase'], true);
  6458. }
  6459. }
  6460. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  6461. class RequestFactory
  6462. {
  6463. private static function parseBody(string $body) /*: ?object*/
  6464. {
  6465. $first = substr($body, 0, 1);
  6466. if ($first == '[' || $first == '{') {
  6467. $object = json_decode($body);
  6468. $causeCode = json_last_error();
  6469. if ($causeCode !== JSON_ERROR_NONE) {
  6470. $object = null;
  6471. }
  6472. } else {
  6473. parse_str($body, $input);
  6474. foreach ($input as $key => $value) {
  6475. if (substr($key, -9) == '__is_null') {
  6476. $input[substr($key, 0, -9)] = null;
  6477. unset($input[$key]);
  6478. }
  6479. }
  6480. $object = (object) $input;
  6481. }
  6482. return $object;
  6483. }
  6484. public static function fromGlobals(): ServerRequestInterface
  6485. {
  6486. $psr17Factory = new Psr17Factory();
  6487. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  6488. $serverRequest = $creator->fromGlobals();
  6489. $body = file_get_contents('php://input');
  6490. if ($body) {
  6491. $serverRequest = $serverRequest->withParsedBody(self::parseBody($body));
  6492. }
  6493. return $serverRequest;
  6494. }
  6495. public static function fromString(string $request): ServerRequestInterface
  6496. {
  6497. $parts = explode("\n\n", trim($request), 2);
  6498. $lines = explode("\n", $parts[0]);
  6499. $first = explode(' ', trim(array_shift($lines)), 2);
  6500. $method = $first[0];
  6501. $body = isset($parts[1]) ? $parts[1] : '';
  6502. $url = isset($first[1]) ? $first[1] : '';
  6503. $psr17Factory = new Psr17Factory();
  6504. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  6505. foreach ($lines as $line) {
  6506. list($key, $value) = explode(':', $line, 2);
  6507. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  6508. }
  6509. if ($body) {
  6510. $stream = $psr17Factory->createStream($body);
  6511. $stream->rewind();
  6512. $serverRequest = $serverRequest->withBody($stream);
  6513. $serverRequest = $serverRequest->withParsedBody(self::parseBody($body));
  6514. }
  6515. return $serverRequest;
  6516. }
  6517. }
  6518. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  6519. class RequestUtils
  6520. {
  6521. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  6522. {
  6523. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  6524. return $request->withUri($request->getUri()->withQuery($query));
  6525. }
  6526. public static function getHeader(ServerRequestInterface $request, string $header): string
  6527. {
  6528. $headers = $request->getHeader($header);
  6529. return isset($headers[0]) ? $headers[0] : '';
  6530. }
  6531. public static function getParams(ServerRequestInterface $request): array
  6532. {
  6533. $params = array();
  6534. $query = $request->getUri()->getQuery();
  6535. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  6536. parse_str($query, $params);
  6537. return $params;
  6538. }
  6539. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  6540. {
  6541. $path = $request->getUri()->getPath();
  6542. $pathSegments = explode('/', rtrim($path, '/'));
  6543. if ($part < 0 || $part >= count($pathSegments)) {
  6544. return '';
  6545. }
  6546. return urldecode($pathSegments[$part]);
  6547. }
  6548. public static function getOperation(ServerRequestInterface $request): string
  6549. {
  6550. $method = $request->getMethod();
  6551. $path = RequestUtils::getPathSegment($request, 1);
  6552. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  6553. switch ($path) {
  6554. case 'openapi':
  6555. return 'document';
  6556. case 'columns':
  6557. return $method == 'get' ? 'reflect' : 'remodel';
  6558. case 'records':
  6559. switch ($method) {
  6560. case 'POST':
  6561. return 'create';
  6562. case 'GET':
  6563. return $hasPk ? 'read' : 'list';
  6564. case 'PUT':
  6565. return 'update';
  6566. case 'DELETE':
  6567. return 'delete';
  6568. case 'PATCH':
  6569. return 'increment';
  6570. }
  6571. }
  6572. return 'unknown';
  6573. }
  6574. private static function getJoinTables(string $tableName, array $parameters): array
  6575. {
  6576. $uniqueTableNames = array();
  6577. $uniqueTableNames[$tableName] = true;
  6578. if (isset($parameters['join'])) {
  6579. foreach ($parameters['join'] as $parameter) {
  6580. $tableNames = explode(',', trim($parameter));
  6581. foreach ($tableNames as $tableName) {
  6582. $uniqueTableNames[$tableName] = true;
  6583. }
  6584. }
  6585. }
  6586. return array_keys($uniqueTableNames);
  6587. }
  6588. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  6589. {
  6590. $path = RequestUtils::getPathSegment($request, 1);
  6591. $tableName = RequestUtils::getPathSegment($request, 2);
  6592. $allTableNames = $reflection->getTableNames();
  6593. switch ($path) {
  6594. case 'openapi':
  6595. return $allTableNames;
  6596. case 'columns':
  6597. return $tableName ? [$tableName] : $allTableNames;
  6598. case 'records':
  6599. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  6600. }
  6601. return $allTableNames;
  6602. }
  6603. }
  6604. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  6605. class ResponseFactory
  6606. {
  6607. const OK = 200;
  6608. const UNAUTHORIZED = 401;
  6609. const FORBIDDEN = 403;
  6610. const NOT_FOUND = 404;
  6611. const METHOD_NOT_ALLOWED = 405;
  6612. const CONFLICT = 409;
  6613. const UNPROCESSABLE_ENTITY = 422;
  6614. const INTERNAL_SERVER_ERROR = 500;
  6615. public static function fromObject(int $status, $body): ResponseInterface
  6616. {
  6617. $psr17Factory = new Psr17Factory();
  6618. $response = $psr17Factory->createResponse($status);
  6619. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  6620. $stream = $psr17Factory->createStream($content);
  6621. $stream->rewind();
  6622. $response = $response->withBody($stream);
  6623. $response = $response->withHeader('Content-Type', 'application/json');
  6624. $response = $response->withHeader('Content-Length', strlen($content));
  6625. return $response;
  6626. }
  6627. public static function fromStatus(int $status): ResponseInterface
  6628. {
  6629. $psr17Factory = new Psr17Factory();
  6630. return $psr17Factory->createResponse($status);
  6631. }
  6632. }
  6633. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  6634. class ResponseUtils
  6635. {
  6636. public static function output(ResponseInterface $response)
  6637. {
  6638. $status = $response->getStatusCode();
  6639. $headers = $response->getHeaders();
  6640. $body = $response->getBody()->getContents();
  6641. http_response_code($status);
  6642. foreach ($headers as $key => $values) {
  6643. foreach ($values as $value) {
  6644. header("$key: $value");
  6645. }
  6646. }
  6647. echo $body;
  6648. }
  6649. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  6650. {
  6651. $response = $response->withHeader('X-Exception-Name', get_class($e));
  6652. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  6653. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  6654. return $response;
  6655. }
  6656. public static function toString(ResponseInterface $response): string
  6657. {
  6658. $status = $response->getStatusCode();
  6659. $headers = $response->getHeaders();
  6660. $body = $response->getBody()->getContents();
  6661. $str = "$status\n";
  6662. foreach ($headers as $key => $values) {
  6663. foreach ($values as $value) {
  6664. $str .= "$key: $value\n";
  6665. }
  6666. }
  6667. if ($body !== '') {
  6668. $str .= "\n";
  6669. $str .= "$body\n";
  6670. }
  6671. return $str;
  6672. }
  6673. }
  6674. // file: src/index.php
  6675. $config = new Config([
  6676. 'username' => 'php-crud-api',
  6677. 'password' => 'php-crud-api',
  6678. 'database' => 'php-crud-api',
  6679. ]);
  6680. $request = RequestFactory::fromGlobals();
  6681. $api = new Api($config);
  6682. $response = $api->handle($request);
  6683. ResponseUtils::output($response);