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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795
  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. // file: vendor/psr/http-factory/src/RequestFactoryInterface.php
  14. namespace Psr\Http\Message {
  15. interface RequestFactoryInterface
  16. {
  17. /**
  18. * Create a new request.
  19. *
  20. * @param string $method The HTTP method associated with the request.
  21. * @param UriInterface|string $uri The URI associated with the request. If
  22. * the value is a string, the factory MUST create a UriInterface
  23. * instance based on it.
  24. *
  25. * @return RequestInterface
  26. */
  27. public function createRequest(string $method, $uri): RequestInterface;
  28. }
  29. }
  30. // file: vendor/psr/http-factory/src/ResponseFactoryInterface.php
  31. namespace Psr\Http\Message {
  32. interface ResponseFactoryInterface
  33. {
  34. /**
  35. * Create a new response.
  36. *
  37. * @param int $code HTTP status code; defaults to 200
  38. * @param string $reasonPhrase Reason phrase to associate with status code
  39. * in generated response; if none is provided implementations MAY use
  40. * the defaults as suggested in the HTTP specification.
  41. *
  42. * @return ResponseInterface
  43. */
  44. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface;
  45. }
  46. }
  47. // file: vendor/psr/http-factory/src/ServerRequestFactoryInterface.php
  48. namespace Psr\Http\Message {
  49. interface ServerRequestFactoryInterface
  50. {
  51. /**
  52. * Create a new server request.
  53. *
  54. * Note that server-params are taken precisely as given - no parsing/processing
  55. * of the given values is performed, and, in particular, no attempt is made to
  56. * determine the HTTP method or URI, which must be provided explicitly.
  57. *
  58. * @param string $method The HTTP method associated with the request.
  59. * @param UriInterface|string $uri The URI associated with the request. If
  60. * the value is a string, the factory MUST create a UriInterface
  61. * instance based on it.
  62. * @param array $serverParams Array of SAPI parameters with which to seed
  63. * the generated request instance.
  64. *
  65. * @return ServerRequestInterface
  66. */
  67. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface;
  68. }
  69. }
  70. // file: vendor/psr/http-factory/src/StreamFactoryInterface.php
  71. namespace Psr\Http\Message {
  72. interface StreamFactoryInterface
  73. {
  74. /**
  75. * Create a new stream from a string.
  76. *
  77. * The stream SHOULD be created with a temporary resource.
  78. *
  79. * @param string $content String content with which to populate the stream.
  80. *
  81. * @return StreamInterface
  82. */
  83. public function createStream(string $content = ''): StreamInterface;
  84. /**
  85. * Create a stream from an existing file.
  86. *
  87. * The file MUST be opened using the given mode, which may be any mode
  88. * supported by the `fopen` function.
  89. *
  90. * The `$filename` MAY be any string supported by `fopen()`.
  91. *
  92. * @param string $filename Filename or stream URI to use as basis of stream.
  93. * @param string $mode Mode with which to open the underlying filename/stream.
  94. *
  95. * @return StreamInterface
  96. * @throws \RuntimeException If the file cannot be opened.
  97. * @throws \InvalidArgumentException If the mode is invalid.
  98. */
  99. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface;
  100. /**
  101. * Create a new stream from an existing resource.
  102. *
  103. * The stream MUST be readable and may be writable.
  104. *
  105. * @param resource $resource PHP resource to use as basis of stream.
  106. *
  107. * @return StreamInterface
  108. */
  109. public function createStreamFromResource($resource): StreamInterface;
  110. }
  111. }
  112. // file: vendor/psr/http-factory/src/UploadedFileFactoryInterface.php
  113. namespace Psr\Http\Message {
  114. interface UploadedFileFactoryInterface
  115. {
  116. /**
  117. * Create a new uploaded file.
  118. *
  119. * If a size is not provided it will be determined by checking the size of
  120. * the file.
  121. *
  122. * @see http://php.net/manual/features.file-upload.post-method.php
  123. * @see http://php.net/manual/features.file-upload.errors.php
  124. *
  125. * @param StreamInterface $stream Underlying stream representing the
  126. * uploaded file content.
  127. * @param int $size in bytes
  128. * @param int $error PHP file upload error
  129. * @param string $clientFilename Filename as provided by the client, if any.
  130. * @param string $clientMediaType Media type as provided by the client, if any.
  131. *
  132. * @return UploadedFileInterface
  133. *
  134. * @throws \InvalidArgumentException If the file resource is not readable.
  135. */
  136. public function createUploadedFile(
  137. StreamInterface $stream,
  138. int $size = null,
  139. int $error = \UPLOAD_ERR_OK,
  140. string $clientFilename = null,
  141. string $clientMediaType = null
  142. ): UploadedFileInterface;
  143. }
  144. }
  145. // file: vendor/psr/http-factory/src/UriFactoryInterface.php
  146. namespace Psr\Http\Message {
  147. interface UriFactoryInterface
  148. {
  149. /**
  150. * Create a new URI.
  151. *
  152. * @param string $uri
  153. *
  154. * @return UriInterface
  155. *
  156. * @throws \InvalidArgumentException If the given URI cannot be parsed.
  157. */
  158. public function createUri(string $uri = ''): UriInterface;
  159. }
  160. }
  161. // file: vendor/psr/http-message/src/MessageInterface.php
  162. namespace Psr\Http\Message {
  163. /**
  164. * HTTP messages consist of requests from a client to a server and responses
  165. * from a server to a client. This interface defines the methods common to
  166. * each.
  167. *
  168. * Messages are considered immutable; all methods that might change state MUST
  169. * be implemented such that they retain the internal state of the current
  170. * message and return an instance that contains the changed state.
  171. *
  172. * @link http://www.ietf.org/rfc/rfc7230.txt
  173. * @link http://www.ietf.org/rfc/rfc7231.txt
  174. */
  175. interface MessageInterface
  176. {
  177. /**
  178. * Retrieves the HTTP protocol version as a string.
  179. *
  180. * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
  181. *
  182. * @return string HTTP protocol version.
  183. */
  184. public function getProtocolVersion();
  185. /**
  186. * Return an instance with the specified HTTP protocol version.
  187. *
  188. * The version string MUST contain only the HTTP version number (e.g.,
  189. * "1.1", "1.0").
  190. *
  191. * This method MUST be implemented in such a way as to retain the
  192. * immutability of the message, and MUST return an instance that has the
  193. * new protocol version.
  194. *
  195. * @param string $version HTTP protocol version
  196. * @return static
  197. */
  198. public function withProtocolVersion($version);
  199. /**
  200. * Retrieves all message header values.
  201. *
  202. * The keys represent the header name as it will be sent over the wire, and
  203. * each value is an array of strings associated with the header.
  204. *
  205. * // Represent the headers as a string
  206. * foreach ($message->getHeaders() as $name => $values) {
  207. * echo $name . ": " . implode(", ", $values);
  208. * }
  209. *
  210. * // Emit headers iteratively:
  211. * foreach ($message->getHeaders() as $name => $values) {
  212. * foreach ($values as $value) {
  213. * header(sprintf('%s: %s', $name, $value), false);
  214. * }
  215. * }
  216. *
  217. * While header names are not case-sensitive, getHeaders() will preserve the
  218. * exact case in which headers were originally specified.
  219. *
  220. * @return string[][] Returns an associative array of the message's headers. Each
  221. * key MUST be a header name, and each value MUST be an array of strings
  222. * for that header.
  223. */
  224. public function getHeaders();
  225. /**
  226. * Checks if a header exists by the given case-insensitive name.
  227. *
  228. * @param string $name Case-insensitive header field name.
  229. * @return bool Returns true if any header names match the given header
  230. * name using a case-insensitive string comparison. Returns false if
  231. * no matching header name is found in the message.
  232. */
  233. public function hasHeader($name);
  234. /**
  235. * Retrieves a message header value by the given case-insensitive name.
  236. *
  237. * This method returns an array of all the header values of the given
  238. * case-insensitive header name.
  239. *
  240. * If the header does not appear in the message, this method MUST return an
  241. * empty array.
  242. *
  243. * @param string $name Case-insensitive header field name.
  244. * @return string[] An array of string values as provided for the given
  245. * header. If the header does not appear in the message, this method MUST
  246. * return an empty array.
  247. */
  248. public function getHeader($name);
  249. /**
  250. * Retrieves a comma-separated string of the values for a single header.
  251. *
  252. * This method returns all of the header values of the given
  253. * case-insensitive header name as a string concatenated together using
  254. * a comma.
  255. *
  256. * NOTE: Not all header values may be appropriately represented using
  257. * comma concatenation. For such headers, use getHeader() instead
  258. * and supply your own delimiter when concatenating.
  259. *
  260. * If the header does not appear in the message, this method MUST return
  261. * an empty string.
  262. *
  263. * @param string $name Case-insensitive header field name.
  264. * @return string A string of values as provided for the given header
  265. * concatenated together using a comma. If the header does not appear in
  266. * the message, this method MUST return an empty string.
  267. */
  268. public function getHeaderLine($name);
  269. /**
  270. * Return an instance with the provided value replacing the specified header.
  271. *
  272. * While header names are case-insensitive, the casing of the header will
  273. * be preserved by this function, and returned from getHeaders().
  274. *
  275. * This method MUST be implemented in such a way as to retain the
  276. * immutability of the message, and MUST return an instance that has the
  277. * new and/or updated header and value.
  278. *
  279. * @param string $name Case-insensitive header field name.
  280. * @param string|string[] $value Header value(s).
  281. * @return static
  282. * @throws \InvalidArgumentException for invalid header names or values.
  283. */
  284. public function withHeader($name, $value);
  285. /**
  286. * Return an instance with the specified header appended with the given value.
  287. *
  288. * Existing values for the specified header will be maintained. The new
  289. * value(s) will be appended to the existing list. If the header did not
  290. * exist previously, it will be added.
  291. *
  292. * This method MUST be implemented in such a way as to retain the
  293. * immutability of the message, and MUST return an instance that has the
  294. * new header and/or value.
  295. *
  296. * @param string $name Case-insensitive header field name to add.
  297. * @param string|string[] $value Header value(s).
  298. * @return static
  299. * @throws \InvalidArgumentException for invalid header names or values.
  300. */
  301. public function withAddedHeader($name, $value);
  302. /**
  303. * Return an instance without the specified header.
  304. *
  305. * Header resolution MUST be done without case-sensitivity.
  306. *
  307. * This method MUST be implemented in such a way as to retain the
  308. * immutability of the message, and MUST return an instance that removes
  309. * the named header.
  310. *
  311. * @param string $name Case-insensitive header field name to remove.
  312. * @return static
  313. */
  314. public function withoutHeader($name);
  315. /**
  316. * Gets the body of the message.
  317. *
  318. * @return StreamInterface Returns the body as a stream.
  319. */
  320. public function getBody();
  321. /**
  322. * Return an instance with the specified message body.
  323. *
  324. * The body MUST be a StreamInterface object.
  325. *
  326. * This method MUST be implemented in such a way as to retain the
  327. * immutability of the message, and MUST return a new instance that has the
  328. * new body stream.
  329. *
  330. * @param StreamInterface $body Body.
  331. * @return static
  332. * @throws \InvalidArgumentException When the body is not valid.
  333. */
  334. public function withBody(StreamInterface $body);
  335. }
  336. }
  337. // file: vendor/psr/http-message/src/RequestInterface.php
  338. namespace Psr\Http\Message {
  339. /**
  340. * Representation of an outgoing, client-side request.
  341. *
  342. * Per the HTTP specification, this interface includes properties for
  343. * each of the following:
  344. *
  345. * - Protocol version
  346. * - HTTP method
  347. * - URI
  348. * - Headers
  349. * - Message body
  350. *
  351. * During construction, implementations MUST attempt to set the Host header from
  352. * a provided URI if no Host header is provided.
  353. *
  354. * Requests are considered immutable; all methods that might change state MUST
  355. * be implemented such that they retain the internal state of the current
  356. * message and return an instance that contains the changed state.
  357. */
  358. interface RequestInterface extends MessageInterface
  359. {
  360. /**
  361. * Retrieves the message's request target.
  362. *
  363. * Retrieves the message's request-target either as it will appear (for
  364. * clients), as it appeared at request (for servers), or as it was
  365. * specified for the instance (see withRequestTarget()).
  366. *
  367. * In most cases, this will be the origin-form of the composed URI,
  368. * unless a value was provided to the concrete implementation (see
  369. * withRequestTarget() below).
  370. *
  371. * If no URI is available, and no request-target has been specifically
  372. * provided, this method MUST return the string "/".
  373. *
  374. * @return string
  375. */
  376. public function getRequestTarget();
  377. /**
  378. * Return an instance with the specific request-target.
  379. *
  380. * If the request needs a non-origin-form request-target — e.g., for
  381. * specifying an absolute-form, authority-form, or asterisk-form —
  382. * this method may be used to create an instance with the specified
  383. * request-target, verbatim.
  384. *
  385. * This method MUST be implemented in such a way as to retain the
  386. * immutability of the message, and MUST return an instance that has the
  387. * changed request target.
  388. *
  389. * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various
  390. * request-target forms allowed in request messages)
  391. * @param mixed $requestTarget
  392. * @return static
  393. */
  394. public function withRequestTarget($requestTarget);
  395. /**
  396. * Retrieves the HTTP method of the request.
  397. *
  398. * @return string Returns the request method.
  399. */
  400. public function getMethod();
  401. /**
  402. * Return an instance with the provided HTTP method.
  403. *
  404. * While HTTP method names are typically all uppercase characters, HTTP
  405. * method names are case-sensitive and thus implementations SHOULD NOT
  406. * modify the given string.
  407. *
  408. * This method MUST be implemented in such a way as to retain the
  409. * immutability of the message, and MUST return an instance that has the
  410. * changed request method.
  411. *
  412. * @param string $method Case-sensitive method.
  413. * @return static
  414. * @throws \InvalidArgumentException for invalid HTTP methods.
  415. */
  416. public function withMethod($method);
  417. /**
  418. * Retrieves the URI instance.
  419. *
  420. * This method MUST return a UriInterface instance.
  421. *
  422. * @link http://tools.ietf.org/html/rfc3986#section-4.3
  423. * @return UriInterface Returns a UriInterface instance
  424. * representing the URI of the request.
  425. */
  426. public function getUri();
  427. /**
  428. * Returns an instance with the provided URI.
  429. *
  430. * This method MUST update the Host header of the returned request by
  431. * default if the URI contains a host component. If the URI does not
  432. * contain a host component, any pre-existing Host header MUST be carried
  433. * over to the returned request.
  434. *
  435. * You can opt-in to preserving the original state of the Host header by
  436. * setting `$preserveHost` to `true`. When `$preserveHost` is set to
  437. * `true`, this method interacts with the Host header in the following ways:
  438. *
  439. * - If the Host header is missing or empty, and the new URI contains
  440. * a host component, this method MUST update the Host header in the returned
  441. * request.
  442. * - If the Host header is missing or empty, and the new URI does not contain a
  443. * host component, this method MUST NOT update the Host header in the returned
  444. * request.
  445. * - If a Host header is present and non-empty, this method MUST NOT update
  446. * the Host header in the returned request.
  447. *
  448. * This method MUST be implemented in such a way as to retain the
  449. * immutability of the message, and MUST return an instance that has the
  450. * new UriInterface instance.
  451. *
  452. * @link http://tools.ietf.org/html/rfc3986#section-4.3
  453. * @param UriInterface $uri New request URI to use.
  454. * @param bool $preserveHost Preserve the original state of the Host header.
  455. * @return static
  456. */
  457. public function withUri(UriInterface $uri, $preserveHost = false);
  458. }
  459. }
  460. // file: vendor/psr/http-message/src/ResponseInterface.php
  461. namespace Psr\Http\Message {
  462. /**
  463. * Representation of an outgoing, server-side response.
  464. *
  465. * Per the HTTP specification, this interface includes properties for
  466. * each of the following:
  467. *
  468. * - Protocol version
  469. * - Status code and reason phrase
  470. * - Headers
  471. * - Message body
  472. *
  473. * Responses are considered immutable; all methods that might change state MUST
  474. * be implemented such that they retain the internal state of the current
  475. * message and return an instance that contains the changed state.
  476. */
  477. interface ResponseInterface extends MessageInterface
  478. {
  479. /**
  480. * Gets the response status code.
  481. *
  482. * The status code is a 3-digit integer result code of the server's attempt
  483. * to understand and satisfy the request.
  484. *
  485. * @return int Status code.
  486. */
  487. public function getStatusCode();
  488. /**
  489. * Return an instance with the specified status code and, optionally, reason phrase.
  490. *
  491. * If no reason phrase is specified, implementations MAY choose to default
  492. * to the RFC 7231 or IANA recommended reason phrase for the response's
  493. * status code.
  494. *
  495. * This method MUST be implemented in such a way as to retain the
  496. * immutability of the message, and MUST return an instance that has the
  497. * updated status and reason phrase.
  498. *
  499. * @link http://tools.ietf.org/html/rfc7231#section-6
  500. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  501. * @param int $code The 3-digit integer result code to set.
  502. * @param string $reasonPhrase The reason phrase to use with the
  503. * provided status code; if none is provided, implementations MAY
  504. * use the defaults as suggested in the HTTP specification.
  505. * @return static
  506. * @throws \InvalidArgumentException For invalid status code arguments.
  507. */
  508. public function withStatus($code, $reasonPhrase = '');
  509. /**
  510. * Gets the response reason phrase associated with the status code.
  511. *
  512. * Because a reason phrase is not a required element in a response
  513. * status line, the reason phrase value MAY be null. Implementations MAY
  514. * choose to return the default RFC 7231 recommended reason phrase (or those
  515. * listed in the IANA HTTP Status Code Registry) for the response's
  516. * status code.
  517. *
  518. * @link http://tools.ietf.org/html/rfc7231#section-6
  519. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  520. * @return string Reason phrase; must return an empty string if none present.
  521. */
  522. public function getReasonPhrase();
  523. }
  524. }
  525. // file: vendor/psr/http-message/src/ServerRequestInterface.php
  526. namespace Psr\Http\Message {
  527. /**
  528. * Representation of an incoming, server-side HTTP request.
  529. *
  530. * Per the HTTP specification, this interface includes properties for
  531. * each of the following:
  532. *
  533. * - Protocol version
  534. * - HTTP method
  535. * - URI
  536. * - Headers
  537. * - Message body
  538. *
  539. * Additionally, it encapsulates all data as it has arrived to the
  540. * application from the CGI and/or PHP environment, including:
  541. *
  542. * - The values represented in $_SERVER.
  543. * - Any cookies provided (generally via $_COOKIE)
  544. * - Query string arguments (generally via $_GET, or as parsed via parse_str())
  545. * - Upload files, if any (as represented by $_FILES)
  546. * - Deserialized body parameters (generally from $_POST)
  547. *
  548. * $_SERVER values MUST be treated as immutable, as they represent application
  549. * state at the time of request; as such, no methods are provided to allow
  550. * modification of those values. The other values provide such methods, as they
  551. * can be restored from $_SERVER or the request body, and may need treatment
  552. * during the application (e.g., body parameters may be deserialized based on
  553. * content type).
  554. *
  555. * Additionally, this interface recognizes the utility of introspecting a
  556. * request to derive and match additional parameters (e.g., via URI path
  557. * matching, decrypting cookie values, deserializing non-form-encoded body
  558. * content, matching authorization headers to users, etc). These parameters
  559. * are stored in an "attributes" property.
  560. *
  561. * Requests are considered immutable; all methods that might change state MUST
  562. * be implemented such that they retain the internal state of the current
  563. * message and return an instance that contains the changed state.
  564. */
  565. interface ServerRequestInterface extends RequestInterface
  566. {
  567. /**
  568. * Retrieve server parameters.
  569. *
  570. * Retrieves data related to the incoming request environment,
  571. * typically derived from PHP's $_SERVER superglobal. The data IS NOT
  572. * REQUIRED to originate from $_SERVER.
  573. *
  574. * @return array
  575. */
  576. public function getServerParams();
  577. /**
  578. * Retrieve cookies.
  579. *
  580. * Retrieves cookies sent by the client to the server.
  581. *
  582. * The data MUST be compatible with the structure of the $_COOKIE
  583. * superglobal.
  584. *
  585. * @return array
  586. */
  587. public function getCookieParams();
  588. /**
  589. * Return an instance with the specified cookies.
  590. *
  591. * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
  592. * be compatible with the structure of $_COOKIE. Typically, this data will
  593. * be injected at instantiation.
  594. *
  595. * This method MUST NOT update the related Cookie header of the request
  596. * instance, nor related values in the server params.
  597. *
  598. * This method MUST be implemented in such a way as to retain the
  599. * immutability of the message, and MUST return an instance that has the
  600. * updated cookie values.
  601. *
  602. * @param array $cookies Array of key/value pairs representing cookies.
  603. * @return static
  604. */
  605. public function withCookieParams(array $cookies);
  606. /**
  607. * Retrieve query string arguments.
  608. *
  609. * Retrieves the deserialized query string arguments, if any.
  610. *
  611. * Note: the query params might not be in sync with the URI or server
  612. * params. If you need to ensure you are only getting the original
  613. * values, you may need to parse the query string from `getUri()->getQuery()`
  614. * or from the `QUERY_STRING` server param.
  615. *
  616. * @return array
  617. */
  618. public function getQueryParams();
  619. /**
  620. * Return an instance with the specified query string arguments.
  621. *
  622. * These values SHOULD remain immutable over the course of the incoming
  623. * request. They MAY be injected during instantiation, such as from PHP's
  624. * $_GET superglobal, or MAY be derived from some other value such as the
  625. * URI. In cases where the arguments are parsed from the URI, the data
  626. * MUST be compatible with what PHP's parse_str() would return for
  627. * purposes of how duplicate query parameters are handled, and how nested
  628. * sets are handled.
  629. *
  630. * Setting query string arguments MUST NOT change the URI stored by the
  631. * request, nor the values in the server params.
  632. *
  633. * This method MUST be implemented in such a way as to retain the
  634. * immutability of the message, and MUST return an instance that has the
  635. * updated query string arguments.
  636. *
  637. * @param array $query Array of query string arguments, typically from
  638. * $_GET.
  639. * @return static
  640. */
  641. public function withQueryParams(array $query);
  642. /**
  643. * Retrieve normalized file upload data.
  644. *
  645. * This method returns upload metadata in a normalized tree, with each leaf
  646. * an instance of Psr\Http\Message\UploadedFileInterface.
  647. *
  648. * These values MAY be prepared from $_FILES or the message body during
  649. * instantiation, or MAY be injected via withUploadedFiles().
  650. *
  651. * @return array An array tree of UploadedFileInterface instances; an empty
  652. * array MUST be returned if no data is present.
  653. */
  654. public function getUploadedFiles();
  655. /**
  656. * Create a new instance with the specified uploaded files.
  657. *
  658. * This method MUST be implemented in such a way as to retain the
  659. * immutability of the message, and MUST return an instance that has the
  660. * updated body parameters.
  661. *
  662. * @param array $uploadedFiles An array tree of UploadedFileInterface instances.
  663. * @return static
  664. * @throws \InvalidArgumentException if an invalid structure is provided.
  665. */
  666. public function withUploadedFiles(array $uploadedFiles);
  667. /**
  668. * Retrieve any parameters provided in the request body.
  669. *
  670. * If the request Content-Type is either application/x-www-form-urlencoded
  671. * or multipart/form-data, and the request method is POST, this method MUST
  672. * return the contents of $_POST.
  673. *
  674. * Otherwise, this method may return any results of deserializing
  675. * the request body content; as parsing returns structured content, the
  676. * potential types MUST be arrays or objects only. A null value indicates
  677. * the absence of body content.
  678. *
  679. * @return null|array|object The deserialized body parameters, if any.
  680. * These will typically be an array or object.
  681. */
  682. public function getParsedBody();
  683. /**
  684. * Return an instance with the specified body parameters.
  685. *
  686. * These MAY be injected during instantiation.
  687. *
  688. * If the request Content-Type is either application/x-www-form-urlencoded
  689. * or multipart/form-data, and the request method is POST, use this method
  690. * ONLY to inject the contents of $_POST.
  691. *
  692. * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
  693. * deserializing the request body content. Deserialization/parsing returns
  694. * structured data, and, as such, this method ONLY accepts arrays or objects,
  695. * or a null value if nothing was available to parse.
  696. *
  697. * As an example, if content negotiation determines that the request data
  698. * is a JSON payload, this method could be used to create a request
  699. * instance with the deserialized parameters.
  700. *
  701. * This method MUST be implemented in such a way as to retain the
  702. * immutability of the message, and MUST return an instance that has the
  703. * updated body parameters.
  704. *
  705. * @param null|array|object $data The deserialized body data. This will
  706. * typically be in an array or object.
  707. * @return static
  708. * @throws \InvalidArgumentException if an unsupported argument type is
  709. * provided.
  710. */
  711. public function withParsedBody($data);
  712. /**
  713. * Retrieve attributes derived from the request.
  714. *
  715. * The request "attributes" may be used to allow injection of any
  716. * parameters derived from the request: e.g., the results of path
  717. * match operations; the results of decrypting cookies; the results of
  718. * deserializing non-form-encoded message bodies; etc. Attributes
  719. * will be application and request specific, and CAN be mutable.
  720. *
  721. * @return array Attributes derived from the request.
  722. */
  723. public function getAttributes();
  724. /**
  725. * Retrieve a single derived request attribute.
  726. *
  727. * Retrieves a single derived request attribute as described in
  728. * getAttributes(). If the attribute has not been previously set, returns
  729. * the default value as provided.
  730. *
  731. * This method obviates the need for a hasAttribute() method, as it allows
  732. * specifying a default value to return if the attribute is not found.
  733. *
  734. * @see getAttributes()
  735. * @param string $name The attribute name.
  736. * @param mixed $default Default value to return if the attribute does not exist.
  737. * @return mixed
  738. */
  739. public function getAttribute($name, $default = null);
  740. /**
  741. * Return an instance with the specified derived request attribute.
  742. *
  743. * This method allows setting a single derived request attribute as
  744. * described in getAttributes().
  745. *
  746. * This method MUST be implemented in such a way as to retain the
  747. * immutability of the message, and MUST return an instance that has the
  748. * updated attribute.
  749. *
  750. * @see getAttributes()
  751. * @param string $name The attribute name.
  752. * @param mixed $value The value of the attribute.
  753. * @return static
  754. */
  755. public function withAttribute($name, $value);
  756. /**
  757. * Return an instance that removes the specified derived request attribute.
  758. *
  759. * This method allows removing a single derived request attribute as
  760. * described in getAttributes().
  761. *
  762. * This method MUST be implemented in such a way as to retain the
  763. * immutability of the message, and MUST return an instance that removes
  764. * the attribute.
  765. *
  766. * @see getAttributes()
  767. * @param string $name The attribute name.
  768. * @return static
  769. */
  770. public function withoutAttribute($name);
  771. }
  772. }
  773. // file: vendor/psr/http-message/src/StreamInterface.php
  774. namespace Psr\Http\Message {
  775. /**
  776. * Describes a data stream.
  777. *
  778. * Typically, an instance will wrap a PHP stream; this interface provides
  779. * a wrapper around the most common operations, including serialization of
  780. * the entire stream to a string.
  781. */
  782. interface StreamInterface
  783. {
  784. /**
  785. * Reads all data from the stream into a string, from the beginning to end.
  786. *
  787. * This method MUST attempt to seek to the beginning of the stream before
  788. * reading data and read the stream until the end is reached.
  789. *
  790. * Warning: This could attempt to load a large amount of data into memory.
  791. *
  792. * This method MUST NOT raise an exception in order to conform with PHP's
  793. * string casting operations.
  794. *
  795. * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
  796. * @return string
  797. */
  798. public function __toString();
  799. /**
  800. * Closes the stream and any underlying resources.
  801. *
  802. * @return void
  803. */
  804. public function close();
  805. /**
  806. * Separates any underlying resources from the stream.
  807. *
  808. * After the stream has been detached, the stream is in an unusable state.
  809. *
  810. * @return resource|null Underlying PHP stream, if any
  811. */
  812. public function detach();
  813. /**
  814. * Get the size of the stream if known.
  815. *
  816. * @return int|null Returns the size in bytes if known, or null if unknown.
  817. */
  818. public function getSize();
  819. /**
  820. * Returns the current position of the file read/write pointer
  821. *
  822. * @return int Position of the file pointer
  823. * @throws \RuntimeException on error.
  824. */
  825. public function tell();
  826. /**
  827. * Returns true if the stream is at the end of the stream.
  828. *
  829. * @return bool
  830. */
  831. public function eof();
  832. /**
  833. * Returns whether or not the stream is seekable.
  834. *
  835. * @return bool
  836. */
  837. public function isSeekable();
  838. /**
  839. * Seek to a position in the stream.
  840. *
  841. * @link http://www.php.net/manual/en/function.fseek.php
  842. * @param int $offset Stream offset
  843. * @param int $whence Specifies how the cursor position will be calculated
  844. * based on the seek offset. Valid values are identical to the built-in
  845. * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
  846. * offset bytes SEEK_CUR: Set position to current location plus offset
  847. * SEEK_END: Set position to end-of-stream plus offset.
  848. * @throws \RuntimeException on failure.
  849. */
  850. public function seek($offset, $whence = SEEK_SET);
  851. /**
  852. * Seek to the beginning of the stream.
  853. *
  854. * If the stream is not seekable, this method will raise an exception;
  855. * otherwise, it will perform a seek(0).
  856. *
  857. * @see seek()
  858. * @link http://www.php.net/manual/en/function.fseek.php
  859. * @throws \RuntimeException on failure.
  860. */
  861. public function rewind();
  862. /**
  863. * Returns whether or not the stream is writable.
  864. *
  865. * @return bool
  866. */
  867. public function isWritable();
  868. /**
  869. * Write data to the stream.
  870. *
  871. * @param string $string The string that is to be written.
  872. * @return int Returns the number of bytes written to the stream.
  873. * @throws \RuntimeException on failure.
  874. */
  875. public function write($string);
  876. /**
  877. * Returns whether or not the stream is readable.
  878. *
  879. * @return bool
  880. */
  881. public function isReadable();
  882. /**
  883. * Read data from the stream.
  884. *
  885. * @param int $length Read up to $length bytes from the object and return
  886. * them. Fewer than $length bytes may be returned if underlying stream
  887. * call returns fewer bytes.
  888. * @return string Returns the data read from the stream, or an empty string
  889. * if no bytes are available.
  890. * @throws \RuntimeException if an error occurs.
  891. */
  892. public function read($length);
  893. /**
  894. * Returns the remaining contents in a string
  895. *
  896. * @return string
  897. * @throws \RuntimeException if unable to read or an error occurs while
  898. * reading.
  899. */
  900. public function getContents();
  901. /**
  902. * Get stream metadata as an associative array or retrieve a specific key.
  903. *
  904. * The keys returned are identical to the keys returned from PHP's
  905. * stream_get_meta_data() function.
  906. *
  907. * @link http://php.net/manual/en/function.stream-get-meta-data.php
  908. * @param string $key Specific metadata to retrieve.
  909. * @return array|mixed|null Returns an associative array if no key is
  910. * provided. Returns a specific key value if a key is provided and the
  911. * value is found, or null if the key is not found.
  912. */
  913. public function getMetadata($key = null);
  914. }
  915. }
  916. // file: vendor/psr/http-message/src/UploadedFileInterface.php
  917. namespace Psr\Http\Message {
  918. /**
  919. * Value object representing a file uploaded through an HTTP request.
  920. *
  921. * Instances of this interface are considered immutable; all methods that
  922. * might change state MUST be implemented such that they retain the internal
  923. * state of the current instance and return an instance that contains the
  924. * changed state.
  925. */
  926. interface UploadedFileInterface
  927. {
  928. /**
  929. * Retrieve a stream representing the uploaded file.
  930. *
  931. * This method MUST return a StreamInterface instance, representing the
  932. * uploaded file. The purpose of this method is to allow utilizing native PHP
  933. * stream functionality to manipulate the file upload, such as
  934. * stream_copy_to_stream() (though the result will need to be decorated in a
  935. * native PHP stream wrapper to work with such functions).
  936. *
  937. * If the moveTo() method has been called previously, this method MUST raise
  938. * an exception.
  939. *
  940. * @return StreamInterface Stream representation of the uploaded file.
  941. * @throws \RuntimeException in cases when no stream is available or can be
  942. * created.
  943. */
  944. public function getStream();
  945. /**
  946. * Move the uploaded file to a new location.
  947. *
  948. * Use this method as an alternative to move_uploaded_file(). This method is
  949. * guaranteed to work in both SAPI and non-SAPI environments.
  950. * Implementations must determine which environment they are in, and use the
  951. * appropriate method (move_uploaded_file(), rename(), or a stream
  952. * operation) to perform the operation.
  953. *
  954. * $targetPath may be an absolute path, or a relative path. If it is a
  955. * relative path, resolution should be the same as used by PHP's rename()
  956. * function.
  957. *
  958. * The original file or stream MUST be removed on completion.
  959. *
  960. * If this method is called more than once, any subsequent calls MUST raise
  961. * an exception.
  962. *
  963. * When used in an SAPI environment where $_FILES is populated, when writing
  964. * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
  965. * used to ensure permissions and upload status are verified correctly.
  966. *
  967. * If you wish to move to a stream, use getStream(), as SAPI operations
  968. * cannot guarantee writing to stream destinations.
  969. *
  970. * @see http://php.net/is_uploaded_file
  971. * @see http://php.net/move_uploaded_file
  972. * @param string $targetPath Path to which to move the uploaded file.
  973. * @throws \InvalidArgumentException if the $targetPath specified is invalid.
  974. * @throws \RuntimeException on any error during the move operation, or on
  975. * the second or subsequent call to the method.
  976. */
  977. public function moveTo($targetPath);
  978. /**
  979. * Retrieve the file size.
  980. *
  981. * Implementations SHOULD return the value stored in the "size" key of
  982. * the file in the $_FILES array if available, as PHP calculates this based
  983. * on the actual size transmitted.
  984. *
  985. * @return int|null The file size in bytes or null if unknown.
  986. */
  987. public function getSize();
  988. /**
  989. * Retrieve the error associated with the uploaded file.
  990. *
  991. * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
  992. *
  993. * If the file was uploaded successfully, this method MUST return
  994. * UPLOAD_ERR_OK.
  995. *
  996. * Implementations SHOULD return the value stored in the "error" key of
  997. * the file in the $_FILES array.
  998. *
  999. * @see http://php.net/manual/en/features.file-upload.errors.php
  1000. * @return int One of PHP's UPLOAD_ERR_XXX constants.
  1001. */
  1002. public function getError();
  1003. /**
  1004. * Retrieve the filename sent by the client.
  1005. *
  1006. * Do not trust the value returned by this method. A client could send
  1007. * a malicious filename with the intention to corrupt or hack your
  1008. * application.
  1009. *
  1010. * Implementations SHOULD return the value stored in the "name" key of
  1011. * the file in the $_FILES array.
  1012. *
  1013. * @return string|null The filename sent by the client or null if none
  1014. * was provided.
  1015. */
  1016. public function getClientFilename();
  1017. /**
  1018. * Retrieve the media type sent by the client.
  1019. *
  1020. * Do not trust the value returned by this method. A client could send
  1021. * a malicious media type with the intention to corrupt or hack your
  1022. * application.
  1023. *
  1024. * Implementations SHOULD return the value stored in the "type" key of
  1025. * the file in the $_FILES array.
  1026. *
  1027. * @return string|null The media type sent by the client or null if none
  1028. * was provided.
  1029. */
  1030. public function getClientMediaType();
  1031. }
  1032. }
  1033. // file: vendor/psr/http-message/src/UriInterface.php
  1034. namespace Psr\Http\Message {
  1035. /**
  1036. * Value object representing a URI.
  1037. *
  1038. * This interface is meant to represent URIs according to RFC 3986 and to
  1039. * provide methods for most common operations. Additional functionality for
  1040. * working with URIs can be provided on top of the interface or externally.
  1041. * Its primary use is for HTTP requests, but may also be used in other
  1042. * contexts.
  1043. *
  1044. * Instances of this interface are considered immutable; all methods that
  1045. * might change state MUST be implemented such that they retain the internal
  1046. * state of the current instance and return an instance that contains the
  1047. * changed state.
  1048. *
  1049. * Typically the Host header will be also be present in the request message.
  1050. * For server-side requests, the scheme will typically be discoverable in the
  1051. * server parameters.
  1052. *
  1053. * @link http://tools.ietf.org/html/rfc3986 (the URI specification)
  1054. */
  1055. interface UriInterface
  1056. {
  1057. /**
  1058. * Retrieve the scheme component of the URI.
  1059. *
  1060. * If no scheme is present, this method MUST return an empty string.
  1061. *
  1062. * The value returned MUST be normalized to lowercase, per RFC 3986
  1063. * Section 3.1.
  1064. *
  1065. * The trailing ":" character is not part of the scheme and MUST NOT be
  1066. * added.
  1067. *
  1068. * @see https://tools.ietf.org/html/rfc3986#section-3.1
  1069. * @return string The URI scheme.
  1070. */
  1071. public function getScheme();
  1072. /**
  1073. * Retrieve the authority component of the URI.
  1074. *
  1075. * If no authority information is present, this method MUST return an empty
  1076. * string.
  1077. *
  1078. * The authority syntax of the URI is:
  1079. *
  1080. * <pre>
  1081. * [user-info@]host[:port]
  1082. * </pre>
  1083. *
  1084. * If the port component is not set or is the standard port for the current
  1085. * scheme, it SHOULD NOT be included.
  1086. *
  1087. * @see https://tools.ietf.org/html/rfc3986#section-3.2
  1088. * @return string The URI authority, in "[user-info@]host[:port]" format.
  1089. */
  1090. public function getAuthority();
  1091. /**
  1092. * Retrieve the user information component of the URI.
  1093. *
  1094. * If no user information is present, this method MUST return an empty
  1095. * string.
  1096. *
  1097. * If a user is present in the URI, this will return that value;
  1098. * additionally, if the password is also present, it will be appended to the
  1099. * user value, with a colon (":") separating the values.
  1100. *
  1101. * The trailing "@" character is not part of the user information and MUST
  1102. * NOT be added.
  1103. *
  1104. * @return string The URI user information, in "username[:password]" format.
  1105. */
  1106. public function getUserInfo();
  1107. /**
  1108. * Retrieve the host component of the URI.
  1109. *
  1110. * If no host is present, this method MUST return an empty string.
  1111. *
  1112. * The value returned MUST be normalized to lowercase, per RFC 3986
  1113. * Section 3.2.2.
  1114. *
  1115. * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
  1116. * @return string The URI host.
  1117. */
  1118. public function getHost();
  1119. /**
  1120. * Retrieve the port component of the URI.
  1121. *
  1122. * If a port is present, and it is non-standard for the current scheme,
  1123. * this method MUST return it as an integer. If the port is the standard port
  1124. * used with the current scheme, this method SHOULD return null.
  1125. *
  1126. * If no port is present, and no scheme is present, this method MUST return
  1127. * a null value.
  1128. *
  1129. * If no port is present, but a scheme is present, this method MAY return
  1130. * the standard port for that scheme, but SHOULD return null.
  1131. *
  1132. * @return null|int The URI port.
  1133. */
  1134. public function getPort();
  1135. /**
  1136. * Retrieve the path component of the URI.
  1137. *
  1138. * The path can either be empty or absolute (starting with a slash) or
  1139. * rootless (not starting with a slash). Implementations MUST support all
  1140. * three syntaxes.
  1141. *
  1142. * Normally, the empty path "" and absolute path "/" are considered equal as
  1143. * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
  1144. * do this normalization because in contexts with a trimmed base path, e.g.
  1145. * the front controller, this difference becomes significant. It's the task
  1146. * of the user to handle both "" and "/".
  1147. *
  1148. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1149. * any characters. To determine what characters to encode, please refer to
  1150. * RFC 3986, Sections 2 and 3.3.
  1151. *
  1152. * As an example, if the value should include a slash ("/") not intended as
  1153. * delimiter between path segments, that value MUST be passed in encoded
  1154. * form (e.g., "%2F") to the instance.
  1155. *
  1156. * @see https://tools.ietf.org/html/rfc3986#section-2
  1157. * @see https://tools.ietf.org/html/rfc3986#section-3.3
  1158. * @return string The URI path.
  1159. */
  1160. public function getPath();
  1161. /**
  1162. * Retrieve the query string of the URI.
  1163. *
  1164. * If no query string is present, this method MUST return an empty string.
  1165. *
  1166. * The leading "?" character is not part of the query and MUST NOT be
  1167. * added.
  1168. *
  1169. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1170. * any characters. To determine what characters to encode, please refer to
  1171. * RFC 3986, Sections 2 and 3.4.
  1172. *
  1173. * As an example, if a value in a key/value pair of the query string should
  1174. * include an ampersand ("&") not intended as a delimiter between values,
  1175. * that value MUST be passed in encoded form (e.g., "%26") to the instance.
  1176. *
  1177. * @see https://tools.ietf.org/html/rfc3986#section-2
  1178. * @see https://tools.ietf.org/html/rfc3986#section-3.4
  1179. * @return string The URI query string.
  1180. */
  1181. public function getQuery();
  1182. /**
  1183. * Retrieve the fragment component of the URI.
  1184. *
  1185. * If no fragment is present, this method MUST return an empty string.
  1186. *
  1187. * The leading "#" character is not part of the fragment and MUST NOT be
  1188. * added.
  1189. *
  1190. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1191. * any characters. To determine what characters to encode, please refer to
  1192. * RFC 3986, Sections 2 and 3.5.
  1193. *
  1194. * @see https://tools.ietf.org/html/rfc3986#section-2
  1195. * @see https://tools.ietf.org/html/rfc3986#section-3.5
  1196. * @return string The URI fragment.
  1197. */
  1198. public function getFragment();
  1199. /**
  1200. * Return an instance with the specified scheme.
  1201. *
  1202. * This method MUST retain the state of the current instance, and return
  1203. * an instance that contains the specified scheme.
  1204. *
  1205. * Implementations MUST support the schemes "http" and "https" case
  1206. * insensitively, and MAY accommodate other schemes if required.
  1207. *
  1208. * An empty scheme is equivalent to removing the scheme.
  1209. *
  1210. * @param string $scheme The scheme to use with the new instance.
  1211. * @return static A new instance with the specified scheme.
  1212. * @throws \InvalidArgumentException for invalid or unsupported schemes.
  1213. */
  1214. public function withScheme($scheme);
  1215. /**
  1216. * Return an instance with the specified user information.
  1217. *
  1218. * This method MUST retain the state of the current instance, and return
  1219. * an instance that contains the specified user information.
  1220. *
  1221. * Password is optional, but the user information MUST include the
  1222. * user; an empty string for the user is equivalent to removing user
  1223. * information.
  1224. *
  1225. * @param string $user The user name to use for authority.
  1226. * @param null|string $password The password associated with $user.
  1227. * @return static A new instance with the specified user information.
  1228. */
  1229. public function withUserInfo($user, $password = null);
  1230. /**
  1231. * Return an instance with the specified host.
  1232. *
  1233. * This method MUST retain the state of the current instance, and return
  1234. * an instance that contains the specified host.
  1235. *
  1236. * An empty host value is equivalent to removing the host.
  1237. *
  1238. * @param string $host The hostname to use with the new instance.
  1239. * @return static A new instance with the specified host.
  1240. * @throws \InvalidArgumentException for invalid hostnames.
  1241. */
  1242. public function withHost($host);
  1243. /**
  1244. * Return an instance with the specified port.
  1245. *
  1246. * This method MUST retain the state of the current instance, and return
  1247. * an instance that contains the specified port.
  1248. *
  1249. * Implementations MUST raise an exception for ports outside the
  1250. * established TCP and UDP port ranges.
  1251. *
  1252. * A null value provided for the port is equivalent to removing the port
  1253. * information.
  1254. *
  1255. * @param null|int $port The port to use with the new instance; a null value
  1256. * removes the port information.
  1257. * @return static A new instance with the specified port.
  1258. * @throws \InvalidArgumentException for invalid ports.
  1259. */
  1260. public function withPort($port);
  1261. /**
  1262. * Return an instance with the specified path.
  1263. *
  1264. * This method MUST retain the state of the current instance, and return
  1265. * an instance that contains the specified path.
  1266. *
  1267. * The path can either be empty or absolute (starting with a slash) or
  1268. * rootless (not starting with a slash). Implementations MUST support all
  1269. * three syntaxes.
  1270. *
  1271. * If the path is intended to be domain-relative rather than path relative then
  1272. * it must begin with a slash ("/"). Paths not starting with a slash ("/")
  1273. * are assumed to be relative to some base path known to the application or
  1274. * consumer.
  1275. *
  1276. * Users can provide both encoded and decoded path characters.
  1277. * Implementations ensure the correct encoding as outlined in getPath().
  1278. *
  1279. * @param string $path The path to use with the new instance.
  1280. * @return static A new instance with the specified path.
  1281. * @throws \InvalidArgumentException for invalid paths.
  1282. */
  1283. public function withPath($path);
  1284. /**
  1285. * Return an instance with the specified query string.
  1286. *
  1287. * This method MUST retain the state of the current instance, and return
  1288. * an instance that contains the specified query string.
  1289. *
  1290. * Users can provide both encoded and decoded query characters.
  1291. * Implementations ensure the correct encoding as outlined in getQuery().
  1292. *
  1293. * An empty query string value is equivalent to removing the query string.
  1294. *
  1295. * @param string $query The query string to use with the new instance.
  1296. * @return static A new instance with the specified query string.
  1297. * @throws \InvalidArgumentException for invalid query strings.
  1298. */
  1299. public function withQuery($query);
  1300. /**
  1301. * Return an instance with the specified URI fragment.
  1302. *
  1303. * This method MUST retain the state of the current instance, and return
  1304. * an instance that contains the specified URI fragment.
  1305. *
  1306. * Users can provide both encoded and decoded fragment characters.
  1307. * Implementations ensure the correct encoding as outlined in getFragment().
  1308. *
  1309. * An empty fragment value is equivalent to removing the fragment.
  1310. *
  1311. * @param string $fragment The fragment to use with the new instance.
  1312. * @return static A new instance with the specified fragment.
  1313. */
  1314. public function withFragment($fragment);
  1315. /**
  1316. * Return the string representation as a URI reference.
  1317. *
  1318. * Depending on which components of the URI are present, the resulting
  1319. * string is either a full URI or relative reference according to RFC 3986,
  1320. * Section 4.1. The method concatenates the various components of the URI,
  1321. * using the appropriate delimiters:
  1322. *
  1323. * - If a scheme is present, it MUST be suffixed by ":".
  1324. * - If an authority is present, it MUST be prefixed by "//".
  1325. * - The path can be concatenated without delimiters. But there are two
  1326. * cases where the path has to be adjusted to make the URI reference
  1327. * valid as PHP does not allow to throw an exception in __toString():
  1328. * - If the path is rootless and an authority is present, the path MUST
  1329. * be prefixed by "/".
  1330. * - If the path is starting with more than one "/" and no authority is
  1331. * present, the starting slashes MUST be reduced to one.
  1332. * - If a query is present, it MUST be prefixed by "?".
  1333. * - If a fragment is present, it MUST be prefixed by "#".
  1334. *
  1335. * @see http://tools.ietf.org/html/rfc3986#section-4.1
  1336. * @return string
  1337. */
  1338. public function __toString();
  1339. }
  1340. }
  1341. // file: vendor/psr/http-server-handler/src/RequestHandlerInterface.php
  1342. namespace Psr\Http\Server {
  1343. use Psr\Http\Message\ResponseInterface;
  1344. use Psr\Http\Message\ServerRequestInterface;
  1345. /**
  1346. * Handles a server request and produces a response.
  1347. *
  1348. * An HTTP request handler process an HTTP request in order to produce an
  1349. * HTTP response.
  1350. */
  1351. interface RequestHandlerInterface
  1352. {
  1353. /**
  1354. * Handles a request and produces a response.
  1355. *
  1356. * May call other collaborating code to generate the response.
  1357. */
  1358. public function handle(ServerRequestInterface $request): ResponseInterface;
  1359. }
  1360. }
  1361. // file: vendor/psr/http-server-middleware/src/MiddlewareInterface.php
  1362. namespace Psr\Http\Server {
  1363. use Psr\Http\Message\ResponseInterface;
  1364. use Psr\Http\Message\ServerRequestInterface;
  1365. /**
  1366. * Participant in processing a server request and response.
  1367. *
  1368. * An HTTP middleware component participates in processing an HTTP message:
  1369. * by acting on the request, generating the response, or forwarding the
  1370. * request to a subsequent middleware and possibly acting on its response.
  1371. */
  1372. interface MiddlewareInterface
  1373. {
  1374. /**
  1375. * Process an incoming server request.
  1376. *
  1377. * Processes an incoming server request in order to produce a response.
  1378. * If unable to produce the response itself, it may delegate to the provided
  1379. * request handler to do so.
  1380. */
  1381. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
  1382. }
  1383. }
  1384. // file: vendor/nyholm/psr7/src/Factory/Psr17Factory.php
  1385. namespace Nyholm\Psr7\Factory {
  1386. use Nyholm\Psr7\{Request, Response, ServerRequest, Stream, UploadedFile, Uri};
  1387. use Psr\Http\Message\{RequestFactoryInterface, RequestInterface, ResponseFactoryInterface, ResponseInterface, ServerRequestFactoryInterface, ServerRequestInterface, StreamFactoryInterface, StreamInterface, UploadedFileFactoryInterface, UploadedFileInterface, UriFactoryInterface, UriInterface};
  1388. /**
  1389. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1390. * @author Martijn van der Ven <martijn@vanderven.se>
  1391. */
  1392. final class Psr17Factory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
  1393. {
  1394. public function createRequest(string $method, $uri): RequestInterface
  1395. {
  1396. return new Request($method, $uri);
  1397. }
  1398. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface
  1399. {
  1400. if (2 > \func_num_args()) {
  1401. // This will make the Response class to use a custom reasonPhrase
  1402. $reasonPhrase = null;
  1403. }
  1404. return new Response($code, [], null, '1.1', $reasonPhrase);
  1405. }
  1406. public function createStream(string $content = ''): StreamInterface
  1407. {
  1408. return Stream::create($content);
  1409. }
  1410. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
  1411. {
  1412. $resource = @\fopen($filename, $mode);
  1413. if (false === $resource) {
  1414. if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'])) {
  1415. throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.');
  1416. }
  1417. throw new \RuntimeException('The file ' . $filename . ' cannot be opened.');
  1418. }
  1419. return Stream::create($resource);
  1420. }
  1421. public function createStreamFromResource($resource): StreamInterface
  1422. {
  1423. return Stream::create($resource);
  1424. }
  1425. public function createUploadedFile(StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null): UploadedFileInterface
  1426. {
  1427. if (null === $size) {
  1428. $size = $stream->getSize();
  1429. }
  1430. return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);
  1431. }
  1432. public function createUri(string $uri = ''): UriInterface
  1433. {
  1434. return new Uri($uri);
  1435. }
  1436. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  1437. {
  1438. return new ServerRequest($method, $uri, [], null, '1.1', $serverParams);
  1439. }
  1440. }
  1441. }
  1442. // file: vendor/nyholm/psr7/src/MessageTrait.php
  1443. namespace Nyholm\Psr7 {
  1444. use Psr\Http\Message\StreamInterface;
  1445. /**
  1446. * Trait implementing functionality common to requests and responses.
  1447. *
  1448. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1449. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1450. * @author Martijn van der Ven <martijn@vanderven.se>
  1451. *
  1452. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1453. */
  1454. trait MessageTrait
  1455. {
  1456. /** @var array Map of all registered headers, as original name => array of values */
  1457. private $headers = [];
  1458. /** @var array Map of lowercase header name => original name at registration */
  1459. private $headerNames = [];
  1460. /** @var string */
  1461. private $protocol = '1.1';
  1462. /** @var StreamInterface|null */
  1463. private $stream;
  1464. public function getProtocolVersion(): string
  1465. {
  1466. return $this->protocol;
  1467. }
  1468. public function withProtocolVersion($version): self
  1469. {
  1470. if ($this->protocol === $version) {
  1471. return $this;
  1472. }
  1473. $new = clone $this;
  1474. $new->protocol = $version;
  1475. return $new;
  1476. }
  1477. public function getHeaders(): array
  1478. {
  1479. return $this->headers;
  1480. }
  1481. public function hasHeader($header): bool
  1482. {
  1483. return isset($this->headerNames[\strtolower($header)]);
  1484. }
  1485. public function getHeader($header): array
  1486. {
  1487. $header = \strtolower($header);
  1488. if (!isset($this->headerNames[$header])) {
  1489. return [];
  1490. }
  1491. $header = $this->headerNames[$header];
  1492. return $this->headers[$header];
  1493. }
  1494. public function getHeaderLine($header): string
  1495. {
  1496. return \implode(', ', $this->getHeader($header));
  1497. }
  1498. public function withHeader($header, $value): self
  1499. {
  1500. $value = $this->validateAndTrimHeader($header, $value);
  1501. $normalized = \strtolower($header);
  1502. $new = clone $this;
  1503. if (isset($new->headerNames[$normalized])) {
  1504. unset($new->headers[$new->headerNames[$normalized]]);
  1505. }
  1506. $new->headerNames[$normalized] = $header;
  1507. $new->headers[$header] = $value;
  1508. return $new;
  1509. }
  1510. public function withAddedHeader($header, $value): self
  1511. {
  1512. if (!\is_string($header) || '' === $header) {
  1513. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1514. }
  1515. $new = clone $this;
  1516. $new->setHeaders([$header => $value]);
  1517. return $new;
  1518. }
  1519. public function withoutHeader($header): self
  1520. {
  1521. $normalized = \strtolower($header);
  1522. if (!isset($this->headerNames[$normalized])) {
  1523. return $this;
  1524. }
  1525. $header = $this->headerNames[$normalized];
  1526. $new = clone $this;
  1527. unset($new->headers[$header], $new->headerNames[$normalized]);
  1528. return $new;
  1529. }
  1530. public function getBody(): StreamInterface
  1531. {
  1532. if (null === $this->stream) {
  1533. $this->stream = Stream::create('');
  1534. }
  1535. return $this->stream;
  1536. }
  1537. public function withBody(StreamInterface $body): self
  1538. {
  1539. if ($body === $this->stream) {
  1540. return $this;
  1541. }
  1542. $new = clone $this;
  1543. $new->stream = $body;
  1544. return $new;
  1545. }
  1546. private function setHeaders(array $headers) /*:void*/
  1547. {
  1548. foreach ($headers as $header => $value) {
  1549. $value = $this->validateAndTrimHeader($header, $value);
  1550. $normalized = \strtolower($header);
  1551. if (isset($this->headerNames[$normalized])) {
  1552. $header = $this->headerNames[$normalized];
  1553. $this->headers[$header] = \array_merge($this->headers[$header], $value);
  1554. } else {
  1555. $this->headerNames[$normalized] = $header;
  1556. $this->headers[$header] = $value;
  1557. }
  1558. }
  1559. }
  1560. /**
  1561. * Make sure the header complies with RFC 7230.
  1562. *
  1563. * Header names must be a non-empty string consisting of token characters.
  1564. *
  1565. * Header values must be strings consisting of visible characters with all optional
  1566. * leading and trailing whitespace stripped. This method will always strip such
  1567. * optional whitespace. Note that the method does not allow folding whitespace within
  1568. * the values as this was deprecated for almost all instances by the RFC.
  1569. *
  1570. * header-field = field-name ":" OWS field-value OWS
  1571. * field-name = 1*( "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^"
  1572. * / "_" / "`" / "|" / "~" / %x30-39 / ( %x41-5A / %x61-7A ) )
  1573. * OWS = *( SP / HTAB )
  1574. * field-value = *( ( %x21-7E / %x80-FF ) [ 1*( SP / HTAB ) ( %x21-7E / %x80-FF ) ] )
  1575. *
  1576. * @see https://tools.ietf.org/html/rfc7230#section-3.2.4
  1577. */
  1578. private function validateAndTrimHeader($header, $values): array
  1579. {
  1580. if (!\is_string($header) || 1 !== \preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@", $header)) {
  1581. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1582. }
  1583. if (!\is_array($values)) {
  1584. // This is simple, just one value.
  1585. if ((!\is_numeric($values) && !\is_string($values)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $values)) {
  1586. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1587. }
  1588. return [\trim((string) $values, " \t")];
  1589. }
  1590. if (empty($values)) {
  1591. throw new \InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
  1592. }
  1593. // Assert Non empty array
  1594. $returnValues = [];
  1595. foreach ($values as $v) {
  1596. if ((!\is_numeric($v) && !\is_string($v)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $v)) {
  1597. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1598. }
  1599. $returnValues[] = \trim((string) $v, " \t");
  1600. }
  1601. return $returnValues;
  1602. }
  1603. }
  1604. }
  1605. // file: vendor/nyholm/psr7/src/Request.php
  1606. namespace Nyholm\Psr7 {
  1607. use Psr\Http\Message\{RequestInterface, StreamInterface, UriInterface};
  1608. /**
  1609. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1610. * @author Martijn van der Ven <martijn@vanderven.se>
  1611. */
  1612. final class Request implements RequestInterface
  1613. {
  1614. use MessageTrait;
  1615. use RequestTrait;
  1616. /**
  1617. * @param string $method HTTP method
  1618. * @param string|UriInterface $uri URI
  1619. * @param array $headers Request headers
  1620. * @param string|resource|StreamInterface|null $body Request body
  1621. * @param string $version Protocol version
  1622. */
  1623. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
  1624. {
  1625. if (!($uri instanceof UriInterface)) {
  1626. $uri = new Uri($uri);
  1627. }
  1628. $this->method = $method;
  1629. $this->uri = $uri;
  1630. $this->setHeaders($headers);
  1631. $this->protocol = $version;
  1632. if (!$this->hasHeader('Host')) {
  1633. $this->updateHostFromUri();
  1634. }
  1635. // If we got no body, defer initialization of the stream until Request::getBody()
  1636. if ('' !== $body && null !== $body) {
  1637. $this->stream = Stream::create($body);
  1638. }
  1639. }
  1640. }
  1641. }
  1642. // file: vendor/nyholm/psr7/src/RequestTrait.php
  1643. namespace Nyholm\Psr7 {
  1644. use Psr\Http\Message\UriInterface;
  1645. /**
  1646. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1647. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1648. * @author Martijn van der Ven <martijn@vanderven.se>
  1649. *
  1650. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1651. */
  1652. trait RequestTrait
  1653. {
  1654. /** @var string */
  1655. private $method;
  1656. /** @var string|null */
  1657. private $requestTarget;
  1658. /** @var UriInterface|null */
  1659. private $uri;
  1660. public function getRequestTarget(): string
  1661. {
  1662. if (null !== $this->requestTarget) {
  1663. return $this->requestTarget;
  1664. }
  1665. if ('' === $target = $this->uri->getPath()) {
  1666. $target = '/';
  1667. }
  1668. if ('' !== $this->uri->getQuery()) {
  1669. $target .= '?' . $this->uri->getQuery();
  1670. }
  1671. return $target;
  1672. }
  1673. public function withRequestTarget($requestTarget): self
  1674. {
  1675. if (\preg_match('#\s#', $requestTarget)) {
  1676. throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
  1677. }
  1678. $new = clone $this;
  1679. $new->requestTarget = $requestTarget;
  1680. return $new;
  1681. }
  1682. public function getMethod(): string
  1683. {
  1684. return $this->method;
  1685. }
  1686. public function withMethod($method): self
  1687. {
  1688. if (!\is_string($method)) {
  1689. throw new \InvalidArgumentException('Method must be a string');
  1690. }
  1691. $new = clone $this;
  1692. $new->method = $method;
  1693. return $new;
  1694. }
  1695. public function getUri(): UriInterface
  1696. {
  1697. return $this->uri;
  1698. }
  1699. public function withUri(UriInterface $uri, $preserveHost = false): self
  1700. {
  1701. if ($uri === $this->uri) {
  1702. return $this;
  1703. }
  1704. $new = clone $this;
  1705. $new->uri = $uri;
  1706. if (!$preserveHost || !$this->hasHeader('Host')) {
  1707. $new->updateHostFromUri();
  1708. }
  1709. return $new;
  1710. }
  1711. private function updateHostFromUri() /*:void*/
  1712. {
  1713. if ('' === $host = $this->uri->getHost()) {
  1714. return;
  1715. }
  1716. if (null !== ($port = $this->uri->getPort())) {
  1717. $host .= ':' . $port;
  1718. }
  1719. if (isset($this->headerNames['host'])) {
  1720. $header = $this->headerNames['host'];
  1721. } else {
  1722. $this->headerNames['host'] = $header = 'Host';
  1723. }
  1724. // Ensure Host is the first header.
  1725. // See: http://tools.ietf.org/html/rfc7230#section-5.4
  1726. $this->headers = [$header => [$host]] + $this->headers;
  1727. }
  1728. }
  1729. }
  1730. // file: vendor/nyholm/psr7/src/Response.php
  1731. namespace Nyholm\Psr7 {
  1732. use Psr\Http\Message\{ResponseInterface, StreamInterface};
  1733. /**
  1734. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1735. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1736. * @author Martijn van der Ven <martijn@vanderven.se>
  1737. */
  1738. final class Response implements ResponseInterface
  1739. {
  1740. use MessageTrait;
  1741. /** @var array Map of standard HTTP status code/reason phrases */
  1742. /*private*/ const PHRASES = [
  1743. 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing',
  1744. 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',
  1745. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect',
  1746. 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',
  1747. 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',
  1748. ];
  1749. /** @var string */
  1750. private $reasonPhrase = '';
  1751. /** @var int */
  1752. private $statusCode;
  1753. /**
  1754. * @param int $status Status code
  1755. * @param array $headers Response headers
  1756. * @param string|resource|StreamInterface|null $body Response body
  1757. * @param string $version Protocol version
  1758. * @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
  1759. */
  1760. public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
  1761. {
  1762. // If we got no body, defer initialization of the stream until Response::getBody()
  1763. if ('' !== $body && null !== $body) {
  1764. $this->stream = Stream::create($body);
  1765. }
  1766. $this->statusCode = $status;
  1767. $this->setHeaders($headers);
  1768. if (null === $reason && isset(self::PHRASES[$this->statusCode])) {
  1769. $this->reasonPhrase = self::PHRASES[$status];
  1770. } else {
  1771. $this->reasonPhrase = $reason ?? '';
  1772. }
  1773. $this->protocol = $version;
  1774. }
  1775. public function getStatusCode(): int
  1776. {
  1777. return $this->statusCode;
  1778. }
  1779. public function getReasonPhrase(): string
  1780. {
  1781. return $this->reasonPhrase;
  1782. }
  1783. public function withStatus($code, $reasonPhrase = ''): self
  1784. {
  1785. if (!\is_int($code) && !\is_string($code)) {
  1786. throw new \InvalidArgumentException('Status code has to be an integer');
  1787. }
  1788. $code = (int) $code;
  1789. if ($code < 100 || $code > 599) {
  1790. throw new \InvalidArgumentException('Status code has to be an integer between 100 and 599');
  1791. }
  1792. $new = clone $this;
  1793. $new->statusCode = $code;
  1794. if ((null === $reasonPhrase || '' === $reasonPhrase) && isset(self::PHRASES[$new->statusCode])) {
  1795. $reasonPhrase = self::PHRASES[$new->statusCode];
  1796. }
  1797. $new->reasonPhrase = $reasonPhrase;
  1798. return $new;
  1799. }
  1800. }
  1801. }
  1802. // file: vendor/nyholm/psr7/src/ServerRequest.php
  1803. namespace Nyholm\Psr7 {
  1804. use Psr\Http\Message\{ServerRequestInterface, StreamInterface, UploadedFileInterface, UriInterface};
  1805. /**
  1806. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1807. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1808. * @author Martijn van der Ven <martijn@vanderven.se>
  1809. */
  1810. final class ServerRequest implements ServerRequestInterface
  1811. {
  1812. use MessageTrait;
  1813. use RequestTrait;
  1814. /** @var array */
  1815. private $attributes = [];
  1816. /** @var array */
  1817. private $cookieParams = [];
  1818. /** @var array|object|null */
  1819. private $parsedBody;
  1820. /** @var array */
  1821. private $queryParams = [];
  1822. /** @var array */
  1823. private $serverParams;
  1824. /** @var UploadedFileInterface[] */
  1825. private $uploadedFiles = [];
  1826. /**
  1827. * @param string $method HTTP method
  1828. * @param string|UriInterface $uri URI
  1829. * @param array $headers Request headers
  1830. * @param string|resource|StreamInterface|null $body Request body
  1831. * @param string $version Protocol version
  1832. * @param array $serverParams Typically the $_SERVER superglobal
  1833. */
  1834. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
  1835. {
  1836. $this->serverParams = $serverParams;
  1837. if (!($uri instanceof UriInterface)) {
  1838. $uri = new Uri($uri);
  1839. }
  1840. $this->method = $method;
  1841. $this->uri = $uri;
  1842. $this->setHeaders($headers);
  1843. $this->protocol = $version;
  1844. if (!$this->hasHeader('Host')) {
  1845. $this->updateHostFromUri();
  1846. }
  1847. // If we got no body, defer initialization of the stream until ServerRequest::getBody()
  1848. if ('' !== $body && null !== $body) {
  1849. $this->stream = Stream::create($body);
  1850. }
  1851. }
  1852. public function getServerParams(): array
  1853. {
  1854. return $this->serverParams;
  1855. }
  1856. public function getUploadedFiles(): array
  1857. {
  1858. return $this->uploadedFiles;
  1859. }
  1860. public function withUploadedFiles(array $uploadedFiles)
  1861. {
  1862. $new = clone $this;
  1863. $new->uploadedFiles = $uploadedFiles;
  1864. return $new;
  1865. }
  1866. public function getCookieParams(): array
  1867. {
  1868. return $this->cookieParams;
  1869. }
  1870. public function withCookieParams(array $cookies)
  1871. {
  1872. $new = clone $this;
  1873. $new->cookieParams = $cookies;
  1874. return $new;
  1875. }
  1876. public function getQueryParams(): array
  1877. {
  1878. return $this->queryParams;
  1879. }
  1880. public function withQueryParams(array $query)
  1881. {
  1882. $new = clone $this;
  1883. $new->queryParams = $query;
  1884. return $new;
  1885. }
  1886. public function getParsedBody()
  1887. {
  1888. return $this->parsedBody;
  1889. }
  1890. public function withParsedBody($data)
  1891. {
  1892. if (!\is_array($data) && !\is_object($data) && null !== $data) {
  1893. throw new \InvalidArgumentException('First parameter to withParsedBody MUST be object, array or null');
  1894. }
  1895. $new = clone $this;
  1896. $new->parsedBody = $data;
  1897. return $new;
  1898. }
  1899. public function getAttributes(): array
  1900. {
  1901. return $this->attributes;
  1902. }
  1903. public function getAttribute($attribute, $default = null)
  1904. {
  1905. if (false === \array_key_exists($attribute, $this->attributes)) {
  1906. return $default;
  1907. }
  1908. return $this->attributes[$attribute];
  1909. }
  1910. public function withAttribute($attribute, $value): self
  1911. {
  1912. $new = clone $this;
  1913. $new->attributes[$attribute] = $value;
  1914. return $new;
  1915. }
  1916. public function withoutAttribute($attribute): self
  1917. {
  1918. if (false === \array_key_exists($attribute, $this->attributes)) {
  1919. return $this;
  1920. }
  1921. $new = clone $this;
  1922. unset($new->attributes[$attribute]);
  1923. return $new;
  1924. }
  1925. }
  1926. }
  1927. // file: vendor/nyholm/psr7/src/Stream.php
  1928. namespace Nyholm\Psr7 {
  1929. use Psr\Http\Message\StreamInterface;
  1930. /**
  1931. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1932. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1933. * @author Martijn van der Ven <martijn@vanderven.se>
  1934. */
  1935. final class Stream implements StreamInterface
  1936. {
  1937. /** @var resource|null A resource reference */
  1938. private $stream;
  1939. /** @var bool */
  1940. private $seekable;
  1941. /** @var bool */
  1942. private $readable;
  1943. /** @var bool */
  1944. private $writable;
  1945. /** @var array|mixed|void|null */
  1946. private $uri;
  1947. /** @var int|null */
  1948. private $size;
  1949. /** @var array Hash of readable and writable stream types */
  1950. /*private*/ const READ_WRITE_HASH = [
  1951. 'read' => [
  1952. 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
  1953. 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
  1954. 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
  1955. 'x+t' => true, 'c+t' => true, 'a+' => true,
  1956. ],
  1957. 'write' => [
  1958. 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
  1959. 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
  1960. 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
  1961. 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
  1962. ],
  1963. ];
  1964. private function __construct()
  1965. {
  1966. }
  1967. /**
  1968. * Creates a new PSR-7 stream.
  1969. *
  1970. * @param string|resource|StreamInterface $body
  1971. *
  1972. * @return StreamInterface
  1973. *
  1974. * @throws \InvalidArgumentException
  1975. */
  1976. public static function create($body = ''): StreamInterface
  1977. {
  1978. if ($body instanceof StreamInterface) {
  1979. return $body;
  1980. }
  1981. if (\is_string($body)) {
  1982. $resource = \fopen('php://temp', 'rw+');
  1983. \fwrite($resource, $body);
  1984. $body = $resource;
  1985. }
  1986. if (\is_resource($body)) {
  1987. $new = new self();
  1988. $new->stream = $body;
  1989. $meta = \stream_get_meta_data($new->stream);
  1990. $new->seekable = $meta['seekable'] && 0 === \fseek($new->stream, 0, \SEEK_CUR);
  1991. $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]);
  1992. $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]);
  1993. $new->uri = $new->getMetadata('uri');
  1994. return $new;
  1995. }
  1996. throw new \InvalidArgumentException('First argument to Stream::create() must be a string, resource or StreamInterface.');
  1997. }
  1998. /**
  1999. * Closes the stream when the destructed.
  2000. */
  2001. public function __destruct()
  2002. {
  2003. $this->close();
  2004. }
  2005. public function __toString(): string
  2006. {
  2007. try {
  2008. if ($this->isSeekable()) {
  2009. $this->seek(0);
  2010. }
  2011. return $this->getContents();
  2012. } catch (\Exception $e) {
  2013. return '';
  2014. }
  2015. }
  2016. public function close() /*:void*/
  2017. {
  2018. if (isset($this->stream)) {
  2019. if (\is_resource($this->stream)) {
  2020. \fclose($this->stream);
  2021. }
  2022. $this->detach();
  2023. }
  2024. }
  2025. public function detach()
  2026. {
  2027. if (!isset($this->stream)) {
  2028. return null;
  2029. }
  2030. $result = $this->stream;
  2031. unset($this->stream);
  2032. $this->size = $this->uri = null;
  2033. $this->readable = $this->writable = $this->seekable = false;
  2034. return $result;
  2035. }
  2036. public function getSize() /*:?int*/
  2037. {
  2038. if (null !== $this->size) {
  2039. return $this->size;
  2040. }
  2041. if (!isset($this->stream)) {
  2042. return null;
  2043. }
  2044. // Clear the stat cache if the stream has a URI
  2045. if ($this->uri) {
  2046. \clearstatcache(true, $this->uri);
  2047. }
  2048. $stats = \fstat($this->stream);
  2049. if (isset($stats['size'])) {
  2050. $this->size = $stats['size'];
  2051. return $this->size;
  2052. }
  2053. return null;
  2054. }
  2055. public function tell(): int
  2056. {
  2057. if (false === $result = \ftell($this->stream)) {
  2058. throw new \RuntimeException('Unable to determine stream position');
  2059. }
  2060. return $result;
  2061. }
  2062. public function eof(): bool
  2063. {
  2064. return !$this->stream || \feof($this->stream);
  2065. }
  2066. public function isSeekable(): bool
  2067. {
  2068. return $this->seekable;
  2069. }
  2070. public function seek($offset, $whence = \SEEK_SET) /*:void*/
  2071. {
  2072. if (!$this->seekable) {
  2073. throw new \RuntimeException('Stream is not seekable');
  2074. }
  2075. if (-1 === \fseek($this->stream, $offset, $whence)) {
  2076. throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, true));
  2077. }
  2078. }
  2079. public function rewind() /*:void*/
  2080. {
  2081. $this->seek(0);
  2082. }
  2083. public function isWritable(): bool
  2084. {
  2085. return $this->writable;
  2086. }
  2087. public function write($string): int
  2088. {
  2089. if (!$this->writable) {
  2090. throw new \RuntimeException('Cannot write to a non-writable stream');
  2091. }
  2092. // We can't know the size after writing anything
  2093. $this->size = null;
  2094. if (false === $result = \fwrite($this->stream, $string)) {
  2095. throw new \RuntimeException('Unable to write to stream');
  2096. }
  2097. return $result;
  2098. }
  2099. public function isReadable(): bool
  2100. {
  2101. return $this->readable;
  2102. }
  2103. public function read($length): string
  2104. {
  2105. if (!$this->readable) {
  2106. throw new \RuntimeException('Cannot read from non-readable stream');
  2107. }
  2108. return \fread($this->stream, $length);
  2109. }
  2110. public function getContents(): string
  2111. {
  2112. if (!isset($this->stream)) {
  2113. throw new \RuntimeException('Unable to read stream contents');
  2114. }
  2115. if (false === $contents = \stream_get_contents($this->stream)) {
  2116. throw new \RuntimeException('Unable to read stream contents');
  2117. }
  2118. return $contents;
  2119. }
  2120. public function getMetadata($key = null)
  2121. {
  2122. if (!isset($this->stream)) {
  2123. return $key ? null : [];
  2124. }
  2125. $meta = \stream_get_meta_data($this->stream);
  2126. if (null === $key) {
  2127. return $meta;
  2128. }
  2129. return $meta[$key] ?? null;
  2130. }
  2131. }
  2132. }
  2133. // file: vendor/nyholm/psr7/src/UploadedFile.php
  2134. namespace Nyholm\Psr7 {
  2135. use Psr\Http\Message\{StreamInterface, UploadedFileInterface};
  2136. /**
  2137. * @author Michael Dowling and contributors to guzzlehttp/psr7
  2138. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2139. * @author Martijn van der Ven <martijn@vanderven.se>
  2140. */
  2141. final class UploadedFile implements UploadedFileInterface
  2142. {
  2143. /** @var array */
  2144. /*private*/ const ERRORS = [
  2145. \UPLOAD_ERR_OK => 1,
  2146. \UPLOAD_ERR_INI_SIZE => 1,
  2147. \UPLOAD_ERR_FORM_SIZE => 1,
  2148. \UPLOAD_ERR_PARTIAL => 1,
  2149. \UPLOAD_ERR_NO_FILE => 1,
  2150. \UPLOAD_ERR_NO_TMP_DIR => 1,
  2151. \UPLOAD_ERR_CANT_WRITE => 1,
  2152. \UPLOAD_ERR_EXTENSION => 1,
  2153. ];
  2154. /** @var string */
  2155. private $clientFilename;
  2156. /** @var string */
  2157. private $clientMediaType;
  2158. /** @var int */
  2159. private $error;
  2160. /** @var string|null */
  2161. private $file;
  2162. /** @var bool */
  2163. private $moved = false;
  2164. /** @var int */
  2165. private $size;
  2166. /** @var StreamInterface|null */
  2167. private $stream;
  2168. /**
  2169. * @param StreamInterface|string|resource $streamOrFile
  2170. * @param int $size
  2171. * @param int $errorStatus
  2172. * @param string|null $clientFilename
  2173. * @param string|null $clientMediaType
  2174. */
  2175. public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
  2176. {
  2177. if (false === \is_int($errorStatus) || !isset(self::ERRORS[$errorStatus])) {
  2178. throw new \InvalidArgumentException('Upload file error status must be an integer value and one of the "UPLOAD_ERR_*" constants.');
  2179. }
  2180. if (false === \is_int($size)) {
  2181. throw new \InvalidArgumentException('Upload file size must be an integer');
  2182. }
  2183. if (null !== $clientFilename && !\is_string($clientFilename)) {
  2184. throw new \InvalidArgumentException('Upload file client filename must be a string or null');
  2185. }
  2186. if (null !== $clientMediaType && !\is_string($clientMediaType)) {
  2187. throw new \InvalidArgumentException('Upload file client media type must be a string or null');
  2188. }
  2189. $this->error = $errorStatus;
  2190. $this->size = $size;
  2191. $this->clientFilename = $clientFilename;
  2192. $this->clientMediaType = $clientMediaType;
  2193. if (\UPLOAD_ERR_OK === $this->error) {
  2194. // Depending on the value set file or stream variable.
  2195. if (\is_string($streamOrFile)) {
  2196. $this->file = $streamOrFile;
  2197. } elseif (\is_resource($streamOrFile)) {
  2198. $this->stream = Stream::create($streamOrFile);
  2199. } elseif ($streamOrFile instanceof StreamInterface) {
  2200. $this->stream = $streamOrFile;
  2201. } else {
  2202. throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile');
  2203. }
  2204. }
  2205. }
  2206. /**
  2207. * @throws \RuntimeException if is moved or not ok
  2208. */
  2209. private function validateActive() /*:void*/
  2210. {
  2211. if (\UPLOAD_ERR_OK !== $this->error) {
  2212. throw new \RuntimeException('Cannot retrieve stream due to upload error');
  2213. }
  2214. if ($this->moved) {
  2215. throw new \RuntimeException('Cannot retrieve stream after it has already been moved');
  2216. }
  2217. }
  2218. public function getStream(): StreamInterface
  2219. {
  2220. $this->validateActive();
  2221. if ($this->stream instanceof StreamInterface) {
  2222. return $this->stream;
  2223. }
  2224. $resource = \fopen($this->file, 'r');
  2225. return Stream::create($resource);
  2226. }
  2227. public function moveTo($targetPath) /*:void*/
  2228. {
  2229. $this->validateActive();
  2230. if (!\is_string($targetPath) || '' === $targetPath) {
  2231. throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
  2232. }
  2233. if (null !== $this->file) {
  2234. $this->moved = 'cli' === \PHP_SAPI ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath);
  2235. } else {
  2236. $stream = $this->getStream();
  2237. if ($stream->isSeekable()) {
  2238. $stream->rewind();
  2239. }
  2240. // Copy the contents of a stream into another stream until end-of-file.
  2241. $dest = Stream::create(\fopen($targetPath, 'w'));
  2242. while (!$stream->eof()) {
  2243. if (!$dest->write($stream->read(1048576))) {
  2244. break;
  2245. }
  2246. }
  2247. $this->moved = true;
  2248. }
  2249. if (false === $this->moved) {
  2250. throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath));
  2251. }
  2252. }
  2253. public function getSize(): int
  2254. {
  2255. return $this->size;
  2256. }
  2257. public function getError(): int
  2258. {
  2259. return $this->error;
  2260. }
  2261. public function getClientFilename() /*:?string*/
  2262. {
  2263. return $this->clientFilename;
  2264. }
  2265. public function getClientMediaType() /*:?string*/
  2266. {
  2267. return $this->clientMediaType;
  2268. }
  2269. }
  2270. }
  2271. // file: vendor/nyholm/psr7/src/Uri.php
  2272. namespace Nyholm\Psr7 {
  2273. use Psr\Http\Message\UriInterface;
  2274. /**
  2275. * PSR-7 URI implementation.
  2276. *
  2277. * @author Michael Dowling
  2278. * @author Tobias Schultze
  2279. * @author Matthew Weier O'Phinney
  2280. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2281. * @author Martijn van der Ven <martijn@vanderven.se>
  2282. */
  2283. final class Uri implements UriInterface
  2284. {
  2285. /*private*/ const SCHEMES = ['http' => 80, 'https' => 443];
  2286. /*private*/ const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  2287. /*private*/ const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  2288. /** @var string Uri scheme. */
  2289. private $scheme = '';
  2290. /** @var string Uri user info. */
  2291. private $userInfo = '';
  2292. /** @var string Uri host. */
  2293. private $host = '';
  2294. /** @var int|null Uri port. */
  2295. private $port;
  2296. /** @var string Uri path. */
  2297. private $path = '';
  2298. /** @var string Uri query string. */
  2299. private $query = '';
  2300. /** @var string Uri fragment. */
  2301. private $fragment = '';
  2302. public function __construct(string $uri = '')
  2303. {
  2304. if ('' !== $uri) {
  2305. if (false === $parts = \parse_url($uri)) {
  2306. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  2307. }
  2308. // Apply parse_url parts to a URI.
  2309. $this->scheme = isset($parts['scheme']) ? \strtolower($parts['scheme']) : '';
  2310. $this->userInfo = $parts['user'] ?? '';
  2311. $this->host = isset($parts['host']) ? \strtolower($parts['host']) : '';
  2312. $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
  2313. $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
  2314. $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : '';
  2315. $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : '';
  2316. if (isset($parts['pass'])) {
  2317. $this->userInfo .= ':' . $parts['pass'];
  2318. }
  2319. }
  2320. }
  2321. public function __toString(): string
  2322. {
  2323. return self::createUriString($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment);
  2324. }
  2325. public function getScheme(): string
  2326. {
  2327. return $this->scheme;
  2328. }
  2329. public function getAuthority(): string
  2330. {
  2331. if ('' === $this->host) {
  2332. return '';
  2333. }
  2334. $authority = $this->host;
  2335. if ('' !== $this->userInfo) {
  2336. $authority = $this->userInfo . '@' . $authority;
  2337. }
  2338. if (null !== $this->port) {
  2339. $authority .= ':' . $this->port;
  2340. }
  2341. return $authority;
  2342. }
  2343. public function getUserInfo(): string
  2344. {
  2345. return $this->userInfo;
  2346. }
  2347. public function getHost(): string
  2348. {
  2349. return $this->host;
  2350. }
  2351. public function getPort() /*:?int*/
  2352. {
  2353. return $this->port;
  2354. }
  2355. public function getPath(): string
  2356. {
  2357. return $this->path;
  2358. }
  2359. public function getQuery(): string
  2360. {
  2361. return $this->query;
  2362. }
  2363. public function getFragment(): string
  2364. {
  2365. return $this->fragment;
  2366. }
  2367. public function withScheme($scheme): self
  2368. {
  2369. if (!\is_string($scheme)) {
  2370. throw new \InvalidArgumentException('Scheme must be a string');
  2371. }
  2372. if ($this->scheme === $scheme = \strtolower($scheme)) {
  2373. return $this;
  2374. }
  2375. $new = clone $this;
  2376. $new->scheme = $scheme;
  2377. $new->port = $new->filterPort($new->port);
  2378. return $new;
  2379. }
  2380. public function withUserInfo($user, $password = null): self
  2381. {
  2382. $info = $user;
  2383. if (null !== $password && '' !== $password) {
  2384. $info .= ':' . $password;
  2385. }
  2386. if ($this->userInfo === $info) {
  2387. return $this;
  2388. }
  2389. $new = clone $this;
  2390. $new->userInfo = $info;
  2391. return $new;
  2392. }
  2393. public function withHost($host): self
  2394. {
  2395. if (!\is_string($host)) {
  2396. throw new \InvalidArgumentException('Host must be a string');
  2397. }
  2398. if ($this->host === $host = \strtolower($host)) {
  2399. return $this;
  2400. }
  2401. $new = clone $this;
  2402. $new->host = $host;
  2403. return $new;
  2404. }
  2405. public function withPort($port): self
  2406. {
  2407. if ($this->port === $port = $this->filterPort($port)) {
  2408. return $this;
  2409. }
  2410. $new = clone $this;
  2411. $new->port = $port;
  2412. return $new;
  2413. }
  2414. public function withPath($path): self
  2415. {
  2416. if ($this->path === $path = $this->filterPath($path)) {
  2417. return $this;
  2418. }
  2419. $new = clone $this;
  2420. $new->path = $path;
  2421. return $new;
  2422. }
  2423. public function withQuery($query): self
  2424. {
  2425. if ($this->query === $query = $this->filterQueryAndFragment($query)) {
  2426. return $this;
  2427. }
  2428. $new = clone $this;
  2429. $new->query = $query;
  2430. return $new;
  2431. }
  2432. public function withFragment($fragment): self
  2433. {
  2434. if ($this->fragment === $fragment = $this->filterQueryAndFragment($fragment)) {
  2435. return $this;
  2436. }
  2437. $new = clone $this;
  2438. $new->fragment = $fragment;
  2439. return $new;
  2440. }
  2441. /**
  2442. * Create a URI string from its various parts.
  2443. */
  2444. private static function createUriString(string $scheme, string $authority, string $path, string $query, string $fragment): string
  2445. {
  2446. $uri = '';
  2447. if ('' !== $scheme) {
  2448. $uri .= $scheme . ':';
  2449. }
  2450. if ('' !== $authority) {
  2451. $uri .= '//' . $authority;
  2452. }
  2453. if ('' !== $path) {
  2454. if ('/' !== $path[0]) {
  2455. if ('' !== $authority) {
  2456. // If the path is rootless and an authority is present, the path MUST be prefixed by "/"
  2457. $path = '/' . $path;
  2458. }
  2459. } elseif (isset($path[1]) && '/' === $path[1]) {
  2460. if ('' === $authority) {
  2461. // If the path is starting with more than one "/" and no authority is present, the
  2462. // starting slashes MUST be reduced to one.
  2463. $path = '/' . \ltrim($path, '/');
  2464. }
  2465. }
  2466. $uri .= $path;
  2467. }
  2468. if ('' !== $query) {
  2469. $uri .= '?' . $query;
  2470. }
  2471. if ('' !== $fragment) {
  2472. $uri .= '#' . $fragment;
  2473. }
  2474. return $uri;
  2475. }
  2476. /**
  2477. * Is a given port non-standard for the current scheme?
  2478. */
  2479. private static function isNonStandardPort(string $scheme, int $port): bool
  2480. {
  2481. return !isset(self::SCHEMES[$scheme]) || $port !== self::SCHEMES[$scheme];
  2482. }
  2483. private function filterPort($port) /*:?int*/
  2484. {
  2485. if (null === $port) {
  2486. return null;
  2487. }
  2488. $port = (int) $port;
  2489. if (0 > $port || 0xffff < $port) {
  2490. throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 0 and 65535', $port));
  2491. }
  2492. return self::isNonStandardPort($this->scheme, $port) ? $port : null;
  2493. }
  2494. private function filterPath($path): string
  2495. {
  2496. if (!\is_string($path)) {
  2497. throw new \InvalidArgumentException('Path must be a string');
  2498. }
  2499. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $path);
  2500. }
  2501. private function filterQueryAndFragment($str): string
  2502. {
  2503. if (!\is_string($str)) {
  2504. throw new \InvalidArgumentException('Query and fragment must be a string');
  2505. }
  2506. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $str);
  2507. }
  2508. private static function rawurlencodeMatchZero(array $match): string
  2509. {
  2510. return \rawurlencode($match[0]);
  2511. }
  2512. }
  2513. }
  2514. // file: vendor/nyholm/psr7-server/src/ServerRequestCreator.php
  2515. namespace Nyholm\Psr7Server {
  2516. use Psr\Http\Message\ServerRequestFactoryInterface;
  2517. use Psr\Http\Message\ServerRequestInterface;
  2518. use Psr\Http\Message\StreamFactoryInterface;
  2519. use Psr\Http\Message\StreamInterface;
  2520. use Psr\Http\Message\UploadedFileFactoryInterface;
  2521. use Psr\Http\Message\UploadedFileInterface;
  2522. use Psr\Http\Message\UriFactoryInterface;
  2523. use Psr\Http\Message\UriInterface;
  2524. /**
  2525. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2526. * @author Martijn van der Ven <martijn@vanderven.se>
  2527. */
  2528. final class ServerRequestCreator implements ServerRequestCreatorInterface
  2529. {
  2530. private $serverRequestFactory;
  2531. private $uriFactory;
  2532. private $uploadedFileFactory;
  2533. private $streamFactory;
  2534. public function __construct(
  2535. ServerRequestFactoryInterface $serverRequestFactory,
  2536. UriFactoryInterface $uriFactory,
  2537. UploadedFileFactoryInterface $uploadedFileFactory,
  2538. StreamFactoryInterface $streamFactory
  2539. ) {
  2540. $this->serverRequestFactory = $serverRequestFactory;
  2541. $this->uriFactory = $uriFactory;
  2542. $this->uploadedFileFactory = $uploadedFileFactory;
  2543. $this->streamFactory = $streamFactory;
  2544. }
  2545. /**
  2546. * {@inheritdoc}
  2547. */
  2548. public function fromGlobals(): ServerRequestInterface
  2549. {
  2550. $server = $_SERVER;
  2551. if (false === isset($server['REQUEST_METHOD'])) {
  2552. $server['REQUEST_METHOD'] = 'GET';
  2553. }
  2554. $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
  2555. return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $_POST, $_FILES, \fopen('php://input', 'r') ?: null);
  2556. }
  2557. /**
  2558. * {@inheritdoc}
  2559. */
  2560. public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
  2561. {
  2562. $method = $this->getMethodFromEnv($server);
  2563. $uri = $this->getUriFromEnvWithHTTP($server);
  2564. $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
  2565. $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
  2566. foreach ($headers as $name => $value) {
  2567. $serverRequest = $serverRequest->withAddedHeader($name, $value);
  2568. }
  2569. $serverRequest = $serverRequest
  2570. ->withProtocolVersion($protocol)
  2571. ->withCookieParams($cookie)
  2572. ->withQueryParams($get)
  2573. ->withParsedBody($post)
  2574. ->withUploadedFiles($this->normalizeFiles($files));
  2575. if (null === $body) {
  2576. return $serverRequest;
  2577. }
  2578. if (\is_resource($body)) {
  2579. $body = $this->streamFactory->createStreamFromResource($body);
  2580. } elseif (\is_string($body)) {
  2581. $body = $this->streamFactory->createStream($body);
  2582. } elseif (!$body instanceof StreamInterface) {
  2583. throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
  2584. }
  2585. return $serverRequest->withBody($body);
  2586. }
  2587. /**
  2588. * Implementation from Zend\Diactoros\marshalHeadersFromSapi().
  2589. */
  2590. public static function getHeadersFromServer(array $server): array
  2591. {
  2592. $headers = [];
  2593. foreach ($server as $key => $value) {
  2594. // Apache prefixes environment variables with REDIRECT_
  2595. // if they are added by rewrite rules
  2596. if (0 === \strpos($key, 'REDIRECT_')) {
  2597. $key = \substr($key, 9);
  2598. // We will not overwrite existing variables with the
  2599. // prefixed versions, though
  2600. if (\array_key_exists($key, $server)) {
  2601. continue;
  2602. }
  2603. }
  2604. if ($value && 0 === \strpos($key, 'HTTP_')) {
  2605. $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
  2606. $headers[$name] = $value;
  2607. continue;
  2608. }
  2609. if ($value && 0 === \strpos($key, 'CONTENT_')) {
  2610. $name = 'content-'.\strtolower(\substr($key, 8));
  2611. $headers[$name] = $value;
  2612. continue;
  2613. }
  2614. }
  2615. return $headers;
  2616. }
  2617. private function getMethodFromEnv(array $environment): string
  2618. {
  2619. if (false === isset($environment['REQUEST_METHOD'])) {
  2620. throw new \InvalidArgumentException('Cannot determine HTTP method');
  2621. }
  2622. return $environment['REQUEST_METHOD'];
  2623. }
  2624. private function getUriFromEnvWithHTTP(array $environment): UriInterface
  2625. {
  2626. $uri = $this->createUriFromArray($environment);
  2627. if (empty($uri->getScheme())) {
  2628. $uri = $uri->withScheme('http');
  2629. }
  2630. return $uri;
  2631. }
  2632. /**
  2633. * Return an UploadedFile instance array.
  2634. *
  2635. * @param array $files A array which respect $_FILES structure
  2636. *
  2637. * @return UploadedFileInterface[]
  2638. *
  2639. * @throws \InvalidArgumentException for unrecognized values
  2640. */
  2641. private function normalizeFiles(array $files): array
  2642. {
  2643. $normalized = [];
  2644. foreach ($files as $key => $value) {
  2645. if ($value instanceof UploadedFileInterface) {
  2646. $normalized[$key] = $value;
  2647. } elseif (\is_array($value) && isset($value['tmp_name'])) {
  2648. $normalized[$key] = $this->createUploadedFileFromSpec($value);
  2649. } elseif (\is_array($value)) {
  2650. $normalized[$key] = $this->normalizeFiles($value);
  2651. } else {
  2652. throw new \InvalidArgumentException('Invalid value in files specification');
  2653. }
  2654. }
  2655. return $normalized;
  2656. }
  2657. /**
  2658. * Create and return an UploadedFile instance from a $_FILES specification.
  2659. *
  2660. * If the specification represents an array of values, this method will
  2661. * delegate to normalizeNestedFileSpec() and return that return value.
  2662. *
  2663. * @param array $value $_FILES struct
  2664. *
  2665. * @return array|UploadedFileInterface
  2666. */
  2667. private function createUploadedFileFromSpec(array $value)
  2668. {
  2669. if (\is_array($value['tmp_name'])) {
  2670. return $this->normalizeNestedFileSpec($value);
  2671. }
  2672. try {
  2673. $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
  2674. } catch (\RuntimeException $e) {
  2675. $stream = $this->streamFactory->createStream();
  2676. }
  2677. return $this->uploadedFileFactory->createUploadedFile(
  2678. $stream,
  2679. (int) $value['size'],
  2680. (int) $value['error'],
  2681. $value['name'],
  2682. $value['type']
  2683. );
  2684. }
  2685. /**
  2686. * Normalize an array of file specifications.
  2687. *
  2688. * Loops through all nested files and returns a normalized array of
  2689. * UploadedFileInterface instances.
  2690. *
  2691. * @param array $files
  2692. *
  2693. * @return UploadedFileInterface[]
  2694. */
  2695. private function normalizeNestedFileSpec(array $files = []): array
  2696. {
  2697. $normalizedFiles = [];
  2698. foreach (\array_keys($files['tmp_name']) as $key) {
  2699. $spec = [
  2700. 'tmp_name' => $files['tmp_name'][$key],
  2701. 'size' => $files['size'][$key],
  2702. 'error' => $files['error'][$key],
  2703. 'name' => $files['name'][$key],
  2704. 'type' => $files['type'][$key],
  2705. ];
  2706. $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
  2707. }
  2708. return $normalizedFiles;
  2709. }
  2710. /**
  2711. * Create a new uri from server variable.
  2712. *
  2713. * @param array $server typically $_SERVER or similar structure
  2714. */
  2715. private function createUriFromArray(array $server): UriInterface
  2716. {
  2717. $uri = $this->uriFactory->createUri('');
  2718. if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
  2719. $uri = $uri->withScheme($server['HTTP_X_FORWARDED_PROTO']);
  2720. } else {
  2721. if (isset($server['REQUEST_SCHEME'])) {
  2722. $uri = $uri->withScheme($server['REQUEST_SCHEME']);
  2723. } elseif (isset($server['HTTPS'])) {
  2724. $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
  2725. }
  2726. if (isset($server['SERVER_PORT'])) {
  2727. $uri = $uri->withPort($server['SERVER_PORT']);
  2728. }
  2729. }
  2730. if (isset($server['HTTP_HOST'])) {
  2731. if (1 === \preg_match('/^(.+)\:(\d+)$/', $server['HTTP_HOST'], $matches)) {
  2732. $uri = $uri->withHost($matches[1])->withPort($matches[2]);
  2733. } else {
  2734. $uri = $uri->withHost($server['HTTP_HOST']);
  2735. }
  2736. } elseif (isset($server['SERVER_NAME'])) {
  2737. $uri = $uri->withHost($server['SERVER_NAME']);
  2738. }
  2739. if (isset($server['REQUEST_URI'])) {
  2740. $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
  2741. }
  2742. if (isset($server['QUERY_STRING'])) {
  2743. $uri = $uri->withQuery($server['QUERY_STRING']);
  2744. }
  2745. return $uri;
  2746. }
  2747. }
  2748. }
  2749. // file: vendor/nyholm/psr7-server/src/ServerRequestCreatorInterface.php
  2750. namespace Nyholm\Psr7Server {
  2751. use Psr\Http\Message\ServerRequestInterface;
  2752. use Psr\Http\Message\StreamInterface;
  2753. /**
  2754. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2755. * @author Martijn van der Ven <martijn@vanderven.se>
  2756. */
  2757. interface ServerRequestCreatorInterface
  2758. {
  2759. /**
  2760. * Create a new server request from the current environment variables.
  2761. * Defaults to a GET request to minimise the risk of an \InvalidArgumentException.
  2762. * Includes the current request headers as supplied by the server through `getallheaders()`.
  2763. * If `getallheaders()` is unavailable on the current server it will fallback to its own `getHeadersFromServer()` method.
  2764. * Defaults to php://input for the request body.
  2765. *
  2766. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2767. */
  2768. public function fromGlobals(): ServerRequestInterface;
  2769. /**
  2770. * Create a new server request from a set of arrays.
  2771. *
  2772. * @param array $server typically $_SERVER or similar structure
  2773. * @param array $headers typically the output of getallheaders() or similar structure
  2774. * @param array $cookie typically $_COOKIE or similar structure
  2775. * @param array $get typically $_GET or similar structure
  2776. * @param array $post typically $_POST or similar structure
  2777. * @param array $files typically $_FILES or similar structure
  2778. * @param StreamInterface|resource|string|null $body Typically stdIn
  2779. *
  2780. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2781. */
  2782. public function fromArrays(
  2783. array $server,
  2784. array $headers = [],
  2785. array $cookie = [],
  2786. array $get = [],
  2787. array $post = [],
  2788. array $files = [],
  2789. $body = null
  2790. ): ServerRequestInterface;
  2791. /**
  2792. * Get parsed headers from ($_SERVER) array.
  2793. *
  2794. * @param array $server typically $_SERVER or similar structure
  2795. *
  2796. * @return array
  2797. */
  2798. public static function getHeadersFromServer(array $server): array;
  2799. }
  2800. }
  2801. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  2802. namespace Tqdev\PhpCrudApi\Cache {
  2803. interface Cache
  2804. {
  2805. public function set(string $key, string $value, int $ttl = 0): bool;
  2806. public function get(string $key): string;
  2807. public function clear(): bool;
  2808. }
  2809. }
  2810. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  2811. namespace Tqdev\PhpCrudApi\Cache {
  2812. class CacheFactory
  2813. {
  2814. public static function create(string $type, string $prefix, string $config): Cache
  2815. {
  2816. switch ($type) {
  2817. case 'TempFile':
  2818. $cache = new TempFileCache($prefix, $config);
  2819. break;
  2820. case 'Redis':
  2821. $cache = new RedisCache($prefix, $config);
  2822. break;
  2823. case 'Memcache':
  2824. $cache = new MemcacheCache($prefix, $config);
  2825. break;
  2826. case 'Memcached':
  2827. $cache = new MemcachedCache($prefix, $config);
  2828. break;
  2829. default:
  2830. $cache = new NoCache();
  2831. }
  2832. return $cache;
  2833. }
  2834. }
  2835. }
  2836. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  2837. namespace Tqdev\PhpCrudApi\Cache {
  2838. class MemcacheCache implements Cache
  2839. {
  2840. protected $prefix;
  2841. protected $memcache;
  2842. public function __construct(string $prefix, string $config)
  2843. {
  2844. $this->prefix = $prefix;
  2845. if ($config == '') {
  2846. $address = 'localhost';
  2847. $port = 11211;
  2848. } elseif (strpos($config, ':') === false) {
  2849. $address = $config;
  2850. $port = 11211;
  2851. } else {
  2852. list($address, $port) = explode(':', $config);
  2853. }
  2854. $this->memcache = $this->create();
  2855. $this->memcache->addServer($address, $port);
  2856. }
  2857. protected function create() /*: \Memcache*/
  2858. {
  2859. return new \Memcache();
  2860. }
  2861. public function set(string $key, string $value, int $ttl = 0): bool
  2862. {
  2863. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  2864. }
  2865. public function get(string $key): string
  2866. {
  2867. return $this->memcache->get($this->prefix . $key) ?: '';
  2868. }
  2869. public function clear(): bool
  2870. {
  2871. return $this->memcache->flush();
  2872. }
  2873. }
  2874. }
  2875. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  2876. namespace Tqdev\PhpCrudApi\Cache {
  2877. class MemcachedCache extends MemcacheCache
  2878. {
  2879. protected function create() /*: \Memcached*/
  2880. {
  2881. return new \Memcached();
  2882. }
  2883. public function set(string $key, string $value, int $ttl = 0): bool
  2884. {
  2885. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  2886. }
  2887. }
  2888. }
  2889. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  2890. namespace Tqdev\PhpCrudApi\Cache {
  2891. class NoCache implements Cache
  2892. {
  2893. public function __construct()
  2894. {
  2895. }
  2896. public function set(string $key, string $value, int $ttl = 0): bool
  2897. {
  2898. return true;
  2899. }
  2900. public function get(string $key): string
  2901. {
  2902. return '';
  2903. }
  2904. public function clear(): bool
  2905. {
  2906. return true;
  2907. }
  2908. }
  2909. }
  2910. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  2911. namespace Tqdev\PhpCrudApi\Cache {
  2912. class RedisCache implements Cache
  2913. {
  2914. protected $prefix;
  2915. protected $redis;
  2916. public function __construct(string $prefix, string $config)
  2917. {
  2918. $this->prefix = $prefix;
  2919. if ($config == '') {
  2920. $config = '127.0.0.1';
  2921. }
  2922. $params = explode(':', $config, 6);
  2923. if (isset($params[3])) {
  2924. $params[3] = null;
  2925. }
  2926. $this->redis = new \Redis();
  2927. call_user_func_array(array($this->redis, 'pconnect'), $params);
  2928. }
  2929. public function set(string $key, string $value, int $ttl = 0): bool
  2930. {
  2931. return $this->redis->set($this->prefix . $key, $value, $ttl);
  2932. }
  2933. public function get(string $key): string
  2934. {
  2935. return $this->redis->get($this->prefix . $key) ?: '';
  2936. }
  2937. public function clear(): bool
  2938. {
  2939. return $this->redis->flushDb();
  2940. }
  2941. }
  2942. }
  2943. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  2944. namespace Tqdev\PhpCrudApi\Cache {
  2945. class TempFileCache implements Cache
  2946. {
  2947. const SUFFIX = 'cache';
  2948. private $path;
  2949. private $segments;
  2950. public function __construct(string $prefix, string $config)
  2951. {
  2952. $this->segments = [];
  2953. $s = DIRECTORY_SEPARATOR;
  2954. $ps = PATH_SEPARATOR;
  2955. if ($config == '') {
  2956. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  2957. } elseif (strpos($config, $ps) === false) {
  2958. $this->path = $config;
  2959. } else {
  2960. list($path, $segments) = explode($ps, $config);
  2961. $this->path = $path;
  2962. $this->segments = explode(',', $segments);
  2963. }
  2964. if (file_exists($this->path) && is_dir($this->path)) {
  2965. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  2966. }
  2967. }
  2968. private function getFileName(string $key): string
  2969. {
  2970. $s = DIRECTORY_SEPARATOR;
  2971. $md5 = md5($key);
  2972. $filename = rtrim($this->path, $s) . $s;
  2973. $i = 0;
  2974. foreach ($this->segments as $segment) {
  2975. $filename .= substr($md5, $i, $segment) . $s;
  2976. $i += $segment;
  2977. }
  2978. $filename .= substr($md5, $i);
  2979. return $filename;
  2980. }
  2981. public function set(string $key, string $value, int $ttl = 0): bool
  2982. {
  2983. $filename = $this->getFileName($key);
  2984. $dirname = dirname($filename);
  2985. if (!file_exists($dirname)) {
  2986. if (!mkdir($dirname, 0755, true)) {
  2987. return false;
  2988. }
  2989. }
  2990. $string = $ttl . '|' . $value;
  2991. return $this->filePutContents($filename, $string) !== false;
  2992. }
  2993. private function filePutContents($filename, $string)
  2994. {
  2995. return file_put_contents($filename, $string, LOCK_EX);
  2996. }
  2997. private function fileGetContents($filename)
  2998. {
  2999. $file = fopen($filename, 'rb');
  3000. if ($file === false) {
  3001. return false;
  3002. }
  3003. $lock = flock($file, LOCK_SH);
  3004. if (!$lock) {
  3005. fclose($file);
  3006. return false;
  3007. }
  3008. $string = '';
  3009. while (!feof($file)) {
  3010. $string .= fread($file, 8192);
  3011. }
  3012. flock($file, LOCK_UN);
  3013. fclose($file);
  3014. return $string;
  3015. }
  3016. private function getString($filename): string
  3017. {
  3018. $data = $this->fileGetContents($filename);
  3019. if ($data === false) {
  3020. return '';
  3021. }
  3022. list($ttl, $string) = explode('|', $data, 2);
  3023. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  3024. return '';
  3025. }
  3026. return $string;
  3027. }
  3028. public function get(string $key): string
  3029. {
  3030. $filename = $this->getFileName($key);
  3031. if (!file_exists($filename)) {
  3032. return '';
  3033. }
  3034. $string = $this->getString($filename);
  3035. if ($string == null) {
  3036. return '';
  3037. }
  3038. return $string;
  3039. }
  3040. private function clean(string $path, array $segments, int $len, bool $all) /*: void*/
  3041. {
  3042. $entries = scandir($path);
  3043. foreach ($entries as $entry) {
  3044. if ($entry === '.' || $entry === '..') {
  3045. continue;
  3046. }
  3047. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  3048. if (count($segments) == 0) {
  3049. if (strlen($entry) != $len) {
  3050. continue;
  3051. }
  3052. if (is_file($filename)) {
  3053. if ($all || $this->getString($filename) == null) {
  3054. unlink($filename);
  3055. }
  3056. }
  3057. } else {
  3058. if (strlen($entry) != $segments[0]) {
  3059. continue;
  3060. }
  3061. if (is_dir($filename)) {
  3062. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  3063. rmdir($filename);
  3064. }
  3065. }
  3066. }
  3067. }
  3068. public function clear(): bool
  3069. {
  3070. if (!file_exists($this->path) || !is_dir($this->path)) {
  3071. return false;
  3072. }
  3073. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  3074. return true;
  3075. }
  3076. }
  3077. }
  3078. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  3079. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3080. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3081. class ReflectedColumn implements \JsonSerializable
  3082. {
  3083. const DEFAULT_LENGTH = 255;
  3084. const DEFAULT_PRECISION = 19;
  3085. const DEFAULT_SCALE = 4;
  3086. private $name;
  3087. private $type;
  3088. private $length;
  3089. private $precision;
  3090. private $scale;
  3091. private $nullable;
  3092. private $pk;
  3093. private $fk;
  3094. public function __construct(string $name, string $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, string $fk)
  3095. {
  3096. $this->name = $name;
  3097. $this->type = $type;
  3098. $this->length = $length;
  3099. $this->precision = $precision;
  3100. $this->scale = $scale;
  3101. $this->nullable = $nullable;
  3102. $this->pk = $pk;
  3103. $this->fk = $fk;
  3104. $this->sanitize();
  3105. }
  3106. private static function parseColumnType(string $columnType, int &$length, int &$precision, int &$scale) /*: void*/
  3107. {
  3108. if (!$columnType) {
  3109. return;
  3110. }
  3111. $pos = strpos($columnType, '(');
  3112. if ($pos) {
  3113. $dataSize = rtrim(substr($columnType, $pos + 1), ')');
  3114. if ($length) {
  3115. $length = (int) $dataSize;
  3116. } else {
  3117. $pos = strpos($dataSize, ',');
  3118. if ($pos) {
  3119. $precision = (int) substr($dataSize, 0, $pos);
  3120. $scale = (int) substr($dataSize, $pos + 1);
  3121. } else {
  3122. $precision = (int) $dataSize;
  3123. $scale = 0;
  3124. }
  3125. }
  3126. }
  3127. }
  3128. private static function getDataSize(int $length, int $precision, int $scale): string
  3129. {
  3130. $dataSize = '';
  3131. if ($length) {
  3132. $dataSize = $length;
  3133. } elseif ($precision) {
  3134. if ($scale) {
  3135. $dataSize = $precision . ',' . $scale;
  3136. } else {
  3137. $dataSize = $precision;
  3138. }
  3139. }
  3140. return $dataSize;
  3141. }
  3142. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  3143. {
  3144. $name = $columnResult['COLUMN_NAME'];
  3145. $dataType = $columnResult['DATA_TYPE'];
  3146. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  3147. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  3148. $scale = (int) $columnResult['NUMERIC_SCALE'];
  3149. $columnType = $columnResult['COLUMN_TYPE'];
  3150. self::parseColumnType($columnType, $length, $precision, $scale);
  3151. $dataSize = self::getDataSize($length, $precision, $scale);
  3152. $type = $reflection->toJdbcType($dataType, $dataSize);
  3153. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  3154. $pk = false;
  3155. $fk = '';
  3156. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3157. }
  3158. public static function fromJson(/* object */$json): ReflectedColumn
  3159. {
  3160. $name = $json->name;
  3161. $type = $json->type;
  3162. $length = isset($json->length) ? (int) $json->length : 0;
  3163. $precision = isset($json->precision) ? (int) $json->precision : 0;
  3164. $scale = isset($json->scale) ? (int) $json->scale : 0;
  3165. $nullable = isset($json->nullable) ? (bool) $json->nullable : false;
  3166. $pk = isset($json->pk) ? (bool) $json->pk : false;
  3167. $fk = isset($json->fk) ? $json->fk : '';
  3168. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3169. }
  3170. private function sanitize()
  3171. {
  3172. $this->length = $this->hasLength() ? $this->getLength() : 0;
  3173. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  3174. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  3175. }
  3176. public function getName(): string
  3177. {
  3178. return $this->name;
  3179. }
  3180. public function getNullable(): bool
  3181. {
  3182. return $this->nullable;
  3183. }
  3184. public function getType(): string
  3185. {
  3186. return $this->type;
  3187. }
  3188. public function getLength(): int
  3189. {
  3190. return $this->length ?: self::DEFAULT_LENGTH;
  3191. }
  3192. public function getPrecision(): int
  3193. {
  3194. return $this->precision ?: self::DEFAULT_PRECISION;
  3195. }
  3196. public function getScale(): int
  3197. {
  3198. return $this->scale ?: self::DEFAULT_SCALE;
  3199. }
  3200. public function hasLength(): bool
  3201. {
  3202. return in_array($this->type, ['varchar', 'varbinary']);
  3203. }
  3204. public function hasPrecision(): bool
  3205. {
  3206. return $this->type == 'decimal';
  3207. }
  3208. public function hasScale(): bool
  3209. {
  3210. return $this->type == 'decimal';
  3211. }
  3212. public function isBinary(): bool
  3213. {
  3214. return in_array($this->type, ['blob', 'varbinary']);
  3215. }
  3216. public function isBoolean(): bool
  3217. {
  3218. return $this->type == 'boolean';
  3219. }
  3220. public function isGeometry(): bool
  3221. {
  3222. return $this->type == 'geometry';
  3223. }
  3224. public function isInteger(): bool
  3225. {
  3226. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  3227. }
  3228. public function setPk($value) /*: void*/
  3229. {
  3230. $this->pk = $value;
  3231. }
  3232. public function getPk(): bool
  3233. {
  3234. return $this->pk;
  3235. }
  3236. public function setFk($value) /*: void*/
  3237. {
  3238. $this->fk = $value;
  3239. }
  3240. public function getFk(): string
  3241. {
  3242. return $this->fk;
  3243. }
  3244. public function serialize()
  3245. {
  3246. return [
  3247. 'name' => $this->name,
  3248. 'type' => $this->type,
  3249. 'length' => $this->length,
  3250. 'precision' => $this->precision,
  3251. 'scale' => $this->scale,
  3252. 'nullable' => $this->nullable,
  3253. 'pk' => $this->pk,
  3254. 'fk' => $this->fk,
  3255. ];
  3256. }
  3257. public function jsonSerialize()
  3258. {
  3259. return array_filter($this->serialize());
  3260. }
  3261. }
  3262. }
  3263. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  3264. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3265. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3266. class ReflectedDatabase implements \JsonSerializable
  3267. {
  3268. private $tableTypes;
  3269. public function __construct(array $tableTypes)
  3270. {
  3271. $this->tableTypes = $tableTypes;
  3272. }
  3273. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  3274. {
  3275. $tableTypes = [];
  3276. foreach ($reflection->getTables() as $table) {
  3277. $tableName = $table['TABLE_NAME'];
  3278. $tableType = $table['TABLE_TYPE'];
  3279. if (in_array($tableName, $reflection->getIgnoredTables())) {
  3280. continue;
  3281. }
  3282. $tableTypes[$tableName] = $tableType;
  3283. }
  3284. return new ReflectedDatabase($tableTypes);
  3285. }
  3286. public static function fromJson(/* object */$json): ReflectedDatabase
  3287. {
  3288. $tableTypes = (array) $json->tables;
  3289. return new ReflectedDatabase($tableTypes);
  3290. }
  3291. public function hasTable(string $tableName): bool
  3292. {
  3293. return isset($this->tableTypes[$tableName]);
  3294. }
  3295. public function getType(string $tableName): string
  3296. {
  3297. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  3298. }
  3299. public function getTableNames(): array
  3300. {
  3301. return array_keys($this->tableTypes);
  3302. }
  3303. public function removeTable(string $tableName): bool
  3304. {
  3305. if (!isset($this->tableTypes[$tableName])) {
  3306. return false;
  3307. }
  3308. unset($this->tableTypes[$tableName]);
  3309. return true;
  3310. }
  3311. public function serialize()
  3312. {
  3313. return [
  3314. 'tables' => $this->tableTypes,
  3315. ];
  3316. }
  3317. public function jsonSerialize()
  3318. {
  3319. return $this->serialize();
  3320. }
  3321. }
  3322. }
  3323. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  3324. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3325. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3326. class ReflectedTable implements \JsonSerializable
  3327. {
  3328. private $name;
  3329. private $type;
  3330. private $columns;
  3331. private $pk;
  3332. private $fks;
  3333. public function __construct(string $name, string $type, array $columns)
  3334. {
  3335. $this->name = $name;
  3336. $this->type = $type;
  3337. // set columns
  3338. $this->columns = [];
  3339. foreach ($columns as $column) {
  3340. $columnName = $column->getName();
  3341. $this->columns[$columnName] = $column;
  3342. }
  3343. // set primary key
  3344. $this->pk = null;
  3345. foreach ($columns as $column) {
  3346. if ($column->getPk() == true) {
  3347. $this->pk = $column;
  3348. }
  3349. }
  3350. // set foreign keys
  3351. $this->fks = [];
  3352. foreach ($columns as $column) {
  3353. $columnName = $column->getName();
  3354. $referencedTableName = $column->getFk();
  3355. if ($referencedTableName != '') {
  3356. $this->fks[$columnName] = $referencedTableName;
  3357. }
  3358. }
  3359. }
  3360. public static function fromReflection(GenericReflection $reflection, string $name, string $type): ReflectedTable
  3361. {
  3362. // set columns
  3363. $columns = [];
  3364. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  3365. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  3366. $columns[$column->getName()] = $column;
  3367. }
  3368. // set primary key
  3369. $columnNames = $reflection->getTablePrimaryKeys($name);
  3370. if (count($columnNames) == 1) {
  3371. $columnName = $columnNames[0];
  3372. if (isset($columns[$columnName])) {
  3373. $pk = $columns[$columnName];
  3374. $pk->setPk(true);
  3375. }
  3376. }
  3377. // set foreign keys
  3378. $fks = $reflection->getTableForeignKeys($name);
  3379. foreach ($fks as $columnName => $table) {
  3380. $columns[$columnName]->setFk($table);
  3381. }
  3382. return new ReflectedTable($name, $type, array_values($columns));
  3383. }
  3384. public static function fromJson(/* object */$json): ReflectedTable
  3385. {
  3386. $name = $json->name;
  3387. $type = isset($json->type) ? $json->type : 'table';
  3388. $columns = [];
  3389. if (isset($json->columns) && is_array($json->columns)) {
  3390. foreach ($json->columns as $column) {
  3391. $columns[] = ReflectedColumn::fromJson($column);
  3392. }
  3393. }
  3394. return new ReflectedTable($name, $type, $columns);
  3395. }
  3396. public function hasColumn(string $columnName): bool
  3397. {
  3398. return isset($this->columns[$columnName]);
  3399. }
  3400. public function hasPk(): bool
  3401. {
  3402. return $this->pk != null;
  3403. }
  3404. public function getPk() /*: ?ReflectedColumn */
  3405. {
  3406. return $this->pk;
  3407. }
  3408. public function getName(): string
  3409. {
  3410. return $this->name;
  3411. }
  3412. public function getType(): string
  3413. {
  3414. return $this->type;
  3415. }
  3416. public function getColumnNames(): array
  3417. {
  3418. return array_keys($this->columns);
  3419. }
  3420. public function getColumn($columnName): ReflectedColumn
  3421. {
  3422. return $this->columns[$columnName];
  3423. }
  3424. public function getFksTo(string $tableName): array
  3425. {
  3426. $columns = array();
  3427. foreach ($this->fks as $columnName => $referencedTableName) {
  3428. if ($tableName == $referencedTableName) {
  3429. $columns[] = $this->columns[$columnName];
  3430. }
  3431. }
  3432. return $columns;
  3433. }
  3434. public function removeColumn(string $columnName): bool
  3435. {
  3436. if (!isset($this->columns[$columnName])) {
  3437. return false;
  3438. }
  3439. unset($this->columns[$columnName]);
  3440. return true;
  3441. }
  3442. public function serialize()
  3443. {
  3444. return [
  3445. 'name' => $this->name,
  3446. 'type' => $this->type,
  3447. 'columns' => array_values($this->columns),
  3448. ];
  3449. }
  3450. public function jsonSerialize()
  3451. {
  3452. return $this->serialize();
  3453. }
  3454. }
  3455. }
  3456. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  3457. namespace Tqdev\PhpCrudApi\Column {
  3458. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  3459. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3460. use Tqdev\PhpCrudApi\Database\GenericDB;
  3461. class DefinitionService
  3462. {
  3463. private $db;
  3464. private $reflection;
  3465. public function __construct(GenericDB $db, ReflectionService $reflection)
  3466. {
  3467. $this->db = $db;
  3468. $this->reflection = $reflection;
  3469. }
  3470. public function updateTable(string $tableName, /* object */ $changes): bool
  3471. {
  3472. $table = $this->reflection->getTable($tableName);
  3473. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  3474. if ($table->getName() != $newTable->getName()) {
  3475. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  3476. return false;
  3477. }
  3478. }
  3479. return true;
  3480. }
  3481. public function updateColumn(string $tableName, string $columnName, /* object */ $changes): bool
  3482. {
  3483. $table = $this->reflection->getTable($tableName);
  3484. $column = $table->getColumn($columnName);
  3485. // remove constraints on other column
  3486. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3487. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  3488. $oldColumn = $table->getPk();
  3489. if ($oldColumn->getName() != $columnName) {
  3490. $oldColumn->setPk(false);
  3491. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  3492. return false;
  3493. }
  3494. }
  3495. }
  3496. // remove constraints
  3497. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  3498. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  3499. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  3500. return false;
  3501. }
  3502. }
  3503. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  3504. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  3505. return false;
  3506. }
  3507. }
  3508. // name and type
  3509. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3510. $newColumn->setPk(false);
  3511. $newColumn->setFk('');
  3512. if ($newColumn->getName() != $column->getName()) {
  3513. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  3514. return false;
  3515. }
  3516. }
  3517. if (
  3518. $newColumn->getType() != $column->getType() ||
  3519. $newColumn->getLength() != $column->getLength() ||
  3520. $newColumn->getPrecision() != $column->getPrecision() ||
  3521. $newColumn->getScale() != $column->getScale()
  3522. ) {
  3523. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  3524. return false;
  3525. }
  3526. }
  3527. if ($newColumn->getNullable() != $column->getNullable()) {
  3528. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  3529. return false;
  3530. }
  3531. }
  3532. // add constraints
  3533. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3534. if ($newColumn->getFk()) {
  3535. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3536. return false;
  3537. }
  3538. }
  3539. if ($newColumn->getPk()) {
  3540. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3541. return false;
  3542. }
  3543. }
  3544. return true;
  3545. }
  3546. public function addTable(/* object */$definition)
  3547. {
  3548. $newTable = ReflectedTable::fromJson($definition);
  3549. if (!$this->db->definition()->addTable($newTable)) {
  3550. return false;
  3551. }
  3552. return true;
  3553. }
  3554. public function addColumn(string $tableName, /* object */ $definition)
  3555. {
  3556. $newColumn = ReflectedColumn::fromJson($definition);
  3557. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  3558. return false;
  3559. }
  3560. if ($newColumn->getFk()) {
  3561. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  3562. return false;
  3563. }
  3564. }
  3565. if ($newColumn->getPk()) {
  3566. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  3567. return false;
  3568. }
  3569. }
  3570. return true;
  3571. }
  3572. public function removeTable(string $tableName)
  3573. {
  3574. if (!$this->db->definition()->removeTable($tableName)) {
  3575. return false;
  3576. }
  3577. return true;
  3578. }
  3579. public function removeColumn(string $tableName, string $columnName)
  3580. {
  3581. $table = $this->reflection->getTable($tableName);
  3582. $newColumn = $table->getColumn($columnName);
  3583. if ($newColumn->getPk()) {
  3584. $newColumn->setPk(false);
  3585. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3586. return false;
  3587. }
  3588. }
  3589. if ($newColumn->getFk()) {
  3590. $newColumn->setFk("");
  3591. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  3592. return false;
  3593. }
  3594. }
  3595. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  3596. return false;
  3597. }
  3598. return true;
  3599. }
  3600. }
  3601. }
  3602. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  3603. namespace Tqdev\PhpCrudApi\Column {
  3604. use Tqdev\PhpCrudApi\Cache\Cache;
  3605. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedDatabase;
  3606. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3607. use Tqdev\PhpCrudApi\Database\GenericDB;
  3608. class ReflectionService
  3609. {
  3610. private $db;
  3611. private $cache;
  3612. private $ttl;
  3613. private $database;
  3614. private $tables;
  3615. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  3616. {
  3617. $this->db = $db;
  3618. $this->cache = $cache;
  3619. $this->ttl = $ttl;
  3620. $this->database = null;
  3621. $this->tables = [];
  3622. }
  3623. private function database(): ReflectedDatabase
  3624. {
  3625. if ($this->database) {
  3626. return $this->database;
  3627. }
  3628. $this->database = $this->loadDatabase(true);
  3629. return $this->database;
  3630. }
  3631. private function loadDatabase(bool $useCache): ReflectedDatabase
  3632. {
  3633. $key = sprintf('%s-ReflectedDatabase', $this->db->getCacheKey());
  3634. $data = $useCache ? $this->cache->get($key) : '';
  3635. if ($data != '') {
  3636. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  3637. } else {
  3638. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  3639. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  3640. $this->cache->set($key, $data, $this->ttl);
  3641. }
  3642. return $database;
  3643. }
  3644. private function loadTable(string $tableName, bool $useCache): ReflectedTable
  3645. {
  3646. $key = sprintf('%s-ReflectedTable(%s)', $this->db->getCacheKey(), $tableName);
  3647. $data = $useCache ? $this->cache->get($key) : '';
  3648. if ($data != '') {
  3649. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  3650. } else {
  3651. $tableType = $this->database()->getType($tableName);
  3652. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  3653. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  3654. $this->cache->set($key, $data, $this->ttl);
  3655. }
  3656. return $table;
  3657. }
  3658. public function refreshTables()
  3659. {
  3660. $this->database = $this->loadDatabase(false);
  3661. }
  3662. public function refreshTable(string $tableName)
  3663. {
  3664. $this->tables[$tableName] = $this->loadTable($tableName, false);
  3665. }
  3666. public function hasTable(string $tableName): bool
  3667. {
  3668. return $this->database()->hasTable($tableName);
  3669. }
  3670. public function getType(string $tableName): string
  3671. {
  3672. return $this->database()->getType($tableName);
  3673. }
  3674. public function getTable(string $tableName): ReflectedTable
  3675. {
  3676. if (!isset($this->tables[$tableName])) {
  3677. $this->tables[$tableName] = $this->loadTable($tableName, true);
  3678. }
  3679. return $this->tables[$tableName];
  3680. }
  3681. public function getTableNames(): array
  3682. {
  3683. return $this->database()->getTableNames();
  3684. }
  3685. public function removeTable(string $tableName): bool
  3686. {
  3687. unset($this->tables[$tableName]);
  3688. return $this->database()->removeTable($tableName);
  3689. }
  3690. }
  3691. }
  3692. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  3693. namespace Tqdev\PhpCrudApi\Controller {
  3694. use Psr\Http\Message\ResponseInterface;
  3695. use Psr\Http\Message\ServerRequestInterface;
  3696. use Tqdev\PhpCrudApi\Cache\Cache;
  3697. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3698. class CacheController
  3699. {
  3700. private $cache;
  3701. private $responder;
  3702. public function __construct(Router $router, Responder $responder, Cache $cache)
  3703. {
  3704. $router->register('GET', '/cache/clear', array($this, 'clear'));
  3705. $this->cache = $cache;
  3706. $this->responder = $responder;
  3707. }
  3708. public function clear(ServerRequestInterface $request): ResponseInterface
  3709. {
  3710. return $this->responder->success($this->cache->clear());
  3711. }
  3712. }
  3713. }
  3714. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  3715. namespace Tqdev\PhpCrudApi\Controller {
  3716. use Psr\Http\Message\ResponseInterface;
  3717. use Psr\Http\Message\ServerRequestInterface;
  3718. use Tqdev\PhpCrudApi\Column\DefinitionService;
  3719. use Tqdev\PhpCrudApi\Column\ReflectionService;
  3720. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3721. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3722. use Tqdev\PhpCrudApi\RequestUtils;
  3723. class ColumnController
  3724. {
  3725. private $responder;
  3726. private $reflection;
  3727. private $definition;
  3728. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  3729. {
  3730. $router->register('GET', '/columns', array($this, 'getDatabase'));
  3731. $router->register('GET', '/columns/*', array($this, 'getTable'));
  3732. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  3733. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  3734. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  3735. $router->register('POST', '/columns', array($this, 'addTable'));
  3736. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  3737. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  3738. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  3739. $this->responder = $responder;
  3740. $this->reflection = $reflection;
  3741. $this->definition = $definition;
  3742. }
  3743. public function getDatabase(ServerRequestInterface $request): ResponseInterface
  3744. {
  3745. $tables = [];
  3746. foreach ($this->reflection->getTableNames() as $table) {
  3747. $tables[] = $this->reflection->getTable($table);
  3748. }
  3749. $database = ['tables' => $tables];
  3750. return $this->responder->success($database);
  3751. }
  3752. public function getTable(ServerRequestInterface $request): ResponseInterface
  3753. {
  3754. $tableName = RequestUtils::getPathSegment($request, 2);
  3755. if (!$this->reflection->hasTable($tableName)) {
  3756. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3757. }
  3758. $table = $this->reflection->getTable($tableName);
  3759. return $this->responder->success($table);
  3760. }
  3761. public function getColumn(ServerRequestInterface $request): ResponseInterface
  3762. {
  3763. $tableName = RequestUtils::getPathSegment($request, 2);
  3764. $columnName = RequestUtils::getPathSegment($request, 3);
  3765. if (!$this->reflection->hasTable($tableName)) {
  3766. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3767. }
  3768. $table = $this->reflection->getTable($tableName);
  3769. if (!$table->hasColumn($columnName)) {
  3770. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3771. }
  3772. $column = $table->getColumn($columnName);
  3773. return $this->responder->success($column);
  3774. }
  3775. public function updateTable(ServerRequestInterface $request): ResponseInterface
  3776. {
  3777. $tableName = RequestUtils::getPathSegment($request, 2);
  3778. if (!$this->reflection->hasTable($tableName)) {
  3779. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3780. }
  3781. $success = $this->definition->updateTable($tableName, $request->getParsedBody());
  3782. if ($success) {
  3783. $this->reflection->refreshTables();
  3784. }
  3785. return $this->responder->success($success);
  3786. }
  3787. public function updateColumn(ServerRequestInterface $request): ResponseInterface
  3788. {
  3789. $tableName = RequestUtils::getPathSegment($request, 2);
  3790. $columnName = RequestUtils::getPathSegment($request, 3);
  3791. if (!$this->reflection->hasTable($tableName)) {
  3792. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3793. }
  3794. $table = $this->reflection->getTable($tableName);
  3795. if (!$table->hasColumn($columnName)) {
  3796. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3797. }
  3798. $success = $this->definition->updateColumn($tableName, $columnName, $request->getParsedBody());
  3799. if ($success) {
  3800. $this->reflection->refreshTable($tableName);
  3801. }
  3802. return $this->responder->success($success);
  3803. }
  3804. public function addTable(ServerRequestInterface $request): ResponseInterface
  3805. {
  3806. $tableName = $request->getParsedBody()->name;
  3807. if ($this->reflection->hasTable($tableName)) {
  3808. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  3809. }
  3810. $success = $this->definition->addTable($request->getParsedBody());
  3811. if ($success) {
  3812. $this->reflection->refreshTables();
  3813. }
  3814. return $this->responder->success($success);
  3815. }
  3816. public function addColumn(ServerRequestInterface $request): ResponseInterface
  3817. {
  3818. $tableName = RequestUtils::getPathSegment($request, 2);
  3819. if (!$this->reflection->hasTable($tableName)) {
  3820. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3821. }
  3822. $columnName = $request->getParsedBody()->name;
  3823. $table = $this->reflection->getTable($tableName);
  3824. if ($table->hasColumn($columnName)) {
  3825. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  3826. }
  3827. $success = $this->definition->addColumn($tableName, $request->getParsedBody());
  3828. if ($success) {
  3829. $this->reflection->refreshTable($tableName);
  3830. }
  3831. return $this->responder->success($success);
  3832. }
  3833. public function removeTable(ServerRequestInterface $request): ResponseInterface
  3834. {
  3835. $tableName = RequestUtils::getPathSegment($request, 2);
  3836. if (!$this->reflection->hasTable($tableName)) {
  3837. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3838. }
  3839. $success = $this->definition->removeTable($tableName);
  3840. if ($success) {
  3841. $this->reflection->refreshTables();
  3842. }
  3843. return $this->responder->success($success);
  3844. }
  3845. public function removeColumn(ServerRequestInterface $request): ResponseInterface
  3846. {
  3847. $tableName = RequestUtils::getPathSegment($request, 2);
  3848. $columnName = RequestUtils::getPathSegment($request, 3);
  3849. if (!$this->reflection->hasTable($tableName)) {
  3850. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3851. }
  3852. $table = $this->reflection->getTable($tableName);
  3853. if (!$table->hasColumn($columnName)) {
  3854. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3855. }
  3856. $success = $this->definition->removeColumn($tableName, $columnName);
  3857. if ($success) {
  3858. $this->reflection->refreshTable($tableName);
  3859. }
  3860. return $this->responder->success($success);
  3861. }
  3862. }
  3863. }
  3864. // file: src/Tqdev/PhpCrudApi/Controller/GeoJsonController.php
  3865. namespace Tqdev\PhpCrudApi\Controller {
  3866. use Psr\Http\Message\ResponseInterface;
  3867. use Psr\Http\Message\ServerRequestInterface;
  3868. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  3869. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3870. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3871. use Tqdev\PhpCrudApi\RequestUtils;
  3872. class GeoJsonController
  3873. {
  3874. private $service;
  3875. private $responder;
  3876. public function __construct(Router $router, Responder $responder, GeoJsonService $service)
  3877. {
  3878. $router->register('GET', '/geojson/*', array($this, '_list'));
  3879. $router->register('GET', '/geojson/*/*', array($this, 'read'));
  3880. $this->service = $service;
  3881. $this->responder = $responder;
  3882. }
  3883. public function _list(ServerRequestInterface $request): ResponseInterface
  3884. {
  3885. $table = RequestUtils::getPathSegment($request, 2);
  3886. $params = RequestUtils::getParams($request);
  3887. if (!$this->service->hasTable($table)) {
  3888. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3889. }
  3890. return $this->responder->success($this->service->_list($table, $params));
  3891. }
  3892. public function read(ServerRequestInterface $request): ResponseInterface
  3893. {
  3894. $table = RequestUtils::getPathSegment($request, 2);
  3895. if (!$this->service->hasTable($table)) {
  3896. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3897. }
  3898. if ($this->service->getType($table) != 'table') {
  3899. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3900. }
  3901. $id = RequestUtils::getPathSegment($request, 3);
  3902. $params = RequestUtils::getParams($request);
  3903. if (strpos($id, ',') !== false) {
  3904. $ids = explode(',', $id);
  3905. $result = (object) array('type' => 'FeatureCollection', 'features' => array());
  3906. for ($i = 0; $i < count($ids); $i++) {
  3907. array_push($result->features, $this->service->read($table, $ids[$i], $params));
  3908. }
  3909. return $this->responder->success($result);
  3910. } else {
  3911. $response = $this->service->read($table, $id, $params);
  3912. if ($response === null) {
  3913. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  3914. }
  3915. return $this->responder->success($response);
  3916. }
  3917. }
  3918. }
  3919. }
  3920. // file: src/Tqdev/PhpCrudApi/Controller/JsonResponder.php
  3921. namespace Tqdev\PhpCrudApi\Controller {
  3922. use Psr\Http\Message\ResponseInterface;
  3923. use Tqdev\PhpCrudApi\Record\Document\ErrorDocument;
  3924. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3925. use Tqdev\PhpCrudApi\ResponseFactory;
  3926. class JsonResponder implements Responder
  3927. {
  3928. public function error(int $error, string $argument, $details = null): ResponseInterface
  3929. {
  3930. $errorCode = new ErrorCode($error);
  3931. $status = $errorCode->getStatus();
  3932. $document = new ErrorDocument($errorCode, $argument, $details);
  3933. return ResponseFactory::fromObject($status, $document);
  3934. }
  3935. public function success($result): ResponseInterface
  3936. {
  3937. return ResponseFactory::fromObject(ResponseFactory::OK, $result);
  3938. }
  3939. }
  3940. }
  3941. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  3942. namespace Tqdev\PhpCrudApi\Controller {
  3943. use Psr\Http\Message\ResponseInterface;
  3944. use Psr\Http\Message\ServerRequestInterface;
  3945. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3946. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  3947. class OpenApiController
  3948. {
  3949. private $openApi;
  3950. private $responder;
  3951. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  3952. {
  3953. $router->register('GET', '/openapi', array($this, 'openapi'));
  3954. $this->openApi = $openApi;
  3955. $this->responder = $responder;
  3956. }
  3957. public function openapi(ServerRequestInterface $request): ResponseInterface
  3958. {
  3959. return $this->responder->success($this->openApi->get());
  3960. }
  3961. }
  3962. }
  3963. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  3964. namespace Tqdev\PhpCrudApi\Controller {
  3965. use Psr\Http\Message\ResponseInterface;
  3966. use Psr\Http\Message\ServerRequestInterface;
  3967. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3968. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3969. use Tqdev\PhpCrudApi\Record\RecordService;
  3970. use Tqdev\PhpCrudApi\RequestUtils;
  3971. class RecordController
  3972. {
  3973. private $service;
  3974. private $responder;
  3975. public function __construct(Router $router, Responder $responder, RecordService $service)
  3976. {
  3977. $router->register('GET', '/records/*', array($this, '_list'));
  3978. $router->register('POST', '/records/*', array($this, 'create'));
  3979. $router->register('GET', '/records/*/*', array($this, 'read'));
  3980. $router->register('PUT', '/records/*/*', array($this, 'update'));
  3981. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  3982. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  3983. $this->service = $service;
  3984. $this->responder = $responder;
  3985. }
  3986. public function _list(ServerRequestInterface $request): ResponseInterface
  3987. {
  3988. $table = RequestUtils::getPathSegment($request, 2);
  3989. $params = RequestUtils::getParams($request);
  3990. if (!$this->service->hasTable($table)) {
  3991. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3992. }
  3993. return $this->responder->success($this->service->_list($table, $params));
  3994. }
  3995. public function read(ServerRequestInterface $request): ResponseInterface
  3996. {
  3997. $table = RequestUtils::getPathSegment($request, 2);
  3998. if (!$this->service->hasTable($table)) {
  3999. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4000. }
  4001. if ($this->service->getType($table) != 'table') {
  4002. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4003. }
  4004. $id = RequestUtils::getPathSegment($request, 3);
  4005. $params = RequestUtils::getParams($request);
  4006. if (strpos($id, ',') !== false) {
  4007. $ids = explode(',', $id);
  4008. $result = [];
  4009. for ($i = 0; $i < count($ids); $i++) {
  4010. array_push($result, $this->service->read($table, $ids[$i], $params));
  4011. }
  4012. return $this->responder->success($result);
  4013. } else {
  4014. $response = $this->service->read($table, $id, $params);
  4015. if ($response === null) {
  4016. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  4017. }
  4018. return $this->responder->success($response);
  4019. }
  4020. }
  4021. public function create(ServerRequestInterface $request): ResponseInterface
  4022. {
  4023. $table = RequestUtils::getPathSegment($request, 2);
  4024. if (!$this->service->hasTable($table)) {
  4025. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4026. }
  4027. if ($this->service->getType($table) != 'table') {
  4028. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4029. }
  4030. $record = $request->getParsedBody();
  4031. if ($record === null) {
  4032. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4033. }
  4034. $params = RequestUtils::getParams($request);
  4035. if (is_array($record)) {
  4036. $result = array();
  4037. foreach ($record as $r) {
  4038. $result[] = $this->service->create($table, $r, $params);
  4039. }
  4040. return $this->responder->success($result);
  4041. } else {
  4042. return $this->responder->success($this->service->create($table, $record, $params));
  4043. }
  4044. }
  4045. public function update(ServerRequestInterface $request): ResponseInterface
  4046. {
  4047. $table = RequestUtils::getPathSegment($request, 2);
  4048. if (!$this->service->hasTable($table)) {
  4049. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4050. }
  4051. if ($this->service->getType($table) != 'table') {
  4052. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4053. }
  4054. $id = RequestUtils::getPathSegment($request, 3);
  4055. $params = RequestUtils::getParams($request);
  4056. $record = $request->getParsedBody();
  4057. if ($record === null) {
  4058. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4059. }
  4060. $ids = explode(',', $id);
  4061. if (is_array($record)) {
  4062. if (count($ids) != count($record)) {
  4063. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4064. }
  4065. $result = array();
  4066. for ($i = 0; $i < count($ids); $i++) {
  4067. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  4068. }
  4069. return $this->responder->success($result);
  4070. } else {
  4071. if (count($ids) != 1) {
  4072. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4073. }
  4074. return $this->responder->success($this->service->update($table, $id, $record, $params));
  4075. }
  4076. }
  4077. public function delete(ServerRequestInterface $request): ResponseInterface
  4078. {
  4079. $table = RequestUtils::getPathSegment($request, 2);
  4080. if (!$this->service->hasTable($table)) {
  4081. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4082. }
  4083. if ($this->service->getType($table) != 'table') {
  4084. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4085. }
  4086. $id = RequestUtils::getPathSegment($request, 3);
  4087. $params = RequestUtils::getParams($request);
  4088. $ids = explode(',', $id);
  4089. if (count($ids) > 1) {
  4090. $result = array();
  4091. for ($i = 0; $i < count($ids); $i++) {
  4092. $result[] = $this->service->delete($table, $ids[$i], $params);
  4093. }
  4094. return $this->responder->success($result);
  4095. } else {
  4096. return $this->responder->success($this->service->delete($table, $id, $params));
  4097. }
  4098. }
  4099. public function increment(ServerRequestInterface $request): ResponseInterface
  4100. {
  4101. $table = RequestUtils::getPathSegment($request, 2);
  4102. if (!$this->service->hasTable($table)) {
  4103. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4104. }
  4105. if ($this->service->getType($table) != 'table') {
  4106. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4107. }
  4108. $id = RequestUtils::getPathSegment($request, 3);
  4109. $record = $request->getParsedBody();
  4110. if ($record === null) {
  4111. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4112. }
  4113. $params = RequestUtils::getParams($request);
  4114. $ids = explode(',', $id);
  4115. if (is_array($record)) {
  4116. if (count($ids) != count($record)) {
  4117. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4118. }
  4119. $result = array();
  4120. for ($i = 0; $i < count($ids); $i++) {
  4121. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  4122. }
  4123. return $this->responder->success($result);
  4124. } else {
  4125. if (count($ids) != 1) {
  4126. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4127. }
  4128. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  4129. }
  4130. }
  4131. }
  4132. }
  4133. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  4134. namespace Tqdev\PhpCrudApi\Controller {
  4135. use Psr\Http\Message\ResponseInterface;
  4136. interface Responder
  4137. {
  4138. public function error(int $error, string $argument, $details = null): ResponseInterface;
  4139. public function success($result): ResponseInterface;
  4140. }
  4141. }
  4142. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  4143. namespace Tqdev\PhpCrudApi\Database {
  4144. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4145. class ColumnConverter
  4146. {
  4147. private $driver;
  4148. public function __construct(string $driver)
  4149. {
  4150. $this->driver = $driver;
  4151. }
  4152. public function convertColumnValue(ReflectedColumn $column): string
  4153. {
  4154. if ($column->isBoolean()) {
  4155. switch ($this->driver) {
  4156. case 'mysql':
  4157. return "IFNULL(IF(?,TRUE,FALSE),NULL)";
  4158. case 'pgsql':
  4159. return "?";
  4160. case 'sqlsrv':
  4161. return "?";
  4162. }
  4163. }
  4164. if ($column->isBinary()) {
  4165. switch ($this->driver) {
  4166. case 'mysql':
  4167. return "FROM_BASE64(?)";
  4168. case 'pgsql':
  4169. return "decode(?, 'base64')";
  4170. case 'sqlsrv':
  4171. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  4172. }
  4173. }
  4174. if ($column->isGeometry()) {
  4175. switch ($this->driver) {
  4176. case 'mysql':
  4177. case 'pgsql':
  4178. return "ST_GeomFromText(?)";
  4179. case 'sqlsrv':
  4180. return "geometry::STGeomFromText(?,0)";
  4181. }
  4182. }
  4183. return '?';
  4184. }
  4185. public function convertColumnName(ReflectedColumn $column, $value): string
  4186. {
  4187. if ($column->isBinary()) {
  4188. switch ($this->driver) {
  4189. case 'mysql':
  4190. return "TO_BASE64($value) as $value";
  4191. case 'pgsql':
  4192. return "encode($value::bytea, 'base64') as $value";
  4193. case 'sqlsrv':
  4194. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  4195. }
  4196. }
  4197. if ($column->isGeometry()) {
  4198. switch ($this->driver) {
  4199. case 'mysql':
  4200. case 'pgsql':
  4201. return "ST_AsText($value) as $value";
  4202. case 'sqlsrv':
  4203. return "REPLACE($value.STAsText(),' (','(') as $value";
  4204. }
  4205. }
  4206. return $value;
  4207. }
  4208. }
  4209. }
  4210. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  4211. namespace Tqdev\PhpCrudApi\Database {
  4212. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4213. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4214. class ColumnsBuilder
  4215. {
  4216. private $driver;
  4217. private $converter;
  4218. public function __construct(string $driver)
  4219. {
  4220. $this->driver = $driver;
  4221. $this->converter = new ColumnConverter($driver);
  4222. }
  4223. public function getOffsetLimit(int $offset, int $limit): string
  4224. {
  4225. if ($limit < 0 || $offset < 0) {
  4226. return '';
  4227. }
  4228. switch ($this->driver) {
  4229. case 'mysql':
  4230. return " LIMIT $offset, $limit";
  4231. case 'pgsql':
  4232. return " LIMIT $limit OFFSET $offset";
  4233. case 'sqlsrv':
  4234. return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  4235. case 'sqlite':
  4236. return " LIMIT $limit OFFSET $offset";
  4237. }
  4238. }
  4239. private function quoteColumnName(ReflectedColumn $column): string
  4240. {
  4241. return '"' . $column->getName() . '"';
  4242. }
  4243. public function getOrderBy(ReflectedTable $table, array $columnOrdering): string
  4244. {
  4245. if (count($columnOrdering) == 0) {
  4246. return '';
  4247. }
  4248. $results = array();
  4249. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  4250. $column = $table->getColumn($columnName);
  4251. $quotedColumnName = $this->quoteColumnName($column);
  4252. $results[] = $quotedColumnName . ' ' . $ordering;
  4253. }
  4254. return ' ORDER BY ' . implode(',', $results);
  4255. }
  4256. public function getSelect(ReflectedTable $table, array $columnNames): string
  4257. {
  4258. $results = array();
  4259. foreach ($columnNames as $columnName) {
  4260. $column = $table->getColumn($columnName);
  4261. $quotedColumnName = $this->quoteColumnName($column);
  4262. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  4263. $results[] = $quotedColumnName;
  4264. }
  4265. return implode(',', $results);
  4266. }
  4267. public function getInsert(ReflectedTable $table, array $columnValues): string
  4268. {
  4269. $columns = array();
  4270. $values = array();
  4271. foreach ($columnValues as $columnName => $columnValue) {
  4272. $column = $table->getColumn($columnName);
  4273. $quotedColumnName = $this->quoteColumnName($column);
  4274. $columns[] = $quotedColumnName;
  4275. $columnValue = $this->converter->convertColumnValue($column);
  4276. $values[] = $columnValue;
  4277. }
  4278. $columnsSql = '(' . implode(',', $columns) . ')';
  4279. $valuesSql = '(' . implode(',', $values) . ')';
  4280. $outputColumn = $this->quoteColumnName($table->getPk());
  4281. switch ($this->driver) {
  4282. case 'mysql':
  4283. return "$columnsSql VALUES $valuesSql";
  4284. case 'pgsql':
  4285. return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  4286. case 'sqlsrv':
  4287. return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  4288. case 'sqlite':
  4289. return "$columnsSql VALUES $valuesSql";
  4290. }
  4291. }
  4292. public function getUpdate(ReflectedTable $table, array $columnValues): string
  4293. {
  4294. $results = array();
  4295. foreach ($columnValues as $columnName => $columnValue) {
  4296. $column = $table->getColumn($columnName);
  4297. $quotedColumnName = $this->quoteColumnName($column);
  4298. $columnValue = $this->converter->convertColumnValue($column);
  4299. $results[] = $quotedColumnName . '=' . $columnValue;
  4300. }
  4301. return implode(',', $results);
  4302. }
  4303. public function getIncrement(ReflectedTable $table, array $columnValues): string
  4304. {
  4305. $results = array();
  4306. foreach ($columnValues as $columnName => $columnValue) {
  4307. if (!is_numeric($columnValue)) {
  4308. continue;
  4309. }
  4310. $column = $table->getColumn($columnName);
  4311. $quotedColumnName = $this->quoteColumnName($column);
  4312. $columnValue = $this->converter->convertColumnValue($column);
  4313. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  4314. }
  4315. return implode(',', $results);
  4316. }
  4317. }
  4318. }
  4319. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  4320. namespace Tqdev\PhpCrudApi\Database {
  4321. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4322. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  4323. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4324. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4325. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  4326. use Tqdev\PhpCrudApi\Record\Condition\NotCondition;
  4327. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  4328. use Tqdev\PhpCrudApi\Record\Condition\SpatialCondition;
  4329. class ConditionsBuilder
  4330. {
  4331. private $driver;
  4332. public function __construct(string $driver)
  4333. {
  4334. $this->driver = $driver;
  4335. }
  4336. private function getConditionSql(Condition $condition, array &$arguments): string
  4337. {
  4338. if ($condition instanceof AndCondition) {
  4339. return $this->getAndConditionSql($condition, $arguments);
  4340. }
  4341. if ($condition instanceof OrCondition) {
  4342. return $this->getOrConditionSql($condition, $arguments);
  4343. }
  4344. if ($condition instanceof NotCondition) {
  4345. return $this->getNotConditionSql($condition, $arguments);
  4346. }
  4347. if ($condition instanceof SpatialCondition) {
  4348. return $this->getSpatialConditionSql($condition, $arguments);
  4349. }
  4350. if ($condition instanceof ColumnCondition) {
  4351. return $this->getColumnConditionSql($condition, $arguments);
  4352. }
  4353. throw new \Exception('Unknown Condition: ' . get_class($condition));
  4354. }
  4355. private function getAndConditionSql(AndCondition $and, array &$arguments): string
  4356. {
  4357. $parts = [];
  4358. foreach ($and->getConditions() as $condition) {
  4359. $parts[] = $this->getConditionSql($condition, $arguments);
  4360. }
  4361. return '(' . implode(' AND ', $parts) . ')';
  4362. }
  4363. private function getOrConditionSql(OrCondition $or, array &$arguments): string
  4364. {
  4365. $parts = [];
  4366. foreach ($or->getConditions() as $condition) {
  4367. $parts[] = $this->getConditionSql($condition, $arguments);
  4368. }
  4369. return '(' . implode(' OR ', $parts) . ')';
  4370. }
  4371. private function getNotConditionSql(NotCondition $not, array &$arguments): string
  4372. {
  4373. $condition = $not->getCondition();
  4374. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  4375. }
  4376. private function quoteColumnName(ReflectedColumn $column): string
  4377. {
  4378. return '"' . $column->getName() . '"';
  4379. }
  4380. private function escapeLikeValue(string $value): string
  4381. {
  4382. return addcslashes($value, '%_');
  4383. }
  4384. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): string
  4385. {
  4386. $column = $this->quoteColumnName($condition->getColumn());
  4387. $operator = $condition->getOperator();
  4388. $value = $condition->getValue();
  4389. switch ($operator) {
  4390. case 'cs':
  4391. $sql = "$column LIKE ?";
  4392. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  4393. break;
  4394. case 'sw':
  4395. $sql = "$column LIKE ?";
  4396. $arguments[] = $this->escapeLikeValue($value) . '%';
  4397. break;
  4398. case 'ew':
  4399. $sql = "$column LIKE ?";
  4400. $arguments[] = '%' . $this->escapeLikeValue($value);
  4401. break;
  4402. case 'eq':
  4403. $sql = "$column = ?";
  4404. $arguments[] = $value;
  4405. break;
  4406. case 'lt':
  4407. $sql = "$column < ?";
  4408. $arguments[] = $value;
  4409. break;
  4410. case 'le':
  4411. $sql = "$column <= ?";
  4412. $arguments[] = $value;
  4413. break;
  4414. case 'ge':
  4415. $sql = "$column >= ?";
  4416. $arguments[] = $value;
  4417. break;
  4418. case 'gt':
  4419. $sql = "$column > ?";
  4420. $arguments[] = $value;
  4421. break;
  4422. case 'bt':
  4423. $parts = explode(',', $value, 2);
  4424. $count = count($parts);
  4425. if ($count == 2) {
  4426. $sql = "($column >= ? AND $column <= ?)";
  4427. $arguments[] = $parts[0];
  4428. $arguments[] = $parts[1];
  4429. } else {
  4430. $sql = "FALSE";
  4431. }
  4432. break;
  4433. case 'in':
  4434. $parts = explode(',', $value);
  4435. $count = count($parts);
  4436. if ($count > 0) {
  4437. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  4438. $sql = "$column IN ($qmarks)";
  4439. for ($i = 0; $i < $count; $i++) {
  4440. $arguments[] = $parts[$i];
  4441. }
  4442. } else {
  4443. $sql = "FALSE";
  4444. }
  4445. break;
  4446. case 'is':
  4447. $sql = "$column IS NULL";
  4448. break;
  4449. }
  4450. return $sql;
  4451. }
  4452. private function getSpatialFunctionName(string $operator): string
  4453. {
  4454. switch ($operator) {
  4455. case 'co':
  4456. return 'ST_Contains';
  4457. case 'cr':
  4458. return 'ST_Crosses';
  4459. case 'di':
  4460. return 'ST_Disjoint';
  4461. case 'eq':
  4462. return 'ST_Equals';
  4463. case 'in':
  4464. return 'ST_Intersects';
  4465. case 'ov':
  4466. return 'ST_Overlaps';
  4467. case 'to':
  4468. return 'ST_Touches';
  4469. case 'wi':
  4470. return 'ST_Within';
  4471. case 'ic':
  4472. return 'ST_IsClosed';
  4473. case 'is':
  4474. return 'ST_IsSimple';
  4475. case 'iv':
  4476. return 'ST_IsValid';
  4477. }
  4478. }
  4479. private function hasSpatialArgument(string $operator): bool
  4480. {
  4481. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  4482. }
  4483. private function getSpatialFunctionCall(string $functionName, string $column, bool $hasArgument): string
  4484. {
  4485. switch ($this->driver) {
  4486. case 'mysql':
  4487. case 'pgsql':
  4488. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  4489. return "$functionName($column, $argument)=TRUE";
  4490. case 'sqlsrv':
  4491. $functionName = str_replace('ST_', 'ST', $functionName);
  4492. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  4493. return "$column.$functionName($argument)=1";
  4494. case 'sqlite':
  4495. $argument = $hasArgument ? '?' : '0';
  4496. return "$functionName($column, $argument)=1";
  4497. }
  4498. }
  4499. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): string
  4500. {
  4501. $column = $this->quoteColumnName($condition->getColumn());
  4502. $operator = $condition->getOperator();
  4503. $value = $condition->getValue();
  4504. $functionName = $this->getSpatialFunctionName($operator);
  4505. $hasArgument = $this->hasSpatialArgument($operator);
  4506. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  4507. if ($hasArgument) {
  4508. $arguments[] = $value;
  4509. }
  4510. return $sql;
  4511. }
  4512. public function getWhereClause(Condition $condition, array &$arguments): string
  4513. {
  4514. if ($condition instanceof NoCondition) {
  4515. return '';
  4516. }
  4517. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  4518. }
  4519. }
  4520. }
  4521. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  4522. namespace Tqdev\PhpCrudApi\Database {
  4523. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4524. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4525. class DataConverter
  4526. {
  4527. private $driver;
  4528. public function __construct(string $driver)
  4529. {
  4530. $this->driver = $driver;
  4531. }
  4532. private function convertRecordValue($conversion, $value)
  4533. {
  4534. switch ($conversion) {
  4535. case 'boolean':
  4536. return $value ? true : false;
  4537. case 'integer':
  4538. return (int) $value;
  4539. }
  4540. return $value;
  4541. }
  4542. private function getRecordValueConversion(ReflectedColumn $column): string
  4543. {
  4544. if (in_array($this->driver, ['mysql', 'sqlsrv', 'sqlite']) && $column->isBoolean()) {
  4545. return 'boolean';
  4546. }
  4547. if (in_array($this->driver, ['sqlsrv', 'sqlite']) && in_array($column->getType(), ['integer', 'bigint'])) {
  4548. return 'integer';
  4549. }
  4550. return 'none';
  4551. }
  4552. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  4553. {
  4554. foreach ($columnNames as $columnName) {
  4555. $column = $table->getColumn($columnName);
  4556. $conversion = $this->getRecordValueConversion($column);
  4557. if ($conversion != 'none') {
  4558. foreach ($records as $i => $record) {
  4559. $value = $records[$i][$columnName];
  4560. if ($value === null) {
  4561. continue;
  4562. }
  4563. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  4564. }
  4565. }
  4566. }
  4567. }
  4568. private function convertInputValue($conversion, $value)
  4569. {
  4570. switch ($conversion) {
  4571. case 'boolean':
  4572. return $value ? 1 : 0;
  4573. case 'base64url_to_base64':
  4574. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  4575. }
  4576. return $value;
  4577. }
  4578. private function getInputValueConversion(ReflectedColumn $column): string
  4579. {
  4580. if ($column->isBoolean()) {
  4581. return 'boolean';
  4582. }
  4583. if ($column->isBinary()) {
  4584. return 'base64url_to_base64';
  4585. }
  4586. return 'none';
  4587. }
  4588. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  4589. {
  4590. $columnNames = array_keys($columnValues);
  4591. foreach ($columnNames as $columnName) {
  4592. $column = $table->getColumn($columnName);
  4593. $conversion = $this->getInputValueConversion($column);
  4594. if ($conversion != 'none') {
  4595. $value = $columnValues[$columnName];
  4596. if ($value !== null) {
  4597. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  4598. }
  4599. }
  4600. }
  4601. }
  4602. }
  4603. }
  4604. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  4605. namespace Tqdev\PhpCrudApi\Database {
  4606. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4607. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  4608. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4609. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4610. class GenericDB
  4611. {
  4612. private $driver;
  4613. private $address;
  4614. private $port;
  4615. private $database;
  4616. private $tables;
  4617. private $username;
  4618. private $password;
  4619. private $pdo;
  4620. private $reflection;
  4621. private $definition;
  4622. private $conditions;
  4623. private $columns;
  4624. private $converter;
  4625. private function getDsn(): string
  4626. {
  4627. switch ($this->driver) {
  4628. case 'mysql':
  4629. return "$this->driver:host=$this->address;port=$this->port;dbname=$this->database;charset=utf8mb4";
  4630. case 'pgsql':
  4631. return "$this->driver:host=$this->address port=$this->port dbname=$this->database options='--client_encoding=UTF8'";
  4632. case 'sqlsrv':
  4633. return "$this->driver:Server=$this->address,$this->port;Database=$this->database";
  4634. case 'sqlite':
  4635. return "$this->driver:$this->address";
  4636. }
  4637. }
  4638. private function getCommands(): array
  4639. {
  4640. switch ($this->driver) {
  4641. case 'mysql':
  4642. return [
  4643. 'SET SESSION sql_warnings=1;',
  4644. 'SET NAMES utf8mb4;',
  4645. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  4646. ];
  4647. case 'pgsql':
  4648. return [
  4649. "SET NAMES 'UTF8';",
  4650. ];
  4651. case 'sqlsrv':
  4652. return [];
  4653. case 'sqlite':
  4654. return [
  4655. 'PRAGMA foreign_keys = on;',
  4656. ];
  4657. }
  4658. }
  4659. private function getOptions(): array
  4660. {
  4661. $options = array(
  4662. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  4663. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  4664. );
  4665. switch ($this->driver) {
  4666. case 'mysql':
  4667. return $options + [
  4668. \PDO::ATTR_EMULATE_PREPARES => false,
  4669. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  4670. \PDO::ATTR_PERSISTENT => true,
  4671. ];
  4672. case 'pgsql':
  4673. return $options + [
  4674. \PDO::ATTR_EMULATE_PREPARES => false,
  4675. \PDO::ATTR_PERSISTENT => true,
  4676. ];
  4677. case 'sqlsrv':
  4678. return $options + [
  4679. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  4680. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  4681. ];
  4682. case 'sqlite':
  4683. return $options + [];
  4684. }
  4685. }
  4686. private function initPdo(): bool
  4687. {
  4688. if ($this->pdo) {
  4689. $result = $this->pdo->reconstruct($this->getDsn(), $this->username, $this->password, $this->getOptions());
  4690. } else {
  4691. $this->pdo = new LazyPdo($this->getDsn(), $this->username, $this->password, $this->getOptions());
  4692. $result = true;
  4693. }
  4694. $commands = $this->getCommands();
  4695. foreach ($commands as $command) {
  4696. $this->pdo->addInitCommand($command);
  4697. }
  4698. $this->reflection = new GenericReflection($this->pdo, $this->driver, $this->database, $this->tables);
  4699. $this->definition = new GenericDefinition($this->pdo, $this->driver, $this->database, $this->tables);
  4700. $this->conditions = new ConditionsBuilder($this->driver);
  4701. $this->columns = new ColumnsBuilder($this->driver);
  4702. $this->converter = new DataConverter($this->driver);
  4703. return $result;
  4704. }
  4705. public function __construct(string $driver, string $address, int $port, string $database, array $tables, string $username, string $password)
  4706. {
  4707. $this->driver = $driver;
  4708. $this->address = $address;
  4709. $this->port = $port;
  4710. $this->database = $database;
  4711. $this->tables = $tables;
  4712. $this->username = $username;
  4713. $this->password = $password;
  4714. $this->initPdo();
  4715. }
  4716. public function reconstruct(string $driver, string $address, int $port, string $database, array $tables, string $username, string $password): bool
  4717. {
  4718. if ($driver) {
  4719. $this->driver = $driver;
  4720. }
  4721. if ($address) {
  4722. $this->address = $address;
  4723. }
  4724. if ($port) {
  4725. $this->port = $port;
  4726. }
  4727. if ($database) {
  4728. $this->database = $database;
  4729. }
  4730. if ($tables) {
  4731. $this->tables = $tables;
  4732. }
  4733. if ($username) {
  4734. $this->username = $username;
  4735. }
  4736. if ($password) {
  4737. $this->password = $password;
  4738. }
  4739. return $this->initPdo();
  4740. }
  4741. public function pdo(): LazyPdo
  4742. {
  4743. return $this->pdo;
  4744. }
  4745. public function reflection(): GenericReflection
  4746. {
  4747. return $this->reflection;
  4748. }
  4749. public function definition(): GenericDefinition
  4750. {
  4751. return $this->definition;
  4752. }
  4753. private function addMiddlewareConditions(string $tableName, Condition $condition): Condition
  4754. {
  4755. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  4756. if ($condition1) {
  4757. $condition = $condition->_and($condition1);
  4758. }
  4759. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  4760. if ($condition2) {
  4761. $condition = $condition->_and($condition2);
  4762. }
  4763. return $condition;
  4764. }
  4765. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  4766. {
  4767. $this->converter->convertColumnValues($table, $columnValues);
  4768. $insertColumns = $this->columns->getInsert($table, $columnValues);
  4769. $tableName = $table->getName();
  4770. $pkName = $table->getPk()->getName();
  4771. $parameters = array_values($columnValues);
  4772. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  4773. $stmt = $this->query($sql, $parameters);
  4774. // return primary key value if specified in the input
  4775. if (isset($columnValues[$pkName])) {
  4776. return $columnValues[$pkName];
  4777. }
  4778. // work around missing "returning" or "output" in mysql
  4779. switch ($this->driver) {
  4780. case 'mysql':
  4781. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  4782. break;
  4783. case 'sqlite':
  4784. $stmt = $this->query('SELECT LAST_INSERT_ROWID()', []);
  4785. break;
  4786. }
  4787. $pkValue = $stmt->fetchColumn(0);
  4788. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  4789. return (int) $pkValue;
  4790. }
  4791. if ($this->driver == 'sqlite' && in_array($table->getPk()->getType(), ['integer', 'bigint'])) {
  4792. return (int) $pkValue;
  4793. }
  4794. return $pkValue;
  4795. }
  4796. public function selectSingle(ReflectedTable $table, array $columnNames, string $id) /*: ?array*/
  4797. {
  4798. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4799. $tableName = $table->getName();
  4800. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4801. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4802. $parameters = array();
  4803. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4804. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4805. $stmt = $this->query($sql, $parameters);
  4806. $record = $stmt->fetch() ?: null;
  4807. if ($record === null) {
  4808. return null;
  4809. }
  4810. $records = array($record);
  4811. $this->converter->convertRecords($table, $columnNames, $records);
  4812. return $records[0];
  4813. }
  4814. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  4815. {
  4816. if (count($ids) == 0) {
  4817. return [];
  4818. }
  4819. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4820. $tableName = $table->getName();
  4821. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  4822. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4823. $parameters = array();
  4824. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4825. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4826. $stmt = $this->query($sql, $parameters);
  4827. $records = $stmt->fetchAll();
  4828. $this->converter->convertRecords($table, $columnNames, $records);
  4829. return $records;
  4830. }
  4831. public function selectCount(ReflectedTable $table, Condition $condition): int
  4832. {
  4833. $tableName = $table->getName();
  4834. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4835. $parameters = array();
  4836. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4837. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  4838. $stmt = $this->query($sql, $parameters);
  4839. return $stmt->fetchColumn(0);
  4840. }
  4841. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  4842. {
  4843. if ($limit == 0) {
  4844. return array();
  4845. }
  4846. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4847. $tableName = $table->getName();
  4848. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4849. $parameters = array();
  4850. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4851. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  4852. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  4853. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  4854. $stmt = $this->query($sql, $parameters);
  4855. $records = $stmt->fetchAll();
  4856. $this->converter->convertRecords($table, $columnNames, $records);
  4857. return $records;
  4858. }
  4859. public function updateSingle(ReflectedTable $table, array $columnValues, string $id)
  4860. {
  4861. if (count($columnValues) == 0) {
  4862. return 0;
  4863. }
  4864. $this->converter->convertColumnValues($table, $columnValues);
  4865. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  4866. $tableName = $table->getName();
  4867. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4868. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4869. $parameters = array_values($columnValues);
  4870. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4871. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4872. $stmt = $this->query($sql, $parameters);
  4873. return $stmt->rowCount();
  4874. }
  4875. public function deleteSingle(ReflectedTable $table, string $id)
  4876. {
  4877. $tableName = $table->getName();
  4878. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4879. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4880. $parameters = array();
  4881. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4882. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  4883. $stmt = $this->query($sql, $parameters);
  4884. return $stmt->rowCount();
  4885. }
  4886. public function incrementSingle(ReflectedTable $table, array $columnValues, string $id)
  4887. {
  4888. if (count($columnValues) == 0) {
  4889. return 0;
  4890. }
  4891. $this->converter->convertColumnValues($table, $columnValues);
  4892. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  4893. $tableName = $table->getName();
  4894. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4895. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4896. $parameters = array_values($columnValues);
  4897. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4898. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4899. $stmt = $this->query($sql, $parameters);
  4900. return $stmt->rowCount();
  4901. }
  4902. private function query(string $sql, array $parameters): \PDOStatement
  4903. {
  4904. $stmt = $this->pdo->prepare($sql);
  4905. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  4906. $stmt->execute($parameters);
  4907. return $stmt;
  4908. }
  4909. public function getCacheKey(): string
  4910. {
  4911. return md5(json_encode([
  4912. $this->driver,
  4913. $this->address,
  4914. $this->port,
  4915. $this->database,
  4916. $this->tables,
  4917. $this->username
  4918. ]));
  4919. }
  4920. }
  4921. }
  4922. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  4923. namespace Tqdev\PhpCrudApi\Database {
  4924. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4925. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4926. use Tqdev\PhpCrudApi\Database\LazyPdo;
  4927. class GenericDefinition
  4928. {
  4929. private $pdo;
  4930. private $driver;
  4931. private $database;
  4932. private $typeConverter;
  4933. private $reflection;
  4934. public function __construct(LazyPdo $pdo, string $driver, string $database, array $tables)
  4935. {
  4936. $this->pdo = $pdo;
  4937. $this->driver = $driver;
  4938. $this->database = $database;
  4939. $this->typeConverter = new TypeConverter($driver);
  4940. $this->reflection = new GenericReflection($pdo, $driver, $database, $tables);
  4941. }
  4942. private function quote(string $identifier): string
  4943. {
  4944. return '"' . str_replace('"', '', $identifier) . '"';
  4945. }
  4946. public function getColumnType(ReflectedColumn $column, bool $update): string
  4947. {
  4948. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  4949. return 'serial';
  4950. }
  4951. $type = $this->typeConverter->fromJdbc($column->getType());
  4952. if ($column->hasPrecision() && $column->hasScale()) {
  4953. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  4954. } elseif ($column->hasPrecision()) {
  4955. $size = '(' . $column->getPrecision() . ')';
  4956. } elseif ($column->hasLength()) {
  4957. $size = '(' . $column->getLength() . ')';
  4958. } else {
  4959. $size = '';
  4960. }
  4961. $null = $this->getColumnNullType($column, $update);
  4962. $auto = $this->getColumnAutoIncrement($column, $update);
  4963. return $type . $size . $null . $auto;
  4964. }
  4965. private function getPrimaryKey(string $tableName): string
  4966. {
  4967. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  4968. if (count($pks) == 1) {
  4969. return $pks[0];
  4970. }
  4971. return "";
  4972. }
  4973. private function canAutoIncrement(ReflectedColumn $column): bool
  4974. {
  4975. return in_array($column->getType(), ['integer', 'bigint']);
  4976. }
  4977. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): string
  4978. {
  4979. if (!$this->canAutoIncrement($column)) {
  4980. return '';
  4981. }
  4982. switch ($this->driver) {
  4983. case 'mysql':
  4984. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  4985. case 'pgsql':
  4986. case 'sqlsrv':
  4987. return '';
  4988. case 'sqlite':
  4989. return $column->getPk() ? ' AUTOINCREMENT' : '';
  4990. }
  4991. }
  4992. private function getColumnNullType(ReflectedColumn $column, bool $update): string
  4993. {
  4994. if ($this->driver == 'pgsql' && $update) {
  4995. return '';
  4996. }
  4997. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  4998. }
  4999. private function getTableRenameSQL(string $tableName, string $newTableName): string
  5000. {
  5001. $p1 = $this->quote($tableName);
  5002. $p2 = $this->quote($newTableName);
  5003. switch ($this->driver) {
  5004. case 'mysql':
  5005. return "RENAME TABLE $p1 TO $p2";
  5006. case 'pgsql':
  5007. return "ALTER TABLE $p1 RENAME TO $p2";
  5008. case 'sqlsrv':
  5009. return "EXEC sp_rename $p1, $p2";
  5010. case 'sqlite':
  5011. return "ALTER TABLE $p1 RENAME TO $p2";
  5012. }
  5013. }
  5014. private function getColumnRenameSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5015. {
  5016. $p1 = $this->quote($tableName);
  5017. $p2 = $this->quote($columnName);
  5018. $p3 = $this->quote($newColumn->getName());
  5019. switch ($this->driver) {
  5020. case 'mysql':
  5021. $p4 = $this->getColumnType($newColumn, true);
  5022. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5023. case 'pgsql':
  5024. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  5025. case 'sqlsrv':
  5026. $p4 = $this->quote($tableName . '.' . $columnName);
  5027. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  5028. case 'sqlite':
  5029. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  5030. }
  5031. }
  5032. private function getColumnRetypeSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5033. {
  5034. $p1 = $this->quote($tableName);
  5035. $p2 = $this->quote($columnName);
  5036. $p3 = $this->quote($newColumn->getName());
  5037. $p4 = $this->getColumnType($newColumn, true);
  5038. switch ($this->driver) {
  5039. case 'mysql':
  5040. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5041. case 'pgsql':
  5042. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  5043. case 'sqlsrv':
  5044. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  5045. }
  5046. }
  5047. private function getSetColumnNullableSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5048. {
  5049. $p1 = $this->quote($tableName);
  5050. $p2 = $this->quote($columnName);
  5051. $p3 = $this->quote($newColumn->getName());
  5052. $p4 = $this->getColumnType($newColumn, true);
  5053. switch ($this->driver) {
  5054. case 'mysql':
  5055. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5056. case 'pgsql':
  5057. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  5058. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  5059. case 'sqlsrv':
  5060. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  5061. }
  5062. }
  5063. private function getSetColumnPkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5064. {
  5065. $p1 = $this->quote($tableName);
  5066. $p2 = $this->quote($columnName);
  5067. $p3 = $this->quote($tableName . '_pkey');
  5068. switch ($this->driver) {
  5069. case 'mysql':
  5070. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  5071. return "ALTER TABLE $p1 $p4";
  5072. case 'pgsql':
  5073. case 'sqlsrv':
  5074. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  5075. return "ALTER TABLE $p1 $p4";
  5076. }
  5077. }
  5078. private function getSetColumnPkSequenceSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5079. {
  5080. $p1 = $this->quote($tableName);
  5081. $p2 = $this->quote($columnName);
  5082. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  5083. switch ($this->driver) {
  5084. case 'mysql':
  5085. return "select 1";
  5086. case 'pgsql':
  5087. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  5088. case 'sqlsrv':
  5089. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  5090. }
  5091. }
  5092. private function getSetColumnPkSequenceStartSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5093. {
  5094. $p1 = $this->quote($tableName);
  5095. $p2 = $this->quote($columnName);
  5096. switch ($this->driver) {
  5097. case 'mysql':
  5098. return "select 1";
  5099. case 'pgsql':
  5100. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  5101. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  5102. case 'sqlsrv':
  5103. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  5104. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  5105. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  5106. }
  5107. }
  5108. private function getSetColumnPkDefaultSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5109. {
  5110. $p1 = $this->quote($tableName);
  5111. $p2 = $this->quote($columnName);
  5112. switch ($this->driver) {
  5113. case 'mysql':
  5114. $p3 = $this->quote($newColumn->getName());
  5115. $p4 = $this->getColumnType($newColumn, true);
  5116. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5117. case 'pgsql':
  5118. if ($newColumn->getPk()) {
  5119. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  5120. $p4 = "SET DEFAULT nextval($p3)";
  5121. } else {
  5122. $p4 = 'DROP DEFAULT';
  5123. }
  5124. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  5125. case 'sqlsrv':
  5126. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  5127. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  5128. if ($newColumn->getPk()) {
  5129. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  5130. } else {
  5131. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  5132. }
  5133. }
  5134. }
  5135. private function getAddColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5136. {
  5137. $p1 = $this->quote($tableName);
  5138. $p2 = $this->quote($columnName);
  5139. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5140. $p4 = $this->quote($newColumn->getFk());
  5141. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  5142. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  5143. }
  5144. private function getRemoveColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5145. {
  5146. $p1 = $this->quote($tableName);
  5147. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5148. switch ($this->driver) {
  5149. case 'mysql':
  5150. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  5151. case 'pgsql':
  5152. case 'sqlsrv':
  5153. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  5154. }
  5155. }
  5156. private function getAddTableSQL(ReflectedTable $newTable): string
  5157. {
  5158. $tableName = $newTable->getName();
  5159. $p1 = $this->quote($tableName);
  5160. $fields = [];
  5161. $constraints = [];
  5162. foreach ($newTable->getColumnNames() as $columnName) {
  5163. $pkColumn = $this->getPrimaryKey($tableName);
  5164. $newColumn = $newTable->getColumn($columnName);
  5165. $f1 = $this->quote($columnName);
  5166. $f2 = $this->getColumnType($newColumn, false);
  5167. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5168. $f4 = $this->quote($newColumn->getFk());
  5169. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  5170. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  5171. if ($this->driver == 'sqlite') {
  5172. if ($newColumn->getPk()) {
  5173. $f2 = str_replace('NULL', 'NULL PRIMARY KEY', $f2);
  5174. }
  5175. $fields[] = "$f1 $f2";
  5176. if ($newColumn->getFk()) {
  5177. $constraints[] = "FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  5178. }
  5179. } else {
  5180. $fields[] = "$f1 $f2";
  5181. if ($newColumn->getPk()) {
  5182. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  5183. }
  5184. if ($newColumn->getFk()) {
  5185. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  5186. }
  5187. }
  5188. }
  5189. $p2 = implode(',', array_merge($fields, $constraints));
  5190. return "CREATE TABLE $p1 ($p2);";
  5191. }
  5192. private function getAddColumnSQL(string $tableName, ReflectedColumn $newColumn): string
  5193. {
  5194. $p1 = $this->quote($tableName);
  5195. $p2 = $this->quote($newColumn->getName());
  5196. $p3 = $this->getColumnType($newColumn, false);
  5197. switch ($this->driver) {
  5198. case 'mysql':
  5199. case 'pgsql':
  5200. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  5201. case 'sqlsrv':
  5202. return "ALTER TABLE $p1 ADD $p2 $p3";
  5203. case 'sqlite':
  5204. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  5205. }
  5206. }
  5207. private function getRemoveTableSQL(string $tableName): string
  5208. {
  5209. $p1 = $this->quote($tableName);
  5210. switch ($this->driver) {
  5211. case 'mysql':
  5212. case 'pgsql':
  5213. return "DROP TABLE $p1 CASCADE;";
  5214. case 'sqlsrv':
  5215. return "DROP TABLE $p1;";
  5216. case 'sqlite':
  5217. return "DROP TABLE $p1;";
  5218. }
  5219. }
  5220. private function getRemoveColumnSQL(string $tableName, string $columnName): string
  5221. {
  5222. $p1 = $this->quote($tableName);
  5223. $p2 = $this->quote($columnName);
  5224. switch ($this->driver) {
  5225. case 'mysql':
  5226. case 'pgsql':
  5227. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  5228. case 'sqlsrv':
  5229. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  5230. case 'sqlite':
  5231. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  5232. }
  5233. }
  5234. public function renameTable(string $tableName, string $newTableName)
  5235. {
  5236. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  5237. return $this->query($sql, []);
  5238. }
  5239. public function renameColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5240. {
  5241. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  5242. return $this->query($sql, []);
  5243. }
  5244. public function retypeColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5245. {
  5246. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  5247. return $this->query($sql, []);
  5248. }
  5249. public function setColumnNullable(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5250. {
  5251. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  5252. return $this->query($sql, []);
  5253. }
  5254. public function addColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5255. {
  5256. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5257. $this->query($sql, []);
  5258. if ($this->canAutoIncrement($newColumn)) {
  5259. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5260. $this->query($sql, []);
  5261. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  5262. $this->query($sql, []);
  5263. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5264. $this->query($sql, []);
  5265. }
  5266. return true;
  5267. }
  5268. public function removeColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5269. {
  5270. if ($this->canAutoIncrement($newColumn)) {
  5271. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5272. $this->query($sql, []);
  5273. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5274. $this->query($sql, []);
  5275. }
  5276. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5277. $this->query($sql, []);
  5278. return true;
  5279. }
  5280. public function addColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5281. {
  5282. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5283. return $this->query($sql, []);
  5284. }
  5285. public function removeColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5286. {
  5287. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5288. return $this->query($sql, []);
  5289. }
  5290. public function addTable(ReflectedTable $newTable)
  5291. {
  5292. $sql = $this->getAddTableSQL($newTable);
  5293. return $this->query($sql, []);
  5294. }
  5295. public function addColumn(string $tableName, ReflectedColumn $newColumn)
  5296. {
  5297. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  5298. return $this->query($sql, []);
  5299. }
  5300. public function removeTable(string $tableName)
  5301. {
  5302. $sql = $this->getRemoveTableSQL($tableName);
  5303. return $this->query($sql, []);
  5304. }
  5305. public function removeColumn(string $tableName, string $columnName)
  5306. {
  5307. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  5308. return $this->query($sql, []);
  5309. }
  5310. private function query(string $sql, array $arguments): bool
  5311. {
  5312. $stmt = $this->pdo->prepare($sql);
  5313. //echo "- $sql -- " . json_encode($arguments) . "\n";
  5314. return $stmt->execute($arguments);
  5315. }
  5316. }
  5317. }
  5318. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  5319. namespace Tqdev\PhpCrudApi\Database {
  5320. use Tqdev\PhpCrudApi\Database\LazyPdo;
  5321. class GenericReflection
  5322. {
  5323. private $pdo;
  5324. private $driver;
  5325. private $database;
  5326. private $tables;
  5327. private $typeConverter;
  5328. public function __construct(LazyPdo $pdo, string $driver, string $database, array $tables)
  5329. {
  5330. $this->pdo = $pdo;
  5331. $this->driver = $driver;
  5332. $this->database = $database;
  5333. $this->tables = $tables;
  5334. $this->typeConverter = new TypeConverter($driver);
  5335. }
  5336. public function getIgnoredTables(): array
  5337. {
  5338. switch ($this->driver) {
  5339. case 'mysql':
  5340. return [];
  5341. case 'pgsql':
  5342. return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  5343. case 'sqlsrv':
  5344. return [];
  5345. case 'sqlite':
  5346. return [];
  5347. }
  5348. }
  5349. private function getTablesSQL(): string
  5350. {
  5351. switch ($this->driver) {
  5352. case 'mysql':
  5353. 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"';
  5354. case 'pgsql':
  5355. 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";';
  5356. case 'sqlsrv':
  5357. 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"';
  5358. case 'sqlite':
  5359. return 'SELECT t.name as "TABLE_NAME", t.type as "TABLE_TYPE" FROM sqlite_master t WHERE t.type IN (\'table\', \'view\') AND \'\' <> ? ORDER BY "TABLE_NAME"';
  5360. }
  5361. }
  5362. private function getTableColumnsSQL(): string
  5363. {
  5364. switch ($this->driver) {
  5365. case 'mysql':
  5366. return 'SELECT "COLUMN_NAME", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH" as "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ? ORDER BY "ORDINAL_POSITION"';
  5367. case 'pgsql':
  5368. 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", \'\' AS "COLUMN_TYPE" 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 ORDER BY a.attnum;';
  5369. case 'sqlsrv':
  5370. 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", \'\' AS "COLUMN_TYPE" 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 \'\' <> ? ORDER BY c.column_id';
  5371. case 'sqlite':
  5372. return 'SELECT "name" AS "COLUMN_NAME", case when "notnull"==1 then \'no\' else \'yes\' end as "IS_NULLABLE", lower("type") AS "DATA_TYPE", 2147483647 AS "CHARACTER_MAXIMUM_LENGTH", 0 AS "NUMERIC_PRECISION", 0 AS "NUMERIC_SCALE", \'\' AS "COLUMN_TYPE" FROM pragma_table_info(?) WHERE \'\' <> ? ORDER BY "cid"';
  5373. }
  5374. }
  5375. private function getTablePrimaryKeysSQL(): string
  5376. {
  5377. switch ($this->driver) {
  5378. case 'mysql':
  5379. return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5380. case 'pgsql':
  5381. 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\'';
  5382. case 'sqlsrv':
  5383. 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 \'\' <> ?';
  5384. case 'sqlite':
  5385. return 'SELECT "name" as "COLUMN_NAME" FROM pragma_table_info(?) WHERE "pk"=1 AND \'\' <> ?';
  5386. }
  5387. }
  5388. private function getTableForeignKeysSQL(): string
  5389. {
  5390. switch ($this->driver) {
  5391. case 'mysql':
  5392. 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" = ?';
  5393. case 'pgsql':
  5394. 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\'';
  5395. case 'sqlsrv':
  5396. 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 \'\' <> ?';
  5397. case 'sqlite':
  5398. return 'SELECT "from" AS "COLUMN_NAME", "table" AS "REFERENCED_TABLE_NAME" FROM pragma_foreign_key_list(?) WHERE \'\' <> ?';
  5399. }
  5400. }
  5401. public function getDatabaseName(): string
  5402. {
  5403. return $this->database;
  5404. }
  5405. public function getTables(): array
  5406. {
  5407. $sql = $this->getTablesSQL();
  5408. $results = $this->query($sql, [$this->database]);
  5409. $tables = $this->tables;
  5410. $results = array_filter($results, function ($v) use ($tables) {
  5411. return !$tables || in_array($v['TABLE_NAME'], $tables);
  5412. });
  5413. foreach ($results as &$result) {
  5414. $map = [];
  5415. switch ($this->driver) {
  5416. case 'mysql':
  5417. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  5418. break;
  5419. case 'pgsql':
  5420. $map = ['r' => 'table', 'v' => 'view'];
  5421. break;
  5422. case 'sqlsrv':
  5423. $map = ['U' => 'table', 'V' => 'view'];
  5424. break;
  5425. case 'sqlite':
  5426. $map = ['table' => 'table', 'view' => 'view'];
  5427. break;
  5428. }
  5429. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  5430. }
  5431. return $results;
  5432. }
  5433. public function getTableColumns(string $tableName, string $type): array
  5434. {
  5435. $sql = $this->getTableColumnsSQL();
  5436. $results = $this->query($sql, [$tableName, $this->database]);
  5437. if ($type == 'view') {
  5438. foreach ($results as &$result) {
  5439. $result['IS_NULLABLE'] = false;
  5440. }
  5441. }
  5442. if ($this->driver == 'mysql') {
  5443. foreach ($results as &$result) {
  5444. // mysql does not properly reflect display width of types
  5445. preg_match('|([a-z]+)(\(([0-9]+)(,([0-9]+))?\))?|', $result['DATA_TYPE'], $matches);
  5446. $result['DATA_TYPE'] = $matches[1];
  5447. if (!$result['CHARACTER_MAXIMUM_LENGTH']) {
  5448. if (isset($matches[3])) {
  5449. $result['NUMERIC_PRECISION'] = $matches[3];
  5450. }
  5451. if (isset($matches[5])) {
  5452. $result['NUMERIC_SCALE'] = $matches[5];
  5453. }
  5454. }
  5455. }
  5456. }
  5457. if ($this->driver == 'sqlite') {
  5458. foreach ($results as &$result) {
  5459. // sqlite does not properly reflect display width of types
  5460. preg_match('|([a-z]+)(\(([0-9]+)(,([0-9]+))?\))?|', $result['DATA_TYPE'], $matches);
  5461. if (isset($matches[1])) {
  5462. $result['DATA_TYPE'] = $matches[1];
  5463. } else {
  5464. $result['DATA_TYPE'] = 'integer';
  5465. }
  5466. if (isset($matches[5])) {
  5467. $result['NUMERIC_PRECISION'] = $matches[3];
  5468. $result['NUMERIC_SCALE'] = $matches[5];
  5469. } else if (isset($matches[3])) {
  5470. $result['CHARACTER_MAXIMUM_LENGTH'] = $matches[3];
  5471. }
  5472. }
  5473. }
  5474. return $results;
  5475. }
  5476. public function getTablePrimaryKeys(string $tableName): array
  5477. {
  5478. $sql = $this->getTablePrimaryKeysSQL();
  5479. $results = $this->query($sql, [$tableName, $this->database]);
  5480. $primaryKeys = [];
  5481. foreach ($results as $result) {
  5482. $primaryKeys[] = $result['COLUMN_NAME'];
  5483. }
  5484. return $primaryKeys;
  5485. }
  5486. public function getTableForeignKeys(string $tableName): array
  5487. {
  5488. $sql = $this->getTableForeignKeysSQL();
  5489. $results = $this->query($sql, [$tableName, $this->database]);
  5490. $foreignKeys = [];
  5491. foreach ($results as $result) {
  5492. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  5493. }
  5494. return $foreignKeys;
  5495. }
  5496. public function toJdbcType(string $type, string $size): string
  5497. {
  5498. return $this->typeConverter->toJdbc($type, $size);
  5499. }
  5500. private function query(string $sql, array $parameters): array
  5501. {
  5502. $stmt = $this->pdo->prepare($sql);
  5503. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  5504. $stmt->execute($parameters);
  5505. return $stmt->fetchAll();
  5506. }
  5507. }
  5508. }
  5509. // file: src/Tqdev/PhpCrudApi/Database/LazyPdo.php
  5510. namespace Tqdev\PhpCrudApi\Database {
  5511. class LazyPdo extends \PDO
  5512. {
  5513. private $dsn;
  5514. private $user;
  5515. private $password;
  5516. private $options;
  5517. private $commands;
  5518. private $pdo = null;
  5519. public function __construct(string $dsn, /*?string*/ $user = null, /*?string*/ $password = null, array $options = array())
  5520. {
  5521. $this->dsn = $dsn;
  5522. $this->user = $user;
  5523. $this->password = $password;
  5524. $this->options = $options;
  5525. $this->commands = array();
  5526. // explicitly NOT calling super::__construct
  5527. }
  5528. public function addInitCommand(string $command)/*: void*/
  5529. {
  5530. $this->commands[] = $command;
  5531. }
  5532. private function pdo()
  5533. {
  5534. if (!$this->pdo) {
  5535. $this->pdo = new \PDO($this->dsn, $this->user, $this->password, $this->options);
  5536. foreach ($this->commands as $command) {
  5537. $this->pdo->query($command);
  5538. }
  5539. }
  5540. return $this->pdo;
  5541. }
  5542. public function reconstruct(string $dsn, /*?string*/ $user = null, /*?string*/ $password = null, array $options = array()): bool
  5543. {
  5544. $this->dsn = $dsn;
  5545. $this->user = $user;
  5546. $this->password = $password;
  5547. $this->options = $options;
  5548. $this->commands = array();
  5549. if ($this->pdo) {
  5550. $this->pdo = null;
  5551. return true;
  5552. }
  5553. return false;
  5554. }
  5555. public function inTransaction(): bool
  5556. {
  5557. // Do not call parent method if there is no pdo object
  5558. return $this->pdo && parent::inTransaction();
  5559. }
  5560. public function setAttribute($attribute, $value): bool
  5561. {
  5562. if ($this->pdo) {
  5563. return $this->pdo()->setAttribute($attribute, $value);
  5564. }
  5565. $this->options[$attribute] = $value;
  5566. return true;
  5567. }
  5568. public function getAttribute($attribute): mixed
  5569. {
  5570. return $this->pdo()->getAttribute($attribute);
  5571. }
  5572. public function beginTransaction(): bool
  5573. {
  5574. return $this->pdo()->beginTransaction();
  5575. }
  5576. public function commit(): bool
  5577. {
  5578. return $this->pdo()->commit();
  5579. }
  5580. public function rollBack(): bool
  5581. {
  5582. return $this->pdo()->rollBack();
  5583. }
  5584. public function errorCode(): mixed
  5585. {
  5586. return $this->pdo()->errorCode();
  5587. }
  5588. public function errorInfo(): array
  5589. {
  5590. return $this->pdo()->errorInfo();
  5591. }
  5592. public function exec($query): int
  5593. {
  5594. return $this->pdo()->exec($query);
  5595. }
  5596. public function prepare($statement, $options = array())
  5597. {
  5598. return $this->pdo()->prepare($statement, $options);
  5599. }
  5600. public function quote($string, $parameter_type = null): string
  5601. {
  5602. return $this->pdo()->quote($string, $parameter_type);
  5603. }
  5604. public function lastInsertId(/* ?string */$name = null): string
  5605. {
  5606. return $this->pdo()->lastInsertId($name);
  5607. }
  5608. public function query(string $statement): \PDOStatement
  5609. {
  5610. return call_user_func_array(array($this->pdo(), 'query'), func_get_args());
  5611. }
  5612. }
  5613. }
  5614. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  5615. namespace Tqdev\PhpCrudApi\Database {
  5616. class TypeConverter
  5617. {
  5618. private $driver;
  5619. public function __construct(string $driver)
  5620. {
  5621. $this->driver = $driver;
  5622. }
  5623. private $fromJdbc = [
  5624. 'mysql' => [
  5625. 'clob' => 'longtext',
  5626. 'boolean' => 'tinyint',
  5627. 'blob' => 'longblob',
  5628. 'timestamp' => 'datetime',
  5629. ],
  5630. 'pgsql' => [
  5631. 'clob' => 'text',
  5632. 'blob' => 'bytea',
  5633. ],
  5634. 'sqlsrv' => [
  5635. 'boolean' => 'bit',
  5636. 'varchar' => 'nvarchar',
  5637. 'clob' => 'ntext',
  5638. 'blob' => 'image',
  5639. ],
  5640. ];
  5641. private $toJdbc = [
  5642. 'simplified' => [
  5643. 'char' => 'varchar',
  5644. 'longvarchar' => 'clob',
  5645. 'nchar' => 'varchar',
  5646. 'nvarchar' => 'varchar',
  5647. 'longnvarchar' => 'clob',
  5648. 'binary' => 'varbinary',
  5649. 'longvarbinary' => 'blob',
  5650. 'tinyint' => 'integer',
  5651. 'smallint' => 'integer',
  5652. 'real' => 'float',
  5653. 'numeric' => 'decimal',
  5654. 'nclob' => 'clob',
  5655. 'time_with_timezone' => 'time',
  5656. 'timestamp_with_timezone' => 'timestamp',
  5657. ],
  5658. 'mysql' => [
  5659. 'tinyint(1)' => 'boolean',
  5660. 'bit(1)' => 'boolean',
  5661. 'tinyblob' => 'blob',
  5662. 'mediumblob' => 'blob',
  5663. 'longblob' => 'blob',
  5664. 'tinytext' => 'clob',
  5665. 'mediumtext' => 'clob',
  5666. 'longtext' => 'clob',
  5667. 'text' => 'clob',
  5668. 'mediumint' => 'integer',
  5669. 'int' => 'integer',
  5670. 'polygon' => 'geometry',
  5671. 'point' => 'geometry',
  5672. 'datetime' => 'timestamp',
  5673. 'year' => 'integer',
  5674. 'enum' => 'varchar',
  5675. 'set' => 'varchar',
  5676. 'json' => 'clob',
  5677. ],
  5678. 'pgsql' => [
  5679. 'bigserial' => 'bigint',
  5680. 'bit varying' => 'bit',
  5681. 'box' => 'geometry',
  5682. 'bytea' => 'blob',
  5683. 'bpchar' => 'char',
  5684. 'character varying' => 'varchar',
  5685. 'character' => 'char',
  5686. 'cidr' => 'varchar',
  5687. 'circle' => 'geometry',
  5688. 'double precision' => 'double',
  5689. 'inet' => 'integer',
  5690. //'interval [ fields ]'
  5691. 'json' => 'clob',
  5692. 'jsonb' => 'clob',
  5693. 'line' => 'geometry',
  5694. 'lseg' => 'geometry',
  5695. 'macaddr' => 'varchar',
  5696. 'money' => 'decimal',
  5697. 'path' => 'geometry',
  5698. 'point' => 'geometry',
  5699. 'polygon' => 'geometry',
  5700. 'real' => 'float',
  5701. 'serial' => 'integer',
  5702. 'text' => 'clob',
  5703. 'time without time zone' => 'time',
  5704. 'time with time zone' => 'time_with_timezone',
  5705. 'timestamp without time zone' => 'timestamp',
  5706. 'timestamp with time zone' => 'timestamp_with_timezone',
  5707. //'tsquery'=
  5708. //'tsvector'
  5709. //'txid_snapshot'
  5710. 'uuid' => 'char',
  5711. 'xml' => 'clob',
  5712. ],
  5713. // source: https://docs.microsoft.com/en-us/sql/connect/jdbc/using-basic-data-types?view=sql-server-2017
  5714. 'sqlsrv' => [
  5715. 'varbinary()' => 'blob',
  5716. 'bit' => 'boolean',
  5717. 'datetime' => 'timestamp',
  5718. 'datetime2' => 'timestamp',
  5719. 'float' => 'double',
  5720. 'image' => 'blob',
  5721. 'int' => 'integer',
  5722. 'money' => 'decimal',
  5723. 'ntext' => 'clob',
  5724. 'smalldatetime' => 'timestamp',
  5725. 'smallmoney' => 'decimal',
  5726. 'text' => 'clob',
  5727. 'timestamp' => 'binary',
  5728. 'udt' => 'varbinary',
  5729. 'uniqueidentifier' => 'char',
  5730. 'xml' => 'clob',
  5731. ],
  5732. 'sqlite' => [
  5733. 'tinytext' => 'clob',
  5734. 'text' => 'clob',
  5735. 'mediumtext' => 'clob',
  5736. 'longtext' => 'clob',
  5737. 'mediumint' => 'integer',
  5738. 'int' => 'integer',
  5739. 'bigint' => 'bigint',
  5740. 'int2' => 'smallint',
  5741. 'int4' => 'integer',
  5742. 'int8' => 'bigint',
  5743. 'double precision' => 'double',
  5744. 'datetime' => 'timestamp'
  5745. ],
  5746. ];
  5747. // source: https://docs.oracle.com/javase/9/docs/api/java/sql/Types.html
  5748. private $valid = [
  5749. //'array' => true,
  5750. 'bigint' => true,
  5751. 'binary' => true,
  5752. 'bit' => true,
  5753. 'blob' => true,
  5754. 'boolean' => true,
  5755. 'char' => true,
  5756. 'clob' => true,
  5757. //'datalink' => true,
  5758. 'date' => true,
  5759. 'decimal' => true,
  5760. //'distinct' => true,
  5761. 'double' => true,
  5762. 'float' => true,
  5763. 'integer' => true,
  5764. //'java_object' => true,
  5765. 'longnvarchar' => true,
  5766. 'longvarbinary' => true,
  5767. 'longvarchar' => true,
  5768. 'nchar' => true,
  5769. 'nclob' => true,
  5770. //'null' => true,
  5771. 'numeric' => true,
  5772. 'nvarchar' => true,
  5773. //'other' => true,
  5774. 'real' => true,
  5775. //'ref' => true,
  5776. //'ref_cursor' => true,
  5777. //'rowid' => true,
  5778. 'smallint' => true,
  5779. //'sqlxml' => true,
  5780. //'struct' => true,
  5781. 'time' => true,
  5782. 'time_with_timezone' => true,
  5783. 'timestamp' => true,
  5784. 'timestamp_with_timezone' => true,
  5785. 'tinyint' => true,
  5786. 'varbinary' => true,
  5787. 'varchar' => true,
  5788. // extra:
  5789. 'geometry' => true,
  5790. ];
  5791. public function toJdbc(string $type, string $size): string
  5792. {
  5793. $jdbcType = strtolower($type);
  5794. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  5795. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  5796. }
  5797. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  5798. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  5799. }
  5800. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  5801. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  5802. }
  5803. if (!isset($this->valid[$jdbcType])) {
  5804. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  5805. }
  5806. return $jdbcType;
  5807. }
  5808. public function fromJdbc(string $type): string
  5809. {
  5810. $jdbcType = strtolower($type);
  5811. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  5812. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  5813. }
  5814. return $jdbcType;
  5815. }
  5816. }
  5817. }
  5818. // file: src/Tqdev/PhpCrudApi/GeoJson/Feature.php
  5819. namespace Tqdev\PhpCrudApi\GeoJson {
  5820. class Feature implements \JsonSerializable
  5821. {
  5822. private $id;
  5823. private $properties;
  5824. private $geometry;
  5825. public function __construct($id, array $properties, /*?Geometry*/ $geometry)
  5826. {
  5827. $this->id = $id;
  5828. $this->properties = $properties;
  5829. $this->geometry = $geometry;
  5830. }
  5831. public function serialize()
  5832. {
  5833. return [
  5834. 'type' => 'Feature',
  5835. 'id' => $this->id,
  5836. 'properties' => $this->properties,
  5837. 'geometry' => $this->geometry,
  5838. ];
  5839. }
  5840. public function jsonSerialize()
  5841. {
  5842. return $this->serialize();
  5843. }
  5844. }
  5845. }
  5846. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  5847. namespace Tqdev\PhpCrudApi\GeoJson {
  5848. class FeatureCollection implements \JsonSerializable
  5849. {
  5850. private $features;
  5851. private $results;
  5852. public function __construct(array $features, int $results)
  5853. {
  5854. $this->features = $features;
  5855. $this->results = $results;
  5856. }
  5857. public function serialize()
  5858. {
  5859. return [
  5860. 'type' => 'FeatureCollection',
  5861. 'features' => $this->features,
  5862. 'results' => $this->results,
  5863. ];
  5864. }
  5865. public function jsonSerialize()
  5866. {
  5867. return array_filter($this->serialize(), function ($v) {
  5868. return $v !== 0;
  5869. });
  5870. }
  5871. }
  5872. }
  5873. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  5874. namespace Tqdev\PhpCrudApi\GeoJson {
  5875. use Tqdev\PhpCrudApi\Column\ReflectionService;
  5876. use Tqdev\PhpCrudApi\GeoJson\FeatureCollection;
  5877. use Tqdev\PhpCrudApi\Record\RecordService;
  5878. class GeoJsonService
  5879. {
  5880. private $reflection;
  5881. private $records;
  5882. public function __construct(ReflectionService $reflection, RecordService $records)
  5883. {
  5884. $this->reflection = $reflection;
  5885. $this->records = $records;
  5886. }
  5887. public function hasTable(string $table): bool
  5888. {
  5889. return $this->reflection->hasTable($table);
  5890. }
  5891. public function getType(string $table): string
  5892. {
  5893. return $this->reflection->getType($table);
  5894. }
  5895. private function getGeometryColumnName(string $tableName, array &$params): string
  5896. {
  5897. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  5898. $table = $this->reflection->getTable($tableName);
  5899. $geometryColumnName = '';
  5900. foreach ($table->getColumnNames() as $columnName) {
  5901. if ($geometryParam && $geometryParam != $columnName) {
  5902. continue;
  5903. }
  5904. $column = $table->getColumn($columnName);
  5905. if ($column->isGeometry()) {
  5906. $geometryColumnName = $columnName;
  5907. break;
  5908. }
  5909. }
  5910. if ($geometryColumnName) {
  5911. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  5912. }
  5913. return $geometryColumnName;
  5914. }
  5915. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  5916. {
  5917. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  5918. if ($boundingBox) {
  5919. $c = explode(',', $boundingBox);
  5920. if (!isset($params['filter'])) {
  5921. $params['filter'] = array();
  5922. }
  5923. $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]))";
  5924. }
  5925. $tile = isset($params['tile']) ? $params['tile'][0] : '';
  5926. if ($tile) {
  5927. $zxy = explode(',', $tile);
  5928. if (count($zxy) == 3) {
  5929. list($z, $x, $y) = $zxy;
  5930. $c = array();
  5931. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x, $y));
  5932. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x + 1, $y + 1));
  5933. $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]))";
  5934. }
  5935. }
  5936. }
  5937. private function convertTileToLatLonOfUpperLeftCorner($z, $x, $y): array
  5938. {
  5939. $n = pow(2, $z);
  5940. $lon = $x / $n * 360.0 - 180.0;
  5941. $lat = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n))));
  5942. return [$lon, $lat];
  5943. }
  5944. private function convertRecordToFeature(/*object*/$record, string $primaryKeyColumnName, string $geometryColumnName)
  5945. {
  5946. $id = null;
  5947. if ($primaryKeyColumnName) {
  5948. $id = $record[$primaryKeyColumnName];
  5949. }
  5950. $geometry = null;
  5951. if (isset($record[$geometryColumnName])) {
  5952. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  5953. }
  5954. $properties = array_diff_key($record, [$primaryKeyColumnName => true, $geometryColumnName => true]);
  5955. return new Feature($id, $properties, $geometry);
  5956. }
  5957. private function getPrimaryKeyColumnName(string $tableName, array &$params): string
  5958. {
  5959. $primaryKeyColumn = $this->reflection->getTable($tableName)->getPk();
  5960. if (!$primaryKeyColumn) {
  5961. return '';
  5962. }
  5963. $primaryKeyColumnName = $primaryKeyColumn->getName();
  5964. $params['mandatory'][] = $tableName . "." . $primaryKeyColumnName;
  5965. return $primaryKeyColumnName;
  5966. }
  5967. public function _list(string $tableName, array $params): FeatureCollection
  5968. {
  5969. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5970. $this->setBoudingBoxFilter($geometryColumnName, $params);
  5971. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5972. $records = $this->records->_list($tableName, $params);
  5973. $features = array();
  5974. foreach ($records->getRecords() as $record) {
  5975. $features[] = $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5976. }
  5977. return new FeatureCollection($features, $records->getResults());
  5978. }
  5979. public function read(string $tableName, string $id, array $params): Feature
  5980. {
  5981. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5982. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5983. $record = $this->records->read($tableName, $id, $params);
  5984. return $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5985. }
  5986. }
  5987. }
  5988. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  5989. namespace Tqdev\PhpCrudApi\GeoJson {
  5990. class Geometry implements \JsonSerializable
  5991. {
  5992. private $type;
  5993. private $geometry;
  5994. public static $types = [
  5995. "Point",
  5996. "MultiPoint",
  5997. "LineString",
  5998. "MultiLineString",
  5999. "Polygon",
  6000. "MultiPolygon",
  6001. //"GeometryCollection",
  6002. ];
  6003. public function __construct(string $type, array $coordinates)
  6004. {
  6005. $this->type = $type;
  6006. $this->coordinates = $coordinates;
  6007. }
  6008. public static function fromWkt(string $wkt): Geometry
  6009. {
  6010. $bracket = strpos($wkt, '(');
  6011. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  6012. $supported = false;
  6013. foreach (Geometry::$types as $typeName) {
  6014. if (strtoupper($typeName) == $type) {
  6015. $type = $typeName;
  6016. $supported = true;
  6017. }
  6018. }
  6019. if (!$supported) {
  6020. throw new \Exception('Geometry type not supported: ' . $type);
  6021. }
  6022. $coordinates = substr($wkt, $bracket);
  6023. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  6024. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  6025. }
  6026. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  6027. $coordinates = json_decode($coordinates);
  6028. if (!$coordinates) {
  6029. throw new \Exception('Could not decode WKT: ' . $wkt);
  6030. }
  6031. return new Geometry($type, $coordinates);
  6032. }
  6033. public function serialize()
  6034. {
  6035. return [
  6036. 'type' => $this->type,
  6037. 'coordinates' => $this->coordinates,
  6038. ];
  6039. }
  6040. public function jsonSerialize()
  6041. {
  6042. return $this->serialize();
  6043. }
  6044. }
  6045. }
  6046. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  6047. namespace Tqdev\PhpCrudApi\Middleware\Base {
  6048. use Psr\Http\Server\MiddlewareInterface;
  6049. use Tqdev\PhpCrudApi\Controller\Responder;
  6050. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6051. abstract class Middleware implements MiddlewareInterface
  6052. {
  6053. protected $next;
  6054. protected $responder;
  6055. private $properties;
  6056. public function __construct(Router $router, Responder $responder, array $properties)
  6057. {
  6058. $router->load($this);
  6059. $this->responder = $responder;
  6060. $this->properties = $properties;
  6061. }
  6062. protected function getArrayProperty(string $key, string $default): array
  6063. {
  6064. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  6065. }
  6066. protected function getMapProperty(string $key, string $default): array
  6067. {
  6068. $pairs = $this->getArrayProperty($key, $default);
  6069. $result = array();
  6070. foreach ($pairs as $pair) {
  6071. if (strpos($pair, ':')) {
  6072. list($k, $v) = explode(':', $pair, 2);
  6073. $result[trim($k)] = trim($v);
  6074. } else {
  6075. $result[] = trim($pair);
  6076. }
  6077. }
  6078. return $result;
  6079. }
  6080. protected function getProperty(string $key, $default)
  6081. {
  6082. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  6083. }
  6084. }
  6085. }
  6086. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  6087. namespace Tqdev\PhpCrudApi\Middleware\Communication {
  6088. class VariableStore
  6089. {
  6090. public static $values = array();
  6091. public static function get(string $key)
  6092. {
  6093. if (isset(self::$values[$key])) {
  6094. return self::$values[$key];
  6095. }
  6096. return null;
  6097. }
  6098. public static function set(string $key, /* object */ $value)
  6099. {
  6100. self::$values[$key] = $value;
  6101. }
  6102. }
  6103. }
  6104. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  6105. namespace Tqdev\PhpCrudApi\Middleware\Router {
  6106. use Psr\Http\Message\ResponseInterface;
  6107. use Psr\Http\Message\ServerRequestInterface;
  6108. use Psr\Http\Server\RequestHandlerInterface;
  6109. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6110. interface Router extends RequestHandlerInterface
  6111. {
  6112. public function register(string $method, string $path, array $handler);
  6113. public function load(Middleware $middleware);
  6114. public function route(ServerRequestInterface $request): ResponseInterface;
  6115. }
  6116. }
  6117. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  6118. namespace Tqdev\PhpCrudApi\Middleware\Router {
  6119. use Psr\Http\Message\ResponseInterface;
  6120. use Psr\Http\Message\ServerRequestInterface;
  6121. use Tqdev\PhpCrudApi\Cache\Cache;
  6122. use Tqdev\PhpCrudApi\Controller\Responder;
  6123. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6124. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6125. use Tqdev\PhpCrudApi\Record\PathTree;
  6126. use Tqdev\PhpCrudApi\RequestUtils;
  6127. use Tqdev\PhpCrudApi\ResponseUtils;
  6128. class SimpleRouter implements Router
  6129. {
  6130. private $basePath;
  6131. private $responder;
  6132. private $cache;
  6133. private $ttl;
  6134. private $debug;
  6135. private $registration;
  6136. private $routes;
  6137. private $routeHandlers;
  6138. private $middlewares;
  6139. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  6140. {
  6141. $this->basePath = rtrim($this->detectBasePath($basePath), '/');
  6142. $this->responder = $responder;
  6143. $this->cache = $cache;
  6144. $this->ttl = $ttl;
  6145. $this->debug = $debug;
  6146. $this->registration = true;
  6147. $this->routes = $this->loadPathTree();
  6148. $this->routeHandlers = [];
  6149. $this->middlewares = array();
  6150. }
  6151. private function detectBasePath(string $basePath): string
  6152. {
  6153. if ($basePath) {
  6154. return $basePath;
  6155. }
  6156. if (isset($_SERVER['REQUEST_URI'])) {
  6157. $fullPath = urldecode(explode('?', $_SERVER['REQUEST_URI'])[0]);
  6158. if (isset($_SERVER['PATH_INFO'])) {
  6159. $path = $_SERVER['PATH_INFO'];
  6160. if (substr($fullPath, -1 * strlen($path)) == $path) {
  6161. return substr($fullPath, 0, -1 * strlen($path));
  6162. }
  6163. }
  6164. return $fullPath;
  6165. }
  6166. return '/';
  6167. }
  6168. private function loadPathTree(): PathTree
  6169. {
  6170. $data = $this->cache->get('PathTree');
  6171. if ($data != '') {
  6172. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  6173. $this->registration = false;
  6174. } else {
  6175. $tree = new PathTree();
  6176. }
  6177. return $tree;
  6178. }
  6179. public function register(string $method, string $path, array $handler)
  6180. {
  6181. $routeNumber = count($this->routeHandlers);
  6182. $this->routeHandlers[$routeNumber] = $handler;
  6183. if ($this->registration) {
  6184. $path = trim($path, '/');
  6185. $parts = array();
  6186. if ($path) {
  6187. $parts = explode('/', $path);
  6188. }
  6189. array_unshift($parts, $method);
  6190. $this->routes->put($parts, $routeNumber);
  6191. }
  6192. }
  6193. public function load(Middleware $middleware) /*: void*/
  6194. {
  6195. array_push($this->middlewares, $middleware);
  6196. }
  6197. public function route(ServerRequestInterface $request): ResponseInterface
  6198. {
  6199. if ($this->registration) {
  6200. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  6201. $this->cache->set('PathTree', $data, $this->ttl);
  6202. }
  6203. return $this->handle($request);
  6204. }
  6205. private function getRouteNumbers(ServerRequestInterface $request): array
  6206. {
  6207. $method = strtoupper($request->getMethod());
  6208. $path = array();
  6209. $segment = $method;
  6210. for ($i = 1; $segment; $i++) {
  6211. array_push($path, $segment);
  6212. $segment = RequestUtils::getPathSegment($request, $i);
  6213. }
  6214. return $this->routes->match($path);
  6215. }
  6216. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  6217. {
  6218. $path = $request->getUri()->getPath();
  6219. if (substr($path, 0, strlen($this->basePath)) == $this->basePath) {
  6220. $path = substr($path, strlen($this->basePath));
  6221. $request = $request->withUri($request->getUri()->withPath($path));
  6222. }
  6223. return $request;
  6224. }
  6225. public function getBasePath(): string
  6226. {
  6227. return $this->basePath;
  6228. }
  6229. public function handle(ServerRequestInterface $request): ResponseInterface
  6230. {
  6231. $request = $this->removeBasePath($request);
  6232. if (count($this->middlewares)) {
  6233. $handler = array_pop($this->middlewares);
  6234. return $handler->process($request, $this);
  6235. }
  6236. $routeNumbers = $this->getRouteNumbers($request);
  6237. if (count($routeNumbers) == 0) {
  6238. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  6239. }
  6240. try {
  6241. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  6242. } catch (\PDOException $e) {
  6243. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  6244. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  6245. } elseif (strpos(strtolower($e->getMessage()), 'unique constraint') !== false) {
  6246. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  6247. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  6248. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  6249. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  6250. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  6251. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  6252. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  6253. } else {
  6254. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  6255. }
  6256. if ($this->debug) {
  6257. $response = ResponseUtils::addExceptionHeaders($response, $e);
  6258. }
  6259. }
  6260. return $response;
  6261. }
  6262. }
  6263. }
  6264. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  6265. namespace Tqdev\PhpCrudApi\Middleware {
  6266. use Psr\Http\Message\ResponseInterface;
  6267. use Psr\Http\Message\ServerRequestInterface;
  6268. use Psr\Http\Server\RequestHandlerInterface;
  6269. use Tqdev\PhpCrudApi\Controller\Responder;
  6270. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6271. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6272. use Tqdev\PhpCrudApi\RequestUtils;
  6273. class AjaxOnlyMiddleware extends Middleware
  6274. {
  6275. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6276. {
  6277. $method = $request->getMethod();
  6278. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  6279. if (!in_array($method, $excludeMethods)) {
  6280. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  6281. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  6282. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  6283. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  6284. }
  6285. }
  6286. return $next->handle($request);
  6287. }
  6288. }
  6289. }
  6290. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  6291. namespace Tqdev\PhpCrudApi\Middleware {
  6292. use Psr\Http\Message\ResponseInterface;
  6293. use Psr\Http\Message\ServerRequestInterface;
  6294. use Psr\Http\Server\RequestHandlerInterface;
  6295. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6296. use Tqdev\PhpCrudApi\Controller\Responder;
  6297. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6298. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6299. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6300. use Tqdev\PhpCrudApi\Record\FilterInfo;
  6301. use Tqdev\PhpCrudApi\RequestUtils;
  6302. class AuthorizationMiddleware extends Middleware
  6303. {
  6304. private $reflection;
  6305. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6306. {
  6307. parent::__construct($router, $responder, $properties);
  6308. $this->reflection = $reflection;
  6309. }
  6310. private function handleColumns(string $operation, string $tableName) /*: void*/
  6311. {
  6312. $columnHandler = $this->getProperty('columnHandler', '');
  6313. if ($columnHandler) {
  6314. $table = $this->reflection->getTable($tableName);
  6315. foreach ($table->getColumnNames() as $columnName) {
  6316. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  6317. if (!$allowed) {
  6318. $table->removeColumn($columnName);
  6319. }
  6320. }
  6321. }
  6322. }
  6323. private function handleTable(string $operation, string $tableName) /*: void*/
  6324. {
  6325. if (!$this->reflection->hasTable($tableName)) {
  6326. return;
  6327. }
  6328. $allowed = true;
  6329. $tableHandler = $this->getProperty('tableHandler', '');
  6330. if ($tableHandler) {
  6331. $allowed = call_user_func($tableHandler, $operation, $tableName);
  6332. }
  6333. if (!$allowed) {
  6334. $this->reflection->removeTable($tableName);
  6335. } else {
  6336. $this->handleColumns($operation, $tableName);
  6337. }
  6338. }
  6339. private function handleRecords(string $operation, string $tableName) /*: void*/
  6340. {
  6341. if (!$this->reflection->hasTable($tableName)) {
  6342. return;
  6343. }
  6344. $recordHandler = $this->getProperty('recordHandler', '');
  6345. if ($recordHandler) {
  6346. $query = call_user_func($recordHandler, $operation, $tableName);
  6347. $filters = new FilterInfo();
  6348. $table = $this->reflection->getTable($tableName);
  6349. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  6350. parse_str($query, $params);
  6351. $condition = $filters->getCombinedConditions($table, $params);
  6352. VariableStore::set("authorization.conditions.$tableName", $condition);
  6353. }
  6354. }
  6355. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6356. {
  6357. $path = RequestUtils::getPathSegment($request, 1);
  6358. $operation = RequestUtils::getOperation($request);
  6359. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  6360. foreach ($tableNames as $tableName) {
  6361. $this->handleTable($operation, $tableName);
  6362. if ($path == 'records') {
  6363. $this->handleRecords($operation, $tableName);
  6364. }
  6365. }
  6366. if ($path == 'openapi') {
  6367. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  6368. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  6369. }
  6370. return $next->handle($request);
  6371. }
  6372. }
  6373. }
  6374. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  6375. namespace Tqdev\PhpCrudApi\Middleware {
  6376. use Psr\Http\Message\ResponseInterface;
  6377. use Psr\Http\Message\ServerRequestInterface;
  6378. use Psr\Http\Server\RequestHandlerInterface;
  6379. use Tqdev\PhpCrudApi\Controller\Responder;
  6380. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6381. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6382. use Tqdev\PhpCrudApi\RequestUtils;
  6383. class BasicAuthMiddleware extends Middleware
  6384. {
  6385. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  6386. {
  6387. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  6388. if ($hash && password_verify($password, $hash)) {
  6389. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  6390. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  6391. }
  6392. return true;
  6393. }
  6394. return false;
  6395. }
  6396. private function getValidUsername(string $username, string $password, string $passwordFile): string
  6397. {
  6398. $passwords = $this->readPasswords($passwordFile);
  6399. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  6400. $this->writePasswords($passwordFile, $passwords);
  6401. return $valid ? $username : '';
  6402. }
  6403. private function readPasswords(string $passwordFile): array
  6404. {
  6405. $passwords = [];
  6406. $passwordLines = file($passwordFile);
  6407. foreach ($passwordLines as $passwordLine) {
  6408. if (strpos($passwordLine, ':') !== false) {
  6409. list($username, $hash) = explode(':', trim($passwordLine), 2);
  6410. if (strlen($hash) > 0 && $hash[0] != '$') {
  6411. $hash = password_hash($hash, PASSWORD_DEFAULT);
  6412. }
  6413. $passwords[$username] = $hash;
  6414. }
  6415. }
  6416. return $passwords;
  6417. }
  6418. private function writePasswords(string $passwordFile, array $passwords): bool
  6419. {
  6420. $success = false;
  6421. $passwordFileContents = '';
  6422. foreach ($passwords as $username => $hash) {
  6423. $passwordFileContents .= "$username:$hash\n";
  6424. }
  6425. if (file_get_contents($passwordFile) != $passwordFileContents) {
  6426. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  6427. }
  6428. return $success;
  6429. }
  6430. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  6431. {
  6432. if (isset($_SERVER['PHP_AUTH_USER'])) {
  6433. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  6434. }
  6435. $header = RequestUtils::getHeader($request, 'Authorization');
  6436. $parts = explode(' ', trim($header), 2);
  6437. if (count($parts) != 2) {
  6438. return '';
  6439. }
  6440. if ($parts[0] != 'Basic') {
  6441. return '';
  6442. }
  6443. return base64_decode(strtr($parts[1], '-_', '+/'));
  6444. }
  6445. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6446. {
  6447. if (session_status() == PHP_SESSION_NONE) {
  6448. if (!headers_sent()) {
  6449. $sessionName = $this->getProperty('sessionName', '');
  6450. if ($sessionName) {
  6451. session_name($sessionName);
  6452. }
  6453. session_start();
  6454. }
  6455. }
  6456. $credentials = $this->getAuthorizationCredentials($request);
  6457. if ($credentials) {
  6458. list($username, $password) = array('', '');
  6459. if (strpos($credentials, ':') !== false) {
  6460. list($username, $password) = explode(':', $credentials, 2);
  6461. }
  6462. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  6463. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  6464. $_SESSION['username'] = $validUser;
  6465. if (!$validUser) {
  6466. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6467. }
  6468. if (!headers_sent()) {
  6469. session_regenerate_id();
  6470. }
  6471. }
  6472. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  6473. $authenticationMode = $this->getProperty('mode', 'required');
  6474. if ($authenticationMode == 'required') {
  6475. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6476. $realm = $this->getProperty('realm', 'Username and password required');
  6477. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  6478. return $response;
  6479. }
  6480. }
  6481. return $next->handle($request);
  6482. }
  6483. }
  6484. }
  6485. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  6486. namespace Tqdev\PhpCrudApi\Middleware {
  6487. use Psr\Http\Message\ResponseInterface;
  6488. use Psr\Http\Message\ServerRequestInterface;
  6489. use Psr\Http\Server\RequestHandlerInterface;
  6490. use Tqdev\PhpCrudApi\Controller\Responder;
  6491. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6492. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6493. use Tqdev\PhpCrudApi\ResponseFactory;
  6494. class CorsMiddleware extends Middleware
  6495. {
  6496. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  6497. {
  6498. $found = false;
  6499. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  6500. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  6501. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  6502. if (preg_match($regex, $origin)) {
  6503. $found = true;
  6504. break;
  6505. }
  6506. }
  6507. return $found;
  6508. }
  6509. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6510. {
  6511. $method = $request->getMethod();
  6512. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  6513. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  6514. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  6515. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  6516. } elseif ($method == 'OPTIONS') {
  6517. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  6518. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  6519. if ($allowHeaders) {
  6520. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  6521. }
  6522. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  6523. if ($allowMethods) {
  6524. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  6525. }
  6526. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6527. if ($allowCredentials) {
  6528. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6529. }
  6530. $maxAge = $this->getProperty('maxAge', '1728000');
  6531. if ($maxAge) {
  6532. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  6533. }
  6534. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  6535. if ($exposeHeaders) {
  6536. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  6537. }
  6538. } else {
  6539. $response = $next->handle($request);
  6540. }
  6541. if ($origin) {
  6542. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6543. if ($allowCredentials) {
  6544. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6545. }
  6546. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  6547. }
  6548. return $response;
  6549. }
  6550. }
  6551. }
  6552. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  6553. namespace Tqdev\PhpCrudApi\Middleware {
  6554. use Psr\Http\Message\ResponseInterface;
  6555. use Psr\Http\Message\ServerRequestInterface;
  6556. use Psr\Http\Server\RequestHandlerInterface;
  6557. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6558. use Tqdev\PhpCrudApi\Controller\Responder;
  6559. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6560. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6561. use Tqdev\PhpCrudApi\RequestUtils;
  6562. class CustomizationMiddleware extends Middleware
  6563. {
  6564. private $reflection;
  6565. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6566. {
  6567. parent::__construct($router, $responder, $properties);
  6568. $this->reflection = $reflection;
  6569. }
  6570. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6571. {
  6572. $operation = RequestUtils::getOperation($request);
  6573. $tableName = RequestUtils::getPathSegment($request, 2);
  6574. $beforeHandler = $this->getProperty('beforeHandler', '');
  6575. $environment = (object) array();
  6576. if ($beforeHandler !== '') {
  6577. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  6578. $request = $result ?: $request;
  6579. }
  6580. $response = $next->handle($request);
  6581. $afterHandler = $this->getProperty('afterHandler', '');
  6582. if ($afterHandler !== '') {
  6583. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  6584. $response = $result ?: $response;
  6585. }
  6586. return $response;
  6587. }
  6588. }
  6589. }
  6590. // file: src/Tqdev/PhpCrudApi/Middleware/DbAuthMiddleware.php
  6591. namespace Tqdev\PhpCrudApi\Middleware {
  6592. use Psr\Http\Message\ResponseInterface;
  6593. use Psr\Http\Message\ServerRequestInterface;
  6594. use Psr\Http\Server\RequestHandlerInterface;
  6595. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6596. use Tqdev\PhpCrudApi\Controller\Responder;
  6597. use Tqdev\PhpCrudApi\Database\GenericDB;
  6598. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6599. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6600. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  6601. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6602. use Tqdev\PhpCrudApi\Record\OrderingInfo;
  6603. use Tqdev\PhpCrudApi\RequestUtils;
  6604. class DbAuthMiddleware extends Middleware
  6605. {
  6606. private $reflection;
  6607. private $db;
  6608. private $ordering;
  6609. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  6610. {
  6611. parent::__construct($router, $responder, $properties);
  6612. $this->reflection = $reflection;
  6613. $this->db = $db;
  6614. $this->ordering = new OrderingInfo();
  6615. }
  6616. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6617. {
  6618. if (session_status() == PHP_SESSION_NONE) {
  6619. if (!headers_sent()) {
  6620. $sessionName = $this->getProperty('sessionName', '');
  6621. if ($sessionName) {
  6622. session_name($sessionName);
  6623. }
  6624. session_start();
  6625. }
  6626. }
  6627. $path = RequestUtils::getPathSegment($request, 1);
  6628. $method = $request->getMethod();
  6629. if ($method == 'POST' && $path == 'login') {
  6630. $body = $request->getParsedBody();
  6631. $username = isset($body->username) ? $body->username : '';
  6632. $password = isset($body->password) ? $body->password : '';
  6633. $tableName = $this->getProperty('usersTable', 'users');
  6634. $table = $this->reflection->getTable($tableName);
  6635. $usernameColumnName = $this->getProperty('usernameColumn', 'username');
  6636. $usernameColumn = $table->getColumn($usernameColumnName);
  6637. $passwordColumnName = $this->getProperty('passwordColumn', 'password');
  6638. $passwordColumn = $table->getColumn($passwordColumnName);
  6639. $condition = new ColumnCondition($usernameColumn, 'eq', $username);
  6640. $returnedColumns = $this->getProperty('returnedColumns', '');
  6641. if (!$returnedColumns) {
  6642. $columnNames = $table->getColumnNames();
  6643. } else {
  6644. $columnNames = array_map('trim', explode(',', $returnedColumns));
  6645. $columnNames[] = $passwordColumnName;
  6646. }
  6647. $columnOrdering = $this->ordering->getDefaultColumnOrdering($table);
  6648. $users = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, 0, 1);
  6649. foreach ($users as $user) {
  6650. if (password_verify($password, $user[$passwordColumnName]) == 1) {
  6651. if (!headers_sent()) {
  6652. session_regenerate_id(true);
  6653. }
  6654. unset($user[$passwordColumnName]);
  6655. $_SESSION['user'] = $user;
  6656. return $this->responder->success($user);
  6657. }
  6658. }
  6659. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6660. }
  6661. if ($method == 'POST' && $path == 'logout') {
  6662. if (isset($_SESSION['user'])) {
  6663. $user = $_SESSION['user'];
  6664. unset($_SESSION['user']);
  6665. if (session_status() != PHP_SESSION_NONE) {
  6666. session_destroy();
  6667. }
  6668. return $this->responder->success($user);
  6669. }
  6670. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6671. }
  6672. if (!isset($_SESSION['user']) || !$_SESSION['user']) {
  6673. $authenticationMode = $this->getProperty('mode', 'required');
  6674. if ($authenticationMode == 'required') {
  6675. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6676. }
  6677. }
  6678. return $next->handle($request);
  6679. }
  6680. }
  6681. }
  6682. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  6683. namespace Tqdev\PhpCrudApi\Middleware {
  6684. use Psr\Http\Message\ResponseInterface;
  6685. use Psr\Http\Message\ServerRequestInterface;
  6686. use Psr\Http\Server\RequestHandlerInterface;
  6687. use Tqdev\PhpCrudApi\Controller\Responder;
  6688. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6689. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6690. class FirewallMiddleware extends Middleware
  6691. {
  6692. private function ipMatch(string $ip, string $cidr): bool
  6693. {
  6694. if (strpos($cidr, '/') !== false) {
  6695. list($subnet, $mask) = explode('/', trim($cidr));
  6696. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  6697. return true;
  6698. }
  6699. } else {
  6700. if (ip2long($ip) == ip2long($cidr)) {
  6701. return true;
  6702. }
  6703. }
  6704. return false;
  6705. }
  6706. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  6707. {
  6708. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  6709. if ($this->ipMatch($ipAddress, $allowedIp)) {
  6710. return true;
  6711. }
  6712. }
  6713. return false;
  6714. }
  6715. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6716. {
  6717. $reverseProxy = $this->getProperty('reverseProxy', '');
  6718. if ($reverseProxy) {
  6719. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  6720. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  6721. $ipAddress = $_SERVER['REMOTE_ADDR'];
  6722. } else {
  6723. $ipAddress = '127.0.0.1';
  6724. }
  6725. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  6726. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  6727. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  6728. } else {
  6729. $response = $next->handle($request);
  6730. }
  6731. return $response;
  6732. }
  6733. }
  6734. }
  6735. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  6736. namespace Tqdev\PhpCrudApi\Middleware {
  6737. use Psr\Http\Message\ResponseInterface;
  6738. use Psr\Http\Message\ServerRequestInterface;
  6739. use Psr\Http\Server\RequestHandlerInterface;
  6740. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6741. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6742. use Tqdev\PhpCrudApi\Controller\Responder;
  6743. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6744. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6745. use Tqdev\PhpCrudApi\RequestUtils;
  6746. class IpAddressMiddleware extends Middleware
  6747. {
  6748. private $reflection;
  6749. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6750. {
  6751. parent::__construct($router, $responder, $properties);
  6752. $this->reflection = $reflection;
  6753. }
  6754. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  6755. {
  6756. $context = (array) $record;
  6757. $columnNames = $this->getProperty('columns', '');
  6758. if ($columnNames) {
  6759. foreach (explode(',', $columnNames) as $columnName) {
  6760. if ($table->hasColumn($columnName)) {
  6761. if ($operation == 'create') {
  6762. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  6763. } else {
  6764. unset($context[$columnName]);
  6765. }
  6766. }
  6767. }
  6768. }
  6769. return (object) $context;
  6770. }
  6771. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6772. {
  6773. $operation = RequestUtils::getOperation($request);
  6774. if (in_array($operation, ['create', 'update', 'increment'])) {
  6775. $tableNames = $this->getProperty('tables', '');
  6776. $tableName = RequestUtils::getPathSegment($request, 2);
  6777. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  6778. if ($this->reflection->hasTable($tableName)) {
  6779. $record = $request->getParsedBody();
  6780. if ($record !== null) {
  6781. $table = $this->reflection->getTable($tableName);
  6782. if (is_array($record)) {
  6783. foreach ($record as &$r) {
  6784. $r = $this->callHandler($r, $operation, $table);
  6785. }
  6786. } else {
  6787. $record = $this->callHandler($record, $operation, $table);
  6788. }
  6789. $request = $request->withParsedBody($record);
  6790. }
  6791. }
  6792. }
  6793. }
  6794. return $next->handle($request);
  6795. }
  6796. }
  6797. }
  6798. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  6799. namespace Tqdev\PhpCrudApi\Middleware {
  6800. use Psr\Http\Message\ResponseInterface;
  6801. use Psr\Http\Message\ServerRequestInterface;
  6802. use Psr\Http\Server\RequestHandlerInterface;
  6803. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6804. use Tqdev\PhpCrudApi\Controller\Responder;
  6805. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6806. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6807. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6808. use Tqdev\PhpCrudApi\RequestUtils;
  6809. class JoinLimitsMiddleware extends Middleware
  6810. {
  6811. private $reflection;
  6812. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6813. {
  6814. parent::__construct($router, $responder, $properties);
  6815. $this->reflection = $reflection;
  6816. }
  6817. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6818. {
  6819. $operation = RequestUtils::getOperation($request);
  6820. $params = RequestUtils::getParams($request);
  6821. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  6822. $maxDepth = (int) $this->getProperty('depth', '3');
  6823. $maxTables = (int) $this->getProperty('tables', '10');
  6824. $maxRecords = (int) $this->getProperty('records', '1000');
  6825. $tableCount = 0;
  6826. $joinPaths = array();
  6827. for ($i = 0; $i < count($params['join']); $i++) {
  6828. $joinPath = array();
  6829. $tables = explode(',', $params['join'][$i]);
  6830. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  6831. array_push($joinPath, $tables[$depth]);
  6832. $tableCount += 1;
  6833. if ($tableCount == $maxTables) {
  6834. break;
  6835. }
  6836. }
  6837. array_push($joinPaths, implode(',', $joinPath));
  6838. if ($tableCount == $maxTables) {
  6839. break;
  6840. }
  6841. }
  6842. $params['join'] = $joinPaths;
  6843. $request = RequestUtils::setParams($request, $params);
  6844. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  6845. }
  6846. return $next->handle($request);
  6847. }
  6848. }
  6849. }
  6850. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  6851. namespace Tqdev\PhpCrudApi\Middleware {
  6852. use Psr\Http\Message\ResponseInterface;
  6853. use Psr\Http\Message\ServerRequestInterface;
  6854. use Psr\Http\Server\RequestHandlerInterface;
  6855. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6856. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6857. use Tqdev\PhpCrudApi\RequestUtils;
  6858. class JwtAuthMiddleware extends Middleware
  6859. {
  6860. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, array $secrets, array $requirements): array
  6861. {
  6862. $algorithms = array(
  6863. 'HS256' => 'sha256',
  6864. 'HS384' => 'sha384',
  6865. 'HS512' => 'sha512',
  6866. 'RS256' => 'sha256',
  6867. 'RS384' => 'sha384',
  6868. 'RS512' => 'sha512',
  6869. );
  6870. $token = explode('.', $token);
  6871. if (count($token) < 3) {
  6872. return array();
  6873. }
  6874. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  6875. $kid = 0;
  6876. if (isset($header['kid'])) {
  6877. $kid = $header['kid'];
  6878. }
  6879. if (!isset($secrets[$kid])) {
  6880. return array();
  6881. }
  6882. $secret = $secrets[$kid];
  6883. if ($header['typ'] != 'JWT') {
  6884. return array();
  6885. }
  6886. $algorithm = $header['alg'];
  6887. if (!isset($algorithms[$algorithm])) {
  6888. return array();
  6889. }
  6890. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  6891. return array();
  6892. }
  6893. $hmac = $algorithms[$algorithm];
  6894. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  6895. $data = "$token[0].$token[1]";
  6896. switch ($algorithm[0]) {
  6897. case 'H':
  6898. $hash = hash_hmac($hmac, $data, $secret, true);
  6899. $equals = hash_equals($hash, $signature);
  6900. if (!$equals) {
  6901. return array();
  6902. }
  6903. break;
  6904. case 'R':
  6905. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  6906. if (!$equals) {
  6907. return array();
  6908. }
  6909. break;
  6910. }
  6911. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  6912. if (!$claims) {
  6913. return array();
  6914. }
  6915. foreach ($requirements as $field => $values) {
  6916. if (!empty($values)) {
  6917. if ($field != 'alg') {
  6918. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  6919. return array();
  6920. }
  6921. }
  6922. }
  6923. }
  6924. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  6925. return array();
  6926. }
  6927. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  6928. return array();
  6929. }
  6930. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  6931. return array();
  6932. }
  6933. if (isset($claims['iat']) && !isset($claims['exp'])) {
  6934. if ($time - $leeway > $claims['iat'] + $ttl) {
  6935. return array();
  6936. }
  6937. }
  6938. return $claims;
  6939. }
  6940. private function getClaims(string $token): array
  6941. {
  6942. $time = (int) $this->getProperty('time', time());
  6943. $leeway = (int) $this->getProperty('leeway', '5');
  6944. $ttl = (int) $this->getProperty('ttl', '30');
  6945. $secrets = $this->getMapProperty('secrets', '');
  6946. if (!$secrets) {
  6947. $secrets = [$this->getProperty('secret', '')];
  6948. }
  6949. $requirements = array(
  6950. 'alg' => $this->getArrayProperty('algorithms', ''),
  6951. 'aud' => $this->getArrayProperty('audiences', ''),
  6952. 'iss' => $this->getArrayProperty('issuers', ''),
  6953. );
  6954. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secrets, $requirements);
  6955. }
  6956. private function getAuthorizationToken(ServerRequestInterface $request): string
  6957. {
  6958. $headerName = $this->getProperty('header', 'X-Authorization');
  6959. $headerValue = RequestUtils::getHeader($request, $headerName);
  6960. $parts = explode(' ', trim($headerValue), 2);
  6961. if (count($parts) != 2) {
  6962. return '';
  6963. }
  6964. if ($parts[0] != 'Bearer') {
  6965. return '';
  6966. }
  6967. return $parts[1];
  6968. }
  6969. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6970. {
  6971. if (session_status() == PHP_SESSION_NONE) {
  6972. if (!headers_sent()) {
  6973. $sessionName = $this->getProperty('sessionName', '');
  6974. if ($sessionName) {
  6975. session_name($sessionName);
  6976. }
  6977. session_start();
  6978. }
  6979. }
  6980. $token = $this->getAuthorizationToken($request);
  6981. if ($token) {
  6982. $claims = $this->getClaims($token);
  6983. $_SESSION['claims'] = $claims;
  6984. if (empty($claims)) {
  6985. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  6986. }
  6987. if (!headers_sent()) {
  6988. session_regenerate_id();
  6989. }
  6990. }
  6991. if (empty($_SESSION['claims'])) {
  6992. $authenticationMode = $this->getProperty('mode', 'required');
  6993. if ($authenticationMode == 'required') {
  6994. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6995. }
  6996. }
  6997. return $next->handle($request);
  6998. }
  6999. }
  7000. }
  7001. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  7002. namespace Tqdev\PhpCrudApi\Middleware {
  7003. use Psr\Http\Message\ResponseInterface;
  7004. use Psr\Http\Message\ServerRequestInterface;
  7005. use Psr\Http\Server\RequestHandlerInterface;
  7006. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7007. use Tqdev\PhpCrudApi\Controller\Responder;
  7008. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7009. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  7010. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7011. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  7012. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  7013. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  7014. use Tqdev\PhpCrudApi\RequestUtils;
  7015. class MultiTenancyMiddleware extends Middleware
  7016. {
  7017. private $reflection;
  7018. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7019. {
  7020. parent::__construct($router, $responder, $properties);
  7021. $this->reflection = $reflection;
  7022. }
  7023. private function getCondition(string $tableName, array $pairs): Condition
  7024. {
  7025. $condition = new NoCondition();
  7026. $table = $this->reflection->getTable($tableName);
  7027. foreach ($pairs as $k => $v) {
  7028. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  7029. }
  7030. return $condition;
  7031. }
  7032. private function getPairs($handler, string $operation, string $tableName): array
  7033. {
  7034. $result = array();
  7035. $pairs = call_user_func($handler, $operation, $tableName);
  7036. $table = $this->reflection->getTable($tableName);
  7037. foreach ($pairs as $k => $v) {
  7038. if ($table->hasColumn($k)) {
  7039. $result[$k] = $v;
  7040. }
  7041. }
  7042. return $result;
  7043. }
  7044. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  7045. {
  7046. $record = $request->getParsedBody();
  7047. if ($record === null) {
  7048. return $request;
  7049. }
  7050. $multi = is_array($record);
  7051. $records = $multi ? $record : [$record];
  7052. foreach ($records as &$record) {
  7053. foreach ($pairs as $column => $value) {
  7054. if ($operation == 'create') {
  7055. $record->$column = $value;
  7056. } else {
  7057. if (isset($record->$column)) {
  7058. unset($record->$column);
  7059. }
  7060. }
  7061. }
  7062. }
  7063. return $request->withParsedBody($multi ? $records : $records[0]);
  7064. }
  7065. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7066. {
  7067. $handler = $this->getProperty('handler', '');
  7068. if ($handler !== '') {
  7069. $path = RequestUtils::getPathSegment($request, 1);
  7070. if ($path == 'records') {
  7071. $operation = RequestUtils::getOperation($request);
  7072. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  7073. foreach ($tableNames as $i => $tableName) {
  7074. if (!$this->reflection->hasTable($tableName)) {
  7075. continue;
  7076. }
  7077. $pairs = $this->getPairs($handler, $operation, $tableName);
  7078. if ($i == 0) {
  7079. if (in_array($operation, ['create', 'update', 'increment'])) {
  7080. $request = $this->handleRecord($request, $operation, $pairs);
  7081. }
  7082. }
  7083. $condition = $this->getCondition($tableName, $pairs);
  7084. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  7085. }
  7086. }
  7087. }
  7088. return $next->handle($request);
  7089. }
  7090. }
  7091. }
  7092. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  7093. namespace Tqdev\PhpCrudApi\Middleware {
  7094. use Psr\Http\Message\ResponseInterface;
  7095. use Psr\Http\Message\ServerRequestInterface;
  7096. use Psr\Http\Server\RequestHandlerInterface;
  7097. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7098. use Tqdev\PhpCrudApi\Controller\Responder;
  7099. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7100. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7101. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7102. use Tqdev\PhpCrudApi\RequestUtils;
  7103. class PageLimitsMiddleware extends Middleware
  7104. {
  7105. private $reflection;
  7106. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7107. {
  7108. parent::__construct($router, $responder, $properties);
  7109. $this->reflection = $reflection;
  7110. }
  7111. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7112. {
  7113. $operation = RequestUtils::getOperation($request);
  7114. if ($operation == 'list') {
  7115. $params = RequestUtils::getParams($request);
  7116. $maxPage = (int) $this->getProperty('pages', '100');
  7117. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  7118. if (strpos($params['page'][0], ',') === false) {
  7119. $page = $params['page'][0];
  7120. } else {
  7121. list($page, $size) = explode(',', $params['page'][0], 2);
  7122. }
  7123. if ($page > $maxPage) {
  7124. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  7125. }
  7126. }
  7127. $maxSize = (int) $this->getProperty('records', '1000');
  7128. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  7129. $params['size'] = array($maxSize);
  7130. } else {
  7131. $params['size'] = array(min($params['size'][0], $maxSize));
  7132. }
  7133. $request = RequestUtils::setParams($request, $params);
  7134. }
  7135. return $next->handle($request);
  7136. }
  7137. }
  7138. }
  7139. // file: src/Tqdev/PhpCrudApi/Middleware/ReconnectMiddleware.php
  7140. namespace Tqdev\PhpCrudApi\Middleware {
  7141. use Psr\Http\Message\ResponseInterface;
  7142. use Psr\Http\Message\ServerRequestInterface;
  7143. use Psr\Http\Server\RequestHandlerInterface;
  7144. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7145. use Tqdev\PhpCrudApi\Controller\Responder;
  7146. use Tqdev\PhpCrudApi\Database\GenericDB;
  7147. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7148. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7149. class ReconnectMiddleware extends Middleware
  7150. {
  7151. private $reflection;
  7152. private $db;
  7153. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  7154. {
  7155. parent::__construct($router, $responder, $properties);
  7156. $this->reflection = $reflection;
  7157. $this->db = $db;
  7158. }
  7159. private function getDriver(): string
  7160. {
  7161. $driverHandler = $this->getProperty('driverHandler', '');
  7162. if ($driverHandler) {
  7163. return call_user_func($driverHandler);
  7164. }
  7165. return '';
  7166. }
  7167. private function getAddress(): string
  7168. {
  7169. $addressHandler = $this->getProperty('addressHandler', '');
  7170. if ($addressHandler) {
  7171. return call_user_func($addressHandler);
  7172. }
  7173. return '';
  7174. }
  7175. private function getPort(): int
  7176. {
  7177. $portHandler = $this->getProperty('portHandler', '');
  7178. if ($portHandler) {
  7179. return call_user_func($portHandler);
  7180. }
  7181. return 0;
  7182. }
  7183. private function getDatabase(): string
  7184. {
  7185. $databaseHandler = $this->getProperty('databaseHandler', '');
  7186. if ($databaseHandler) {
  7187. return call_user_func($databaseHandler);
  7188. }
  7189. return '';
  7190. }
  7191. private function getTables(): array
  7192. {
  7193. $tablesHandler = $this->getProperty('tablesHandler', '');
  7194. if ($tablesHandler) {
  7195. return call_user_func($tablesHandler);
  7196. }
  7197. return [];
  7198. }
  7199. private function getUsername(): string
  7200. {
  7201. $usernameHandler = $this->getProperty('usernameHandler', '');
  7202. if ($usernameHandler) {
  7203. return call_user_func($usernameHandler);
  7204. }
  7205. return '';
  7206. }
  7207. private function getPassword(): string
  7208. {
  7209. $passwordHandler = $this->getProperty('passwordHandler', '');
  7210. if ($passwordHandler) {
  7211. return call_user_func($passwordHandler);
  7212. }
  7213. return '';
  7214. }
  7215. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7216. {
  7217. $driver = $this->getDriver();
  7218. $address = $this->getAddress();
  7219. $port = $this->getPort();
  7220. $database = $this->getDatabase();
  7221. $tables = $this->getTables();
  7222. $username = $this->getUsername();
  7223. $password = $this->getPassword();
  7224. if ($driver || $address || $port || $database || $tables || $username || $password) {
  7225. $this->db->reconstruct($driver, $address, $port, $database, $tables, $username, $password);
  7226. }
  7227. return $next->handle($request);
  7228. }
  7229. }
  7230. }
  7231. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  7232. namespace Tqdev\PhpCrudApi\Middleware {
  7233. use Psr\Http\Message\ResponseInterface;
  7234. use Psr\Http\Message\ServerRequestInterface;
  7235. use Psr\Http\Server\RequestHandlerInterface;
  7236. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7237. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7238. use Tqdev\PhpCrudApi\Controller\Responder;
  7239. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7240. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7241. use Tqdev\PhpCrudApi\RequestUtils;
  7242. class SanitationMiddleware extends Middleware
  7243. {
  7244. private $reflection;
  7245. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7246. {
  7247. parent::__construct($router, $responder, $properties);
  7248. $this->reflection = $reflection;
  7249. }
  7250. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  7251. {
  7252. $context = (array) $record;
  7253. $tableName = $table->getName();
  7254. foreach ($context as $columnName => &$value) {
  7255. if ($table->hasColumn($columnName)) {
  7256. $column = $table->getColumn($columnName);
  7257. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  7258. }
  7259. }
  7260. return (object) $context;
  7261. }
  7262. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7263. {
  7264. $operation = RequestUtils::getOperation($request);
  7265. if (in_array($operation, ['create', 'update', 'increment'])) {
  7266. $tableName = RequestUtils::getPathSegment($request, 2);
  7267. if ($this->reflection->hasTable($tableName)) {
  7268. $record = $request->getParsedBody();
  7269. if ($record !== null) {
  7270. $handler = $this->getProperty('handler', '');
  7271. if ($handler !== '') {
  7272. $table = $this->reflection->getTable($tableName);
  7273. if (is_array($record)) {
  7274. foreach ($record as &$r) {
  7275. $r = $this->callHandler($handler, $r, $operation, $table);
  7276. }
  7277. } else {
  7278. $record = $this->callHandler($handler, $record, $operation, $table);
  7279. }
  7280. $request = $request->withParsedBody($record);
  7281. }
  7282. }
  7283. }
  7284. }
  7285. return $next->handle($request);
  7286. }
  7287. }
  7288. }
  7289. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  7290. namespace Tqdev\PhpCrudApi\Middleware {
  7291. use Psr\Http\Message\ResponseInterface;
  7292. use Psr\Http\Message\ServerRequestInterface;
  7293. use Psr\Http\Server\RequestHandlerInterface;
  7294. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7295. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7296. use Tqdev\PhpCrudApi\Controller\Responder;
  7297. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7298. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7299. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7300. use Tqdev\PhpCrudApi\RequestUtils;
  7301. class ValidationMiddleware extends Middleware
  7302. {
  7303. private $reflection;
  7304. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7305. {
  7306. parent::__construct($router, $responder, $properties);
  7307. $this->reflection = $reflection;
  7308. }
  7309. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  7310. {
  7311. $context = (array) $record;
  7312. $details = array();
  7313. $tableName = $table->getName();
  7314. foreach ($context as $columnName => $value) {
  7315. if ($table->hasColumn($columnName)) {
  7316. $column = $table->getColumn($columnName);
  7317. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  7318. if ($valid !== true && $valid !== '') {
  7319. $details[$columnName] = $valid;
  7320. }
  7321. }
  7322. }
  7323. if (count($details) > 0) {
  7324. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  7325. }
  7326. return null;
  7327. }
  7328. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7329. {
  7330. $operation = RequestUtils::getOperation($request);
  7331. if (in_array($operation, ['create', 'update', 'increment'])) {
  7332. $tableName = RequestUtils::getPathSegment($request, 2);
  7333. if ($this->reflection->hasTable($tableName)) {
  7334. $record = $request->getParsedBody();
  7335. if ($record !== null) {
  7336. $handler = $this->getProperty('handler', '');
  7337. if ($handler !== '') {
  7338. $table = $this->reflection->getTable($tableName);
  7339. if (is_array($record)) {
  7340. foreach ($record as $r) {
  7341. $response = $this->callHandler($handler, $r, $operation, $table);
  7342. if ($response !== null) {
  7343. return $response;
  7344. }
  7345. }
  7346. } else {
  7347. $response = $this->callHandler($handler, $record, $operation, $table);
  7348. if ($response !== null) {
  7349. return $response;
  7350. }
  7351. }
  7352. }
  7353. }
  7354. }
  7355. }
  7356. return $next->handle($request);
  7357. }
  7358. }
  7359. }
  7360. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  7361. namespace Tqdev\PhpCrudApi\Middleware {
  7362. use Psr\Http\Message\ResponseInterface;
  7363. use Psr\Http\Message\ServerRequestInterface;
  7364. use Psr\Http\Server\RequestHandlerInterface;
  7365. use Tqdev\PhpCrudApi\Controller\Responder;
  7366. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7367. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7368. class XsrfMiddleware extends Middleware
  7369. {
  7370. private function getToken(): string
  7371. {
  7372. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  7373. if (isset($_COOKIE[$cookieName])) {
  7374. $token = $_COOKIE[$cookieName];
  7375. } else {
  7376. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  7377. $token = bin2hex(random_bytes(8));
  7378. if (!headers_sent()) {
  7379. setcookie($cookieName, $token, 0, '', '', $secure);
  7380. }
  7381. }
  7382. return $token;
  7383. }
  7384. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7385. {
  7386. $token = $this->getToken();
  7387. $method = $request->getMethod();
  7388. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  7389. if (!in_array($method, $excludeMethods)) {
  7390. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  7391. if ($token != $request->getHeader($headerName)) {
  7392. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  7393. }
  7394. }
  7395. return $next->handle($request);
  7396. }
  7397. }
  7398. }
  7399. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  7400. namespace Tqdev\PhpCrudApi\OpenApi {
  7401. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7402. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  7403. class OpenApiBuilder
  7404. {
  7405. private $openapi;
  7406. private $records;
  7407. private $columns;
  7408. private $builders;
  7409. public function __construct(ReflectionService $reflection, array $base, array $controllers, array $builders)
  7410. {
  7411. $this->openapi = new OpenApiDefinition($base);
  7412. $this->records = in_array('records', $controllers) ? new OpenApiRecordsBuilder($this->openapi, $reflection) : null;
  7413. $this->columns = in_array('columns', $controllers) ? new OpenApiColumnsBuilder($this->openapi) : null;
  7414. $this->builders = array();
  7415. foreach ($builders as $className) {
  7416. $this->builders[] = new $className($this->openapi, $reflection);
  7417. }
  7418. }
  7419. private function getServerUrl(): string
  7420. {
  7421. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  7422. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  7423. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  7424. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  7425. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  7426. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  7427. }
  7428. public function build(): OpenApiDefinition
  7429. {
  7430. $this->openapi->set("openapi", "3.0.0");
  7431. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  7432. $this->openapi->set("servers|0|url", $this->getServerUrl());
  7433. }
  7434. if ($this->records) {
  7435. $this->records->build();
  7436. }
  7437. if ($this->columns) {
  7438. $this->columns->build();
  7439. }
  7440. foreach ($this->builders as $builder) {
  7441. $builder->build();
  7442. }
  7443. return $this->openapi;
  7444. }
  7445. }
  7446. }
  7447. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiColumnsBuilder.php
  7448. namespace Tqdev\PhpCrudApi\OpenApi {
  7449. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  7450. class OpenApiColumnsBuilder
  7451. {
  7452. private $openapi;
  7453. private $operations = [
  7454. 'database' => [
  7455. 'read' => 'get',
  7456. ],
  7457. 'table' => [
  7458. 'create' => 'post',
  7459. 'read' => 'get',
  7460. 'update' => 'put', //rename
  7461. 'delete' => 'delete',
  7462. ],
  7463. 'column' => [
  7464. 'create' => 'post',
  7465. 'read' => 'get',
  7466. 'update' => 'put',
  7467. 'delete' => 'delete',
  7468. ]
  7469. ];
  7470. public function __construct(OpenApiDefinition $openapi)
  7471. {
  7472. $this->openapi = $openapi;
  7473. }
  7474. public function build() /*: void*/
  7475. {
  7476. $this->setPaths();
  7477. $this->openapi->set("components|responses|boolSuccess|description", "boolean indicating success or failure");
  7478. $this->openapi->set("components|responses|boolSuccess|content|application/json|schema|type", "boolean");
  7479. $this->setComponentSchema();
  7480. $this->setComponentResponse();
  7481. $this->setComponentRequestBody();
  7482. $this->setComponentParameters();
  7483. foreach (array_keys($this->operations) as $index => $type) {
  7484. $this->setTag($index, $type);
  7485. }
  7486. }
  7487. private function setPaths() /*: void*/
  7488. {
  7489. foreach (array_keys($this->operations) as $type) {
  7490. foreach ($this->operations[$type] as $operation => $method) {
  7491. $parameters = [];
  7492. switch ($type) {
  7493. case 'database':
  7494. $path = '/columns';
  7495. break;
  7496. case 'table':
  7497. $path = $operation == 'create' ? '/columns' : '/columns/{table}';
  7498. break;
  7499. case 'column':
  7500. $path = $operation == 'create' ? '/columns/{table}' : '/columns/{table}/{column}';
  7501. break;
  7502. }
  7503. if (strpos($path, '{table}')) {
  7504. $parameters[] = 'table';
  7505. }
  7506. if (strpos($path, '{column}')) {
  7507. $parameters[] = 'column';
  7508. }
  7509. foreach ($parameters as $p => $parameter) {
  7510. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  7511. }
  7512. $operationType = $operation . ucfirst($type);
  7513. if (in_array($operation, ['create', 'update'])) {
  7514. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operationType");
  7515. }
  7516. $this->openapi->set("paths|$path|$method|tags|0", "$type");
  7517. $this->openapi->set("paths|$path|$method|operationId", "$operation" . "_" . "$type");
  7518. if ($operationType == 'updateTable') {
  7519. $this->openapi->set("paths|$path|$method|description", "rename table");
  7520. } else {
  7521. $this->openapi->set("paths|$path|$method|description", "$operation $type");
  7522. }
  7523. switch ($operation) {
  7524. case 'read':
  7525. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operationType");
  7526. break;
  7527. case 'create':
  7528. case 'update':
  7529. case 'delete':
  7530. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/boolSuccess");
  7531. break;
  7532. }
  7533. }
  7534. }
  7535. }
  7536. private function setComponentSchema() /*: void*/
  7537. {
  7538. foreach (array_keys($this->operations) as $type) {
  7539. foreach (array_keys($this->operations[$type]) as $operation) {
  7540. if ($operation == 'delete') {
  7541. continue;
  7542. }
  7543. $operationType = $operation . ucfirst($type);
  7544. $prefix = "components|schemas|$operationType";
  7545. $this->openapi->set("$prefix|type", "object");
  7546. switch ($type) {
  7547. case 'database':
  7548. $this->openapi->set("$prefix|properties|tables|type", 'array');
  7549. $this->openapi->set("$prefix|properties|tables|items|\$ref", "#/components/schemas/readTable");
  7550. break;
  7551. case 'table':
  7552. if ($operation == 'update') {
  7553. $this->openapi->set("$prefix|required", ['name']);
  7554. $this->openapi->set("$prefix|properties|name|type", 'string');
  7555. } else {
  7556. $this->openapi->set("$prefix|properties|name|type", 'string');
  7557. if ($operation == 'read') {
  7558. $this->openapi->set("$prefix|properties|type|type", 'string');
  7559. }
  7560. $this->openapi->set("$prefix|properties|columns|type", 'array');
  7561. $this->openapi->set("$prefix|properties|columns|items|\$ref", "#/components/schemas/readColumn");
  7562. }
  7563. break;
  7564. case 'column':
  7565. $this->openapi->set("$prefix|required", ['name', 'type']);
  7566. $this->openapi->set("$prefix|properties|name|type", 'string');
  7567. $this->openapi->set("$prefix|properties|type|type", 'string');
  7568. $this->openapi->set("$prefix|properties|length|type", 'integer');
  7569. $this->openapi->set("$prefix|properties|length|format", "int64");
  7570. $this->openapi->set("$prefix|properties|precision|type", 'integer');
  7571. $this->openapi->set("$prefix|properties|precision|format", "int64");
  7572. $this->openapi->set("$prefix|properties|scale|type", 'integer');
  7573. $this->openapi->set("$prefix|properties|scale|format", "int64");
  7574. $this->openapi->set("$prefix|properties|nullable|type", 'boolean');
  7575. $this->openapi->set("$prefix|properties|pk|type", 'boolean');
  7576. $this->openapi->set("$prefix|properties|fk|type", 'string');
  7577. break;
  7578. }
  7579. }
  7580. }
  7581. }
  7582. private function setComponentResponse() /*: void*/
  7583. {
  7584. foreach (array_keys($this->operations) as $type) {
  7585. foreach (array_keys($this->operations[$type]) as $operation) {
  7586. if ($operation != 'read') {
  7587. continue;
  7588. }
  7589. $operationType = $operation . ucfirst($type);
  7590. $this->openapi->set("components|responses|$operationType|description", "single $type record");
  7591. $this->openapi->set("components|responses|$operationType|content|application/json|schema|\$ref", "#/components/schemas/$operationType");
  7592. }
  7593. }
  7594. }
  7595. private function setComponentRequestBody() /*: void*/
  7596. {
  7597. foreach (array_keys($this->operations) as $type) {
  7598. foreach (array_keys($this->operations[$type]) as $operation) {
  7599. if (!in_array($operation, ['create', 'update'])) {
  7600. continue;
  7601. }
  7602. $operationType = $operation . ucfirst($type);
  7603. $this->openapi->set("components|requestBodies|$operationType|description", "single $type record");
  7604. $this->openapi->set("components|requestBodies|$operationType|content|application/json|schema|\$ref", "#/components/schemas/$operationType");
  7605. }
  7606. }
  7607. }
  7608. private function setComponentParameters() /*: void*/
  7609. {
  7610. $this->openapi->set("components|parameters|table|name", "table");
  7611. $this->openapi->set("components|parameters|table|in", "path");
  7612. $this->openapi->set("components|parameters|table|schema|type", "string");
  7613. $this->openapi->set("components|parameters|table|description", "table name");
  7614. $this->openapi->set("components|parameters|table|required", true);
  7615. $this->openapi->set("components|parameters|column|name", "column");
  7616. $this->openapi->set("components|parameters|column|in", "path");
  7617. $this->openapi->set("components|parameters|column|schema|type", "string");
  7618. $this->openapi->set("components|parameters|column|description", "column name");
  7619. $this->openapi->set("components|parameters|column|required", true);
  7620. }
  7621. private function setTag(int $index, string $type) /*: void*/
  7622. {
  7623. $this->openapi->set("tags|$index|name", "$type");
  7624. $this->openapi->set("tags|$index|description", "$type operations");
  7625. }
  7626. }
  7627. }
  7628. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  7629. namespace Tqdev\PhpCrudApi\OpenApi {
  7630. class OpenApiDefinition implements \JsonSerializable
  7631. {
  7632. private $root;
  7633. public function __construct(array $base)
  7634. {
  7635. $this->root = $base;
  7636. }
  7637. public function set(string $path, $value) /*: void*/
  7638. {
  7639. $parts = explode('|', trim($path, '|'));
  7640. $current = &$this->root;
  7641. while (count($parts) > 0) {
  7642. $part = array_shift($parts);
  7643. if (!isset($current[$part])) {
  7644. $current[$part] = [];
  7645. }
  7646. $current = &$current[$part];
  7647. }
  7648. $current = $value;
  7649. }
  7650. public function has(string $path): bool
  7651. {
  7652. $parts = explode('|', trim($path, '|'));
  7653. $current = &$this->root;
  7654. while (count($parts) > 0) {
  7655. $part = array_shift($parts);
  7656. if (!isset($current[$part])) {
  7657. return false;
  7658. }
  7659. $current = &$current[$part];
  7660. }
  7661. return true;
  7662. }
  7663. public function jsonSerialize()
  7664. {
  7665. return $this->root;
  7666. }
  7667. }
  7668. }
  7669. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiRecordsBuilder.php
  7670. namespace Tqdev\PhpCrudApi\OpenApi {
  7671. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7672. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  7673. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  7674. class OpenApiRecordsBuilder
  7675. {
  7676. private $openapi;
  7677. private $reflection;
  7678. private $operations = [
  7679. 'list' => 'get',
  7680. 'create' => 'post',
  7681. 'read' => 'get',
  7682. 'update' => 'put',
  7683. 'delete' => 'delete',
  7684. 'increment' => 'patch',
  7685. ];
  7686. private $types = [
  7687. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  7688. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  7689. 'varchar' => ['type' => 'string'],
  7690. 'clob' => ['type' => 'string'],
  7691. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  7692. 'blob' => ['type' => 'string', 'format' => 'byte'],
  7693. 'decimal' => ['type' => 'string'],
  7694. 'float' => ['type' => 'number', 'format' => 'float'],
  7695. 'double' => ['type' => 'number', 'format' => 'double'],
  7696. 'date' => ['type' => 'string', 'format' => 'date'],
  7697. 'time' => ['type' => 'string', 'format' => 'date-time'],
  7698. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  7699. 'geometry' => ['type' => 'string'],
  7700. 'boolean' => ['type' => 'boolean'],
  7701. ];
  7702. public function __construct(OpenApiDefinition $openapi, ReflectionService $reflection)
  7703. {
  7704. $this->openapi = $openapi;
  7705. $this->reflection = $reflection;
  7706. }
  7707. private function getAllTableReferences(): array
  7708. {
  7709. $tableReferences = array();
  7710. foreach ($this->reflection->getTableNames() as $tableName) {
  7711. $table = $this->reflection->getTable($tableName);
  7712. foreach ($table->getColumnNames() as $columnName) {
  7713. $column = $table->getColumn($columnName);
  7714. $referencedTableName = $column->getFk();
  7715. if ($referencedTableName) {
  7716. if (!isset($tableReferences[$referencedTableName])) {
  7717. $tableReferences[$referencedTableName] = array();
  7718. }
  7719. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  7720. }
  7721. }
  7722. }
  7723. return $tableReferences;
  7724. }
  7725. public function build() /*: void*/
  7726. {
  7727. $tableNames = $this->reflection->getTableNames();
  7728. foreach ($tableNames as $tableName) {
  7729. $this->setPath($tableName);
  7730. }
  7731. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  7732. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  7733. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  7734. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  7735. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  7736. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  7737. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  7738. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  7739. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  7740. $tableReferences = $this->getAllTableReferences();
  7741. foreach ($tableNames as $tableName) {
  7742. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  7743. $this->setComponentSchema($tableName, $references);
  7744. $this->setComponentResponse($tableName);
  7745. $this->setComponentRequestBody($tableName);
  7746. }
  7747. $this->setComponentParameters();
  7748. foreach ($tableNames as $index => $tableName) {
  7749. $this->setTag($index, $tableName);
  7750. }
  7751. }
  7752. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  7753. {
  7754. $tableHandler = VariableStore::get('authorization.tableHandler');
  7755. if (!$tableHandler) {
  7756. return true;
  7757. }
  7758. return (bool) call_user_func($tableHandler, $operation, $tableName);
  7759. }
  7760. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  7761. {
  7762. $columnHandler = VariableStore::get('authorization.columnHandler');
  7763. if (!$columnHandler) {
  7764. return true;
  7765. }
  7766. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  7767. }
  7768. private function setPath(string $tableName) /*: void*/
  7769. {
  7770. $table = $this->reflection->getTable($tableName);
  7771. $type = $table->getType();
  7772. $pk = $table->getPk();
  7773. $pkName = $pk ? $pk->getName() : '';
  7774. foreach ($this->operations as $operation => $method) {
  7775. if (!$pkName && $operation != 'list') {
  7776. continue;
  7777. }
  7778. if ($type != 'table' && $operation != 'list') {
  7779. continue;
  7780. }
  7781. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7782. continue;
  7783. }
  7784. $parameters = [];
  7785. if (in_array($operation, ['list', 'create'])) {
  7786. $path = sprintf('/records/%s', $tableName);
  7787. if ($operation == 'list') {
  7788. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  7789. }
  7790. } else {
  7791. $path = sprintf('/records/%s/{id}', $tableName);
  7792. if ($operation == 'read') {
  7793. $parameters = ['pk', 'include', 'exclude', 'join'];
  7794. } else {
  7795. $parameters = ['pk'];
  7796. }
  7797. }
  7798. foreach ($parameters as $p => $parameter) {
  7799. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  7800. }
  7801. if (in_array($operation, ['create', 'update', 'increment'])) {
  7802. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . rawurlencode($tableName));
  7803. }
  7804. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  7805. $this->openapi->set("paths|$path|$method|operationId", "$operation" . "_" . "$tableName");
  7806. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  7807. switch ($operation) {
  7808. case 'list':
  7809. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . rawurlencode($tableName));
  7810. break;
  7811. case 'create':
  7812. if ($pk->getType() == 'integer') {
  7813. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  7814. } else {
  7815. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  7816. }
  7817. break;
  7818. case 'read':
  7819. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . rawurlencode($tableName));
  7820. break;
  7821. case 'update':
  7822. case 'delete':
  7823. case 'increment':
  7824. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  7825. break;
  7826. }
  7827. }
  7828. }
  7829. private function setComponentSchema(string $tableName, array $references) /*: void*/
  7830. {
  7831. $table = $this->reflection->getTable($tableName);
  7832. $type = $table->getType();
  7833. $pk = $table->getPk();
  7834. $pkName = $pk ? $pk->getName() : '';
  7835. foreach ($this->operations as $operation => $method) {
  7836. if (!$pkName && $operation != 'list') {
  7837. continue;
  7838. }
  7839. if ($type != 'table' && $operation != 'list') {
  7840. continue;
  7841. }
  7842. if ($operation == 'delete') {
  7843. continue;
  7844. }
  7845. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7846. continue;
  7847. }
  7848. if ($operation == 'list') {
  7849. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  7850. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  7851. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  7852. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  7853. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  7854. } else {
  7855. $prefix = "components|schemas|$operation-$tableName";
  7856. }
  7857. $this->openapi->set("$prefix|type", "object");
  7858. foreach ($table->getColumnNames() as $columnName) {
  7859. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  7860. continue;
  7861. }
  7862. $column = $table->getColumn($columnName);
  7863. $properties = $this->types[$column->getType()];
  7864. foreach ($properties as $key => $value) {
  7865. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  7866. }
  7867. if ($column->getPk()) {
  7868. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  7869. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  7870. }
  7871. $fk = $column->getFk();
  7872. if ($fk) {
  7873. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  7874. }
  7875. }
  7876. }
  7877. }
  7878. private function setComponentResponse(string $tableName) /*: void*/
  7879. {
  7880. $table = $this->reflection->getTable($tableName);
  7881. $type = $table->getType();
  7882. $pk = $table->getPk();
  7883. $pkName = $pk ? $pk->getName() : '';
  7884. foreach (['list', 'read'] as $operation) {
  7885. if (!$pkName && $operation != 'list') {
  7886. continue;
  7887. }
  7888. if ($type != 'table' && $operation != 'list') {
  7889. continue;
  7890. }
  7891. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7892. continue;
  7893. }
  7894. if ($operation == 'list') {
  7895. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  7896. } else {
  7897. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  7898. }
  7899. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . rawurlencode($tableName));
  7900. }
  7901. }
  7902. private function setComponentRequestBody(string $tableName) /*: void*/
  7903. {
  7904. $table = $this->reflection->getTable($tableName);
  7905. $type = $table->getType();
  7906. $pk = $table->getPk();
  7907. $pkName = $pk ? $pk->getName() : '';
  7908. if ($pkName && $type == 'table') {
  7909. foreach (['create', 'update', 'increment'] as $operation) {
  7910. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7911. continue;
  7912. }
  7913. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  7914. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . rawurlencode($tableName));
  7915. }
  7916. }
  7917. }
  7918. private function setComponentParameters() /*: void*/
  7919. {
  7920. $this->openapi->set("components|parameters|pk|name", "id");
  7921. $this->openapi->set("components|parameters|pk|in", "path");
  7922. $this->openapi->set("components|parameters|pk|schema|type", "string");
  7923. $this->openapi->set("components|parameters|pk|description", "primary key value");
  7924. $this->openapi->set("components|parameters|pk|required", true);
  7925. $this->openapi->set("components|parameters|filter|name", "filter");
  7926. $this->openapi->set("components|parameters|filter|in", "query");
  7927. $this->openapi->set("components|parameters|filter|schema|type", "array");
  7928. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  7929. $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");
  7930. $this->openapi->set("components|parameters|filter|required", false);
  7931. $this->openapi->set("components|parameters|include|name", "include");
  7932. $this->openapi->set("components|parameters|include|in", "query");
  7933. $this->openapi->set("components|parameters|include|schema|type", "string");
  7934. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  7935. $this->openapi->set("components|parameters|include|required", false);
  7936. $this->openapi->set("components|parameters|exclude|name", "exclude");
  7937. $this->openapi->set("components|parameters|exclude|in", "query");
  7938. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  7939. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  7940. $this->openapi->set("components|parameters|exclude|required", false);
  7941. $this->openapi->set("components|parameters|order|name", "order");
  7942. $this->openapi->set("components|parameters|order|in", "query");
  7943. $this->openapi->set("components|parameters|order|schema|type", "array");
  7944. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  7945. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  7946. $this->openapi->set("components|parameters|order|required", false);
  7947. $this->openapi->set("components|parameters|size|name", "size");
  7948. $this->openapi->set("components|parameters|size|in", "query");
  7949. $this->openapi->set("components|parameters|size|schema|type", "string");
  7950. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  7951. $this->openapi->set("components|parameters|size|required", false);
  7952. $this->openapi->set("components|parameters|page|name", "page");
  7953. $this->openapi->set("components|parameters|page|in", "query");
  7954. $this->openapi->set("components|parameters|page|schema|type", "string");
  7955. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  7956. $this->openapi->set("components|parameters|page|required", false);
  7957. $this->openapi->set("components|parameters|join|name", "join");
  7958. $this->openapi->set("components|parameters|join|in", "query");
  7959. $this->openapi->set("components|parameters|join|schema|type", "array");
  7960. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  7961. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  7962. $this->openapi->set("components|parameters|join|required", false);
  7963. }
  7964. private function setTag(int $index, string $tableName) /*: void*/
  7965. {
  7966. $this->openapi->set("tags|$index|name", "$tableName");
  7967. $this->openapi->set("tags|$index|description", "$tableName operations");
  7968. }
  7969. }
  7970. }
  7971. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  7972. namespace Tqdev\PhpCrudApi\OpenApi {
  7973. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7974. use Tqdev\PhpCrudApi\OpenApi\OpenApiBuilder;
  7975. class OpenApiService
  7976. {
  7977. private $builder;
  7978. public function __construct(ReflectionService $reflection, array $base, array $controllers, array $customBuilders)
  7979. {
  7980. $this->builder = new OpenApiBuilder($reflection, $base, $controllers, $customBuilders);
  7981. }
  7982. public function get(): OpenApiDefinition
  7983. {
  7984. return $this->builder->build();
  7985. }
  7986. }
  7987. }
  7988. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  7989. namespace Tqdev\PhpCrudApi\Record\Condition {
  7990. class AndCondition extends Condition
  7991. {
  7992. private $conditions;
  7993. public function __construct(Condition $condition1, Condition $condition2)
  7994. {
  7995. $this->conditions = [$condition1, $condition2];
  7996. }
  7997. public function _and(Condition $condition): Condition
  7998. {
  7999. if ($condition instanceof NoCondition) {
  8000. return $this;
  8001. }
  8002. $this->conditions[] = $condition;
  8003. return $this;
  8004. }
  8005. public function getConditions(): array
  8006. {
  8007. return $this->conditions;
  8008. }
  8009. public static function fromArray(array $conditions): Condition
  8010. {
  8011. $condition = new NoCondition();
  8012. foreach ($conditions as $c) {
  8013. $condition = $condition->_and($c);
  8014. }
  8015. return $condition;
  8016. }
  8017. }
  8018. }
  8019. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  8020. namespace Tqdev\PhpCrudApi\Record\Condition {
  8021. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  8022. class ColumnCondition extends Condition
  8023. {
  8024. private $column;
  8025. private $operator;
  8026. private $value;
  8027. public function __construct(ReflectedColumn $column, string $operator, string $value)
  8028. {
  8029. $this->column = $column;
  8030. $this->operator = $operator;
  8031. $this->value = $value;
  8032. }
  8033. public function getColumn(): ReflectedColumn
  8034. {
  8035. return $this->column;
  8036. }
  8037. public function getOperator(): string
  8038. {
  8039. return $this->operator;
  8040. }
  8041. public function getValue(): string
  8042. {
  8043. return $this->value;
  8044. }
  8045. }
  8046. }
  8047. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  8048. namespace Tqdev\PhpCrudApi\Record\Condition {
  8049. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8050. abstract class Condition
  8051. {
  8052. public function _and(Condition $condition): Condition
  8053. {
  8054. if ($condition instanceof NoCondition) {
  8055. return $this;
  8056. }
  8057. return new AndCondition($this, $condition);
  8058. }
  8059. public function _or(Condition $condition): Condition
  8060. {
  8061. if ($condition instanceof NoCondition) {
  8062. return $this;
  8063. }
  8064. return new OrCondition($this, $condition);
  8065. }
  8066. public function _not(): Condition
  8067. {
  8068. return new NotCondition($this);
  8069. }
  8070. public static function fromString(ReflectedTable $table, string $value): Condition
  8071. {
  8072. $condition = new NoCondition();
  8073. $parts = explode(',', $value, 3);
  8074. if (count($parts) < 2) {
  8075. return $condition;
  8076. }
  8077. if (count($parts) < 3) {
  8078. $parts[2] = '';
  8079. }
  8080. $field = $table->getColumn($parts[0]);
  8081. $command = $parts[1];
  8082. $negate = false;
  8083. $spatial = false;
  8084. if (strlen($command) > 2) {
  8085. if (substr($command, 0, 1) == 'n') {
  8086. $negate = true;
  8087. $command = substr($command, 1);
  8088. }
  8089. if (substr($command, 0, 1) == 's') {
  8090. $spatial = true;
  8091. $command = substr($command, 1);
  8092. }
  8093. }
  8094. if ($spatial) {
  8095. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  8096. $condition = new SpatialCondition($field, $command, $parts[2]);
  8097. }
  8098. } else {
  8099. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  8100. $condition = new ColumnCondition($field, $command, $parts[2]);
  8101. }
  8102. }
  8103. if ($negate) {
  8104. $condition = $condition->_not();
  8105. }
  8106. return $condition;
  8107. }
  8108. }
  8109. }
  8110. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  8111. namespace Tqdev\PhpCrudApi\Record\Condition {
  8112. class NoCondition extends Condition
  8113. {
  8114. public function _and(Condition $condition): Condition
  8115. {
  8116. return $condition;
  8117. }
  8118. public function _or(Condition $condition): Condition
  8119. {
  8120. return $condition;
  8121. }
  8122. public function _not(): Condition
  8123. {
  8124. return $this;
  8125. }
  8126. }
  8127. }
  8128. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  8129. namespace Tqdev\PhpCrudApi\Record\Condition {
  8130. class NotCondition extends Condition
  8131. {
  8132. private $condition;
  8133. public function __construct(Condition $condition)
  8134. {
  8135. $this->condition = $condition;
  8136. }
  8137. public function getCondition(): Condition
  8138. {
  8139. return $this->condition;
  8140. }
  8141. }
  8142. }
  8143. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  8144. namespace Tqdev\PhpCrudApi\Record\Condition {
  8145. class OrCondition extends Condition
  8146. {
  8147. private $conditions;
  8148. public function __construct(Condition $condition1, Condition $condition2)
  8149. {
  8150. $this->conditions = [$condition1, $condition2];
  8151. }
  8152. public function _or(Condition $condition): Condition
  8153. {
  8154. if ($condition instanceof NoCondition) {
  8155. return $this;
  8156. }
  8157. $this->conditions[] = $condition;
  8158. return $this;
  8159. }
  8160. public function getConditions(): array
  8161. {
  8162. return $this->conditions;
  8163. }
  8164. public static function fromArray(array $conditions): Condition
  8165. {
  8166. $condition = new NoCondition();
  8167. foreach ($conditions as $c) {
  8168. $condition = $condition->_or($c);
  8169. }
  8170. return $condition;
  8171. }
  8172. }
  8173. }
  8174. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  8175. namespace Tqdev\PhpCrudApi\Record\Condition {
  8176. class SpatialCondition extends ColumnCondition
  8177. {
  8178. }
  8179. }
  8180. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  8181. namespace Tqdev\PhpCrudApi\Record\Document {
  8182. use Tqdev\PhpCrudApi\Record\ErrorCode;
  8183. class ErrorDocument implements \JsonSerializable
  8184. {
  8185. public $code;
  8186. public $message;
  8187. public $details;
  8188. public function __construct(ErrorCode $errorCode, string $argument, $details)
  8189. {
  8190. $this->code = $errorCode->getCode();
  8191. $this->message = $errorCode->getMessage($argument);
  8192. $this->details = $details;
  8193. }
  8194. public function getCode(): int
  8195. {
  8196. return $this->code;
  8197. }
  8198. public function getMessage(): string
  8199. {
  8200. return $this->message;
  8201. }
  8202. public function serialize()
  8203. {
  8204. return [
  8205. 'code' => $this->code,
  8206. 'message' => $this->message,
  8207. 'details' => $this->details,
  8208. ];
  8209. }
  8210. public function jsonSerialize()
  8211. {
  8212. return array_filter($this->serialize());
  8213. }
  8214. }
  8215. }
  8216. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  8217. namespace Tqdev\PhpCrudApi\Record\Document {
  8218. class ListDocument implements \JsonSerializable
  8219. {
  8220. private $records;
  8221. private $results;
  8222. public function __construct(array $records, int $results)
  8223. {
  8224. $this->records = $records;
  8225. $this->results = $results;
  8226. }
  8227. public function getRecords(): array
  8228. {
  8229. return $this->records;
  8230. }
  8231. public function getResults(): int
  8232. {
  8233. return $this->results;
  8234. }
  8235. public function serialize()
  8236. {
  8237. return [
  8238. 'records' => $this->records,
  8239. 'results' => $this->results,
  8240. ];
  8241. }
  8242. public function jsonSerialize()
  8243. {
  8244. return array_filter($this->serialize(), function ($v) {
  8245. return $v !== 0;
  8246. });
  8247. }
  8248. }
  8249. }
  8250. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  8251. namespace Tqdev\PhpCrudApi\Record {
  8252. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8253. class ColumnIncluder
  8254. {
  8255. private function isMandatory(string $tableName, string $columnName, array $params): bool
  8256. {
  8257. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  8258. }
  8259. private function select(
  8260. string $tableName,
  8261. bool $primaryTable,
  8262. array $params,
  8263. string $paramName,
  8264. array $columnNames,
  8265. bool $include
  8266. ): array {
  8267. if (!isset($params[$paramName])) {
  8268. return $columnNames;
  8269. }
  8270. $columns = array();
  8271. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  8272. $columns[$columnName] = true;
  8273. }
  8274. $result = array();
  8275. foreach ($columnNames as $columnName) {
  8276. $match = isset($columns['*.*']);
  8277. if (!$match) {
  8278. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  8279. }
  8280. if ($primaryTable && !$match) {
  8281. $match = isset($columns['*']) || isset($columns[$columnName]);
  8282. }
  8283. if ($match) {
  8284. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  8285. $result[] = $columnName;
  8286. }
  8287. } else {
  8288. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  8289. $result[] = $columnName;
  8290. }
  8291. }
  8292. }
  8293. return $result;
  8294. }
  8295. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  8296. {
  8297. $tableName = $table->getName();
  8298. $results = $table->getColumnNames();
  8299. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  8300. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  8301. return $results;
  8302. }
  8303. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  8304. {
  8305. $results = array();
  8306. $columnNames = $this->getNames($table, $primaryTable, $params);
  8307. foreach ($columnNames as $columnName) {
  8308. if (property_exists($record, $columnName)) {
  8309. $results[$columnName] = $record->$columnName;
  8310. }
  8311. }
  8312. return $results;
  8313. }
  8314. }
  8315. }
  8316. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  8317. namespace Tqdev\PhpCrudApi\Record {
  8318. use Tqdev\PhpCrudApi\ResponseFactory;
  8319. class ErrorCode
  8320. {
  8321. private $code;
  8322. private $message;
  8323. private $status;
  8324. const ERROR_NOT_FOUND = 9999;
  8325. const ROUTE_NOT_FOUND = 1000;
  8326. const TABLE_NOT_FOUND = 1001;
  8327. const ARGUMENT_COUNT_MISMATCH = 1002;
  8328. const RECORD_NOT_FOUND = 1003;
  8329. const ORIGIN_FORBIDDEN = 1004;
  8330. const COLUMN_NOT_FOUND = 1005;
  8331. const TABLE_ALREADY_EXISTS = 1006;
  8332. const COLUMN_ALREADY_EXISTS = 1007;
  8333. const HTTP_MESSAGE_NOT_READABLE = 1008;
  8334. const DUPLICATE_KEY_EXCEPTION = 1009;
  8335. const DATA_INTEGRITY_VIOLATION = 1010;
  8336. const AUTHENTICATION_REQUIRED = 1011;
  8337. const AUTHENTICATION_FAILED = 1012;
  8338. const INPUT_VALIDATION_FAILED = 1013;
  8339. const OPERATION_FORBIDDEN = 1014;
  8340. const OPERATION_NOT_SUPPORTED = 1015;
  8341. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  8342. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  8343. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  8344. const PAGINATION_FORBIDDEN = 1019;
  8345. private $values = [
  8346. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  8347. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  8348. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  8349. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  8350. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  8351. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  8352. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  8353. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  8354. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  8355. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  8356. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  8357. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  8358. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  8359. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  8360. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  8361. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  8362. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  8363. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  8364. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  8365. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  8366. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  8367. ];
  8368. public function __construct(int $code)
  8369. {
  8370. if (!isset($this->values[$code])) {
  8371. $code = 9999;
  8372. }
  8373. $this->code = $code;
  8374. $this->message = $this->values[$code][0];
  8375. $this->status = $this->values[$code][1];
  8376. }
  8377. public function getCode(): int
  8378. {
  8379. return $this->code;
  8380. }
  8381. public function getMessage(string $argument): string
  8382. {
  8383. return sprintf($this->message, $argument);
  8384. }
  8385. public function getStatus(): int
  8386. {
  8387. return $this->status;
  8388. }
  8389. }
  8390. }
  8391. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  8392. namespace Tqdev\PhpCrudApi\Record {
  8393. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8394. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  8395. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  8396. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  8397. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  8398. class FilterInfo
  8399. {
  8400. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  8401. {
  8402. $key = 'filter' . implode('', $path);
  8403. if (isset($params[$key])) {
  8404. foreach ($params[$key] as $filter) {
  8405. $condition = Condition::fromString($table, $filter);
  8406. if (($condition instanceof NoCondition) == false) {
  8407. $conditions->put($path, $condition);
  8408. }
  8409. }
  8410. }
  8411. }
  8412. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  8413. {
  8414. $conditions = new PathTree();
  8415. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  8416. for ($n = ord('0'); $n <= ord('9'); $n++) {
  8417. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  8418. for ($l = ord('a'); $l <= ord('f'); $l++) {
  8419. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  8420. }
  8421. }
  8422. return $conditions;
  8423. }
  8424. private function combinePathTreeOfConditions(PathTree $tree): Condition
  8425. {
  8426. $andConditions = $tree->getValues();
  8427. $and = AndCondition::fromArray($andConditions);
  8428. $orConditions = [];
  8429. foreach ($tree->getKeys() as $p) {
  8430. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  8431. }
  8432. $or = OrCondition::fromArray($orConditions);
  8433. return $and->_and($or);
  8434. }
  8435. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  8436. {
  8437. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  8438. }
  8439. }
  8440. }
  8441. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  8442. namespace Tqdev\PhpCrudApi\Record {
  8443. class HabtmValues
  8444. {
  8445. public $pkValues;
  8446. public $fkValues;
  8447. public function __construct(array $pkValues, array $fkValues)
  8448. {
  8449. $this->pkValues = $pkValues;
  8450. $this->fkValues = $fkValues;
  8451. }
  8452. }
  8453. }
  8454. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  8455. namespace Tqdev\PhpCrudApi\Record {
  8456. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8457. class OrderingInfo
  8458. {
  8459. public function getColumnOrdering(ReflectedTable $table, array $params): array
  8460. {
  8461. $fields = array();
  8462. if (isset($params['order'])) {
  8463. foreach ($params['order'] as $order) {
  8464. $parts = explode(',', $order, 3);
  8465. $columnName = $parts[0];
  8466. if (!$table->hasColumn($columnName)) {
  8467. continue;
  8468. }
  8469. $ascending = 'ASC';
  8470. if (count($parts) > 1) {
  8471. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  8472. $ascending = 'DESC';
  8473. }
  8474. }
  8475. $fields[] = [$columnName, $ascending];
  8476. }
  8477. }
  8478. if (count($fields) == 0) {
  8479. return $this->getDefaultColumnOrdering($table);
  8480. }
  8481. return $fields;
  8482. }
  8483. public function getDefaultColumnOrdering(ReflectedTable $table): array
  8484. {
  8485. $fields = array();
  8486. $pk = $table->getPk();
  8487. if ($pk) {
  8488. $fields[] = [$pk->getName(), 'ASC'];
  8489. } else {
  8490. foreach ($table->getColumnNames() as $columnName) {
  8491. $fields[] = [$columnName, 'ASC'];
  8492. }
  8493. }
  8494. return $fields;
  8495. }
  8496. }
  8497. }
  8498. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  8499. namespace Tqdev\PhpCrudApi\Record {
  8500. class PaginationInfo
  8501. {
  8502. public $DEFAULT_PAGE_SIZE = 20;
  8503. public function hasPage(array $params): bool
  8504. {
  8505. return isset($params['page']);
  8506. }
  8507. public function getPageOffset(array $params): int
  8508. {
  8509. $offset = 0;
  8510. $pageSize = $this->getPageSize($params);
  8511. if (isset($params['page'])) {
  8512. foreach ($params['page'] as $page) {
  8513. $parts = explode(',', $page, 2);
  8514. $page = intval($parts[0]) - 1;
  8515. $offset = $page * $pageSize;
  8516. }
  8517. }
  8518. return $offset;
  8519. }
  8520. private function getPageSize(array $params): int
  8521. {
  8522. $pageSize = $this->DEFAULT_PAGE_SIZE;
  8523. if (isset($params['page'])) {
  8524. foreach ($params['page'] as $page) {
  8525. $parts = explode(',', $page, 2);
  8526. if (count($parts) > 1) {
  8527. $pageSize = intval($parts[1]);
  8528. }
  8529. }
  8530. }
  8531. return $pageSize;
  8532. }
  8533. public function getResultSize(array $params): int
  8534. {
  8535. $numberOfRows = -1;
  8536. if (isset($params['size'])) {
  8537. foreach ($params['size'] as $size) {
  8538. $numberOfRows = intval($size);
  8539. }
  8540. }
  8541. return $numberOfRows;
  8542. }
  8543. public function getPageLimit(array $params): int
  8544. {
  8545. $pageLimit = -1;
  8546. if ($this->hasPage($params)) {
  8547. $pageLimit = $this->getPageSize($params);
  8548. }
  8549. $resultSize = $this->getResultSize($params);
  8550. if ($resultSize >= 0) {
  8551. if ($pageLimit >= 0) {
  8552. $pageLimit = min($pageLimit, $resultSize);
  8553. } else {
  8554. $pageLimit = $resultSize;
  8555. }
  8556. }
  8557. return $pageLimit;
  8558. }
  8559. }
  8560. }
  8561. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  8562. namespace Tqdev\PhpCrudApi\Record {
  8563. class PathTree implements \JsonSerializable
  8564. {
  8565. const WILDCARD = '*';
  8566. private $tree;
  8567. public function __construct(/* object */&$tree = null)
  8568. {
  8569. if (!$tree) {
  8570. $tree = $this->newTree();
  8571. }
  8572. $this->tree = &$tree;
  8573. }
  8574. public function newTree()
  8575. {
  8576. return (object) ['values' => [], 'branches' => (object) []];
  8577. }
  8578. public function getKeys(): array
  8579. {
  8580. $branches = (array) $this->tree->branches;
  8581. return array_keys($branches);
  8582. }
  8583. public function getValues(): array
  8584. {
  8585. return $this->tree->values;
  8586. }
  8587. public function get(string $key): PathTree
  8588. {
  8589. if (!isset($this->tree->branches->$key)) {
  8590. return null;
  8591. }
  8592. return new PathTree($this->tree->branches->$key);
  8593. }
  8594. public function put(array $path, $value)
  8595. {
  8596. $tree = &$this->tree;
  8597. foreach ($path as $key) {
  8598. if (!isset($tree->branches->$key)) {
  8599. $tree->branches->$key = $this->newTree();
  8600. }
  8601. $tree = &$tree->branches->$key;
  8602. }
  8603. $tree->values[] = $value;
  8604. }
  8605. public function match(array $path): array
  8606. {
  8607. $star = self::WILDCARD;
  8608. $tree = &$this->tree;
  8609. foreach ($path as $key) {
  8610. if (isset($tree->branches->$key)) {
  8611. $tree = &$tree->branches->$key;
  8612. } elseif (isset($tree->branches->$star)) {
  8613. $tree = &$tree->branches->$star;
  8614. } else {
  8615. return [];
  8616. }
  8617. }
  8618. return $tree->values;
  8619. }
  8620. public static function fromJson(/* object */$tree): PathTree
  8621. {
  8622. return new PathTree($tree);
  8623. }
  8624. public function jsonSerialize()
  8625. {
  8626. return $this->tree;
  8627. }
  8628. }
  8629. }
  8630. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  8631. namespace Tqdev\PhpCrudApi\Record {
  8632. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8633. use Tqdev\PhpCrudApi\Database\GenericDB;
  8634. use Tqdev\PhpCrudApi\Record\Document\ListDocument;
  8635. class RecordService
  8636. {
  8637. private $db;
  8638. private $reflection;
  8639. private $columns;
  8640. private $joiner;
  8641. private $filters;
  8642. private $ordering;
  8643. private $pagination;
  8644. public function __construct(GenericDB $db, ReflectionService $reflection)
  8645. {
  8646. $this->db = $db;
  8647. $this->reflection = $reflection;
  8648. $this->columns = new ColumnIncluder();
  8649. $this->joiner = new RelationJoiner($reflection, $this->columns);
  8650. $this->filters = new FilterInfo();
  8651. $this->ordering = new OrderingInfo();
  8652. $this->pagination = new PaginationInfo();
  8653. }
  8654. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  8655. {
  8656. $keyset = array_keys((array) $record);
  8657. foreach ($keyset as $key) {
  8658. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  8659. unset($record->$key);
  8660. }
  8661. }
  8662. if ($id != '') {
  8663. $pk = $this->reflection->getTable($tableName)->getPk();
  8664. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  8665. $field = $this->reflection->getTable($tableName)->getColumn($key);
  8666. if ($field->getName() == $pk->getName()) {
  8667. unset($record->$key);
  8668. }
  8669. }
  8670. }
  8671. }
  8672. public function hasTable(string $table): bool
  8673. {
  8674. return $this->reflection->hasTable($table);
  8675. }
  8676. public function getType(string $table): string
  8677. {
  8678. return $this->reflection->getType($table);
  8679. }
  8680. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  8681. {
  8682. $this->sanitizeRecord($tableName, $record, '');
  8683. $table = $this->reflection->getTable($tableName);
  8684. $columnValues = $this->columns->getValues($table, true, $record, $params);
  8685. return $this->db->createSingle($table, $columnValues);
  8686. }
  8687. public function read(string $tableName, string $id, array $params) /*: ?object*/
  8688. {
  8689. $table = $this->reflection->getTable($tableName);
  8690. $this->joiner->addMandatoryColumns($table, $params);
  8691. $columnNames = $this->columns->getNames($table, true, $params);
  8692. $record = $this->db->selectSingle($table, $columnNames, $id);
  8693. if ($record == null) {
  8694. return null;
  8695. }
  8696. $records = array($record);
  8697. $this->joiner->addJoins($table, $records, $params, $this->db);
  8698. return $records[0];
  8699. }
  8700. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  8701. {
  8702. $this->sanitizeRecord($tableName, $record, $id);
  8703. $table = $this->reflection->getTable($tableName);
  8704. $columnValues = $this->columns->getValues($table, true, $record, $params);
  8705. return $this->db->updateSingle($table, $columnValues, $id);
  8706. }
  8707. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  8708. {
  8709. $table = $this->reflection->getTable($tableName);
  8710. return $this->db->deleteSingle($table, $id);
  8711. }
  8712. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  8713. {
  8714. $this->sanitizeRecord($tableName, $record, $id);
  8715. $table = $this->reflection->getTable($tableName);
  8716. $columnValues = $this->columns->getValues($table, true, $record, $params);
  8717. return $this->db->incrementSingle($table, $columnValues, $id);
  8718. }
  8719. public function _list(string $tableName, array $params): ListDocument
  8720. {
  8721. $table = $this->reflection->getTable($tableName);
  8722. $this->joiner->addMandatoryColumns($table, $params);
  8723. $columnNames = $this->columns->getNames($table, true, $params);
  8724. $condition = $this->filters->getCombinedConditions($table, $params);
  8725. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  8726. if (!$this->pagination->hasPage($params)) {
  8727. $offset = 0;
  8728. $limit = $this->pagination->getPageLimit($params);
  8729. $count = 0;
  8730. } else {
  8731. $offset = $this->pagination->getPageOffset($params);
  8732. $limit = $this->pagination->getPageLimit($params);
  8733. $count = $this->db->selectCount($table, $condition);
  8734. }
  8735. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  8736. $this->joiner->addJoins($table, $records, $params, $this->db);
  8737. return new ListDocument($records, $count);
  8738. }
  8739. }
  8740. }
  8741. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  8742. namespace Tqdev\PhpCrudApi\Record {
  8743. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8744. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8745. use Tqdev\PhpCrudApi\Database\GenericDB;
  8746. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  8747. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  8748. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  8749. class RelationJoiner
  8750. {
  8751. private $reflection;
  8752. private $ordering;
  8753. private $columns;
  8754. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  8755. {
  8756. $this->reflection = $reflection;
  8757. $this->ordering = new OrderingInfo();
  8758. $this->columns = $columns;
  8759. }
  8760. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  8761. {
  8762. if (!isset($params['join']) || !isset($params['include'])) {
  8763. return;
  8764. }
  8765. $params['mandatory'] = array();
  8766. foreach ($params['join'] as $tableNames) {
  8767. $t1 = $table;
  8768. foreach (explode(',', $tableNames) as $tableName) {
  8769. if (!$this->reflection->hasTable($tableName)) {
  8770. continue;
  8771. }
  8772. $t2 = $this->reflection->getTable($tableName);
  8773. $fks1 = $t1->getFksTo($t2->getName());
  8774. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  8775. if ($t3 != null || count($fks1) > 0) {
  8776. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  8777. }
  8778. foreach ($fks1 as $fk) {
  8779. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  8780. }
  8781. $fks2 = $t2->getFksTo($t1->getName());
  8782. if ($t3 != null || count($fks2) > 0) {
  8783. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  8784. }
  8785. foreach ($fks2 as $fk) {
  8786. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  8787. }
  8788. $t1 = $t2;
  8789. }
  8790. }
  8791. }
  8792. private function getJoinsAsPathTree(array $params): PathTree
  8793. {
  8794. $joins = new PathTree();
  8795. if (isset($params['join'])) {
  8796. foreach ($params['join'] as $tableNames) {
  8797. $path = array();
  8798. foreach (explode(',', $tableNames) as $tableName) {
  8799. if (!$this->reflection->hasTable($tableName)) {
  8800. continue;
  8801. }
  8802. $t = $this->reflection->getTable($tableName);
  8803. if ($t != null) {
  8804. $path[] = $t->getName();
  8805. }
  8806. }
  8807. $joins->put($path, true);
  8808. }
  8809. }
  8810. return $joins;
  8811. }
  8812. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  8813. {
  8814. $joins = $this->getJoinsAsPathTree($params);
  8815. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  8816. }
  8817. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  8818. {
  8819. foreach ($this->reflection->getTableNames() as $tableName) {
  8820. $t3 = $this->reflection->getTable($tableName);
  8821. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  8822. return $t3;
  8823. }
  8824. }
  8825. return null;
  8826. }
  8827. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  8828. {
  8829. foreach ($joins->getKeys() as $t2Name) {
  8830. $t2 = $this->reflection->getTable($t2Name);
  8831. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  8832. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  8833. if (!$belongsTo && !$hasMany) {
  8834. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  8835. } else {
  8836. $t3 = null;
  8837. }
  8838. $hasAndBelongsToMany = ($t3 != null);
  8839. $newRecords = array();
  8840. $fkValues = null;
  8841. $pkValues = null;
  8842. $habtmValues = null;
  8843. if ($belongsTo) {
  8844. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  8845. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  8846. }
  8847. if ($hasMany) {
  8848. $pkValues = $this->getPkEmptyValues($t1, $records);
  8849. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  8850. }
  8851. if ($hasAndBelongsToMany) {
  8852. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  8853. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  8854. }
  8855. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  8856. if ($fkValues != null) {
  8857. $this->fillFkValues($t2, $newRecords, $fkValues);
  8858. $this->setFkValues($t1, $t2, $records, $fkValues);
  8859. }
  8860. if ($pkValues != null) {
  8861. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  8862. $this->setPkValues($t1, $t2, $records, $pkValues);
  8863. }
  8864. if ($habtmValues != null) {
  8865. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  8866. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  8867. }
  8868. }
  8869. }
  8870. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  8871. {
  8872. $fkValues = array();
  8873. $fks = $t1->getFksTo($t2->getName());
  8874. foreach ($fks as $fk) {
  8875. $fkName = $fk->getName();
  8876. foreach ($records as $record) {
  8877. if (isset($record[$fkName])) {
  8878. $fkValue = $record[$fkName];
  8879. $fkValues[$fkValue] = null;
  8880. }
  8881. }
  8882. }
  8883. return $fkValues;
  8884. }
  8885. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  8886. {
  8887. $columnNames = $this->columns->getNames($t2, false, $params);
  8888. $fkIds = array_keys($fkValues);
  8889. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  8890. $records[] = $record;
  8891. }
  8892. }
  8893. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  8894. {
  8895. $pkName = $t2->getPk()->getName();
  8896. foreach ($fkRecords as $fkRecord) {
  8897. $pkValue = $fkRecord[$pkName];
  8898. $fkValues[$pkValue] = $fkRecord;
  8899. }
  8900. }
  8901. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  8902. {
  8903. $fks = $t1->getFksTo($t2->getName());
  8904. foreach ($fks as $fk) {
  8905. $fkName = $fk->getName();
  8906. foreach ($records as $i => $record) {
  8907. if (isset($record[$fkName])) {
  8908. $key = $record[$fkName];
  8909. $records[$i][$fkName] = $fkValues[$key];
  8910. }
  8911. }
  8912. }
  8913. }
  8914. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  8915. {
  8916. $pkValues = array();
  8917. $pkName = $t1->getPk()->getName();
  8918. foreach ($records as $record) {
  8919. $key = $record[$pkName];
  8920. $pkValues[$key] = array();
  8921. }
  8922. return $pkValues;
  8923. }
  8924. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  8925. {
  8926. $fks = $t2->getFksTo($t1->getName());
  8927. $columnNames = $this->columns->getNames($t2, false, $params);
  8928. $pkValueKeys = implode(',', array_keys($pkValues));
  8929. $conditions = array();
  8930. foreach ($fks as $fk) {
  8931. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  8932. }
  8933. $condition = OrCondition::fromArray($conditions);
  8934. $columnOrdering = array();
  8935. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  8936. if ($limit != -1) {
  8937. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  8938. }
  8939. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  8940. $records[] = $record;
  8941. }
  8942. }
  8943. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  8944. {
  8945. $fks = $t2->getFksTo($t1->getName());
  8946. foreach ($fks as $fk) {
  8947. $fkName = $fk->getName();
  8948. foreach ($pkRecords as $pkRecord) {
  8949. $key = $pkRecord[$fkName];
  8950. if (isset($pkValues[$key])) {
  8951. $pkValues[$key][] = $pkRecord;
  8952. }
  8953. }
  8954. }
  8955. }
  8956. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  8957. {
  8958. $pkName = $t1->getPk()->getName();
  8959. $t2Name = $t2->getName();
  8960. foreach ($records as $i => $record) {
  8961. $key = $record[$pkName];
  8962. $records[$i][$t2Name] = $pkValues[$key];
  8963. }
  8964. }
  8965. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  8966. {
  8967. $pkValues = $this->getPkEmptyValues($t1, $records);
  8968. $fkValues = array();
  8969. $fk1 = $t3->getFksTo($t1->getName())[0];
  8970. $fk2 = $t3->getFksTo($t2->getName())[0];
  8971. $fk1Name = $fk1->getName();
  8972. $fk2Name = $fk2->getName();
  8973. $columnNames = array($fk1Name, $fk2Name);
  8974. $pkIds = implode(',', array_keys($pkValues));
  8975. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  8976. $columnOrdering = array();
  8977. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  8978. if ($limit != -1) {
  8979. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  8980. }
  8981. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  8982. foreach ($records as $record) {
  8983. $val1 = $record[$fk1Name];
  8984. $val2 = $record[$fk2Name];
  8985. $pkValues[$val1][] = $val2;
  8986. $fkValues[$val2] = null;
  8987. }
  8988. return new HabtmValues($pkValues, $fkValues);
  8989. }
  8990. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  8991. {
  8992. $pkName = $t1->getPk()->getName();
  8993. $t2Name = $t2->getName();
  8994. foreach ($records as $i => $record) {
  8995. $key = $record[$pkName];
  8996. $val = array();
  8997. $fks = $habtmValues->pkValues[$key];
  8998. foreach ($fks as $fk) {
  8999. $val[] = $habtmValues->fkValues[$fk];
  9000. }
  9001. $records[$i][$t2Name] = $val;
  9002. }
  9003. }
  9004. }
  9005. }
  9006. // file: src/Tqdev/PhpCrudApi/Api.php
  9007. namespace Tqdev\PhpCrudApi {
  9008. use Psr\Http\Message\ResponseInterface;
  9009. use Psr\Http\Message\ServerRequestInterface;
  9010. use Psr\Http\Server\RequestHandlerInterface;
  9011. use Tqdev\PhpCrudApi\Cache\CacheFactory;
  9012. use Tqdev\PhpCrudApi\Column\DefinitionService;
  9013. use Tqdev\PhpCrudApi\Column\ReflectionService;
  9014. use Tqdev\PhpCrudApi\Controller\CacheController;
  9015. use Tqdev\PhpCrudApi\Controller\ColumnController;
  9016. use Tqdev\PhpCrudApi\Controller\GeoJsonController;
  9017. use Tqdev\PhpCrudApi\Controller\JsonResponder;
  9018. use Tqdev\PhpCrudApi\Controller\OpenApiController;
  9019. use Tqdev\PhpCrudApi\Controller\RecordController;
  9020. use Tqdev\PhpCrudApi\Database\GenericDB;
  9021. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  9022. use Tqdev\PhpCrudApi\Middleware\AuthorizationMiddleware;
  9023. use Tqdev\PhpCrudApi\Middleware\BasicAuthMiddleware;
  9024. use Tqdev\PhpCrudApi\Middleware\CorsMiddleware;
  9025. use Tqdev\PhpCrudApi\Middleware\CustomizationMiddleware;
  9026. use Tqdev\PhpCrudApi\Middleware\DbAuthMiddleware;
  9027. use Tqdev\PhpCrudApi\Middleware\FirewallMiddleware;
  9028. use Tqdev\PhpCrudApi\Middleware\IpAddressMiddleware;
  9029. use Tqdev\PhpCrudApi\Middleware\JoinLimitsMiddleware;
  9030. use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware;
  9031. use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware;
  9032. use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware;
  9033. use Tqdev\PhpCrudApi\Middleware\ReconnectMiddleware;
  9034. use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter;
  9035. use Tqdev\PhpCrudApi\Middleware\SanitationMiddleware;
  9036. use Tqdev\PhpCrudApi\Middleware\ValidationMiddleware;
  9037. use Tqdev\PhpCrudApi\Middleware\XsrfMiddleware;
  9038. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  9039. use Tqdev\PhpCrudApi\Record\ErrorCode;
  9040. use Tqdev\PhpCrudApi\Record\RecordService;
  9041. use Tqdev\PhpCrudApi\ResponseUtils;
  9042. class Api implements RequestHandlerInterface
  9043. {
  9044. private $router;
  9045. private $responder;
  9046. private $debug;
  9047. public function __construct(Config $config)
  9048. {
  9049. $db = new GenericDB(
  9050. $config->getDriver(),
  9051. $config->getAddress(),
  9052. $config->getPort(),
  9053. $config->getDatabase(),
  9054. $config->getTables(),
  9055. $config->getUsername(),
  9056. $config->getPassword()
  9057. );
  9058. $prefix = sprintf('phpcrudapi-%s-', substr(md5(__FILE__), 0, 8));
  9059. $cache = CacheFactory::create($config->getCacheType(), $prefix, $config->getCachePath());
  9060. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  9061. $responder = new JsonResponder();
  9062. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  9063. foreach ($config->getMiddlewares() as $middleware => $properties) {
  9064. switch ($middleware) {
  9065. case 'cors':
  9066. new CorsMiddleware($router, $responder, $properties);
  9067. break;
  9068. case 'firewall':
  9069. new FirewallMiddleware($router, $responder, $properties);
  9070. break;
  9071. case 'basicAuth':
  9072. new BasicAuthMiddleware($router, $responder, $properties);
  9073. break;
  9074. case 'jwtAuth':
  9075. new JwtAuthMiddleware($router, $responder, $properties);
  9076. break;
  9077. case 'dbAuth':
  9078. new DbAuthMiddleware($router, $responder, $properties, $reflection, $db);
  9079. break;
  9080. case 'reconnect':
  9081. new ReconnectMiddleware($router, $responder, $properties, $reflection, $db);
  9082. break;
  9083. case 'validation':
  9084. new ValidationMiddleware($router, $responder, $properties, $reflection);
  9085. break;
  9086. case 'ipAddress':
  9087. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  9088. break;
  9089. case 'sanitation':
  9090. new SanitationMiddleware($router, $responder, $properties, $reflection);
  9091. break;
  9092. case 'multiTenancy':
  9093. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  9094. break;
  9095. case 'authorization':
  9096. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  9097. break;
  9098. case 'xsrf':
  9099. new XsrfMiddleware($router, $responder, $properties);
  9100. break;
  9101. case 'pageLimits':
  9102. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  9103. break;
  9104. case 'joinLimits':
  9105. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  9106. break;
  9107. case 'customization':
  9108. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  9109. break;
  9110. }
  9111. }
  9112. foreach ($config->getControllers() as $controller) {
  9113. switch ($controller) {
  9114. case 'records':
  9115. $records = new RecordService($db, $reflection);
  9116. new RecordController($router, $responder, $records);
  9117. break;
  9118. case 'columns':
  9119. $definition = new DefinitionService($db, $reflection);
  9120. new ColumnController($router, $responder, $reflection, $definition);
  9121. break;
  9122. case 'cache':
  9123. new CacheController($router, $responder, $cache);
  9124. break;
  9125. case 'openapi':
  9126. $openApi = new OpenApiService($reflection, $config->getOpenApiBase(), $config->getControllers(), $config->getCustomOpenApiBuilders());
  9127. new OpenApiController($router, $responder, $openApi);
  9128. break;
  9129. case 'geojson':
  9130. $records = new RecordService($db, $reflection);
  9131. $geoJson = new GeoJsonService($reflection, $records);
  9132. new GeoJsonController($router, $responder, $geoJson);
  9133. break;
  9134. }
  9135. }
  9136. foreach ($config->getCustomControllers() as $className) {
  9137. if (class_exists($className)) {
  9138. $records = new RecordService($db, $reflection);
  9139. new $className($router, $responder, $records);
  9140. }
  9141. }
  9142. $this->router = $router;
  9143. $this->responder = $responder;
  9144. $this->debug = $config->getDebug();
  9145. }
  9146. private function parseBody(string $body) /*: ?object*/
  9147. {
  9148. $first = substr($body, 0, 1);
  9149. if ($first == '[' || $first == '{') {
  9150. $object = json_decode($body);
  9151. $causeCode = json_last_error();
  9152. if ($causeCode !== JSON_ERROR_NONE) {
  9153. $object = null;
  9154. }
  9155. } else {
  9156. parse_str($body, $input);
  9157. foreach ($input as $key => $value) {
  9158. if (substr($key, -9) == '__is_null') {
  9159. $input[substr($key, 0, -9)] = null;
  9160. unset($input[$key]);
  9161. }
  9162. }
  9163. $object = (object) $input;
  9164. }
  9165. return $object;
  9166. }
  9167. private function addParsedBody(ServerRequestInterface $request): ServerRequestInterface
  9168. {
  9169. $parsedBody = $request->getParsedBody();
  9170. if ($parsedBody) {
  9171. $request = $this->applyParsedBodyHack($request);
  9172. } else {
  9173. $body = $request->getBody();
  9174. if ($body->isReadable()) {
  9175. if ($body->isSeekable()) {
  9176. $body->rewind();
  9177. }
  9178. $contents = $body->getContents();
  9179. if ($body->isSeekable()) {
  9180. $body->rewind();
  9181. }
  9182. if ($contents) {
  9183. $parsedBody = $this->parseBody($contents);
  9184. $request = $request->withParsedBody($parsedBody);
  9185. }
  9186. }
  9187. }
  9188. return $request;
  9189. }
  9190. private function applyParsedBodyHack(ServerRequestInterface $request): ServerRequestInterface
  9191. {
  9192. $parsedBody = $request->getParsedBody();
  9193. if (is_array($parsedBody)) { // is it really?
  9194. $contents = json_encode($parsedBody);
  9195. $parsedBody = $this->parseBody($contents);
  9196. $request = $request->withParsedBody($parsedBody);
  9197. }
  9198. return $request;
  9199. }
  9200. public function handle(ServerRequestInterface $request): ResponseInterface
  9201. {
  9202. $response = null;
  9203. try {
  9204. $response = $this->router->route($this->addParsedBody($request));
  9205. } catch (\Throwable $e) {
  9206. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  9207. if ($this->debug) {
  9208. $response = ResponseUtils::addExceptionHeaders($response, $e);
  9209. }
  9210. }
  9211. return $response;
  9212. }
  9213. }
  9214. }
  9215. // file: src/Tqdev/PhpCrudApi/Config.php
  9216. namespace Tqdev\PhpCrudApi {
  9217. class Config
  9218. {
  9219. private $values = [
  9220. 'driver' => null,
  9221. 'address' => 'localhost',
  9222. 'port' => null,
  9223. 'username' => null,
  9224. 'password' => null,
  9225. 'database' => null,
  9226. 'tables' => '',
  9227. 'middlewares' => 'cors',
  9228. 'controllers' => 'records,geojson,openapi',
  9229. 'customControllers' => '',
  9230. 'customOpenApiBuilders' => '',
  9231. 'cacheType' => 'TempFile',
  9232. 'cachePath' => '',
  9233. 'cacheTime' => 10,
  9234. 'debug' => false,
  9235. 'basePath' => '',
  9236. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  9237. ];
  9238. private function getDefaultDriver(array $values): string
  9239. {
  9240. if (isset($values['driver'])) {
  9241. return $values['driver'];
  9242. }
  9243. return 'mysql';
  9244. }
  9245. private function getDefaultPort(string $driver): int
  9246. {
  9247. switch ($driver) {
  9248. case 'mysql':
  9249. return 3306;
  9250. case 'pgsql':
  9251. return 5432;
  9252. case 'sqlsrv':
  9253. return 1433;
  9254. case 'sqlite':
  9255. return 0;
  9256. }
  9257. }
  9258. private function getDefaultAddress(string $driver): string
  9259. {
  9260. switch ($driver) {
  9261. case 'mysql':
  9262. return 'localhost';
  9263. case 'pgsql':
  9264. return 'localhost';
  9265. case 'sqlsrv':
  9266. return 'localhost';
  9267. case 'sqlite':
  9268. return 'data.db';
  9269. }
  9270. }
  9271. private function getDriverDefaults(string $driver): array
  9272. {
  9273. return [
  9274. 'driver' => $driver,
  9275. 'address' => $this->getDefaultAddress($driver),
  9276. 'port' => $this->getDefaultPort($driver),
  9277. ];
  9278. }
  9279. public function __construct(array $values)
  9280. {
  9281. $driver = $this->getDefaultDriver($values);
  9282. $defaults = $this->getDriverDefaults($driver);
  9283. $newValues = array_merge($this->values, $defaults, $values);
  9284. $newValues = $this->parseMiddlewares($newValues);
  9285. $diff = array_diff_key($newValues, $this->values);
  9286. if (!empty($diff)) {
  9287. $key = array_keys($diff)[0];
  9288. throw new \Exception("Config has invalid value '$key'");
  9289. }
  9290. $this->values = $newValues;
  9291. }
  9292. private function parseMiddlewares(array $values): array
  9293. {
  9294. $newValues = array();
  9295. $properties = array();
  9296. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  9297. foreach ($middlewares as $middleware) {
  9298. $properties[$middleware] = [];
  9299. }
  9300. foreach ($values as $key => $value) {
  9301. if (strpos($key, '.') === false) {
  9302. $newValues[$key] = $value;
  9303. } else {
  9304. list($middleware, $key2) = explode('.', $key, 2);
  9305. if (isset($properties[$middleware])) {
  9306. $properties[$middleware][$key2] = $value;
  9307. } else {
  9308. throw new \Exception("Config has invalid value '$key'");
  9309. }
  9310. }
  9311. }
  9312. $newValues['middlewares'] = array_reverse($properties, true);
  9313. return $newValues;
  9314. }
  9315. public function getDriver(): string
  9316. {
  9317. return $this->values['driver'];
  9318. }
  9319. public function getAddress(): string
  9320. {
  9321. return $this->values['address'];
  9322. }
  9323. public function getPort(): int
  9324. {
  9325. return $this->values['port'];
  9326. }
  9327. public function getUsername(): string
  9328. {
  9329. return $this->values['username'];
  9330. }
  9331. public function getPassword(): string
  9332. {
  9333. return $this->values['password'];
  9334. }
  9335. public function getDatabase(): string
  9336. {
  9337. return $this->values['database'];
  9338. }
  9339. public function getTables(): array
  9340. {
  9341. return array_filter(array_map('trim', explode(',', $this->values['tables'])));
  9342. }
  9343. public function getMiddlewares(): array
  9344. {
  9345. return $this->values['middlewares'];
  9346. }
  9347. public function getControllers(): array
  9348. {
  9349. return array_filter(array_map('trim', explode(',', $this->values['controllers'])));
  9350. }
  9351. public function getCustomControllers(): array
  9352. {
  9353. return array_filter(array_map('trim', explode(',', $this->values['customControllers'])));
  9354. }
  9355. public function getCustomOpenApiBuilders(): array
  9356. {
  9357. return array_filter(array_map('trim', explode(',', $this->values['customOpenApiBuilders'])));
  9358. }
  9359. public function getCacheType(): string
  9360. {
  9361. return $this->values['cacheType'];
  9362. }
  9363. public function getCachePath(): string
  9364. {
  9365. return $this->values['cachePath'];
  9366. }
  9367. public function getCacheTime(): int
  9368. {
  9369. return $this->values['cacheTime'];
  9370. }
  9371. public function getDebug(): bool
  9372. {
  9373. return $this->values['debug'];
  9374. }
  9375. public function getBasePath(): string
  9376. {
  9377. return $this->values['basePath'];
  9378. }
  9379. public function getOpenApiBase(): array
  9380. {
  9381. return json_decode($this->values['openApiBase'], true);
  9382. }
  9383. }
  9384. }
  9385. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  9386. namespace Tqdev\PhpCrudApi {
  9387. use Nyholm\Psr7\Factory\Psr17Factory;
  9388. use Nyholm\Psr7Server\ServerRequestCreator;
  9389. use Psr\Http\Message\ServerRequestInterface;
  9390. class RequestFactory
  9391. {
  9392. public static function fromGlobals(): ServerRequestInterface
  9393. {
  9394. $psr17Factory = new Psr17Factory();
  9395. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  9396. $serverRequest = $creator->fromGlobals();
  9397. $stream = $psr17Factory->createStreamFromFile('php://input');
  9398. $serverRequest = $serverRequest->withBody($stream);
  9399. return $serverRequest;
  9400. }
  9401. public static function fromString(string $request): ServerRequestInterface
  9402. {
  9403. $parts = explode("\n\n", trim($request), 2);
  9404. $lines = explode("\n", $parts[0]);
  9405. $first = explode(' ', trim(array_shift($lines)), 2);
  9406. $method = $first[0];
  9407. $body = isset($parts[1]) ? $parts[1] : '';
  9408. $url = isset($first[1]) ? $first[1] : '';
  9409. $psr17Factory = new Psr17Factory();
  9410. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  9411. foreach ($lines as $line) {
  9412. list($key, $value) = explode(':', $line, 2);
  9413. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  9414. }
  9415. if ($body) {
  9416. $stream = $psr17Factory->createStream($body);
  9417. $stream->rewind();
  9418. $serverRequest = $serverRequest->withBody($stream);
  9419. }
  9420. return $serverRequest;
  9421. }
  9422. }
  9423. }
  9424. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  9425. namespace Tqdev\PhpCrudApi {
  9426. use Psr\Http\Message\ServerRequestInterface;
  9427. use Tqdev\PhpCrudApi\Column\ReflectionService;
  9428. class RequestUtils
  9429. {
  9430. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  9431. {
  9432. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  9433. return $request->withUri($request->getUri()->withQuery($query));
  9434. }
  9435. public static function getHeader(ServerRequestInterface $request, string $header): string
  9436. {
  9437. $headers = $request->getHeader($header);
  9438. return isset($headers[0]) ? $headers[0] : '';
  9439. }
  9440. public static function getParams(ServerRequestInterface $request): array
  9441. {
  9442. $params = array();
  9443. $query = $request->getUri()->getQuery();
  9444. //$query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  9445. $query = str_replace('%5D%5B%5D=', '%5D=', str_replace('=', '%5B%5D=', $query));
  9446. parse_str($query, $params);
  9447. return $params;
  9448. }
  9449. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  9450. {
  9451. $path = $request->getUri()->getPath();
  9452. $pathSegments = explode('/', rtrim($path, '/'));
  9453. if ($part < 0 || $part >= count($pathSegments)) {
  9454. return '';
  9455. }
  9456. return urldecode($pathSegments[$part]);
  9457. }
  9458. public static function getOperation(ServerRequestInterface $request): string
  9459. {
  9460. $method = $request->getMethod();
  9461. $path = RequestUtils::getPathSegment($request, 1);
  9462. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  9463. switch ($path) {
  9464. case 'openapi':
  9465. return 'document';
  9466. case 'columns':
  9467. return $method == 'get' ? 'reflect' : 'remodel';
  9468. case 'geojson':
  9469. case 'records':
  9470. switch ($method) {
  9471. case 'POST':
  9472. return 'create';
  9473. case 'GET':
  9474. return $hasPk ? 'read' : 'list';
  9475. case 'PUT':
  9476. return 'update';
  9477. case 'DELETE':
  9478. return 'delete';
  9479. case 'PATCH':
  9480. return 'increment';
  9481. }
  9482. }
  9483. return 'unknown';
  9484. }
  9485. private static function getJoinTables(string $tableName, array $parameters): array
  9486. {
  9487. $uniqueTableNames = array();
  9488. $uniqueTableNames[$tableName] = true;
  9489. if (isset($parameters['join'])) {
  9490. foreach ($parameters['join'] as $parameter) {
  9491. $tableNames = explode(',', trim($parameter));
  9492. foreach ($tableNames as $tableName) {
  9493. $uniqueTableNames[$tableName] = true;
  9494. }
  9495. }
  9496. }
  9497. return array_keys($uniqueTableNames);
  9498. }
  9499. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  9500. {
  9501. $path = RequestUtils::getPathSegment($request, 1);
  9502. $tableName = RequestUtils::getPathSegment($request, 2);
  9503. $allTableNames = $reflection->getTableNames();
  9504. switch ($path) {
  9505. case 'openapi':
  9506. return $allTableNames;
  9507. case 'columns':
  9508. return $tableName ? [$tableName] : $allTableNames;
  9509. case 'records':
  9510. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  9511. }
  9512. return $allTableNames;
  9513. }
  9514. }
  9515. }
  9516. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  9517. namespace Tqdev\PhpCrudApi {
  9518. use Nyholm\Psr7\Factory\Psr17Factory;
  9519. use Psr\Http\Message\ResponseInterface;
  9520. class ResponseFactory
  9521. {
  9522. const OK = 200;
  9523. const UNAUTHORIZED = 401;
  9524. const FORBIDDEN = 403;
  9525. const NOT_FOUND = 404;
  9526. const METHOD_NOT_ALLOWED = 405;
  9527. const CONFLICT = 409;
  9528. const UNPROCESSABLE_ENTITY = 422;
  9529. const INTERNAL_SERVER_ERROR = 500;
  9530. public static function fromCsv(int $status, string $csv): ResponseInterface
  9531. {
  9532. $response = self::from($status, 'text/csv', $csv);
  9533. return $response->withHeader('Content-Type', 'text/csv');
  9534. }
  9535. public static function fromHtml(int $status, string $html): ResponseInterface
  9536. {
  9537. return self::from($status, 'text/html', $html);
  9538. }
  9539. public static function fromObject(int $status, $body): ResponseInterface
  9540. {
  9541. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  9542. return self::from($status, 'application/json', $content);
  9543. }
  9544. private static function from(int $status, string $contentType, string $content): ResponseInterface
  9545. {
  9546. $psr17Factory = new Psr17Factory();
  9547. $response = $psr17Factory->createResponse($status);
  9548. $stream = $psr17Factory->createStream($content);
  9549. $stream->rewind();
  9550. $response = $response->withBody($stream);
  9551. $response = $response->withHeader('Content-Type', $contentType);
  9552. $response = $response->withHeader('Content-Length', strlen($content));
  9553. return $response;
  9554. }
  9555. public static function fromStatus(int $status): ResponseInterface
  9556. {
  9557. $psr17Factory = new Psr17Factory();
  9558. return $psr17Factory->createResponse($status);
  9559. }
  9560. }
  9561. }
  9562. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  9563. namespace Tqdev\PhpCrudApi {
  9564. use Psr\Http\Message\ResponseInterface;
  9565. class ResponseUtils
  9566. {
  9567. public static function output(ResponseInterface $response)
  9568. {
  9569. $status = $response->getStatusCode();
  9570. $headers = $response->getHeaders();
  9571. $body = $response->getBody()->getContents();
  9572. http_response_code($status);
  9573. foreach ($headers as $key => $values) {
  9574. foreach ($values as $value) {
  9575. header("$key: $value");
  9576. }
  9577. }
  9578. echo $body;
  9579. }
  9580. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  9581. {
  9582. $response = $response->withHeader('X-Exception-Name', get_class($e));
  9583. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  9584. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  9585. return $response;
  9586. }
  9587. public static function toString(ResponseInterface $response): string
  9588. {
  9589. $status = $response->getStatusCode();
  9590. $headers = $response->getHeaders();
  9591. $body = $response->getBody()->getContents();
  9592. $str = "$status\n";
  9593. foreach ($headers as $key => $values) {
  9594. foreach ($values as $value) {
  9595. $str .= "$key: $value\n";
  9596. }
  9597. }
  9598. if ($body !== '') {
  9599. $str .= "\n";
  9600. $str .= "$body\n";
  9601. }
  9602. return $str;
  9603. }
  9604. }
  9605. }
  9606. // file: src/index.php
  9607. namespace Tqdev\PhpCrudApi {
  9608. use Tqdev\PhpCrudApi\Api;
  9609. use Tqdev\PhpCrudApi\Config;
  9610. use Tqdev\PhpCrudApi\RequestFactory;
  9611. use Tqdev\PhpCrudApi\ResponseUtils;
  9612. $config = new Config([
  9613. 'username' => 'php-crud-api',
  9614. 'password' => 'php-crud-api',
  9615. 'database' => 'php-crud-api'
  9616. ]);
  9617. $request = RequestFactory::fromGlobals();
  9618. $api = new Api($config);
  9619. $response = $api->handle($request);
  9620. ResponseUtils::output($response);
  9621. }