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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171
  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. return new Response($code, [], null, '1.1', $reasonPhrase);
  1401. }
  1402. public function createStream(string $content = ''): StreamInterface
  1403. {
  1404. return Stream::create($content);
  1405. }
  1406. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
  1407. {
  1408. $resource = @\fopen($filename, $mode);
  1409. if (false === $resource) {
  1410. if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'])) {
  1411. throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.');
  1412. }
  1413. throw new \RuntimeException('The file ' . $filename . ' cannot be opened.');
  1414. }
  1415. return Stream::create($resource);
  1416. }
  1417. public function createStreamFromResource($resource): StreamInterface
  1418. {
  1419. return Stream::create($resource);
  1420. }
  1421. public function createUploadedFile(StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null): UploadedFileInterface
  1422. {
  1423. if (null === $size) {
  1424. $size = $stream->getSize();
  1425. }
  1426. return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);
  1427. }
  1428. public function createUri(string $uri = ''): UriInterface
  1429. {
  1430. return new Uri($uri);
  1431. }
  1432. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  1433. {
  1434. return new ServerRequest($method, $uri, [], null, '1.1', $serverParams);
  1435. }
  1436. }
  1437. }
  1438. // file: vendor/nyholm/psr7/src/MessageTrait.php
  1439. namespace Nyholm\Psr7 {
  1440. use Psr\Http\Message\StreamInterface;
  1441. /**
  1442. * Trait implementing functionality common to requests and responses.
  1443. *
  1444. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1445. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1446. * @author Martijn van der Ven <martijn@vanderven.se>
  1447. *
  1448. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1449. */
  1450. trait MessageTrait
  1451. {
  1452. /** @var array Map of all registered headers, as original name => array of values */
  1453. private $headers = [];
  1454. /** @var array Map of lowercase header name => original name at registration */
  1455. private $headerNames = [];
  1456. /** @var string */
  1457. private $protocol = '1.1';
  1458. /** @var StreamInterface|null */
  1459. private $stream;
  1460. public function getProtocolVersion(): string
  1461. {
  1462. return $this->protocol;
  1463. }
  1464. public function withProtocolVersion($version): self
  1465. {
  1466. if ($this->protocol === $version) {
  1467. return $this;
  1468. }
  1469. $new = clone $this;
  1470. $new->protocol = $version;
  1471. return $new;
  1472. }
  1473. public function getHeaders(): array
  1474. {
  1475. return $this->headers;
  1476. }
  1477. public function hasHeader($header): bool
  1478. {
  1479. return isset($this->headerNames[\strtolower($header)]);
  1480. }
  1481. public function getHeader($header): array
  1482. {
  1483. $header = \strtolower($header);
  1484. if (!isset($this->headerNames[$header])) {
  1485. return [];
  1486. }
  1487. $header = $this->headerNames[$header];
  1488. return $this->headers[$header];
  1489. }
  1490. public function getHeaderLine($header): string
  1491. {
  1492. return \implode(', ', $this->getHeader($header));
  1493. }
  1494. public function withHeader($header, $value): self
  1495. {
  1496. $value = $this->validateAndTrimHeader($header, $value);
  1497. $normalized = \strtolower($header);
  1498. $new = clone $this;
  1499. if (isset($new->headerNames[$normalized])) {
  1500. unset($new->headers[$new->headerNames[$normalized]]);
  1501. }
  1502. $new->headerNames[$normalized] = $header;
  1503. $new->headers[$header] = $value;
  1504. return $new;
  1505. }
  1506. public function withAddedHeader($header, $value): self
  1507. {
  1508. if (!\is_string($header) || '' === $header) {
  1509. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1510. }
  1511. $new = clone $this;
  1512. $new->setHeaders([$header => $value]);
  1513. return $new;
  1514. }
  1515. public function withoutHeader($header): self
  1516. {
  1517. $normalized = \strtolower($header);
  1518. if (!isset($this->headerNames[$normalized])) {
  1519. return $this;
  1520. }
  1521. $header = $this->headerNames[$normalized];
  1522. $new = clone $this;
  1523. unset($new->headers[$header], $new->headerNames[$normalized]);
  1524. return $new;
  1525. }
  1526. public function getBody(): StreamInterface
  1527. {
  1528. if (null === $this->stream) {
  1529. $this->stream = Stream::create('');
  1530. }
  1531. return $this->stream;
  1532. }
  1533. public function withBody(StreamInterface $body): self
  1534. {
  1535. if ($body === $this->stream) {
  1536. return $this;
  1537. }
  1538. $new = clone $this;
  1539. $new->stream = $body;
  1540. return $new;
  1541. }
  1542. private function setHeaders(array $headers) /*:void*/
  1543. {
  1544. foreach ($headers as $header => $value) {
  1545. $value = $this->validateAndTrimHeader($header, $value);
  1546. $normalized = \strtolower($header);
  1547. if (isset($this->headerNames[$normalized])) {
  1548. $header = $this->headerNames[$normalized];
  1549. $this->headers[$header] = \array_merge($this->headers[$header], $value);
  1550. } else {
  1551. $this->headerNames[$normalized] = $header;
  1552. $this->headers[$header] = $value;
  1553. }
  1554. }
  1555. }
  1556. /**
  1557. * Make sure the header complies with RFC 7230.
  1558. *
  1559. * Header names must be a non-empty string consisting of token characters.
  1560. *
  1561. * Header values must be strings consisting of visible characters with all optional
  1562. * leading and trailing whitespace stripped. This method will always strip such
  1563. * optional whitespace. Note that the method does not allow folding whitespace within
  1564. * the values as this was deprecated for almost all instances by the RFC.
  1565. *
  1566. * header-field = field-name ":" OWS field-value OWS
  1567. * field-name = 1*( "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^"
  1568. * / "_" / "`" / "|" / "~" / %x30-39 / ( %x41-5A / %x61-7A ) )
  1569. * OWS = *( SP / HTAB )
  1570. * field-value = *( ( %x21-7E / %x80-FF ) [ 1*( SP / HTAB ) ( %x21-7E / %x80-FF ) ] )
  1571. *
  1572. * @see https://tools.ietf.org/html/rfc7230#section-3.2.4
  1573. */
  1574. private function validateAndTrimHeader($header, $values): array
  1575. {
  1576. if (!\is_string($header) || 1 !== \preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@", $header)) {
  1577. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1578. }
  1579. if (!\is_array($values)) {
  1580. // This is simple, just one value.
  1581. if ((!\is_numeric($values) && !\is_string($values)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $values)) {
  1582. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1583. }
  1584. return [\trim((string) $values, " \t")];
  1585. }
  1586. if (empty($values)) {
  1587. throw new \InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
  1588. }
  1589. // Assert Non empty array
  1590. $returnValues = [];
  1591. foreach ($values as $v) {
  1592. if ((!\is_numeric($v) && !\is_string($v)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $v)) {
  1593. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1594. }
  1595. $returnValues[] = \trim((string) $v, " \t");
  1596. }
  1597. return $returnValues;
  1598. }
  1599. }
  1600. }
  1601. // file: vendor/nyholm/psr7/src/Request.php
  1602. namespace Nyholm\Psr7 {
  1603. use Psr\Http\Message\{RequestInterface, StreamInterface, UriInterface};
  1604. /**
  1605. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1606. * @author Martijn van der Ven <martijn@vanderven.se>
  1607. */
  1608. final class Request implements RequestInterface
  1609. {
  1610. use MessageTrait;
  1611. use RequestTrait;
  1612. /**
  1613. * @param string $method HTTP method
  1614. * @param string|UriInterface $uri URI
  1615. * @param array $headers Request headers
  1616. * @param string|resource|StreamInterface|null $body Request body
  1617. * @param string $version Protocol version
  1618. */
  1619. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
  1620. {
  1621. if (!($uri instanceof UriInterface)) {
  1622. $uri = new Uri($uri);
  1623. }
  1624. $this->method = $method;
  1625. $this->uri = $uri;
  1626. $this->setHeaders($headers);
  1627. $this->protocol = $version;
  1628. if (!$this->hasHeader('Host')) {
  1629. $this->updateHostFromUri();
  1630. }
  1631. // If we got no body, defer initialization of the stream until Request::getBody()
  1632. if ('' !== $body && null !== $body) {
  1633. $this->stream = Stream::create($body);
  1634. }
  1635. }
  1636. }
  1637. }
  1638. // file: vendor/nyholm/psr7/src/RequestTrait.php
  1639. namespace Nyholm\Psr7 {
  1640. use Psr\Http\Message\UriInterface;
  1641. /**
  1642. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1643. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1644. * @author Martijn van der Ven <martijn@vanderven.se>
  1645. *
  1646. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1647. */
  1648. trait RequestTrait
  1649. {
  1650. /** @var string */
  1651. private $method;
  1652. /** @var string|null */
  1653. private $requestTarget;
  1654. /** @var UriInterface|null */
  1655. private $uri;
  1656. public function getRequestTarget(): string
  1657. {
  1658. if (null !== $this->requestTarget) {
  1659. return $this->requestTarget;
  1660. }
  1661. if ('' === $target = $this->uri->getPath()) {
  1662. $target = '/';
  1663. }
  1664. if ('' !== $this->uri->getQuery()) {
  1665. $target .= '?' . $this->uri->getQuery();
  1666. }
  1667. return $target;
  1668. }
  1669. public function withRequestTarget($requestTarget): self
  1670. {
  1671. if (\preg_match('#\s#', $requestTarget)) {
  1672. throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
  1673. }
  1674. $new = clone $this;
  1675. $new->requestTarget = $requestTarget;
  1676. return $new;
  1677. }
  1678. public function getMethod(): string
  1679. {
  1680. return $this->method;
  1681. }
  1682. public function withMethod($method): self
  1683. {
  1684. if (!\is_string($method)) {
  1685. throw new \InvalidArgumentException('Method must be a string');
  1686. }
  1687. $new = clone $this;
  1688. $new->method = $method;
  1689. return $new;
  1690. }
  1691. public function getUri(): UriInterface
  1692. {
  1693. return $this->uri;
  1694. }
  1695. public function withUri(UriInterface $uri, $preserveHost = false): self
  1696. {
  1697. if ($uri === $this->uri) {
  1698. return $this;
  1699. }
  1700. $new = clone $this;
  1701. $new->uri = $uri;
  1702. if (!$preserveHost || !$this->hasHeader('Host')) {
  1703. $new->updateHostFromUri();
  1704. }
  1705. return $new;
  1706. }
  1707. private function updateHostFromUri() /*:void*/
  1708. {
  1709. if ('' === $host = $this->uri->getHost()) {
  1710. return;
  1711. }
  1712. if (null !== ($port = $this->uri->getPort())) {
  1713. $host .= ':' . $port;
  1714. }
  1715. if (isset($this->headerNames['host'])) {
  1716. $header = $this->headerNames['host'];
  1717. } else {
  1718. $this->headerNames['host'] = $header = 'Host';
  1719. }
  1720. // Ensure Host is the first header.
  1721. // See: http://tools.ietf.org/html/rfc7230#section-5.4
  1722. $this->headers = [$header => [$host]] + $this->headers;
  1723. }
  1724. }
  1725. }
  1726. // file: vendor/nyholm/psr7/src/Response.php
  1727. namespace Nyholm\Psr7 {
  1728. use Psr\Http\Message\{ResponseInterface, StreamInterface};
  1729. /**
  1730. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1731. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1732. * @author Martijn van der Ven <martijn@vanderven.se>
  1733. */
  1734. final class Response implements ResponseInterface
  1735. {
  1736. use MessageTrait;
  1737. /** @var array Map of standard HTTP status code/reason phrases */
  1738. /*private*/ const PHRASES = [
  1739. 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing',
  1740. 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',
  1741. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect',
  1742. 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',
  1743. 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',
  1744. ];
  1745. /** @var string */
  1746. private $reasonPhrase = '';
  1747. /** @var int */
  1748. private $statusCode;
  1749. /**
  1750. * @param int $status Status code
  1751. * @param array $headers Response headers
  1752. * @param string|resource|StreamInterface|null $body Response body
  1753. * @param string $version Protocol version
  1754. * @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
  1755. */
  1756. public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
  1757. {
  1758. // If we got no body, defer initialization of the stream until Response::getBody()
  1759. if ('' !== $body && null !== $body) {
  1760. $this->stream = Stream::create($body);
  1761. }
  1762. $this->statusCode = $status;
  1763. $this->setHeaders($headers);
  1764. if (null === $reason && isset(self::PHRASES[$this->statusCode])) {
  1765. $this->reasonPhrase = self::PHRASES[$status];
  1766. } else {
  1767. $this->reasonPhrase = $reason;
  1768. }
  1769. $this->protocol = $version;
  1770. }
  1771. public function getStatusCode(): int
  1772. {
  1773. return $this->statusCode;
  1774. }
  1775. public function getReasonPhrase(): string
  1776. {
  1777. return $this->reasonPhrase;
  1778. }
  1779. public function withStatus($code, $reasonPhrase = ''): self
  1780. {
  1781. if (!\is_int($code) && !\is_string($code)) {
  1782. throw new \InvalidArgumentException('Status code has to be an integer');
  1783. }
  1784. $code = (int) $code;
  1785. if ($code < 100 || $code > 599) {
  1786. throw new \InvalidArgumentException('Status code has to be an integer between 100 and 599');
  1787. }
  1788. $new = clone $this;
  1789. $new->statusCode = $code;
  1790. if ((null === $reasonPhrase || '' === $reasonPhrase) && isset(self::PHRASES[$new->statusCode])) {
  1791. $reasonPhrase = self::PHRASES[$new->statusCode];
  1792. }
  1793. $new->reasonPhrase = $reasonPhrase;
  1794. return $new;
  1795. }
  1796. }
  1797. }
  1798. // file: vendor/nyholm/psr7/src/ServerRequest.php
  1799. namespace Nyholm\Psr7 {
  1800. use Psr\Http\Message\{ServerRequestInterface, StreamInterface, UploadedFileInterface, UriInterface};
  1801. /**
  1802. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1803. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1804. * @author Martijn van der Ven <martijn@vanderven.se>
  1805. */
  1806. final class ServerRequest implements ServerRequestInterface
  1807. {
  1808. use MessageTrait;
  1809. use RequestTrait;
  1810. /** @var array */
  1811. private $attributes = [];
  1812. /** @var array */
  1813. private $cookieParams = [];
  1814. /** @var array|object|null */
  1815. private $parsedBody;
  1816. /** @var array */
  1817. private $queryParams = [];
  1818. /** @var array */
  1819. private $serverParams;
  1820. /** @var UploadedFileInterface[] */
  1821. private $uploadedFiles = [];
  1822. /**
  1823. * @param string $method HTTP method
  1824. * @param string|UriInterface $uri URI
  1825. * @param array $headers Request headers
  1826. * @param string|resource|StreamInterface|null $body Request body
  1827. * @param string $version Protocol version
  1828. * @param array $serverParams Typically the $_SERVER superglobal
  1829. */
  1830. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
  1831. {
  1832. $this->serverParams = $serverParams;
  1833. if (!($uri instanceof UriInterface)) {
  1834. $uri = new Uri($uri);
  1835. }
  1836. $this->method = $method;
  1837. $this->uri = $uri;
  1838. $this->setHeaders($headers);
  1839. $this->protocol = $version;
  1840. if (!$this->hasHeader('Host')) {
  1841. $this->updateHostFromUri();
  1842. }
  1843. // If we got no body, defer initialization of the stream until ServerRequest::getBody()
  1844. if ('' !== $body && null !== $body) {
  1845. $this->stream = Stream::create($body);
  1846. }
  1847. }
  1848. public function getServerParams(): array
  1849. {
  1850. return $this->serverParams;
  1851. }
  1852. public function getUploadedFiles(): array
  1853. {
  1854. return $this->uploadedFiles;
  1855. }
  1856. public function withUploadedFiles(array $uploadedFiles)
  1857. {
  1858. $new = clone $this;
  1859. $new->uploadedFiles = $uploadedFiles;
  1860. return $new;
  1861. }
  1862. public function getCookieParams(): array
  1863. {
  1864. return $this->cookieParams;
  1865. }
  1866. public function withCookieParams(array $cookies)
  1867. {
  1868. $new = clone $this;
  1869. $new->cookieParams = $cookies;
  1870. return $new;
  1871. }
  1872. public function getQueryParams(): array
  1873. {
  1874. return $this->queryParams;
  1875. }
  1876. public function withQueryParams(array $query)
  1877. {
  1878. $new = clone $this;
  1879. $new->queryParams = $query;
  1880. return $new;
  1881. }
  1882. public function getParsedBody()
  1883. {
  1884. return $this->parsedBody;
  1885. }
  1886. public function withParsedBody($data)
  1887. {
  1888. if (!\is_array($data) && !\is_object($data) && null !== $data) {
  1889. throw new \InvalidArgumentException('First parameter to withParsedBody MUST be object, array or null');
  1890. }
  1891. $new = clone $this;
  1892. $new->parsedBody = $data;
  1893. return $new;
  1894. }
  1895. public function getAttributes(): array
  1896. {
  1897. return $this->attributes;
  1898. }
  1899. public function getAttribute($attribute, $default = null)
  1900. {
  1901. if (false === \array_key_exists($attribute, $this->attributes)) {
  1902. return $default;
  1903. }
  1904. return $this->attributes[$attribute];
  1905. }
  1906. public function withAttribute($attribute, $value): self
  1907. {
  1908. $new = clone $this;
  1909. $new->attributes[$attribute] = $value;
  1910. return $new;
  1911. }
  1912. public function withoutAttribute($attribute): self
  1913. {
  1914. if (false === \array_key_exists($attribute, $this->attributes)) {
  1915. return $this;
  1916. }
  1917. $new = clone $this;
  1918. unset($new->attributes[$attribute]);
  1919. return $new;
  1920. }
  1921. }
  1922. }
  1923. // file: vendor/nyholm/psr7/src/Stream.php
  1924. namespace Nyholm\Psr7 {
  1925. use Psr\Http\Message\StreamInterface;
  1926. /**
  1927. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1928. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1929. * @author Martijn van der Ven <martijn@vanderven.se>
  1930. */
  1931. final class Stream implements StreamInterface
  1932. {
  1933. /** @var resource|null A resource reference */
  1934. private $stream;
  1935. /** @var bool */
  1936. private $seekable;
  1937. /** @var bool */
  1938. private $readable;
  1939. /** @var bool */
  1940. private $writable;
  1941. /** @var array|mixed|void|null */
  1942. private $uri;
  1943. /** @var int|null */
  1944. private $size;
  1945. /** @var array Hash of readable and writable stream types */
  1946. /*private*/ const READ_WRITE_HASH = [
  1947. 'read' => [
  1948. 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
  1949. 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
  1950. 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
  1951. 'x+t' => true, 'c+t' => true, 'a+' => true,
  1952. ],
  1953. 'write' => [
  1954. 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
  1955. 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
  1956. 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
  1957. 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
  1958. ],
  1959. ];
  1960. private function __construct()
  1961. {
  1962. }
  1963. /**
  1964. * Creates a new PSR-7 stream.
  1965. *
  1966. * @param string|resource|StreamInterface $body
  1967. *
  1968. * @return StreamInterface
  1969. *
  1970. * @throws \InvalidArgumentException
  1971. */
  1972. public static function create($body = ''): StreamInterface
  1973. {
  1974. if ($body instanceof StreamInterface) {
  1975. return $body;
  1976. }
  1977. if (\is_string($body)) {
  1978. $resource = \fopen('php://temp', 'rw+');
  1979. \fwrite($resource, $body);
  1980. $body = $resource;
  1981. }
  1982. if (\is_resource($body)) {
  1983. $new = new self();
  1984. $new->stream = $body;
  1985. $meta = \stream_get_meta_data($new->stream);
  1986. $new->seekable = $meta['seekable'];
  1987. $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]);
  1988. $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]);
  1989. $new->uri = $new->getMetadata('uri');
  1990. return $new;
  1991. }
  1992. throw new \InvalidArgumentException('First argument to Stream::create() must be a string, resource or StreamInterface.');
  1993. }
  1994. /**
  1995. * Closes the stream when the destructed.
  1996. */
  1997. public function __destruct()
  1998. {
  1999. $this->close();
  2000. }
  2001. public function __toString(): string
  2002. {
  2003. try {
  2004. if ($this->isSeekable()) {
  2005. $this->seek(0);
  2006. }
  2007. return $this->getContents();
  2008. } catch (\Exception $e) {
  2009. return '';
  2010. }
  2011. }
  2012. public function close() /*:void*/
  2013. {
  2014. if (isset($this->stream)) {
  2015. if (\is_resource($this->stream)) {
  2016. \fclose($this->stream);
  2017. }
  2018. $this->detach();
  2019. }
  2020. }
  2021. public function detach()
  2022. {
  2023. if (!isset($this->stream)) {
  2024. return null;
  2025. }
  2026. $result = $this->stream;
  2027. unset($this->stream);
  2028. $this->size = $this->uri = null;
  2029. $this->readable = $this->writable = $this->seekable = false;
  2030. return $result;
  2031. }
  2032. public function getSize() /*:?int*/
  2033. {
  2034. if (null !== $this->size) {
  2035. return $this->size;
  2036. }
  2037. if (!isset($this->stream)) {
  2038. return null;
  2039. }
  2040. // Clear the stat cache if the stream has a URI
  2041. if ($this->uri) {
  2042. \clearstatcache(true, $this->uri);
  2043. }
  2044. $stats = \fstat($this->stream);
  2045. if (isset($stats['size'])) {
  2046. $this->size = $stats['size'];
  2047. return $this->size;
  2048. }
  2049. return null;
  2050. }
  2051. public function tell(): int
  2052. {
  2053. if (false === $result = \ftell($this->stream)) {
  2054. throw new \RuntimeException('Unable to determine stream position');
  2055. }
  2056. return $result;
  2057. }
  2058. public function eof(): bool
  2059. {
  2060. return !$this->stream || \feof($this->stream);
  2061. }
  2062. public function isSeekable(): bool
  2063. {
  2064. return $this->seekable;
  2065. }
  2066. public function seek($offset, $whence = \SEEK_SET) /*:void*/
  2067. {
  2068. if (!$this->seekable) {
  2069. throw new \RuntimeException('Stream is not seekable');
  2070. }
  2071. if (-1 === \fseek($this->stream, $offset, $whence)) {
  2072. throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, true));
  2073. }
  2074. }
  2075. public function rewind() /*:void*/
  2076. {
  2077. $this->seek(0);
  2078. }
  2079. public function isWritable(): bool
  2080. {
  2081. return $this->writable;
  2082. }
  2083. public function write($string): int
  2084. {
  2085. if (!$this->writable) {
  2086. throw new \RuntimeException('Cannot write to a non-writable stream');
  2087. }
  2088. // We can't know the size after writing anything
  2089. $this->size = null;
  2090. if (false === $result = \fwrite($this->stream, $string)) {
  2091. throw new \RuntimeException('Unable to write to stream');
  2092. }
  2093. return $result;
  2094. }
  2095. public function isReadable(): bool
  2096. {
  2097. return $this->readable;
  2098. }
  2099. public function read($length): string
  2100. {
  2101. if (!$this->readable) {
  2102. throw new \RuntimeException('Cannot read from non-readable stream');
  2103. }
  2104. return \fread($this->stream, $length);
  2105. }
  2106. public function getContents(): string
  2107. {
  2108. if (!isset($this->stream)) {
  2109. throw new \RuntimeException('Unable to read stream contents');
  2110. }
  2111. if (false === $contents = \stream_get_contents($this->stream)) {
  2112. throw new \RuntimeException('Unable to read stream contents');
  2113. }
  2114. return $contents;
  2115. }
  2116. public function getMetadata($key = null)
  2117. {
  2118. if (!isset($this->stream)) {
  2119. return $key ? null : [];
  2120. }
  2121. $meta = \stream_get_meta_data($this->stream);
  2122. if (null === $key) {
  2123. return $meta;
  2124. }
  2125. return $meta[$key] ?? null;
  2126. }
  2127. }
  2128. }
  2129. // file: vendor/nyholm/psr7/src/UploadedFile.php
  2130. namespace Nyholm\Psr7 {
  2131. use Psr\Http\Message\{StreamInterface, UploadedFileInterface};
  2132. /**
  2133. * @author Michael Dowling and contributors to guzzlehttp/psr7
  2134. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2135. * @author Martijn van der Ven <martijn@vanderven.se>
  2136. */
  2137. final class UploadedFile implements UploadedFileInterface
  2138. {
  2139. /** @var array */
  2140. /*private*/ const ERRORS = [
  2141. \UPLOAD_ERR_OK => 1,
  2142. \UPLOAD_ERR_INI_SIZE => 1,
  2143. \UPLOAD_ERR_FORM_SIZE => 1,
  2144. \UPLOAD_ERR_PARTIAL => 1,
  2145. \UPLOAD_ERR_NO_FILE => 1,
  2146. \UPLOAD_ERR_NO_TMP_DIR => 1,
  2147. \UPLOAD_ERR_CANT_WRITE => 1,
  2148. \UPLOAD_ERR_EXTENSION => 1,
  2149. ];
  2150. /** @var string */
  2151. private $clientFilename;
  2152. /** @var string */
  2153. private $clientMediaType;
  2154. /** @var int */
  2155. private $error;
  2156. /** @var string|null */
  2157. private $file;
  2158. /** @var bool */
  2159. private $moved = false;
  2160. /** @var int */
  2161. private $size;
  2162. /** @var StreamInterface|null */
  2163. private $stream;
  2164. /**
  2165. * @param StreamInterface|string|resource $streamOrFile
  2166. * @param int $size
  2167. * @param int $errorStatus
  2168. * @param string|null $clientFilename
  2169. * @param string|null $clientMediaType
  2170. */
  2171. public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
  2172. {
  2173. if (false === \is_int($errorStatus) || !isset(self::ERRORS[$errorStatus])) {
  2174. throw new \InvalidArgumentException('Upload file error status must be an integer value and one of the "UPLOAD_ERR_*" constants.');
  2175. }
  2176. if (false === \is_int($size)) {
  2177. throw new \InvalidArgumentException('Upload file size must be an integer');
  2178. }
  2179. if (null !== $clientFilename && !\is_string($clientFilename)) {
  2180. throw new \InvalidArgumentException('Upload file client filename must be a string or null');
  2181. }
  2182. if (null !== $clientMediaType && !\is_string($clientMediaType)) {
  2183. throw new \InvalidArgumentException('Upload file client media type must be a string or null');
  2184. }
  2185. $this->error = $errorStatus;
  2186. $this->size = $size;
  2187. $this->clientFilename = $clientFilename;
  2188. $this->clientMediaType = $clientMediaType;
  2189. if (\UPLOAD_ERR_OK === $this->error) {
  2190. // Depending on the value set file or stream variable.
  2191. if (\is_string($streamOrFile)) {
  2192. $this->file = $streamOrFile;
  2193. } elseif (\is_resource($streamOrFile)) {
  2194. $this->stream = Stream::create($streamOrFile);
  2195. } elseif ($streamOrFile instanceof StreamInterface) {
  2196. $this->stream = $streamOrFile;
  2197. } else {
  2198. throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile');
  2199. }
  2200. }
  2201. }
  2202. /**
  2203. * @throws \RuntimeException if is moved or not ok
  2204. */
  2205. private function validateActive() /*:void*/
  2206. {
  2207. if (\UPLOAD_ERR_OK !== $this->error) {
  2208. throw new \RuntimeException('Cannot retrieve stream due to upload error');
  2209. }
  2210. if ($this->moved) {
  2211. throw new \RuntimeException('Cannot retrieve stream after it has already been moved');
  2212. }
  2213. }
  2214. public function getStream(): StreamInterface
  2215. {
  2216. $this->validateActive();
  2217. if ($this->stream instanceof StreamInterface) {
  2218. return $this->stream;
  2219. }
  2220. $resource = \fopen($this->file, 'r');
  2221. return Stream::create($resource);
  2222. }
  2223. public function moveTo($targetPath) /*:void*/
  2224. {
  2225. $this->validateActive();
  2226. if (!\is_string($targetPath) || '' === $targetPath) {
  2227. throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
  2228. }
  2229. if (null !== $this->file) {
  2230. $this->moved = 'cli' === \PHP_SAPI ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath);
  2231. } else {
  2232. $stream = $this->getStream();
  2233. if ($stream->isSeekable()) {
  2234. $stream->rewind();
  2235. }
  2236. // Copy the contents of a stream into another stream until end-of-file.
  2237. $dest = Stream::create(\fopen($targetPath, 'w'));
  2238. while (!$stream->eof()) {
  2239. if (!$dest->write($stream->read(1048576))) {
  2240. break;
  2241. }
  2242. }
  2243. $this->moved = true;
  2244. }
  2245. if (false === $this->moved) {
  2246. throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath));
  2247. }
  2248. }
  2249. public function getSize(): int
  2250. {
  2251. return $this->size;
  2252. }
  2253. public function getError(): int
  2254. {
  2255. return $this->error;
  2256. }
  2257. public function getClientFilename() /*:?string*/
  2258. {
  2259. return $this->clientFilename;
  2260. }
  2261. public function getClientMediaType() /*:?string*/
  2262. {
  2263. return $this->clientMediaType;
  2264. }
  2265. }
  2266. }
  2267. // file: vendor/nyholm/psr7/src/Uri.php
  2268. namespace Nyholm\Psr7 {
  2269. use Psr\Http\Message\UriInterface;
  2270. /**
  2271. * PSR-7 URI implementation.
  2272. *
  2273. * @author Michael Dowling
  2274. * @author Tobias Schultze
  2275. * @author Matthew Weier O'Phinney
  2276. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2277. * @author Martijn van der Ven <martijn@vanderven.se>
  2278. */
  2279. final class Uri implements UriInterface
  2280. {
  2281. /*private*/ const SCHEMES = ['http' => 80, 'https' => 443];
  2282. /*private*/ const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  2283. /*private*/ const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  2284. /** @var string Uri scheme. */
  2285. private $scheme = '';
  2286. /** @var string Uri user info. */
  2287. private $userInfo = '';
  2288. /** @var string Uri host. */
  2289. private $host = '';
  2290. /** @var int|null Uri port. */
  2291. private $port;
  2292. /** @var string Uri path. */
  2293. private $path = '';
  2294. /** @var string Uri query string. */
  2295. private $query = '';
  2296. /** @var string Uri fragment. */
  2297. private $fragment = '';
  2298. public function __construct(string $uri = '')
  2299. {
  2300. if ('' !== $uri) {
  2301. if (false === $parts = \parse_url($uri)) {
  2302. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  2303. }
  2304. // Apply parse_url parts to a URI.
  2305. $this->scheme = isset($parts['scheme']) ? \strtolower($parts['scheme']) : '';
  2306. $this->userInfo = $parts['user'] ?? '';
  2307. $this->host = isset($parts['host']) ? \strtolower($parts['host']) : '';
  2308. $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
  2309. $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
  2310. $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : '';
  2311. $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : '';
  2312. if (isset($parts['pass'])) {
  2313. $this->userInfo .= ':' . $parts['pass'];
  2314. }
  2315. }
  2316. }
  2317. public function __toString(): string
  2318. {
  2319. return self::createUriString($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment);
  2320. }
  2321. public function getScheme(): string
  2322. {
  2323. return $this->scheme;
  2324. }
  2325. public function getAuthority(): string
  2326. {
  2327. if ('' === $this->host) {
  2328. return '';
  2329. }
  2330. $authority = $this->host;
  2331. if ('' !== $this->userInfo) {
  2332. $authority = $this->userInfo . '@' . $authority;
  2333. }
  2334. if (null !== $this->port) {
  2335. $authority .= ':' . $this->port;
  2336. }
  2337. return $authority;
  2338. }
  2339. public function getUserInfo(): string
  2340. {
  2341. return $this->userInfo;
  2342. }
  2343. public function getHost(): string
  2344. {
  2345. return $this->host;
  2346. }
  2347. public function getPort() /*:?int*/
  2348. {
  2349. return $this->port;
  2350. }
  2351. public function getPath(): string
  2352. {
  2353. return $this->path;
  2354. }
  2355. public function getQuery(): string
  2356. {
  2357. return $this->query;
  2358. }
  2359. public function getFragment(): string
  2360. {
  2361. return $this->fragment;
  2362. }
  2363. public function withScheme($scheme): self
  2364. {
  2365. if (!\is_string($scheme)) {
  2366. throw new \InvalidArgumentException('Scheme must be a string');
  2367. }
  2368. if ($this->scheme === $scheme = \strtolower($scheme)) {
  2369. return $this;
  2370. }
  2371. $new = clone $this;
  2372. $new->scheme = $scheme;
  2373. $new->port = $new->filterPort($new->port);
  2374. return $new;
  2375. }
  2376. public function withUserInfo($user, $password = null): self
  2377. {
  2378. $info = $user;
  2379. if (null !== $password && '' !== $password) {
  2380. $info .= ':' . $password;
  2381. }
  2382. if ($this->userInfo === $info) {
  2383. return $this;
  2384. }
  2385. $new = clone $this;
  2386. $new->userInfo = $info;
  2387. return $new;
  2388. }
  2389. public function withHost($host): self
  2390. {
  2391. if (!\is_string($host)) {
  2392. throw new \InvalidArgumentException('Host must be a string');
  2393. }
  2394. if ($this->host === $host = \strtolower($host)) {
  2395. return $this;
  2396. }
  2397. $new = clone $this;
  2398. $new->host = $host;
  2399. return $new;
  2400. }
  2401. public function withPort($port): self
  2402. {
  2403. if ($this->port === $port = $this->filterPort($port)) {
  2404. return $this;
  2405. }
  2406. $new = clone $this;
  2407. $new->port = $port;
  2408. return $new;
  2409. }
  2410. public function withPath($path): self
  2411. {
  2412. if ($this->path === $path = $this->filterPath($path)) {
  2413. return $this;
  2414. }
  2415. $new = clone $this;
  2416. $new->path = $path;
  2417. return $new;
  2418. }
  2419. public function withQuery($query): self
  2420. {
  2421. if ($this->query === $query = $this->filterQueryAndFragment($query)) {
  2422. return $this;
  2423. }
  2424. $new = clone $this;
  2425. $new->query = $query;
  2426. return $new;
  2427. }
  2428. public function withFragment($fragment): self
  2429. {
  2430. if ($this->fragment === $fragment = $this->filterQueryAndFragment($fragment)) {
  2431. return $this;
  2432. }
  2433. $new = clone $this;
  2434. $new->fragment = $fragment;
  2435. return $new;
  2436. }
  2437. /**
  2438. * Create a URI string from its various parts.
  2439. */
  2440. private static function createUriString(string $scheme, string $authority, string $path, string $query, string $fragment): string
  2441. {
  2442. $uri = '';
  2443. if ('' !== $scheme) {
  2444. $uri .= $scheme . ':';
  2445. }
  2446. if ('' !== $authority) {
  2447. $uri .= '//' . $authority;
  2448. }
  2449. if ('' !== $path) {
  2450. if ('/' !== $path[0]) {
  2451. if ('' !== $authority) {
  2452. // If the path is rootless and an authority is present, the path MUST be prefixed by "/"
  2453. $path = '/' . $path;
  2454. }
  2455. } elseif (isset($path[1]) && '/' === $path[1]) {
  2456. if ('' === $authority) {
  2457. // If the path is starting with more than one "/" and no authority is present, the
  2458. // starting slashes MUST be reduced to one.
  2459. $path = '/' . \ltrim($path, '/');
  2460. }
  2461. }
  2462. $uri .= $path;
  2463. }
  2464. if ('' !== $query) {
  2465. $uri .= '?' . $query;
  2466. }
  2467. if ('' !== $fragment) {
  2468. $uri .= '#' . $fragment;
  2469. }
  2470. return $uri;
  2471. }
  2472. /**
  2473. * Is a given port non-standard for the current scheme?
  2474. */
  2475. private static function isNonStandardPort(string $scheme, int $port): bool
  2476. {
  2477. return !isset(self::SCHEMES[$scheme]) || $port !== self::SCHEMES[$scheme];
  2478. }
  2479. private function filterPort($port) /*:?int*/
  2480. {
  2481. if (null === $port) {
  2482. return null;
  2483. }
  2484. $port = (int) $port;
  2485. if (1 > $port || 0xffff < $port) {
  2486. throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 1 and 65535', $port));
  2487. }
  2488. return self::isNonStandardPort($this->scheme, $port) ? $port : null;
  2489. }
  2490. private function filterPath($path): string
  2491. {
  2492. if (!\is_string($path)) {
  2493. throw new \InvalidArgumentException('Path must be a string');
  2494. }
  2495. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $path);
  2496. }
  2497. private function filterQueryAndFragment($str): string
  2498. {
  2499. if (!\is_string($str)) {
  2500. throw new \InvalidArgumentException('Query and fragment must be a string');
  2501. }
  2502. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $str);
  2503. }
  2504. private static function rawurlencodeMatchZero(array $match): string
  2505. {
  2506. return \rawurlencode($match[0]);
  2507. }
  2508. }
  2509. }
  2510. // file: vendor/nyholm/psr7-server/src/ServerRequestCreator.php
  2511. namespace Nyholm\Psr7Server {
  2512. use Psr\Http\Message\ServerRequestFactoryInterface;
  2513. use Psr\Http\Message\ServerRequestInterface;
  2514. use Psr\Http\Message\StreamFactoryInterface;
  2515. use Psr\Http\Message\StreamInterface;
  2516. use Psr\Http\Message\UploadedFileFactoryInterface;
  2517. use Psr\Http\Message\UploadedFileInterface;
  2518. use Psr\Http\Message\UriFactoryInterface;
  2519. use Psr\Http\Message\UriInterface;
  2520. /**
  2521. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2522. * @author Martijn van der Ven <martijn@vanderven.se>
  2523. */
  2524. final class ServerRequestCreator implements ServerRequestCreatorInterface
  2525. {
  2526. private $serverRequestFactory;
  2527. private $uriFactory;
  2528. private $uploadedFileFactory;
  2529. private $streamFactory;
  2530. public function __construct(
  2531. ServerRequestFactoryInterface $serverRequestFactory,
  2532. UriFactoryInterface $uriFactory,
  2533. UploadedFileFactoryInterface $uploadedFileFactory,
  2534. StreamFactoryInterface $streamFactory
  2535. ) {
  2536. $this->serverRequestFactory = $serverRequestFactory;
  2537. $this->uriFactory = $uriFactory;
  2538. $this->uploadedFileFactory = $uploadedFileFactory;
  2539. $this->streamFactory = $streamFactory;
  2540. }
  2541. /**
  2542. * {@inheritdoc}
  2543. */
  2544. public function fromGlobals(): ServerRequestInterface
  2545. {
  2546. $server = $_SERVER;
  2547. if (false === isset($server['REQUEST_METHOD'])) {
  2548. $server['REQUEST_METHOD'] = 'GET';
  2549. }
  2550. $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
  2551. return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $_POST, $_FILES, fopen('php://input', 'r') ?: null);
  2552. }
  2553. /**
  2554. * {@inheritdoc}
  2555. */
  2556. public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
  2557. {
  2558. $method = $this->getMethodFromEnv($server);
  2559. $uri = $this->getUriFromEnvWithHTTP($server);
  2560. $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
  2561. $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
  2562. foreach ($headers as $name => $value) {
  2563. $serverRequest = $serverRequest->withAddedHeader($name, $value);
  2564. }
  2565. $serverRequest = $serverRequest
  2566. ->withProtocolVersion($protocol)
  2567. ->withCookieParams($cookie)
  2568. ->withQueryParams($get)
  2569. ->withParsedBody($post)
  2570. ->withUploadedFiles($this->normalizeFiles($files));
  2571. if (null === $body) {
  2572. return $serverRequest;
  2573. }
  2574. if (\is_resource($body)) {
  2575. $body = $this->streamFactory->createStreamFromResource($body);
  2576. } elseif (\is_string($body)) {
  2577. $body = $this->streamFactory->createStream($body);
  2578. } elseif (!$body instanceof StreamInterface) {
  2579. throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
  2580. }
  2581. return $serverRequest->withBody($body);
  2582. }
  2583. /**
  2584. * Implementation from Zend\Diactoros\marshalHeadersFromSapi().
  2585. */
  2586. public static function getHeadersFromServer(array $server): array
  2587. {
  2588. $headers = [];
  2589. foreach ($server as $key => $value) {
  2590. // Apache prefixes environment variables with REDIRECT_
  2591. // if they are added by rewrite rules
  2592. if (0 === \strpos($key, 'REDIRECT_')) {
  2593. $key = \substr($key, 9);
  2594. // We will not overwrite existing variables with the
  2595. // prefixed versions, though
  2596. if (\array_key_exists($key, $server)) {
  2597. continue;
  2598. }
  2599. }
  2600. if ($value && 0 === \strpos($key, 'HTTP_')) {
  2601. $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
  2602. $headers[$name] = $value;
  2603. continue;
  2604. }
  2605. if ($value && 0 === \strpos($key, 'CONTENT_')) {
  2606. $name = 'content-'.\strtolower(\substr($key, 8));
  2607. $headers[$name] = $value;
  2608. continue;
  2609. }
  2610. }
  2611. return $headers;
  2612. }
  2613. private function getMethodFromEnv(array $environment): string
  2614. {
  2615. if (false === isset($environment['REQUEST_METHOD'])) {
  2616. throw new \InvalidArgumentException('Cannot determine HTTP method');
  2617. }
  2618. return $environment['REQUEST_METHOD'];
  2619. }
  2620. private function getUriFromEnvWithHTTP(array $environment): UriInterface
  2621. {
  2622. $uri = $this->createUriFromArray($environment);
  2623. if (empty($uri->getScheme())) {
  2624. $uri = $uri->withScheme('http');
  2625. }
  2626. return $uri;
  2627. }
  2628. /**
  2629. * Return an UploadedFile instance array.
  2630. *
  2631. * @param array $files A array which respect $_FILES structure
  2632. *
  2633. * @return UploadedFileInterface[]
  2634. *
  2635. * @throws \InvalidArgumentException for unrecognized values
  2636. */
  2637. private function normalizeFiles(array $files): array
  2638. {
  2639. $normalized = [];
  2640. foreach ($files as $key => $value) {
  2641. if ($value instanceof UploadedFileInterface) {
  2642. $normalized[$key] = $value;
  2643. } elseif (\is_array($value) && isset($value['tmp_name'])) {
  2644. $normalized[$key] = $this->createUploadedFileFromSpec($value);
  2645. } elseif (\is_array($value)) {
  2646. $normalized[$key] = $this->normalizeFiles($value);
  2647. } else {
  2648. throw new \InvalidArgumentException('Invalid value in files specification');
  2649. }
  2650. }
  2651. return $normalized;
  2652. }
  2653. /**
  2654. * Create and return an UploadedFile instance from a $_FILES specification.
  2655. *
  2656. * If the specification represents an array of values, this method will
  2657. * delegate to normalizeNestedFileSpec() and return that return value.
  2658. *
  2659. * @param array $value $_FILES struct
  2660. *
  2661. * @return array|UploadedFileInterface
  2662. */
  2663. private function createUploadedFileFromSpec(array $value)
  2664. {
  2665. if (\is_array($value['tmp_name'])) {
  2666. return $this->normalizeNestedFileSpec($value);
  2667. }
  2668. try {
  2669. $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
  2670. } catch (\RuntimeException $e) {
  2671. $stream = $this->streamFactory->createStream();
  2672. }
  2673. return $this->uploadedFileFactory->createUploadedFile(
  2674. $stream,
  2675. (int) $value['size'],
  2676. (int) $value['error'],
  2677. $value['name'],
  2678. $value['type']
  2679. );
  2680. }
  2681. /**
  2682. * Normalize an array of file specifications.
  2683. *
  2684. * Loops through all nested files and returns a normalized array of
  2685. * UploadedFileInterface instances.
  2686. *
  2687. * @param array $files
  2688. *
  2689. * @return UploadedFileInterface[]
  2690. */
  2691. private function normalizeNestedFileSpec(array $files = []): array
  2692. {
  2693. $normalizedFiles = [];
  2694. foreach (\array_keys($files['tmp_name']) as $key) {
  2695. $spec = [
  2696. 'tmp_name' => $files['tmp_name'][$key],
  2697. 'size' => $files['size'][$key],
  2698. 'error' => $files['error'][$key],
  2699. 'name' => $files['name'][$key],
  2700. 'type' => $files['type'][$key],
  2701. ];
  2702. $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
  2703. }
  2704. return $normalizedFiles;
  2705. }
  2706. /**
  2707. * Create a new uri from server variable.
  2708. *
  2709. * @param array $server typically $_SERVER or similar structure
  2710. */
  2711. private function createUriFromArray(array $server): UriInterface
  2712. {
  2713. $uri = $this->uriFactory->createUri('');
  2714. if (isset($server['REQUEST_SCHEME'])) {
  2715. $uri = $uri->withScheme($server['REQUEST_SCHEME']);
  2716. } elseif (isset($server['HTTPS'])) {
  2717. $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
  2718. }
  2719. if (isset($server['HTTP_HOST'])) {
  2720. $uri = $uri->withHost($server['HTTP_HOST']);
  2721. } elseif (isset($server['SERVER_NAME'])) {
  2722. $uri = $uri->withHost($server['SERVER_NAME']);
  2723. }
  2724. if (isset($server['SERVER_PORT'])) {
  2725. $uri = $uri->withPort($server['SERVER_PORT']);
  2726. }
  2727. if (isset($server['REQUEST_URI'])) {
  2728. $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
  2729. }
  2730. if (isset($server['QUERY_STRING'])) {
  2731. $uri = $uri->withQuery($server['QUERY_STRING']);
  2732. }
  2733. return $uri;
  2734. }
  2735. }
  2736. }
  2737. // file: vendor/nyholm/psr7-server/src/ServerRequestCreatorInterface.php
  2738. namespace Nyholm\Psr7Server {
  2739. use Psr\Http\Message\ServerRequestInterface;
  2740. use Psr\Http\Message\StreamInterface;
  2741. /**
  2742. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2743. * @author Martijn van der Ven <martijn@vanderven.se>
  2744. */
  2745. interface ServerRequestCreatorInterface
  2746. {
  2747. /**
  2748. * Create a new server request from the current environment variables.
  2749. * Defaults to a GET request to minimise the risk of an \InvalidArgumentException.
  2750. * Includes the current request headers as supplied by the server through `getallheaders()`.
  2751. * If `getallheaders()` is unavailable on the current server it will fallback to its own `getHeadersFromServer()` method.
  2752. * Defaults to php://input for the request body.
  2753. *
  2754. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2755. */
  2756. public function fromGlobals(): ServerRequestInterface;
  2757. /**
  2758. * Create a new server request from a set of arrays.
  2759. *
  2760. * @param array $server typically $_SERVER or similar structure
  2761. * @param array $headers typically the output of getallheaders() or similar structure
  2762. * @param array $cookie typically $_COOKIE or similar structure
  2763. * @param array $get typically $_GET or similar structure
  2764. * @param array $post typically $_POST or similar structure
  2765. * @param array $files typically $_FILES or similar structure
  2766. * @param StreamInterface|resource|string|null $body Typically stdIn
  2767. *
  2768. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2769. */
  2770. public function fromArrays(
  2771. array $server,
  2772. array $headers = [],
  2773. array $cookie = [],
  2774. array $get = [],
  2775. array $post = [],
  2776. array $files = [],
  2777. $body = null
  2778. ): ServerRequestInterface;
  2779. /**
  2780. * Get parsed headers from ($_SERVER) array.
  2781. *
  2782. * @param array $server typically $_SERVER or similar structure
  2783. *
  2784. * @return array
  2785. */
  2786. public static function getHeadersFromServer(array $server): array;
  2787. }
  2788. }
  2789. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  2790. namespace Tqdev\PhpCrudApi\Cache {
  2791. interface Cache
  2792. {
  2793. public function set(string $key, string $value, int $ttl = 0): bool;
  2794. public function get(string $key): string;
  2795. public function clear(): bool;
  2796. }
  2797. }
  2798. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  2799. namespace Tqdev\PhpCrudApi\Cache {
  2800. class CacheFactory
  2801. {
  2802. public static function create(string $type, string $prefix, string $config): Cache
  2803. {
  2804. switch ($type) {
  2805. case 'TempFile':
  2806. $cache = new TempFileCache($prefix, $config);
  2807. break;
  2808. case 'Redis':
  2809. $cache = new RedisCache($prefix, $config);
  2810. break;
  2811. case 'Memcache':
  2812. $cache = new MemcacheCache($prefix, $config);
  2813. break;
  2814. case 'Memcached':
  2815. $cache = new MemcachedCache($prefix, $config);
  2816. break;
  2817. default:
  2818. $cache = new NoCache();
  2819. }
  2820. return $cache;
  2821. }
  2822. }
  2823. }
  2824. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  2825. namespace Tqdev\PhpCrudApi\Cache {
  2826. class MemcacheCache implements Cache
  2827. {
  2828. protected $prefix;
  2829. protected $memcache;
  2830. public function __construct(string $prefix, string $config)
  2831. {
  2832. $this->prefix = $prefix;
  2833. if ($config == '') {
  2834. $address = 'localhost';
  2835. $port = 11211;
  2836. } elseif (strpos($config, ':') === false) {
  2837. $address = $config;
  2838. $port = 11211;
  2839. } else {
  2840. list($address, $port) = explode(':', $config);
  2841. }
  2842. $this->memcache = $this->create();
  2843. $this->memcache->addServer($address, $port);
  2844. }
  2845. protected function create() /*: \Memcache*/
  2846. {
  2847. return new \Memcache();
  2848. }
  2849. public function set(string $key, string $value, int $ttl = 0): bool
  2850. {
  2851. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  2852. }
  2853. public function get(string $key): string
  2854. {
  2855. return $this->memcache->get($this->prefix . $key) ?: '';
  2856. }
  2857. public function clear(): bool
  2858. {
  2859. return $this->memcache->flush();
  2860. }
  2861. }
  2862. }
  2863. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  2864. namespace Tqdev\PhpCrudApi\Cache {
  2865. class MemcachedCache extends MemcacheCache
  2866. {
  2867. protected function create() /*: \Memcached*/
  2868. {
  2869. return new \Memcached();
  2870. }
  2871. public function set(string $key, string $value, int $ttl = 0): bool
  2872. {
  2873. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  2874. }
  2875. }
  2876. }
  2877. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  2878. namespace Tqdev\PhpCrudApi\Cache {
  2879. class NoCache implements Cache
  2880. {
  2881. public function __construct()
  2882. {
  2883. }
  2884. public function set(string $key, string $value, int $ttl = 0): bool
  2885. {
  2886. return true;
  2887. }
  2888. public function get(string $key): string
  2889. {
  2890. return '';
  2891. }
  2892. public function clear(): bool
  2893. {
  2894. return true;
  2895. }
  2896. }
  2897. }
  2898. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  2899. namespace Tqdev\PhpCrudApi\Cache {
  2900. class RedisCache implements Cache
  2901. {
  2902. protected $prefix;
  2903. protected $redis;
  2904. public function __construct(string $prefix, string $config)
  2905. {
  2906. $this->prefix = $prefix;
  2907. if ($config == '') {
  2908. $config = '127.0.0.1';
  2909. }
  2910. $params = explode(':', $config, 6);
  2911. if (isset($params[3])) {
  2912. $params[3] = null;
  2913. }
  2914. $this->redis = new \Redis();
  2915. call_user_func_array(array($this->redis, 'pconnect'), $params);
  2916. }
  2917. public function set(string $key, string $value, int $ttl = 0): bool
  2918. {
  2919. return $this->redis->set($this->prefix . $key, $value, $ttl);
  2920. }
  2921. public function get(string $key): string
  2922. {
  2923. return $this->redis->get($this->prefix . $key) ?: '';
  2924. }
  2925. public function clear(): bool
  2926. {
  2927. return $this->redis->flushDb();
  2928. }
  2929. }
  2930. }
  2931. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  2932. namespace Tqdev\PhpCrudApi\Cache {
  2933. class TempFileCache implements Cache
  2934. {
  2935. const SUFFIX = 'cache';
  2936. private $path;
  2937. private $segments;
  2938. public function __construct(string $prefix, string $config)
  2939. {
  2940. $this->segments = [];
  2941. $s = DIRECTORY_SEPARATOR;
  2942. $ps = PATH_SEPARATOR;
  2943. if ($config == '') {
  2944. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  2945. } elseif (strpos($config, $ps) === false) {
  2946. $this->path = $config;
  2947. } else {
  2948. list($path, $segments) = explode($ps, $config);
  2949. $this->path = $path;
  2950. $this->segments = explode(',', $segments);
  2951. }
  2952. if (file_exists($this->path) && is_dir($this->path)) {
  2953. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  2954. }
  2955. }
  2956. private function getFileName(string $key): string
  2957. {
  2958. $s = DIRECTORY_SEPARATOR;
  2959. $md5 = md5($key);
  2960. $filename = rtrim($this->path, $s) . $s;
  2961. $i = 0;
  2962. foreach ($this->segments as $segment) {
  2963. $filename .= substr($md5, $i, $segment) . $s;
  2964. $i += $segment;
  2965. }
  2966. $filename .= substr($md5, $i);
  2967. return $filename;
  2968. }
  2969. public function set(string $key, string $value, int $ttl = 0): bool
  2970. {
  2971. $filename = $this->getFileName($key);
  2972. $dirname = dirname($filename);
  2973. if (!file_exists($dirname)) {
  2974. if (!mkdir($dirname, 0755, true)) {
  2975. return false;
  2976. }
  2977. }
  2978. $string = $ttl . '|' . $value;
  2979. return $this->filePutContents($filename, $string) !== false;
  2980. }
  2981. private function filePutContents($filename, $string)
  2982. {
  2983. return file_put_contents($filename, $string, LOCK_EX);
  2984. }
  2985. private function fileGetContents($filename)
  2986. {
  2987. $file = fopen($filename, 'rb');
  2988. if ($file === false) {
  2989. return false;
  2990. }
  2991. $lock = flock($file, LOCK_SH);
  2992. if (!$lock) {
  2993. fclose($file);
  2994. return false;
  2995. }
  2996. $string = '';
  2997. while (!feof($file)) {
  2998. $string .= fread($file, 8192);
  2999. }
  3000. flock($file, LOCK_UN);
  3001. fclose($file);
  3002. return $string;
  3003. }
  3004. private function getString($filename): string
  3005. {
  3006. $data = $this->fileGetContents($filename);
  3007. if ($data === false) {
  3008. return '';
  3009. }
  3010. list($ttl, $string) = explode('|', $data, 2);
  3011. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  3012. return '';
  3013. }
  3014. return $string;
  3015. }
  3016. public function get(string $key): string
  3017. {
  3018. $filename = $this->getFileName($key);
  3019. if (!file_exists($filename)) {
  3020. return '';
  3021. }
  3022. $string = $this->getString($filename);
  3023. if ($string == null) {
  3024. return '';
  3025. }
  3026. return $string;
  3027. }
  3028. private function clean(string $path, array $segments, int $len, bool $all) /*: void*/
  3029. {
  3030. $entries = scandir($path);
  3031. foreach ($entries as $entry) {
  3032. if ($entry === '.' || $entry === '..') {
  3033. continue;
  3034. }
  3035. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  3036. if (count($segments) == 0) {
  3037. if (strlen($entry) != $len) {
  3038. continue;
  3039. }
  3040. if (is_file($filename)) {
  3041. if ($all || $this->getString($filename) == null) {
  3042. unlink($filename);
  3043. }
  3044. }
  3045. } else {
  3046. if (strlen($entry) != $segments[0]) {
  3047. continue;
  3048. }
  3049. if (is_dir($filename)) {
  3050. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  3051. rmdir($filename);
  3052. }
  3053. }
  3054. }
  3055. }
  3056. public function clear(): bool
  3057. {
  3058. if (!file_exists($this->path) || !is_dir($this->path)) {
  3059. return false;
  3060. }
  3061. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  3062. return true;
  3063. }
  3064. }
  3065. }
  3066. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  3067. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3068. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3069. class ReflectedColumn implements \JsonSerializable
  3070. {
  3071. const DEFAULT_LENGTH = 255;
  3072. const DEFAULT_PRECISION = 19;
  3073. const DEFAULT_SCALE = 4;
  3074. private $name;
  3075. private $type;
  3076. private $length;
  3077. private $precision;
  3078. private $scale;
  3079. private $nullable;
  3080. private $pk;
  3081. private $fk;
  3082. public function __construct(string $name, string $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, string $fk)
  3083. {
  3084. $this->name = $name;
  3085. $this->type = $type;
  3086. $this->length = $length;
  3087. $this->precision = $precision;
  3088. $this->scale = $scale;
  3089. $this->nullable = $nullable;
  3090. $this->pk = $pk;
  3091. $this->fk = $fk;
  3092. $this->sanitize();
  3093. }
  3094. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  3095. {
  3096. $name = $columnResult['COLUMN_NAME'];
  3097. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  3098. $type = $reflection->toJdbcType($columnResult['DATA_TYPE'], $length);
  3099. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  3100. $scale = (int) $columnResult['NUMERIC_SCALE'];
  3101. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  3102. $pk = false;
  3103. $fk = '';
  3104. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3105. }
  3106. public static function fromJson( /* object */$json): ReflectedColumn
  3107. {
  3108. $name = $json->name;
  3109. $type = $json->type;
  3110. $length = isset($json->length) ? $json->length : 0;
  3111. $precision = isset($json->precision) ? $json->precision : 0;
  3112. $scale = isset($json->scale) ? $json->scale : 0;
  3113. $nullable = isset($json->nullable) ? $json->nullable : false;
  3114. $pk = isset($json->pk) ? $json->pk : false;
  3115. $fk = isset($json->fk) ? $json->fk : '';
  3116. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3117. }
  3118. private function sanitize()
  3119. {
  3120. $this->length = $this->hasLength() ? $this->getLength() : 0;
  3121. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  3122. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  3123. }
  3124. public function getName(): string
  3125. {
  3126. return $this->name;
  3127. }
  3128. public function getNullable(): bool
  3129. {
  3130. return $this->nullable;
  3131. }
  3132. public function getType(): string
  3133. {
  3134. return $this->type;
  3135. }
  3136. public function getLength(): int
  3137. {
  3138. return $this->length ?: self::DEFAULT_LENGTH;
  3139. }
  3140. public function getPrecision(): int
  3141. {
  3142. return $this->precision ?: self::DEFAULT_PRECISION;
  3143. }
  3144. public function getScale(): int
  3145. {
  3146. return $this->scale ?: self::DEFAULT_SCALE;
  3147. }
  3148. public function hasLength(): bool
  3149. {
  3150. return in_array($this->type, ['varchar', 'varbinary']);
  3151. }
  3152. public function hasPrecision(): bool
  3153. {
  3154. return $this->type == 'decimal';
  3155. }
  3156. public function hasScale(): bool
  3157. {
  3158. return $this->type == 'decimal';
  3159. }
  3160. public function isBinary(): bool
  3161. {
  3162. return in_array($this->type, ['blob', 'varbinary']);
  3163. }
  3164. public function isBoolean(): bool
  3165. {
  3166. return $this->type == 'boolean';
  3167. }
  3168. public function isGeometry(): bool
  3169. {
  3170. return $this->type == 'geometry';
  3171. }
  3172. public function isInteger(): bool
  3173. {
  3174. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  3175. }
  3176. public function setPk($value) /*: void*/
  3177. {
  3178. $this->pk = $value;
  3179. }
  3180. public function getPk(): bool
  3181. {
  3182. return $this->pk;
  3183. }
  3184. public function setFk($value) /*: void*/
  3185. {
  3186. $this->fk = $value;
  3187. }
  3188. public function getFk(): string
  3189. {
  3190. return $this->fk;
  3191. }
  3192. public function serialize()
  3193. {
  3194. return [
  3195. 'name' => $this->name,
  3196. 'type' => $this->type,
  3197. 'length' => $this->length,
  3198. 'precision' => $this->precision,
  3199. 'scale' => $this->scale,
  3200. 'nullable' => $this->nullable,
  3201. 'pk' => $this->pk,
  3202. 'fk' => $this->fk,
  3203. ];
  3204. }
  3205. public function jsonSerialize()
  3206. {
  3207. return array_filter($this->serialize());
  3208. }
  3209. }
  3210. }
  3211. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  3212. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3213. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3214. class ReflectedDatabase implements \JsonSerializable
  3215. {
  3216. private $tableTypes;
  3217. public function __construct(array $tableTypes)
  3218. {
  3219. $this->tableTypes = $tableTypes;
  3220. }
  3221. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  3222. {
  3223. $tableTypes = [];
  3224. foreach ($reflection->getTables() as $table) {
  3225. $tableName = $table['TABLE_NAME'];
  3226. $tableType = $table['TABLE_TYPE'];
  3227. if (in_array($tableName, $reflection->getIgnoredTables())) {
  3228. continue;
  3229. }
  3230. $tableTypes[$tableName] = $tableType;
  3231. }
  3232. return new ReflectedDatabase($tableTypes);
  3233. }
  3234. public static function fromJson( /* object */$json): ReflectedDatabase
  3235. {
  3236. $tableTypes = (array) $json->tables;
  3237. return new ReflectedDatabase($tableTypes);
  3238. }
  3239. public function hasTable(string $tableName): bool
  3240. {
  3241. return isset($this->tableTypes[$tableName]);
  3242. }
  3243. public function getType(string $tableName): string
  3244. {
  3245. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  3246. }
  3247. public function getTableNames(): array
  3248. {
  3249. return array_keys($this->tableTypes);
  3250. }
  3251. public function removeTable(string $tableName): bool
  3252. {
  3253. if (!isset($this->tableTypes[$tableName])) {
  3254. return false;
  3255. }
  3256. unset($this->tableTypes[$tableName]);
  3257. return true;
  3258. }
  3259. public function serialize()
  3260. {
  3261. return [
  3262. 'tables' => $this->tableTypes,
  3263. ];
  3264. }
  3265. public function jsonSerialize()
  3266. {
  3267. return $this->serialize();
  3268. }
  3269. }
  3270. }
  3271. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  3272. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3273. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3274. class ReflectedTable implements \JsonSerializable
  3275. {
  3276. private $name;
  3277. private $type;
  3278. private $columns;
  3279. private $pk;
  3280. private $fks;
  3281. public function __construct(string $name, string $type, array $columns)
  3282. {
  3283. $this->name = $name;
  3284. $this->type = $type;
  3285. // set columns
  3286. $this->columns = [];
  3287. foreach ($columns as $column) {
  3288. $columnName = $column->getName();
  3289. $this->columns[$columnName] = $column;
  3290. }
  3291. // set primary key
  3292. $this->pk = null;
  3293. foreach ($columns as $column) {
  3294. if ($column->getPk() == true) {
  3295. $this->pk = $column;
  3296. }
  3297. }
  3298. // set foreign keys
  3299. $this->fks = [];
  3300. foreach ($columns as $column) {
  3301. $columnName = $column->getName();
  3302. $referencedTableName = $column->getFk();
  3303. if ($referencedTableName != '') {
  3304. $this->fks[$columnName] = $referencedTableName;
  3305. }
  3306. }
  3307. }
  3308. public static function fromReflection(GenericReflection $reflection, string $name, string $type): ReflectedTable
  3309. {
  3310. // set columns
  3311. $columns = [];
  3312. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  3313. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  3314. $columns[$column->getName()] = $column;
  3315. }
  3316. // set primary key
  3317. $columnNames = $reflection->getTablePrimaryKeys($name);
  3318. if (count($columnNames) == 1) {
  3319. $columnName = $columnNames[0];
  3320. if (isset($columns[$columnName])) {
  3321. $pk = $columns[$columnName];
  3322. $pk->setPk(true);
  3323. }
  3324. }
  3325. // set foreign keys
  3326. $fks = $reflection->getTableForeignKeys($name);
  3327. foreach ($fks as $columnName => $table) {
  3328. $columns[$columnName]->setFk($table);
  3329. }
  3330. return new ReflectedTable($name, $type, array_values($columns));
  3331. }
  3332. public static function fromJson( /* object */$json): ReflectedTable
  3333. {
  3334. $name = $json->name;
  3335. $type = $json->type;
  3336. $columns = [];
  3337. if (isset($json->columns) && is_array($json->columns)) {
  3338. foreach ($json->columns as $column) {
  3339. $columns[] = ReflectedColumn::fromJson($column);
  3340. }
  3341. }
  3342. return new ReflectedTable($name, $type, $columns);
  3343. }
  3344. public function hasColumn(string $columnName): bool
  3345. {
  3346. return isset($this->columns[$columnName]);
  3347. }
  3348. public function hasPk(): bool
  3349. {
  3350. return $this->pk != null;
  3351. }
  3352. public function getPk() /*: ?ReflectedColumn */
  3353. {
  3354. return $this->pk;
  3355. }
  3356. public function getName(): string
  3357. {
  3358. return $this->name;
  3359. }
  3360. public function getType(): string
  3361. {
  3362. return $this->type;
  3363. }
  3364. public function getColumnNames(): array
  3365. {
  3366. return array_keys($this->columns);
  3367. }
  3368. public function getColumn($columnName): ReflectedColumn
  3369. {
  3370. return $this->columns[$columnName];
  3371. }
  3372. public function getFksTo(string $tableName): array
  3373. {
  3374. $columns = array();
  3375. foreach ($this->fks as $columnName => $referencedTableName) {
  3376. if ($tableName == $referencedTableName) {
  3377. $columns[] = $this->columns[$columnName];
  3378. }
  3379. }
  3380. return $columns;
  3381. }
  3382. public function removeColumn(string $columnName): bool
  3383. {
  3384. if (!isset($this->columns[$columnName])) {
  3385. return false;
  3386. }
  3387. unset($this->columns[$columnName]);
  3388. return true;
  3389. }
  3390. public function serialize()
  3391. {
  3392. return [
  3393. 'name' => $this->name,
  3394. 'type' => $this->type,
  3395. 'columns' => array_values($this->columns),
  3396. ];
  3397. }
  3398. public function jsonSerialize()
  3399. {
  3400. return $this->serialize();
  3401. }
  3402. }
  3403. }
  3404. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  3405. namespace Tqdev\PhpCrudApi\Column {
  3406. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  3407. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3408. use Tqdev\PhpCrudApi\Database\GenericDB;
  3409. class DefinitionService
  3410. {
  3411. private $db;
  3412. private $reflection;
  3413. public function __construct(GenericDB $db, ReflectionService $reflection)
  3414. {
  3415. $this->db = $db;
  3416. $this->reflection = $reflection;
  3417. }
  3418. public function updateTable(string $tableName, /* object */ $changes): bool
  3419. {
  3420. $table = $this->reflection->getTable($tableName);
  3421. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  3422. if ($table->getName() != $newTable->getName()) {
  3423. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  3424. return false;
  3425. }
  3426. }
  3427. return true;
  3428. }
  3429. public function updateColumn(string $tableName, string $columnName, /* object */ $changes): bool
  3430. {
  3431. $table = $this->reflection->getTable($tableName);
  3432. $column = $table->getColumn($columnName);
  3433. // remove constraints on other column
  3434. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3435. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  3436. $oldColumn = $table->getPk();
  3437. if ($oldColumn->getName() != $columnName) {
  3438. $oldColumn->setPk(false);
  3439. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  3440. return false;
  3441. }
  3442. }
  3443. }
  3444. // remove constraints
  3445. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  3446. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  3447. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  3448. return false;
  3449. }
  3450. }
  3451. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  3452. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  3453. return false;
  3454. }
  3455. }
  3456. // name and type
  3457. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3458. $newColumn->setPk(false);
  3459. $newColumn->setFk('');
  3460. if ($newColumn->getName() != $column->getName()) {
  3461. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  3462. return false;
  3463. }
  3464. }
  3465. if ($newColumn->getType() != $column->getType() ||
  3466. $newColumn->getLength() != $column->getLength() ||
  3467. $newColumn->getPrecision() != $column->getPrecision() ||
  3468. $newColumn->getScale() != $column->getScale()
  3469. ) {
  3470. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  3471. return false;
  3472. }
  3473. }
  3474. if ($newColumn->getNullable() != $column->getNullable()) {
  3475. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  3476. return false;
  3477. }
  3478. }
  3479. // add constraints
  3480. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3481. if ($newColumn->getFk()) {
  3482. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3483. return false;
  3484. }
  3485. }
  3486. if ($newColumn->getPk()) {
  3487. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3488. return false;
  3489. }
  3490. }
  3491. return true;
  3492. }
  3493. public function addTable( /* object */$definition)
  3494. {
  3495. $newTable = ReflectedTable::fromJson($definition);
  3496. if (!$this->db->definition()->addTable($newTable)) {
  3497. return false;
  3498. }
  3499. return true;
  3500. }
  3501. public function addColumn(string $tableName, /* object */ $definition)
  3502. {
  3503. $newColumn = ReflectedColumn::fromJson($definition);
  3504. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  3505. return false;
  3506. }
  3507. if ($newColumn->getFk()) {
  3508. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  3509. return false;
  3510. }
  3511. }
  3512. if ($newColumn->getPk()) {
  3513. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  3514. return false;
  3515. }
  3516. }
  3517. return true;
  3518. }
  3519. public function removeTable(string $tableName)
  3520. {
  3521. if (!$this->db->definition()->removeTable($tableName)) {
  3522. return false;
  3523. }
  3524. return true;
  3525. }
  3526. public function removeColumn(string $tableName, string $columnName)
  3527. {
  3528. $table = $this->reflection->getTable($tableName);
  3529. $newColumn = $table->getColumn($columnName);
  3530. if ($newColumn->getPk()) {
  3531. $newColumn->setPk(false);
  3532. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3533. return false;
  3534. }
  3535. }
  3536. if ($newColumn->getFk()) {
  3537. $newColumn->setFk("");
  3538. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  3539. return false;
  3540. }
  3541. }
  3542. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  3543. return false;
  3544. }
  3545. return true;
  3546. }
  3547. }
  3548. }
  3549. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  3550. namespace Tqdev\PhpCrudApi\Column {
  3551. use Tqdev\PhpCrudApi\Cache\Cache;
  3552. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedDatabase;
  3553. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3554. use Tqdev\PhpCrudApi\Database\GenericDB;
  3555. class ReflectionService
  3556. {
  3557. private $db;
  3558. private $cache;
  3559. private $ttl;
  3560. private $database;
  3561. private $tables;
  3562. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  3563. {
  3564. $this->db = $db;
  3565. $this->cache = $cache;
  3566. $this->ttl = $ttl;
  3567. $this->database = null;
  3568. $this->tables = [];
  3569. }
  3570. private function database(): ReflectedDatabase
  3571. {
  3572. if (!$this->database) {
  3573. $this->database = $this->loadDatabase(true);
  3574. }
  3575. return $this->database;
  3576. }
  3577. private function loadDatabase(bool $useCache): ReflectedDatabase
  3578. {
  3579. $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
  3580. if ($data != '') {
  3581. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  3582. } else {
  3583. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  3584. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  3585. $this->cache->set('ReflectedDatabase', $data, $this->ttl);
  3586. }
  3587. return $database;
  3588. }
  3589. private function loadTable(string $tableName, bool $useCache): ReflectedTable
  3590. {
  3591. $data = $useCache ? $this->cache->get("ReflectedTable($tableName)") : '';
  3592. if ($data != '') {
  3593. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  3594. } else {
  3595. $tableType = $this->database()->getType($tableName);
  3596. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  3597. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  3598. $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
  3599. }
  3600. return $table;
  3601. }
  3602. public function refreshTables()
  3603. {
  3604. $this->database = $this->loadDatabase(false);
  3605. }
  3606. public function refreshTable(string $tableName)
  3607. {
  3608. $this->tables[$tableName] = $this->loadTable($tableName, false);
  3609. }
  3610. public function hasTable(string $tableName): bool
  3611. {
  3612. return $this->database()->hasTable($tableName);
  3613. }
  3614. public function getType(string $tableName): string
  3615. {
  3616. return $this->database()->getType($tableName);
  3617. }
  3618. public function getTable(string $tableName): ReflectedTable
  3619. {
  3620. if (!isset($this->tables[$tableName])) {
  3621. $this->tables[$tableName] = $this->loadTable($tableName, true);
  3622. }
  3623. return $this->tables[$tableName];
  3624. }
  3625. public function getTableNames(): array
  3626. {
  3627. return $this->database()->getTableNames();
  3628. }
  3629. public function getDatabaseName(): string
  3630. {
  3631. return $this->database()->getName();
  3632. }
  3633. public function removeTable(string $tableName): bool
  3634. {
  3635. unset($this->tables[$tableName]);
  3636. return $this->database()->removeTable($tableName);
  3637. }
  3638. }
  3639. }
  3640. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  3641. namespace Tqdev\PhpCrudApi\Controller {
  3642. use Psr\Http\Message\ResponseInterface;
  3643. use Psr\Http\Message\ServerRequestInterface;
  3644. use Tqdev\PhpCrudApi\Cache\Cache;
  3645. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3646. class CacheController
  3647. {
  3648. private $cache;
  3649. private $responder;
  3650. public function __construct(Router $router, Responder $responder, Cache $cache)
  3651. {
  3652. $router->register('GET', '/cache/clear', array($this, 'clear'));
  3653. $this->cache = $cache;
  3654. $this->responder = $responder;
  3655. }
  3656. public function clear(ServerRequestInterface $request): ResponseInterface
  3657. {
  3658. return $this->responder->success($this->cache->clear());
  3659. }
  3660. }
  3661. }
  3662. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  3663. namespace Tqdev\PhpCrudApi\Controller {
  3664. use Psr\Http\Message\ResponseInterface;
  3665. use Psr\Http\Message\ServerRequestInterface;
  3666. use Tqdev\PhpCrudApi\Column\DefinitionService;
  3667. use Tqdev\PhpCrudApi\Column\ReflectionService;
  3668. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3669. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3670. use Tqdev\PhpCrudApi\RequestUtils;
  3671. class ColumnController
  3672. {
  3673. private $responder;
  3674. private $reflection;
  3675. private $definition;
  3676. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  3677. {
  3678. $router->register('GET', '/columns', array($this, 'getDatabase'));
  3679. $router->register('GET', '/columns/*', array($this, 'getTable'));
  3680. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  3681. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  3682. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  3683. $router->register('POST', '/columns', array($this, 'addTable'));
  3684. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  3685. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  3686. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  3687. $this->responder = $responder;
  3688. $this->reflection = $reflection;
  3689. $this->definition = $definition;
  3690. }
  3691. public function getDatabase(ServerRequestInterface $request): ResponseInterface
  3692. {
  3693. $tables = [];
  3694. foreach ($this->reflection->getTableNames() as $table) {
  3695. $tables[] = $this->reflection->getTable($table);
  3696. }
  3697. $database = ['tables' => $tables];
  3698. return $this->responder->success($database);
  3699. }
  3700. public function getTable(ServerRequestInterface $request): ResponseInterface
  3701. {
  3702. $tableName = RequestUtils::getPathSegment($request, 2);
  3703. if (!$this->reflection->hasTable($tableName)) {
  3704. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3705. }
  3706. $table = $this->reflection->getTable($tableName);
  3707. return $this->responder->success($table);
  3708. }
  3709. public function getColumn(ServerRequestInterface $request): ResponseInterface
  3710. {
  3711. $tableName = RequestUtils::getPathSegment($request, 2);
  3712. $columnName = RequestUtils::getPathSegment($request, 3);
  3713. if (!$this->reflection->hasTable($tableName)) {
  3714. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3715. }
  3716. $table = $this->reflection->getTable($tableName);
  3717. if (!$table->hasColumn($columnName)) {
  3718. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3719. }
  3720. $column = $table->getColumn($columnName);
  3721. return $this->responder->success($column);
  3722. }
  3723. public function updateTable(ServerRequestInterface $request): ResponseInterface
  3724. {
  3725. $tableName = RequestUtils::getPathSegment($request, 2);
  3726. if (!$this->reflection->hasTable($tableName)) {
  3727. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3728. }
  3729. $success = $this->definition->updateTable($tableName, $request->getParsedBody());
  3730. if ($success) {
  3731. $this->reflection->refreshTables();
  3732. }
  3733. return $this->responder->success($success);
  3734. }
  3735. public function updateColumn(ServerRequestInterface $request): ResponseInterface
  3736. {
  3737. $tableName = RequestUtils::getPathSegment($request, 2);
  3738. $columnName = RequestUtils::getPathSegment($request, 3);
  3739. if (!$this->reflection->hasTable($tableName)) {
  3740. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3741. }
  3742. $table = $this->reflection->getTable($tableName);
  3743. if (!$table->hasColumn($columnName)) {
  3744. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3745. }
  3746. $success = $this->definition->updateColumn($tableName, $columnName, $request->getParsedBody());
  3747. if ($success) {
  3748. $this->reflection->refreshTable($tableName);
  3749. }
  3750. return $this->responder->success($success);
  3751. }
  3752. public function addTable(ServerRequestInterface $request): ResponseInterface
  3753. {
  3754. $tableName = $request->getParsedBody()->name;
  3755. if ($this->reflection->hasTable($tableName)) {
  3756. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  3757. }
  3758. $success = $this->definition->addTable($request->getParsedBody());
  3759. if ($success) {
  3760. $this->reflection->refreshTables();
  3761. }
  3762. return $this->responder->success($success);
  3763. }
  3764. public function addColumn(ServerRequestInterface $request): ResponseInterface
  3765. {
  3766. $tableName = RequestUtils::getPathSegment($request, 2);
  3767. if (!$this->reflection->hasTable($tableName)) {
  3768. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3769. }
  3770. $columnName = $request->getParsedBody()->name;
  3771. $table = $this->reflection->getTable($tableName);
  3772. if ($table->hasColumn($columnName)) {
  3773. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  3774. }
  3775. $success = $this->definition->addColumn($tableName, $request->getParsedBody());
  3776. if ($success) {
  3777. $this->reflection->refreshTable($tableName);
  3778. }
  3779. return $this->responder->success($success);
  3780. }
  3781. public function removeTable(ServerRequestInterface $request): ResponseInterface
  3782. {
  3783. $tableName = RequestUtils::getPathSegment($request, 2);
  3784. if (!$this->reflection->hasTable($tableName)) {
  3785. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3786. }
  3787. $success = $this->definition->removeTable($tableName);
  3788. if ($success) {
  3789. $this->reflection->refreshTables();
  3790. }
  3791. return $this->responder->success($success);
  3792. }
  3793. public function removeColumn(ServerRequestInterface $request): ResponseInterface
  3794. {
  3795. $tableName = RequestUtils::getPathSegment($request, 2);
  3796. $columnName = RequestUtils::getPathSegment($request, 3);
  3797. if (!$this->reflection->hasTable($tableName)) {
  3798. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3799. }
  3800. $table = $this->reflection->getTable($tableName);
  3801. if (!$table->hasColumn($columnName)) {
  3802. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3803. }
  3804. $success = $this->definition->removeColumn($tableName, $columnName);
  3805. if ($success) {
  3806. $this->reflection->refreshTable($tableName);
  3807. }
  3808. return $this->responder->success($success);
  3809. }
  3810. }
  3811. }
  3812. // file: src/Tqdev/PhpCrudApi/Controller/GeoJsonController.php
  3813. namespace Tqdev\PhpCrudApi\Controller {
  3814. use Psr\Http\Message\ResponseInterface;
  3815. use Psr\Http\Message\ServerRequestInterface;
  3816. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  3817. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3818. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3819. use Tqdev\PhpCrudApi\RequestUtils;
  3820. class GeoJsonController
  3821. {
  3822. private $service;
  3823. private $responder;
  3824. private $geoJsonConverter;
  3825. public function __construct(Router $router, Responder $responder, GeoJsonService $service)
  3826. {
  3827. $router->register('GET', '/geojson/*', array($this, '_list'));
  3828. $router->register('GET', '/geojson/*/*', array($this, 'read'));
  3829. $this->service = $service;
  3830. $this->responder = $responder;
  3831. }
  3832. public function _list(ServerRequestInterface $request): ResponseInterface
  3833. {
  3834. $table = RequestUtils::getPathSegment($request, 2);
  3835. $params = RequestUtils::getParams($request);
  3836. if (!$this->service->hasTable($table)) {
  3837. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3838. }
  3839. return $this->responder->success($this->service->_list($table, $params));
  3840. }
  3841. public function read(ServerRequestInterface $request): ResponseInterface
  3842. {
  3843. $table = RequestUtils::getPathSegment($request, 2);
  3844. if (!$this->service->hasTable($table)) {
  3845. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3846. }
  3847. if ($this->service->getType($table) != 'table') {
  3848. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3849. }
  3850. $id = RequestUtils::getPathSegment($request, 3);
  3851. $params = RequestUtils::getParams($request);
  3852. if (strpos($id, ',') !== false) {
  3853. $ids = explode(',', $id);
  3854. $result = (object) array('type' => 'FeatureCollection', 'features' => array());
  3855. for ($i = 0; $i < count($ids); $i++) {
  3856. array_push($result->features, $this->service->read($table, $ids[$i], $params));
  3857. }
  3858. return $this->responder->success($result);
  3859. } else {
  3860. $response = $this->service->read($table, $id, $params);
  3861. if ($response === null) {
  3862. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  3863. }
  3864. return $this->responder->success($response);
  3865. }
  3866. }
  3867. }
  3868. }
  3869. // file: src/Tqdev/PhpCrudApi/Controller/JsonResponder.php
  3870. namespace Tqdev\PhpCrudApi\Controller {
  3871. use Psr\Http\Message\ResponseInterface;
  3872. use Tqdev\PhpCrudApi\Record\Document\ErrorDocument;
  3873. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3874. use Tqdev\PhpCrudApi\ResponseFactory;
  3875. class JsonResponder implements Responder
  3876. {
  3877. public function error(int $error, string $argument, $details = null): ResponseInterface
  3878. {
  3879. $errorCode = new ErrorCode($error);
  3880. $status = $errorCode->getStatus();
  3881. $document = new ErrorDocument($errorCode, $argument, $details);
  3882. return ResponseFactory::fromObject($status, $document);
  3883. }
  3884. public function success($result): ResponseInterface
  3885. {
  3886. return ResponseFactory::fromObject(ResponseFactory::OK, $result);
  3887. }
  3888. }
  3889. }
  3890. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  3891. namespace Tqdev\PhpCrudApi\Controller {
  3892. use Psr\Http\Message\ResponseInterface;
  3893. use Psr\Http\Message\ServerRequestInterface;
  3894. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3895. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  3896. class OpenApiController
  3897. {
  3898. private $openApi;
  3899. private $responder;
  3900. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  3901. {
  3902. $router->register('GET', '/openapi', array($this, 'openapi'));
  3903. $this->openApi = $openApi;
  3904. $this->responder = $responder;
  3905. }
  3906. public function openapi(ServerRequestInterface $request): ResponseInterface
  3907. {
  3908. return $this->responder->success($this->openApi->get());
  3909. }
  3910. }
  3911. }
  3912. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  3913. namespace Tqdev\PhpCrudApi\Controller {
  3914. use Psr\Http\Message\ResponseInterface;
  3915. use Psr\Http\Message\ServerRequestInterface;
  3916. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3917. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3918. use Tqdev\PhpCrudApi\Record\RecordService;
  3919. use Tqdev\PhpCrudApi\RequestUtils;
  3920. class RecordController
  3921. {
  3922. private $service;
  3923. private $responder;
  3924. public function __construct(Router $router, Responder $responder, RecordService $service)
  3925. {
  3926. $router->register('GET', '/records/*', array($this, '_list'));
  3927. $router->register('POST', '/records/*', array($this, 'create'));
  3928. $router->register('GET', '/records/*/*', array($this, 'read'));
  3929. $router->register('PUT', '/records/*/*', array($this, 'update'));
  3930. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  3931. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  3932. $this->service = $service;
  3933. $this->responder = $responder;
  3934. }
  3935. public function _list(ServerRequestInterface $request): ResponseInterface
  3936. {
  3937. $table = RequestUtils::getPathSegment($request, 2);
  3938. $params = RequestUtils::getParams($request);
  3939. if (!$this->service->hasTable($table)) {
  3940. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3941. }
  3942. return $this->responder->success($this->service->_list($table, $params));
  3943. }
  3944. public function read(ServerRequestInterface $request): ResponseInterface
  3945. {
  3946. $table = RequestUtils::getPathSegment($request, 2);
  3947. if (!$this->service->hasTable($table)) {
  3948. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3949. }
  3950. if ($this->service->getType($table) != 'table') {
  3951. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3952. }
  3953. $id = RequestUtils::getPathSegment($request, 3);
  3954. $params = RequestUtils::getParams($request);
  3955. if (strpos($id, ',') !== false) {
  3956. $ids = explode(',', $id);
  3957. $result = [];
  3958. for ($i = 0; $i < count($ids); $i++) {
  3959. array_push($result, $this->service->read($table, $ids[$i], $params));
  3960. }
  3961. return $this->responder->success($result);
  3962. } else {
  3963. $response = $this->service->read($table, $id, $params);
  3964. if ($response === null) {
  3965. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  3966. }
  3967. return $this->responder->success($response);
  3968. }
  3969. }
  3970. public function create(ServerRequestInterface $request): ResponseInterface
  3971. {
  3972. $table = RequestUtils::getPathSegment($request, 2);
  3973. if (!$this->service->hasTable($table)) {
  3974. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3975. }
  3976. if ($this->service->getType($table) != 'table') {
  3977. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3978. }
  3979. $record = $request->getParsedBody();
  3980. if ($record === null) {
  3981. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  3982. }
  3983. $params = RequestUtils::getParams($request);
  3984. if (is_array($record)) {
  3985. $result = array();
  3986. foreach ($record as $r) {
  3987. $result[] = $this->service->create($table, $r, $params);
  3988. }
  3989. return $this->responder->success($result);
  3990. } else {
  3991. return $this->responder->success($this->service->create($table, $record, $params));
  3992. }
  3993. }
  3994. public function update(ServerRequestInterface $request): ResponseInterface
  3995. {
  3996. $table = RequestUtils::getPathSegment($request, 2);
  3997. if (!$this->service->hasTable($table)) {
  3998. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3999. }
  4000. if ($this->service->getType($table) != 'table') {
  4001. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4002. }
  4003. $id = RequestUtils::getPathSegment($request, 3);
  4004. $params = RequestUtils::getParams($request);
  4005. $record = $request->getParsedBody();
  4006. if ($record === null) {
  4007. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4008. }
  4009. $ids = explode(',', $id);
  4010. if (is_array($record)) {
  4011. if (count($ids) != count($record)) {
  4012. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4013. }
  4014. $result = array();
  4015. for ($i = 0; $i < count($ids); $i++) {
  4016. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  4017. }
  4018. return $this->responder->success($result);
  4019. } else {
  4020. if (count($ids) != 1) {
  4021. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4022. }
  4023. return $this->responder->success($this->service->update($table, $id, $record, $params));
  4024. }
  4025. }
  4026. public function delete(ServerRequestInterface $request): ResponseInterface
  4027. {
  4028. $table = RequestUtils::getPathSegment($request, 2);
  4029. if (!$this->service->hasTable($table)) {
  4030. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4031. }
  4032. if ($this->service->getType($table) != 'table') {
  4033. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4034. }
  4035. $id = RequestUtils::getPathSegment($request, 3);
  4036. $params = RequestUtils::getParams($request);
  4037. $ids = explode(',', $id);
  4038. if (count($ids) > 1) {
  4039. $result = array();
  4040. for ($i = 0; $i < count($ids); $i++) {
  4041. $result[] = $this->service->delete($table, $ids[$i], $params);
  4042. }
  4043. return $this->responder->success($result);
  4044. } else {
  4045. return $this->responder->success($this->service->delete($table, $id, $params));
  4046. }
  4047. }
  4048. public function increment(ServerRequestInterface $request): ResponseInterface
  4049. {
  4050. $table = RequestUtils::getPathSegment($request, 2);
  4051. if (!$this->service->hasTable($table)) {
  4052. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4053. }
  4054. if ($this->service->getType($table) != 'table') {
  4055. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4056. }
  4057. $id = RequestUtils::getPathSegment($request, 3);
  4058. $record = $request->getParsedBody();
  4059. if ($record === null) {
  4060. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4061. }
  4062. $params = RequestUtils::getParams($request);
  4063. $ids = explode(',', $id);
  4064. if (is_array($record)) {
  4065. if (count($ids) != count($record)) {
  4066. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4067. }
  4068. $result = array();
  4069. for ($i = 0; $i < count($ids); $i++) {
  4070. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  4071. }
  4072. return $this->responder->success($result);
  4073. } else {
  4074. if (count($ids) != 1) {
  4075. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4076. }
  4077. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  4078. }
  4079. }
  4080. }
  4081. }
  4082. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  4083. namespace Tqdev\PhpCrudApi\Controller {
  4084. use Psr\Http\Message\ResponseInterface;
  4085. interface Responder
  4086. {
  4087. public function error(int $error, string $argument, $details = null): ResponseInterface;
  4088. public function success($result): ResponseInterface;
  4089. }
  4090. }
  4091. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  4092. namespace Tqdev\PhpCrudApi\Database {
  4093. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4094. class ColumnConverter
  4095. {
  4096. private $driver;
  4097. public function __construct(string $driver)
  4098. {
  4099. $this->driver = $driver;
  4100. }
  4101. public function convertColumnValue(ReflectedColumn $column): string
  4102. {
  4103. if ($column->isBinary()) {
  4104. switch ($this->driver) {
  4105. case 'mysql':
  4106. return "FROM_BASE64(?)";
  4107. case 'pgsql':
  4108. return "decode(?, 'base64')";
  4109. case 'sqlsrv':
  4110. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  4111. }
  4112. }
  4113. if ($column->isGeometry()) {
  4114. switch ($this->driver) {
  4115. case 'mysql':
  4116. case 'pgsql':
  4117. return "ST_GeomFromText(?)";
  4118. case 'sqlsrv':
  4119. return "geometry::STGeomFromText(?,0)";
  4120. }
  4121. }
  4122. return '?';
  4123. }
  4124. public function convertColumnName(ReflectedColumn $column, $value): string
  4125. {
  4126. if ($column->isBinary()) {
  4127. switch ($this->driver) {
  4128. case 'mysql':
  4129. return "TO_BASE64($value) as $value";
  4130. case 'pgsql':
  4131. return "encode($value::bytea, 'base64') as $value";
  4132. case 'sqlsrv':
  4133. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  4134. }
  4135. }
  4136. if ($column->isGeometry()) {
  4137. switch ($this->driver) {
  4138. case 'mysql':
  4139. case 'pgsql':
  4140. return "ST_AsText($value) as $value";
  4141. case 'sqlsrv':
  4142. return "REPLACE($value.STAsText(),' (','(') as $value";
  4143. }
  4144. }
  4145. return $value;
  4146. }
  4147. }
  4148. }
  4149. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  4150. namespace Tqdev\PhpCrudApi\Database {
  4151. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4152. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4153. class ColumnsBuilder
  4154. {
  4155. private $driver;
  4156. private $converter;
  4157. public function __construct(string $driver)
  4158. {
  4159. $this->driver = $driver;
  4160. $this->converter = new ColumnConverter($driver);
  4161. }
  4162. public function getOffsetLimit(int $offset, int $limit): string
  4163. {
  4164. if ($limit < 0 || $offset < 0) {
  4165. return '';
  4166. }
  4167. switch ($this->driver) {
  4168. case 'mysql':return " LIMIT $offset, $limit";
  4169. case 'pgsql':return " LIMIT $limit OFFSET $offset";
  4170. case 'sqlsrv':return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  4171. }
  4172. }
  4173. private function quoteColumnName(ReflectedColumn $column): string
  4174. {
  4175. return '"' . $column->getName() . '"';
  4176. }
  4177. public function getOrderBy(ReflectedTable $table, array $columnOrdering): string
  4178. {
  4179. if (count($columnOrdering) == 0) {
  4180. return '';
  4181. }
  4182. $results = array();
  4183. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  4184. $column = $table->getColumn($columnName);
  4185. $quotedColumnName = $this->quoteColumnName($column);
  4186. $results[] = $quotedColumnName . ' ' . $ordering;
  4187. }
  4188. return ' ORDER BY ' . implode(',', $results);
  4189. }
  4190. public function getSelect(ReflectedTable $table, array $columnNames): string
  4191. {
  4192. $results = array();
  4193. foreach ($columnNames as $columnName) {
  4194. $column = $table->getColumn($columnName);
  4195. $quotedColumnName = $this->quoteColumnName($column);
  4196. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  4197. $results[] = $quotedColumnName;
  4198. }
  4199. return implode(',', $results);
  4200. }
  4201. public function getInsert(ReflectedTable $table, array $columnValues): string
  4202. {
  4203. $columns = array();
  4204. $values = array();
  4205. foreach ($columnValues as $columnName => $columnValue) {
  4206. $column = $table->getColumn($columnName);
  4207. $quotedColumnName = $this->quoteColumnName($column);
  4208. $columns[] = $quotedColumnName;
  4209. $columnValue = $this->converter->convertColumnValue($column);
  4210. $values[] = $columnValue;
  4211. }
  4212. $columnsSql = '(' . implode(',', $columns) . ')';
  4213. $valuesSql = '(' . implode(',', $values) . ')';
  4214. $outputColumn = $this->quoteColumnName($table->getPk());
  4215. switch ($this->driver) {
  4216. case 'mysql':return "$columnsSql VALUES $valuesSql";
  4217. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  4218. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  4219. }
  4220. }
  4221. public function getUpdate(ReflectedTable $table, array $columnValues): string
  4222. {
  4223. $results = array();
  4224. foreach ($columnValues as $columnName => $columnValue) {
  4225. $column = $table->getColumn($columnName);
  4226. $quotedColumnName = $this->quoteColumnName($column);
  4227. $columnValue = $this->converter->convertColumnValue($column);
  4228. $results[] = $quotedColumnName . '=' . $columnValue;
  4229. }
  4230. return implode(',', $results);
  4231. }
  4232. public function getIncrement(ReflectedTable $table, array $columnValues): string
  4233. {
  4234. $results = array();
  4235. foreach ($columnValues as $columnName => $columnValue) {
  4236. if (!is_numeric($columnValue)) {
  4237. continue;
  4238. }
  4239. $column = $table->getColumn($columnName);
  4240. $quotedColumnName = $this->quoteColumnName($column);
  4241. $columnValue = $this->converter->convertColumnValue($column);
  4242. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  4243. }
  4244. return implode(',', $results);
  4245. }
  4246. }
  4247. }
  4248. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  4249. namespace Tqdev\PhpCrudApi\Database {
  4250. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4251. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  4252. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4253. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4254. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  4255. use Tqdev\PhpCrudApi\Record\Condition\NotCondition;
  4256. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  4257. use Tqdev\PhpCrudApi\Record\Condition\SpatialCondition;
  4258. class ConditionsBuilder
  4259. {
  4260. private $driver;
  4261. public function __construct(string $driver)
  4262. {
  4263. $this->driver = $driver;
  4264. }
  4265. private function getConditionSql(Condition $condition, array &$arguments): string
  4266. {
  4267. if ($condition instanceof AndCondition) {
  4268. return $this->getAndConditionSql($condition, $arguments);
  4269. }
  4270. if ($condition instanceof OrCondition) {
  4271. return $this->getOrConditionSql($condition, $arguments);
  4272. }
  4273. if ($condition instanceof NotCondition) {
  4274. return $this->getNotConditionSql($condition, $arguments);
  4275. }
  4276. if ($condition instanceof SpatialCondition) {
  4277. return $this->getSpatialConditionSql($condition, $arguments);
  4278. }
  4279. if ($condition instanceof ColumnCondition) {
  4280. return $this->getColumnConditionSql($condition, $arguments);
  4281. }
  4282. throw new \Exception('Unknown Condition: ' . get_class($condition));
  4283. }
  4284. private function getAndConditionSql(AndCondition $and, array &$arguments): string
  4285. {
  4286. $parts = [];
  4287. foreach ($and->getConditions() as $condition) {
  4288. $parts[] = $this->getConditionSql($condition, $arguments);
  4289. }
  4290. return '(' . implode(' AND ', $parts) . ')';
  4291. }
  4292. private function getOrConditionSql(OrCondition $or, array &$arguments): string
  4293. {
  4294. $parts = [];
  4295. foreach ($or->getConditions() as $condition) {
  4296. $parts[] = $this->getConditionSql($condition, $arguments);
  4297. }
  4298. return '(' . implode(' OR ', $parts) . ')';
  4299. }
  4300. private function getNotConditionSql(NotCondition $not, array &$arguments): string
  4301. {
  4302. $condition = $not->getCondition();
  4303. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  4304. }
  4305. private function quoteColumnName(ReflectedColumn $column): string
  4306. {
  4307. return '"' . $column->getName() . '"';
  4308. }
  4309. private function escapeLikeValue(string $value): string
  4310. {
  4311. return addcslashes($value, '%_');
  4312. }
  4313. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): string
  4314. {
  4315. $column = $this->quoteColumnName($condition->getColumn());
  4316. $operator = $condition->getOperator();
  4317. $value = $condition->getValue();
  4318. switch ($operator) {
  4319. case 'cs':
  4320. $sql = "$column LIKE ?";
  4321. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  4322. break;
  4323. case 'sw':
  4324. $sql = "$column LIKE ?";
  4325. $arguments[] = $this->escapeLikeValue($value) . '%';
  4326. break;
  4327. case 'ew':
  4328. $sql = "$column LIKE ?";
  4329. $arguments[] = '%' . $this->escapeLikeValue($value);
  4330. break;
  4331. case 'eq':
  4332. $sql = "$column = ?";
  4333. $arguments[] = $value;
  4334. break;
  4335. case 'lt':
  4336. $sql = "$column < ?";
  4337. $arguments[] = $value;
  4338. break;
  4339. case 'le':
  4340. $sql = "$column <= ?";
  4341. $arguments[] = $value;
  4342. break;
  4343. case 'ge':
  4344. $sql = "$column >= ?";
  4345. $arguments[] = $value;
  4346. break;
  4347. case 'gt':
  4348. $sql = "$column > ?";
  4349. $arguments[] = $value;
  4350. break;
  4351. case 'bt':
  4352. $parts = explode(',', $value, 2);
  4353. $count = count($parts);
  4354. if ($count == 2) {
  4355. $sql = "($column >= ? AND $column <= ?)";
  4356. $arguments[] = $parts[0];
  4357. $arguments[] = $parts[1];
  4358. } else {
  4359. $sql = "FALSE";
  4360. }
  4361. break;
  4362. case 'in':
  4363. $parts = explode(',', $value);
  4364. $count = count($parts);
  4365. if ($count > 0) {
  4366. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  4367. $sql = "$column IN ($qmarks)";
  4368. for ($i = 0; $i < $count; $i++) {
  4369. $arguments[] = $parts[$i];
  4370. }
  4371. } else {
  4372. $sql = "FALSE";
  4373. }
  4374. break;
  4375. case 'is':
  4376. $sql = "$column IS NULL";
  4377. break;
  4378. }
  4379. return $sql;
  4380. }
  4381. private function getSpatialFunctionName(string $operator): string
  4382. {
  4383. switch ($operator) {
  4384. case 'co':return 'ST_Contains';
  4385. case 'cr':return 'ST_Crosses';
  4386. case 'di':return 'ST_Disjoint';
  4387. case 'eq':return 'ST_Equals';
  4388. case 'in':return 'ST_Intersects';
  4389. case 'ov':return 'ST_Overlaps';
  4390. case 'to':return 'ST_Touches';
  4391. case 'wi':return 'ST_Within';
  4392. case 'ic':return 'ST_IsClosed';
  4393. case 'is':return 'ST_IsSimple';
  4394. case 'iv':return 'ST_IsValid';
  4395. }
  4396. }
  4397. private function hasSpatialArgument(string $operator): bool
  4398. {
  4399. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  4400. }
  4401. private function getSpatialFunctionCall(string $functionName, string $column, bool $hasArgument): string
  4402. {
  4403. switch ($this->driver) {
  4404. case 'mysql':
  4405. case 'pgsql':
  4406. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  4407. return "$functionName($column, $argument)=TRUE";
  4408. case 'sqlsrv':
  4409. $functionName = str_replace('ST_', 'ST', $functionName);
  4410. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  4411. return "$column.$functionName($argument)=1";
  4412. }
  4413. }
  4414. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): string
  4415. {
  4416. $column = $this->quoteColumnName($condition->getColumn());
  4417. $operator = $condition->getOperator();
  4418. $value = $condition->getValue();
  4419. $functionName = $this->getSpatialFunctionName($operator);
  4420. $hasArgument = $this->hasSpatialArgument($operator);
  4421. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  4422. if ($hasArgument) {
  4423. $arguments[] = $value;
  4424. }
  4425. return $sql;
  4426. }
  4427. public function getWhereClause(Condition $condition, array &$arguments): string
  4428. {
  4429. if ($condition instanceof NoCondition) {
  4430. return '';
  4431. }
  4432. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  4433. }
  4434. }
  4435. }
  4436. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  4437. namespace Tqdev\PhpCrudApi\Database {
  4438. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4439. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4440. class DataConverter
  4441. {
  4442. private $driver;
  4443. public function __construct(string $driver)
  4444. {
  4445. $this->driver = $driver;
  4446. }
  4447. private function convertRecordValue($conversion, $value)
  4448. {
  4449. switch ($conversion) {
  4450. case 'boolean':
  4451. return $value ? true : false;
  4452. case 'integer':
  4453. return (int) $value;
  4454. }
  4455. return $value;
  4456. }
  4457. private function getRecordValueConversion(ReflectedColumn $column): string
  4458. {
  4459. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  4460. return 'boolean';
  4461. }
  4462. if ($this->driver == 'sqlsrv' && $column->getType() == 'bigint') {
  4463. return 'integer';
  4464. }
  4465. return 'none';
  4466. }
  4467. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  4468. {
  4469. foreach ($columnNames as $columnName) {
  4470. $column = $table->getColumn($columnName);
  4471. $conversion = $this->getRecordValueConversion($column);
  4472. if ($conversion != 'none') {
  4473. foreach ($records as $i => $record) {
  4474. $value = $records[$i][$columnName];
  4475. if ($value === null) {
  4476. continue;
  4477. }
  4478. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  4479. }
  4480. }
  4481. }
  4482. }
  4483. private function convertInputValue($conversion, $value)
  4484. {
  4485. switch ($conversion) {
  4486. case 'base64url_to_base64':
  4487. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  4488. }
  4489. return $value;
  4490. }
  4491. private function getInputValueConversion(ReflectedColumn $column): string
  4492. {
  4493. if ($column->isBinary()) {
  4494. return 'base64url_to_base64';
  4495. }
  4496. return 'none';
  4497. }
  4498. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  4499. {
  4500. $columnNames = array_keys($columnValues);
  4501. foreach ($columnNames as $columnName) {
  4502. $column = $table->getColumn($columnName);
  4503. $conversion = $this->getInputValueConversion($column);
  4504. if ($conversion != 'none') {
  4505. $value = $columnValues[$columnName];
  4506. if ($value !== null) {
  4507. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  4508. }
  4509. }
  4510. }
  4511. }
  4512. }
  4513. }
  4514. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  4515. namespace Tqdev\PhpCrudApi\Database {
  4516. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4517. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  4518. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4519. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4520. class GenericDB
  4521. {
  4522. private $driver;
  4523. private $database;
  4524. private $pdo;
  4525. private $reflection;
  4526. private $definition;
  4527. private $conditions;
  4528. private $columns;
  4529. private $converter;
  4530. private function getDsn(string $address, int $port, string $database): string
  4531. {
  4532. switch ($this->driver) {
  4533. case 'mysql':
  4534. return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  4535. case 'pgsql':
  4536. return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  4537. case 'sqlsrv':
  4538. return "$this->driver:Server=$address,$port;Database=$database";
  4539. }
  4540. }
  4541. private function getCommands(): array
  4542. {
  4543. switch ($this->driver) {
  4544. case 'mysql':
  4545. return [
  4546. 'SET SESSION sql_warnings=1;',
  4547. 'SET NAMES utf8mb4;',
  4548. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  4549. ];
  4550. case 'pgsql':
  4551. return [
  4552. "SET NAMES 'UTF8';",
  4553. ];
  4554. case 'sqlsrv':
  4555. return [];
  4556. }
  4557. }
  4558. private function getOptions(): array
  4559. {
  4560. $options = array(
  4561. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  4562. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  4563. );
  4564. switch ($this->driver) {
  4565. case 'mysql':
  4566. return $options + [
  4567. \PDO::ATTR_EMULATE_PREPARES => false,
  4568. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  4569. \PDO::ATTR_PERSISTENT => true,
  4570. ];
  4571. case 'pgsql':
  4572. return $options + [
  4573. \PDO::ATTR_EMULATE_PREPARES => false,
  4574. \PDO::ATTR_PERSISTENT => true,
  4575. ];
  4576. case 'sqlsrv':
  4577. return $options + [
  4578. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  4579. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  4580. ];
  4581. }
  4582. }
  4583. public function __construct(string $driver, string $address, int $port, string $database, string $username, string $password)
  4584. {
  4585. $this->driver = $driver;
  4586. $this->database = $database;
  4587. $dsn = $this->getDsn($address, $port, $database);
  4588. $options = $this->getOptions();
  4589. $this->pdo = new LazyPdo($dsn, $username, $password, $options);
  4590. $commands = $this->getCommands();
  4591. foreach ($commands as $command) {
  4592. $this->pdo->addInitCommand($command);
  4593. }
  4594. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  4595. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  4596. $this->conditions = new ConditionsBuilder($driver);
  4597. $this->columns = new ColumnsBuilder($driver);
  4598. $this->converter = new DataConverter($driver);
  4599. }
  4600. public function pdo(): LazyPdo
  4601. {
  4602. return $this->pdo;
  4603. }
  4604. public function reflection(): GenericReflection
  4605. {
  4606. return $this->reflection;
  4607. }
  4608. public function definition(): GenericDefinition
  4609. {
  4610. return $this->definition;
  4611. }
  4612. private function addMiddlewareConditions(string $tableName, Condition $condition): Condition
  4613. {
  4614. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  4615. if ($condition1) {
  4616. $condition = $condition->_and($condition1);
  4617. }
  4618. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  4619. if ($condition2) {
  4620. $condition = $condition->_and($condition2);
  4621. }
  4622. return $condition;
  4623. }
  4624. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  4625. {
  4626. $this->converter->convertColumnValues($table, $columnValues);
  4627. $insertColumns = $this->columns->getInsert($table, $columnValues);
  4628. $tableName = $table->getName();
  4629. $pkName = $table->getPk()->getName();
  4630. $parameters = array_values($columnValues);
  4631. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  4632. $stmt = $this->query($sql, $parameters);
  4633. // return primary key value if specified in the input
  4634. if (isset($columnValues[$pkName])) {
  4635. return $columnValues[$pkName];
  4636. }
  4637. // work around missing "returning" or "output" in mysql
  4638. switch ($this->driver) {
  4639. case 'mysql':
  4640. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  4641. break;
  4642. }
  4643. $pkValue = $stmt->fetchColumn(0);
  4644. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  4645. return (int) $pkValue;
  4646. }
  4647. return $pkValue;
  4648. }
  4649. public function selectSingle(ReflectedTable $table, array $columnNames, string $id) /*: ?array*/
  4650. {
  4651. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4652. $tableName = $table->getName();
  4653. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4654. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4655. $parameters = array();
  4656. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4657. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4658. $stmt = $this->query($sql, $parameters);
  4659. $record = $stmt->fetch() ?: null;
  4660. if ($record === null) {
  4661. return null;
  4662. }
  4663. $records = array($record);
  4664. $this->converter->convertRecords($table, $columnNames, $records);
  4665. return $records[0];
  4666. }
  4667. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  4668. {
  4669. if (count($ids) == 0) {
  4670. return [];
  4671. }
  4672. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4673. $tableName = $table->getName();
  4674. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  4675. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4676. $parameters = array();
  4677. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4678. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4679. $stmt = $this->query($sql, $parameters);
  4680. $records = $stmt->fetchAll();
  4681. $this->converter->convertRecords($table, $columnNames, $records);
  4682. return $records;
  4683. }
  4684. public function selectCount(ReflectedTable $table, Condition $condition): int
  4685. {
  4686. $tableName = $table->getName();
  4687. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4688. $parameters = array();
  4689. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4690. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  4691. $stmt = $this->query($sql, $parameters);
  4692. return $stmt->fetchColumn(0);
  4693. }
  4694. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  4695. {
  4696. if ($limit == 0) {
  4697. return array();
  4698. }
  4699. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4700. $tableName = $table->getName();
  4701. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4702. $parameters = array();
  4703. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4704. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  4705. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  4706. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  4707. $stmt = $this->query($sql, $parameters);
  4708. $records = $stmt->fetchAll();
  4709. $this->converter->convertRecords($table, $columnNames, $records);
  4710. return $records;
  4711. }
  4712. public function updateSingle(ReflectedTable $table, array $columnValues, string $id)
  4713. {
  4714. if (count($columnValues) == 0) {
  4715. return 0;
  4716. }
  4717. $this->converter->convertColumnValues($table, $columnValues);
  4718. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  4719. $tableName = $table->getName();
  4720. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4721. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4722. $parameters = array_values($columnValues);
  4723. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4724. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4725. $stmt = $this->query($sql, $parameters);
  4726. return $stmt->rowCount();
  4727. }
  4728. public function deleteSingle(ReflectedTable $table, string $id)
  4729. {
  4730. $tableName = $table->getName();
  4731. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4732. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4733. $parameters = array();
  4734. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4735. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  4736. $stmt = $this->query($sql, $parameters);
  4737. return $stmt->rowCount();
  4738. }
  4739. public function incrementSingle(ReflectedTable $table, array $columnValues, string $id)
  4740. {
  4741. if (count($columnValues) == 0) {
  4742. return 0;
  4743. }
  4744. $this->converter->convertColumnValues($table, $columnValues);
  4745. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  4746. $tableName = $table->getName();
  4747. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4748. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4749. $parameters = array_values($columnValues);
  4750. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4751. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4752. $stmt = $this->query($sql, $parameters);
  4753. return $stmt->rowCount();
  4754. }
  4755. private function query(string $sql, array $parameters): \PDOStatement
  4756. {
  4757. $stmt = $this->pdo->prepare($sql);
  4758. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  4759. $stmt->execute($parameters);
  4760. return $stmt;
  4761. }
  4762. }
  4763. }
  4764. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  4765. namespace Tqdev\PhpCrudApi\Database {
  4766. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4767. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4768. use Tqdev\PhpCrudApi\Database\LazyPdo;
  4769. class GenericDefinition
  4770. {
  4771. private $pdo;
  4772. private $driver;
  4773. private $database;
  4774. private $typeConverter;
  4775. private $reflection;
  4776. public function __construct(LazyPdo $pdo, string $driver, string $database)
  4777. {
  4778. $this->pdo = $pdo;
  4779. $this->driver = $driver;
  4780. $this->database = $database;
  4781. $this->typeConverter = new TypeConverter($driver);
  4782. $this->reflection = new GenericReflection($pdo, $driver, $database);
  4783. }
  4784. private function quote(string $identifier): string
  4785. {
  4786. return '"' . str_replace('"', '', $identifier) . '"';
  4787. }
  4788. public function getColumnType(ReflectedColumn $column, bool $update): string
  4789. {
  4790. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  4791. return 'serial';
  4792. }
  4793. $type = $this->typeConverter->fromJdbc($column->getType());
  4794. if ($column->hasPrecision() && $column->hasScale()) {
  4795. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  4796. } else if ($column->hasPrecision()) {
  4797. $size = '(' . $column->getPrecision() . ')';
  4798. } else if ($column->hasLength()) {
  4799. $size = '(' . $column->getLength() . ')';
  4800. } else {
  4801. $size = '';
  4802. }
  4803. $null = $this->getColumnNullType($column, $update);
  4804. $auto = $this->getColumnAutoIncrement($column, $update);
  4805. return $type . $size . $null . $auto;
  4806. }
  4807. private function getPrimaryKey(string $tableName): string
  4808. {
  4809. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  4810. if (count($pks) == 1) {
  4811. return $pks[0];
  4812. }
  4813. return "";
  4814. }
  4815. private function canAutoIncrement(ReflectedColumn $column): bool
  4816. {
  4817. return in_array($column->getType(), ['integer', 'bigint']);
  4818. }
  4819. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): string
  4820. {
  4821. if (!$this->canAutoIncrement($column)) {
  4822. return '';
  4823. }
  4824. switch ($this->driver) {
  4825. case 'mysql':
  4826. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  4827. case 'pgsql':
  4828. case 'sqlsrv':
  4829. return '';
  4830. }
  4831. }
  4832. private function getColumnNullType(ReflectedColumn $column, bool $update): string
  4833. {
  4834. if ($this->driver == 'pgsql' && $update) {
  4835. return '';
  4836. }
  4837. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  4838. }
  4839. private function getTableRenameSQL(string $tableName, string $newTableName): string
  4840. {
  4841. $p1 = $this->quote($tableName);
  4842. $p2 = $this->quote($newTableName);
  4843. switch ($this->driver) {
  4844. case 'mysql':
  4845. return "RENAME TABLE $p1 TO $p2";
  4846. case 'pgsql':
  4847. return "ALTER TABLE $p1 RENAME TO $p2";
  4848. case 'sqlsrv':
  4849. return "EXEC sp_rename $p1, $p2";
  4850. }
  4851. }
  4852. private function getColumnRenameSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4853. {
  4854. $p1 = $this->quote($tableName);
  4855. $p2 = $this->quote($columnName);
  4856. $p3 = $this->quote($newColumn->getName());
  4857. switch ($this->driver) {
  4858. case 'mysql':
  4859. $p4 = $this->getColumnType($newColumn, true);
  4860. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4861. case 'pgsql':
  4862. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  4863. case 'sqlsrv':
  4864. $p4 = $this->quote($tableName . '.' . $columnName);
  4865. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  4866. }
  4867. }
  4868. private function getColumnRetypeSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4869. {
  4870. $p1 = $this->quote($tableName);
  4871. $p2 = $this->quote($columnName);
  4872. $p3 = $this->quote($newColumn->getName());
  4873. $p4 = $this->getColumnType($newColumn, true);
  4874. switch ($this->driver) {
  4875. case 'mysql':
  4876. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4877. case 'pgsql':
  4878. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  4879. case 'sqlsrv':
  4880. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  4881. }
  4882. }
  4883. private function getSetColumnNullableSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4884. {
  4885. $p1 = $this->quote($tableName);
  4886. $p2 = $this->quote($columnName);
  4887. $p3 = $this->quote($newColumn->getName());
  4888. $p4 = $this->getColumnType($newColumn, true);
  4889. switch ($this->driver) {
  4890. case 'mysql':
  4891. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4892. case 'pgsql':
  4893. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  4894. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  4895. case 'sqlsrv':
  4896. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  4897. }
  4898. }
  4899. private function getSetColumnPkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4900. {
  4901. $p1 = $this->quote($tableName);
  4902. $p2 = $this->quote($columnName);
  4903. $p3 = $this->quote($tableName . '_pkey');
  4904. switch ($this->driver) {
  4905. case 'mysql':
  4906. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  4907. return "ALTER TABLE $p1 $p4";
  4908. case 'pgsql':
  4909. case 'sqlsrv':
  4910. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  4911. return "ALTER TABLE $p1 $p4";
  4912. }
  4913. }
  4914. private function getSetColumnPkSequenceSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4915. {
  4916. $p1 = $this->quote($tableName);
  4917. $p2 = $this->quote($columnName);
  4918. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  4919. switch ($this->driver) {
  4920. case 'mysql':
  4921. return "select 1";
  4922. case 'pgsql':
  4923. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  4924. case 'sqlsrv':
  4925. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  4926. }
  4927. }
  4928. private function getSetColumnPkSequenceStartSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4929. {
  4930. $p1 = $this->quote($tableName);
  4931. $p2 = $this->quote($columnName);
  4932. switch ($this->driver) {
  4933. case 'mysql':
  4934. return "select 1";
  4935. case 'pgsql':
  4936. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  4937. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  4938. case 'sqlsrv':
  4939. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  4940. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  4941. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  4942. }
  4943. }
  4944. private function getSetColumnPkDefaultSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4945. {
  4946. $p1 = $this->quote($tableName);
  4947. $p2 = $this->quote($columnName);
  4948. switch ($this->driver) {
  4949. case 'mysql':
  4950. $p3 = $this->quote($newColumn->getName());
  4951. $p4 = $this->getColumnType($newColumn, true);
  4952. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  4953. case 'pgsql':
  4954. if ($newColumn->getPk()) {
  4955. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  4956. $p4 = "SET DEFAULT nextval($p3)";
  4957. } else {
  4958. $p4 = 'DROP DEFAULT';
  4959. }
  4960. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  4961. case 'sqlsrv':
  4962. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  4963. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  4964. if ($newColumn->getPk()) {
  4965. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  4966. } else {
  4967. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  4968. }
  4969. }
  4970. }
  4971. private function getAddColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4972. {
  4973. $p1 = $this->quote($tableName);
  4974. $p2 = $this->quote($columnName);
  4975. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  4976. $p4 = $this->quote($newColumn->getFk());
  4977. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  4978. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  4979. }
  4980. private function getRemoveColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  4981. {
  4982. $p1 = $this->quote($tableName);
  4983. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  4984. switch ($this->driver) {
  4985. case 'mysql':
  4986. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  4987. case 'pgsql':
  4988. case 'sqlsrv':
  4989. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  4990. }
  4991. }
  4992. private function getAddTableSQL(ReflectedTable $newTable): string
  4993. {
  4994. $tableName = $newTable->getName();
  4995. $p1 = $this->quote($tableName);
  4996. $fields = [];
  4997. $constraints = [];
  4998. foreach ($newTable->getColumnNames() as $columnName) {
  4999. $pkColumn = $this->getPrimaryKey($tableName);
  5000. $newColumn = $newTable->getColumn($columnName);
  5001. $f1 = $this->quote($columnName);
  5002. $f2 = $this->getColumnType($newColumn, false);
  5003. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5004. $f4 = $this->quote($newColumn->getFk());
  5005. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  5006. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  5007. $fields[] = "$f1 $f2";
  5008. if ($newColumn->getPk()) {
  5009. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  5010. }
  5011. if ($newColumn->getFk()) {
  5012. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  5013. }
  5014. }
  5015. $p2 = implode(',', array_merge($fields, $constraints));
  5016. return "CREATE TABLE $p1 ($p2);";
  5017. }
  5018. private function getAddColumnSQL(string $tableName, ReflectedColumn $newColumn): string
  5019. {
  5020. $p1 = $this->quote($tableName);
  5021. $p2 = $this->quote($newColumn->getName());
  5022. $p3 = $this->getColumnType($newColumn, false);
  5023. switch ($this->driver) {
  5024. case 'mysql':
  5025. case 'pgsql':
  5026. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  5027. case 'sqlsrv':
  5028. return "ALTER TABLE $p1 ADD $p2 $p3";
  5029. }
  5030. }
  5031. private function getRemoveTableSQL(string $tableName): string
  5032. {
  5033. $p1 = $this->quote($tableName);
  5034. switch ($this->driver) {
  5035. case 'mysql':
  5036. case 'pgsql':
  5037. return "DROP TABLE $p1 CASCADE;";
  5038. case 'sqlsrv':
  5039. return "DROP TABLE $p1;";
  5040. }
  5041. }
  5042. private function getRemoveColumnSQL(string $tableName, string $columnName): string
  5043. {
  5044. $p1 = $this->quote($tableName);
  5045. $p2 = $this->quote($columnName);
  5046. switch ($this->driver) {
  5047. case 'mysql':
  5048. case 'pgsql':
  5049. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  5050. case 'sqlsrv':
  5051. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  5052. }
  5053. }
  5054. public function renameTable(string $tableName, string $newTableName)
  5055. {
  5056. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  5057. return $this->query($sql);
  5058. }
  5059. public function renameColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5060. {
  5061. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  5062. return $this->query($sql);
  5063. }
  5064. public function retypeColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5065. {
  5066. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  5067. return $this->query($sql);
  5068. }
  5069. public function setColumnNullable(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5070. {
  5071. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  5072. return $this->query($sql);
  5073. }
  5074. public function addColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5075. {
  5076. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5077. $this->query($sql);
  5078. if ($this->canAutoIncrement($newColumn)) {
  5079. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5080. $this->query($sql);
  5081. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  5082. $this->query($sql);
  5083. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5084. $this->query($sql);
  5085. }
  5086. return true;
  5087. }
  5088. public function removeColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5089. {
  5090. if ($this->canAutoIncrement($newColumn)) {
  5091. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5092. $this->query($sql);
  5093. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5094. $this->query($sql);
  5095. }
  5096. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5097. $this->query($sql);
  5098. return true;
  5099. }
  5100. public function addColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5101. {
  5102. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5103. return $this->query($sql);
  5104. }
  5105. public function removeColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5106. {
  5107. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5108. return $this->query($sql);
  5109. }
  5110. public function addTable(ReflectedTable $newTable)
  5111. {
  5112. $sql = $this->getAddTableSQL($newTable);
  5113. return $this->query($sql);
  5114. }
  5115. public function addColumn(string $tableName, ReflectedColumn $newColumn)
  5116. {
  5117. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  5118. return $this->query($sql);
  5119. }
  5120. public function removeTable(string $tableName)
  5121. {
  5122. $sql = $this->getRemoveTableSQL($tableName);
  5123. return $this->query($sql);
  5124. }
  5125. public function removeColumn(string $tableName, string $columnName)
  5126. {
  5127. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  5128. return $this->query($sql);
  5129. }
  5130. private function query(string $sql): bool
  5131. {
  5132. $stmt = $this->pdo->prepare($sql);
  5133. //echo "- $sql -- []\n";
  5134. return $stmt->execute();
  5135. }
  5136. }
  5137. }
  5138. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  5139. namespace Tqdev\PhpCrudApi\Database {
  5140. use Tqdev\PhpCrudApi\Database\LazyPdo;
  5141. class GenericReflection
  5142. {
  5143. private $pdo;
  5144. private $driver;
  5145. private $database;
  5146. private $typeConverter;
  5147. public function __construct(LazyPdo $pdo, string $driver, string $database)
  5148. {
  5149. $this->pdo = $pdo;
  5150. $this->driver = $driver;
  5151. $this->database = $database;
  5152. $this->typeConverter = new TypeConverter($driver);
  5153. }
  5154. public function getIgnoredTables(): array
  5155. {
  5156. switch ($this->driver) {
  5157. case 'mysql':return [];
  5158. case 'pgsql':return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  5159. case 'sqlsrv':return [];
  5160. }
  5161. }
  5162. private function getTablesSQL(): string
  5163. {
  5164. switch ($this->driver) {
  5165. case 'mysql':return 'SELECT "TABLE_NAME", "TABLE_TYPE" FROM "INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" IN (\'BASE TABLE\' , \'VIEW\') AND "TABLE_SCHEMA" = ? ORDER BY BINARY "TABLE_NAME"';
  5166. case 'pgsql':return 'SELECT c.relname as "TABLE_NAME", c.relkind as "TABLE_TYPE" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN (\'r\', \'v\') AND n.nspname <> \'pg_catalog\' AND n.nspname <> \'information_schema\' AND n.nspname !~ \'^pg_toast\' AND pg_catalog.pg_table_is_visible(c.oid) AND \'\' <> ? ORDER BY "TABLE_NAME";';
  5167. case 'sqlsrv':return 'SELECT o.name as "TABLE_NAME", o.xtype as "TABLE_TYPE" FROM sysobjects o WHERE o.xtype IN (\'U\', \'V\') ORDER BY "TABLE_NAME"';
  5168. }
  5169. }
  5170. private function getTableColumnsSQL(): string
  5171. {
  5172. switch ($this->driver) {
  5173. case 'mysql':return 'SELECT "COLUMN_NAME", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5174. case 'pgsql':return 'SELECT a.attname AS "COLUMN_NAME", case when a.attnotnull then \'NO\' else \'YES\' end as "IS_NULLABLE", pg_catalog.format_type(a.atttypid, -1) as "DATA_TYPE", case when a.atttypmod < 0 then NULL else a.atttypmod-4 end as "CHARACTER_MAXIMUM_LENGTH", case when a.atttypid != 1700 then NULL else ((a.atttypmod - 4) >> 16) & 65535 end as "NUMERIC_PRECISION", case when a.atttypid != 1700 then NULL else (a.atttypmod - 4) & 65535 end as "NUMERIC_SCALE" FROM pg_attribute a JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND a.attnum > 0 AND NOT a.attisdropped;';
  5175. case 'sqlsrv':return 'SELECT c.name AS "COLUMN_NAME", c.is_nullable AS "IS_NULLABLE", t.Name AS "DATA_TYPE", (c.max_length/2) AS "CHARACTER_MAXIMUM_LENGTH", c.precision AS "NUMERIC_PRECISION", c.scale AS "NUMERIC_SCALE" FROM sys.columns c INNER JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE c.object_id = OBJECT_ID(?) AND \'\' <> ?';
  5176. }
  5177. }
  5178. private function getTablePrimaryKeysSQL(): string
  5179. {
  5180. switch ($this->driver) {
  5181. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5182. case 'pgsql':return 'SELECT a.attname AS "COLUMN_NAME" FROM pg_attribute a JOIN pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum) JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND c.contype = \'p\'';
  5183. case 'sqlsrv':return 'SELECT c.NAME as "COLUMN_NAME" FROM sys.key_constraints kc inner join sys.objects t on t.object_id = kc.parent_object_id INNER JOIN sys.index_columns ic ON kc.parent_object_id = ic.object_id and kc.unique_index_id = ic.index_id INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE kc.type = \'PK\' and t.object_id = OBJECT_ID(?) and \'\' <> ?';
  5184. }
  5185. }
  5186. private function getTableForeignKeysSQL(): string
  5187. {
  5188. switch ($this->driver) {
  5189. case 'mysql':return 'SELECT "COLUMN_NAME", "REFERENCED_TABLE_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "REFERENCED_TABLE_NAME" IS NOT NULL AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5190. case 'pgsql':return 'SELECT a.attname AS "COLUMN_NAME", c.confrelid::regclass::text AS "REFERENCED_TABLE_NAME" FROM pg_attribute a JOIN pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum) JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND c.contype = \'f\'';
  5191. case 'sqlsrv':return 'SELECT COL_NAME(fc.parent_object_id, fc.parent_column_id) AS "COLUMN_NAME", OBJECT_NAME (f.referenced_object_id) AS "REFERENCED_TABLE_NAME" FROM sys.foreign_keys AS f INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id WHERE f.parent_object_id = OBJECT_ID(?) and \'\' <> ?';
  5192. }
  5193. }
  5194. public function getDatabaseName(): string
  5195. {
  5196. return $this->database;
  5197. }
  5198. public function getTables(): array
  5199. {
  5200. $sql = $this->getTablesSQL();
  5201. $results = $this->query($sql, [$this->database]);
  5202. foreach ($results as &$result) {
  5203. switch ($this->driver) {
  5204. case 'mysql':
  5205. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  5206. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  5207. break;
  5208. case 'pgsql':
  5209. $map = ['r' => 'table', 'v' => 'view'];
  5210. $result['TABLE_TYPE'] = $map[$result['TABLE_TYPE']];
  5211. break;
  5212. case 'sqlsrv':
  5213. $map = ['U' => 'table', 'V' => 'view'];
  5214. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  5215. break;
  5216. }
  5217. }
  5218. return $results;
  5219. }
  5220. public function getTableColumns(string $tableName, string $type): array
  5221. {
  5222. $sql = $this->getTableColumnsSQL();
  5223. $results = $this->query($sql, [$tableName, $this->database]);
  5224. if ($type == 'view') {
  5225. foreach ($results as &$result) {
  5226. $result['IS_NULLABLE'] = false;
  5227. }
  5228. }
  5229. return $results;
  5230. }
  5231. public function getTablePrimaryKeys(string $tableName): array
  5232. {
  5233. $sql = $this->getTablePrimaryKeysSQL();
  5234. $results = $this->query($sql, [$tableName, $this->database]);
  5235. $primaryKeys = [];
  5236. foreach ($results as $result) {
  5237. $primaryKeys[] = $result['COLUMN_NAME'];
  5238. }
  5239. return $primaryKeys;
  5240. }
  5241. public function getTableForeignKeys(string $tableName): array
  5242. {
  5243. $sql = $this->getTableForeignKeysSQL();
  5244. $results = $this->query($sql, [$tableName, $this->database]);
  5245. $foreignKeys = [];
  5246. foreach ($results as $result) {
  5247. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  5248. }
  5249. return $foreignKeys;
  5250. }
  5251. public function toJdbcType(string $type, int $size): string
  5252. {
  5253. return $this->typeConverter->toJdbc($type, $size);
  5254. }
  5255. private function query(string $sql, array $parameters): array
  5256. {
  5257. $stmt = $this->pdo->prepare($sql);
  5258. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  5259. $stmt->execute($parameters);
  5260. return $stmt->fetchAll();
  5261. }
  5262. }
  5263. }
  5264. // file: src/Tqdev/PhpCrudApi/Database/LazyPdo.php
  5265. namespace Tqdev\PhpCrudApi\Database {
  5266. class LazyPdo extends \PDO
  5267. {
  5268. private $dsn;
  5269. private $user;
  5270. private $password;
  5271. private $options;
  5272. private $commands;
  5273. private $pdo = null;
  5274. public function __construct(string $dsn, /*?string*/ $user = null, /*?string*/ $password = null, array $options = array())
  5275. {
  5276. $this->dsn = $dsn;
  5277. $this->user = $user;
  5278. $this->password = $password;
  5279. $this->options = $options;
  5280. $this->commands = array();
  5281. // explicitly NOT calling super::__construct
  5282. }
  5283. public function addInitCommand(string $command)/*: void*/
  5284. {
  5285. $this->commands[] = $command;
  5286. }
  5287. private function pdo()
  5288. {
  5289. if (!$this->pdo) {
  5290. $this->pdo = new \PDO($this->dsn, $this->user, $this->password, $this->options);
  5291. foreach ($this->commands as $command) {
  5292. $this->pdo->query($command);
  5293. }
  5294. }
  5295. return $this->pdo;
  5296. }
  5297. public function reauthenticate(/*?string*/$user, /*?string*/ $password): bool
  5298. {
  5299. $this->user = $user;
  5300. $this->password = $password;
  5301. if ($this->pdo) {
  5302. $this->pdo = null;
  5303. return false;
  5304. }
  5305. return true;
  5306. }
  5307. public function inTransaction(): bool
  5308. {
  5309. // Do not call parent method if there is no pdo object
  5310. return $this->pdo && parent::inTransaction();
  5311. }
  5312. public function setAttribute($attribute, $value): bool
  5313. {
  5314. if ($this->pdo) {
  5315. return $this->pdo()->setAttribute($attribute, $value);
  5316. }
  5317. $this->options[$attribute] = $value;
  5318. return true;
  5319. }
  5320. public function getAttribute($attribute): mixed
  5321. {
  5322. return $this->pdo()->getAttribute($attribute);
  5323. }
  5324. public function beginTransaction(): bool
  5325. {
  5326. return $this->pdo()->beginTransaction();
  5327. }
  5328. public function commit(): bool
  5329. {
  5330. return $this->pdo()->commit();
  5331. }
  5332. public function rollBack(): bool
  5333. {
  5334. return $this->pdo()->rollBack();
  5335. }
  5336. public function errorCode(): mixed
  5337. {
  5338. return $this->pdo()->errorCode();
  5339. }
  5340. public function errorInfo(): array
  5341. {
  5342. return $this->pdo()->errorInfo();
  5343. }
  5344. public function exec($query): int
  5345. {
  5346. return $this->pdo()->exec($query);
  5347. }
  5348. public function prepare($statement, $options = array())
  5349. {
  5350. return $this->pdo()->prepare($statement, $options);
  5351. }
  5352. public function quote($string, $parameter_type = null): string
  5353. {
  5354. return $this->pdo()->quote($string, $parameter_type);
  5355. }
  5356. public function lastInsertId(/* ?string */$name = null): string
  5357. {
  5358. return $this->pdo()->lastInsertId($name);
  5359. }
  5360. public function query(string $statement): \PDOStatement
  5361. {
  5362. return call_user_func_array(array($this->pdo(), 'query'), func_get_args());
  5363. }
  5364. }
  5365. }
  5366. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  5367. namespace Tqdev\PhpCrudApi\Database {
  5368. class TypeConverter
  5369. {
  5370. private $driver;
  5371. public function __construct(string $driver)
  5372. {
  5373. $this->driver = $driver;
  5374. }
  5375. private $fromJdbc = [
  5376. 'mysql' => [
  5377. 'clob' => 'longtext',
  5378. 'boolean' => 'bit',
  5379. 'blob' => 'longblob',
  5380. 'timestamp' => 'datetime',
  5381. ],
  5382. 'pgsql' => [
  5383. 'clob' => 'text',
  5384. 'blob' => 'bytea',
  5385. ],
  5386. 'sqlsrv' => [
  5387. 'boolean' => 'bit',
  5388. 'varchar' => 'nvarchar',
  5389. 'clob' => 'ntext',
  5390. 'blob' => 'image',
  5391. ],
  5392. ];
  5393. private $toJdbc = [
  5394. 'simplified' => [
  5395. 'char' => 'varchar',
  5396. 'longvarchar' => 'clob',
  5397. 'nchar' => 'varchar',
  5398. 'nvarchar' => 'varchar',
  5399. 'longnvarchar' => 'clob',
  5400. 'binary' => 'varbinary',
  5401. 'longvarbinary' => 'blob',
  5402. 'tinyint' => 'integer',
  5403. 'smallint' => 'integer',
  5404. 'real' => 'float',
  5405. 'numeric' => 'decimal',
  5406. 'time_with_timezone' => 'time',
  5407. 'timestamp_with_timezone' => 'timestamp',
  5408. ],
  5409. 'mysql' => [
  5410. 'bit' => 'boolean',
  5411. 'tinyblob' => 'blob',
  5412. 'mediumblob' => 'blob',
  5413. 'longblob' => 'blob',
  5414. 'tinytext' => 'clob',
  5415. 'mediumtext' => 'clob',
  5416. 'longtext' => 'clob',
  5417. 'text' => 'clob',
  5418. 'mediumint' => 'integer',
  5419. 'int' => 'integer',
  5420. 'polygon' => 'geometry',
  5421. 'point' => 'geometry',
  5422. 'datetime' => 'timestamp',
  5423. 'year' => 'integer',
  5424. 'enum' => 'varchar',
  5425. 'json' => 'clob',
  5426. ],
  5427. 'pgsql' => [
  5428. 'bigserial' => 'bigint',
  5429. 'bit varying' => 'bit',
  5430. 'box' => 'geometry',
  5431. 'bytea' => 'blob',
  5432. 'bpchar' => 'char',
  5433. 'character varying' => 'varchar',
  5434. 'character' => 'char',
  5435. 'cidr' => 'varchar',
  5436. 'circle' => 'geometry',
  5437. 'double precision' => 'double',
  5438. 'inet' => 'integer',
  5439. //'interval [ fields ]'
  5440. 'json' => 'clob',
  5441. 'jsonb' => 'clob',
  5442. 'line' => 'geometry',
  5443. 'lseg' => 'geometry',
  5444. 'macaddr' => 'varchar',
  5445. 'money' => 'decimal',
  5446. 'path' => 'geometry',
  5447. 'point' => 'geometry',
  5448. 'polygon' => 'geometry',
  5449. 'real' => 'float',
  5450. 'serial' => 'integer',
  5451. 'text' => 'clob',
  5452. 'time without time zone' => 'time',
  5453. 'time with time zone' => 'time_with_timezone',
  5454. 'timestamp without time zone' => 'timestamp',
  5455. 'timestamp with time zone' => 'timestamp_with_timezone',
  5456. //'tsquery'=
  5457. //'tsvector'
  5458. //'txid_snapshot'
  5459. 'uuid' => 'char',
  5460. 'xml' => 'clob',
  5461. ],
  5462. // source: https://docs.microsoft.com/en-us/sql/connect/jdbc/using-basic-data-types?view=sql-server-2017
  5463. 'sqlsrv' => [
  5464. 'varbinary(0)' => 'blob',
  5465. 'bit' => 'boolean',
  5466. 'datetime' => 'timestamp',
  5467. 'datetime2' => 'timestamp',
  5468. 'float' => 'double',
  5469. 'image' => 'blob',
  5470. 'int' => 'integer',
  5471. 'money' => 'decimal',
  5472. 'ntext' => 'clob',
  5473. 'smalldatetime' => 'timestamp',
  5474. 'smallmoney' => 'decimal',
  5475. 'text' => 'clob',
  5476. 'timestamp' => 'binary',
  5477. 'udt' => 'varbinary',
  5478. 'uniqueidentifier' => 'char',
  5479. 'xml' => 'clob',
  5480. ],
  5481. ];
  5482. // source: https://docs.oracle.com/javase/9/docs/api/java/sql/Types.html
  5483. private $valid = [
  5484. //'array' => true,
  5485. 'bigint' => true,
  5486. 'binary' => true,
  5487. 'bit' => true,
  5488. 'blob' => true,
  5489. 'boolean' => true,
  5490. 'char' => true,
  5491. 'clob' => true,
  5492. //'datalink' => true,
  5493. 'date' => true,
  5494. 'decimal' => true,
  5495. 'distinct' => true,
  5496. 'double' => true,
  5497. 'float' => true,
  5498. 'integer' => true,
  5499. //'java_object' => true,
  5500. 'longnvarchar' => true,
  5501. 'longvarbinary' => true,
  5502. 'longvarchar' => true,
  5503. 'nchar' => true,
  5504. 'nclob' => true,
  5505. //'null' => true,
  5506. 'numeric' => true,
  5507. 'nvarchar' => true,
  5508. //'other' => true,
  5509. 'real' => true,
  5510. //'ref' => true,
  5511. //'ref_cursor' => true,
  5512. //'rowid' => true,
  5513. 'smallint' => true,
  5514. //'sqlxml' => true,
  5515. //'struct' => true,
  5516. 'time' => true,
  5517. 'time_with_timezone' => true,
  5518. 'timestamp' => true,
  5519. 'timestamp_with_timezone' => true,
  5520. 'tinyint' => true,
  5521. 'varbinary' => true,
  5522. 'varchar' => true,
  5523. // extra:
  5524. 'geometry' => true,
  5525. ];
  5526. public function toJdbc(string $type, int $size): string
  5527. {
  5528. $jdbcType = strtolower($type);
  5529. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  5530. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  5531. }
  5532. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  5533. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  5534. }
  5535. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  5536. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  5537. }
  5538. if (!isset($this->valid[$jdbcType])) {
  5539. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  5540. }
  5541. return $jdbcType;
  5542. }
  5543. public function fromJdbc(string $type): string
  5544. {
  5545. $jdbcType = strtolower($type);
  5546. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  5547. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  5548. }
  5549. return $jdbcType;
  5550. }
  5551. }
  5552. }
  5553. // file: src/Tqdev/PhpCrudApi/GeoJson/Feature.php
  5554. namespace Tqdev\PhpCrudApi\GeoJson {
  5555. class Feature implements \JsonSerializable
  5556. {
  5557. private $id;
  5558. private $properties;
  5559. private $geometry;
  5560. public function __construct($id, array $properties, /*?Geometry*/ $geometry)
  5561. {
  5562. $this->id = $id;
  5563. $this->properties = $properties;
  5564. $this->geometry = $geometry;
  5565. }
  5566. public function serialize()
  5567. {
  5568. return [
  5569. 'type' => 'Feature',
  5570. 'id' => $this->id,
  5571. 'properties' => $this->properties,
  5572. 'geometry' => $this->geometry,
  5573. ];
  5574. }
  5575. public function jsonSerialize()
  5576. {
  5577. return $this->serialize();
  5578. }
  5579. }
  5580. }
  5581. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  5582. namespace Tqdev\PhpCrudApi\GeoJson {
  5583. class FeatureCollection implements \JsonSerializable
  5584. {
  5585. private $features;
  5586. private $results;
  5587. public function __construct(array $features, int $results)
  5588. {
  5589. $this->features = $features;
  5590. $this->results = $results;
  5591. }
  5592. public function serialize()
  5593. {
  5594. return [
  5595. 'type' => 'FeatureCollection',
  5596. 'features' => $this->features,
  5597. 'results' => $this->results,
  5598. ];
  5599. }
  5600. public function jsonSerialize()
  5601. {
  5602. return array_filter($this->serialize(), function ($v) {
  5603. return $v !== 0;
  5604. });
  5605. }
  5606. }
  5607. }
  5608. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  5609. namespace Tqdev\PhpCrudApi\GeoJson {
  5610. use Tqdev\PhpCrudApi\Column\ReflectionService;
  5611. use Tqdev\PhpCrudApi\GeoJson\FeatureCollection;
  5612. use Tqdev\PhpCrudApi\Record\RecordService;
  5613. class GeoJsonService
  5614. {
  5615. private $reflection;
  5616. private $records;
  5617. public function __construct(ReflectionService $reflection, RecordService $records)
  5618. {
  5619. $this->reflection = $reflection;
  5620. $this->records = $records;
  5621. }
  5622. public function hasTable(string $table): bool
  5623. {
  5624. return $this->reflection->hasTable($table);
  5625. }
  5626. public function getType(string $table): string
  5627. {
  5628. return $this->reflection->getType($table);
  5629. }
  5630. private function getGeometryColumnName(string $tableName, array &$params): string
  5631. {
  5632. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  5633. $table = $this->reflection->getTable($tableName);
  5634. $geometryColumnName = '';
  5635. foreach ($table->getColumnNames() as $columnName) {
  5636. if ($geometryParam && $geometryParam != $columnName) {
  5637. continue;
  5638. }
  5639. $column = $table->getColumn($columnName);
  5640. if ($column->isGeometry()) {
  5641. $geometryColumnName = $columnName;
  5642. break;
  5643. }
  5644. }
  5645. if ($geometryColumnName) {
  5646. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  5647. }
  5648. return $geometryColumnName;
  5649. }
  5650. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  5651. {
  5652. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  5653. if ($boundingBox) {
  5654. $c = explode(',', $boundingBox);
  5655. if (!isset($params['filter'])) {
  5656. $params['filter'] = array();
  5657. }
  5658. $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]))";
  5659. }
  5660. $tile = isset($params['tile']) ? $params['tile'][0] : '';
  5661. if ($tile) {
  5662. $zxy = explode(',', $tile);
  5663. if (count($zxy) == 3) {
  5664. list($z, $x, $y) = $zxy;
  5665. $c = array();
  5666. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x, $y));
  5667. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x + 1, $y + 1));
  5668. $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]))";
  5669. }
  5670. }
  5671. }
  5672. private function convertTileToLatLonOfUpperLeftCorner($z, $x, $y): array
  5673. {
  5674. $n = pow(2, $z);
  5675. $lon = $x / $n * 360.0 - 180.0;
  5676. $lat = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n))));
  5677. return [$lon, $lat];
  5678. }
  5679. private function convertRecordToFeature( /*object*/$record, string $primaryKeyColumnName, string $geometryColumnName)
  5680. {
  5681. $id = null;
  5682. if ($primaryKeyColumnName) {
  5683. $id = $record[$primaryKeyColumnName];
  5684. }
  5685. $geometry = null;
  5686. if (isset($record[$geometryColumnName])) {
  5687. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  5688. }
  5689. $properties = array_diff_key($record, [$primaryKeyColumnName => true, $geometryColumnName => true]);
  5690. return new Feature($id, $properties, $geometry);
  5691. }
  5692. private function getPrimaryKeyColumnName(string $tableName, array &$params): string
  5693. {
  5694. $primaryKeyColumn = $this->reflection->getTable($tableName)->getPk();
  5695. if (!$primaryKeyColumn) {
  5696. return '';
  5697. }
  5698. $primaryKeyColumnName = $primaryKeyColumn->getName();
  5699. $params['mandatory'][] = $tableName . "." . $primaryKeyColumnName;
  5700. return $primaryKeyColumnName;
  5701. }
  5702. public function _list(string $tableName, array $params): FeatureCollection
  5703. {
  5704. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5705. $this->setBoudingBoxFilter($geometryColumnName, $params);
  5706. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5707. $records = $this->records->_list($tableName, $params);
  5708. $features = array();
  5709. foreach ($records->getRecords() as $record) {
  5710. $features[] = $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5711. }
  5712. return new FeatureCollection($features, $records->getResults());
  5713. }
  5714. public function read(string $tableName, string $id, array $params): Feature
  5715. {
  5716. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5717. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5718. $record = $this->records->read($tableName, $id, $params);
  5719. return $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5720. }
  5721. }
  5722. }
  5723. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  5724. namespace Tqdev\PhpCrudApi\GeoJson {
  5725. class Geometry implements \JsonSerializable
  5726. {
  5727. private $type;
  5728. private $geometry;
  5729. public static $types = [
  5730. "Point",
  5731. "MultiPoint",
  5732. "LineString",
  5733. "MultiLineString",
  5734. "Polygon",
  5735. "MultiPolygon",
  5736. //"GeometryCollection",
  5737. ];
  5738. public function __construct(string $type, array $coordinates)
  5739. {
  5740. $this->type = $type;
  5741. $this->coordinates = $coordinates;
  5742. }
  5743. public static function fromWkt(string $wkt): Geometry
  5744. {
  5745. $bracket = strpos($wkt, '(');
  5746. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  5747. $supported = false;
  5748. foreach (Geometry::$types as $typeName) {
  5749. if (strtoupper($typeName) == $type) {
  5750. $type = $typeName;
  5751. $supported = true;
  5752. }
  5753. }
  5754. if (!$supported) {
  5755. throw new \Exception('Geometry type not supported: ' . $type);
  5756. }
  5757. $coordinates = substr($wkt, $bracket);
  5758. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  5759. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  5760. }
  5761. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  5762. $json = $coordinates;
  5763. $coordinates = json_decode($coordinates);
  5764. if (!$coordinates) {
  5765. throw new \Exception('Could not decode WKT: ' . $wkt);
  5766. }
  5767. return new Geometry($type, $coordinates);
  5768. }
  5769. public function serialize()
  5770. {
  5771. return [
  5772. 'type' => $this->type,
  5773. 'coordinates' => $this->coordinates,
  5774. ];
  5775. }
  5776. public function jsonSerialize()
  5777. {
  5778. return $this->serialize();
  5779. }
  5780. }
  5781. }
  5782. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  5783. namespace Tqdev\PhpCrudApi\Middleware\Base {
  5784. use Psr\Http\Server\MiddlewareInterface;
  5785. use Tqdev\PhpCrudApi\Controller\Responder;
  5786. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  5787. abstract class Middleware implements MiddlewareInterface
  5788. {
  5789. protected $next;
  5790. protected $responder;
  5791. private $properties;
  5792. public function __construct(Router $router, Responder $responder, array $properties)
  5793. {
  5794. $router->load($this);
  5795. $this->responder = $responder;
  5796. $this->properties = $properties;
  5797. }
  5798. protected function getArrayProperty(string $key, string $default): array
  5799. {
  5800. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  5801. }
  5802. protected function getProperty(string $key, $default)
  5803. {
  5804. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  5805. }
  5806. }
  5807. }
  5808. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  5809. namespace Tqdev\PhpCrudApi\Middleware\Communication {
  5810. class VariableStore
  5811. {
  5812. static $values = array();
  5813. public static function get(string $key)
  5814. {
  5815. if (isset(self::$values[$key])) {
  5816. return self::$values[$key];
  5817. }
  5818. return null;
  5819. }
  5820. public static function set(string $key, /* object */ $value)
  5821. {
  5822. self::$values[$key] = $value;
  5823. }
  5824. }
  5825. }
  5826. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  5827. namespace Tqdev\PhpCrudApi\Middleware\Router {
  5828. use Psr\Http\Message\ResponseInterface;
  5829. use Psr\Http\Message\ServerRequestInterface;
  5830. use Psr\Http\Server\RequestHandlerInterface;
  5831. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5832. interface Router extends RequestHandlerInterface
  5833. {
  5834. public function register(string $method, string $path, array $handler);
  5835. public function load(Middleware $middleware);
  5836. public function route(ServerRequestInterface $request): ResponseInterface;
  5837. }
  5838. }
  5839. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  5840. namespace Tqdev\PhpCrudApi\Middleware\Router {
  5841. use Psr\Http\Message\ResponseInterface;
  5842. use Psr\Http\Message\ServerRequestInterface;
  5843. use Tqdev\PhpCrudApi\Cache\Cache;
  5844. use Tqdev\PhpCrudApi\Controller\Responder;
  5845. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5846. use Tqdev\PhpCrudApi\Record\ErrorCode;
  5847. use Tqdev\PhpCrudApi\Record\PathTree;
  5848. use Tqdev\PhpCrudApi\RequestUtils;
  5849. use Tqdev\PhpCrudApi\ResponseUtils;
  5850. class SimpleRouter implements Router
  5851. {
  5852. private $basePath;
  5853. private $responder;
  5854. private $cache;
  5855. private $ttl;
  5856. private $debug;
  5857. private $registration;
  5858. private $routes;
  5859. private $routeHandlers;
  5860. private $middlewares;
  5861. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  5862. {
  5863. $this->basePath = $this->detectBasePath($basePath);
  5864. $this->responder = $responder;
  5865. $this->cache = $cache;
  5866. $this->ttl = $ttl;
  5867. $this->debug = $debug;
  5868. $this->registration = true;
  5869. $this->routes = $this->loadPathTree();
  5870. $this->routeHandlers = [];
  5871. $this->middlewares = array();
  5872. }
  5873. private function detectBasePath(string $basePath): string
  5874. {
  5875. if ($basePath) {
  5876. return $basePath;
  5877. }
  5878. if (isset($_SERVER['REQUEST_URI'])) {
  5879. $fullPath = urldecode(explode('?', $_SERVER['REQUEST_URI'])[0]);
  5880. if (isset($_SERVER['PATH_INFO'])) {
  5881. $path = $_SERVER['PATH_INFO'];
  5882. if (substr($fullPath, -1 * strlen($path)) == $path) {
  5883. return substr($fullPath, 0, -1 * strlen($path));
  5884. }
  5885. }
  5886. return $fullPath;
  5887. }
  5888. return '/';
  5889. }
  5890. private function loadPathTree(): PathTree
  5891. {
  5892. $data = $this->cache->get('PathTree');
  5893. if ($data != '') {
  5894. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  5895. $this->registration = false;
  5896. } else {
  5897. $tree = new PathTree();
  5898. }
  5899. return $tree;
  5900. }
  5901. public function register(string $method, string $path, array $handler)
  5902. {
  5903. $routeNumber = count($this->routeHandlers);
  5904. $this->routeHandlers[$routeNumber] = $handler;
  5905. if ($this->registration) {
  5906. $path = trim($path, '/');
  5907. $parts = array();
  5908. if ($path) {
  5909. $parts = explode('/', $path);
  5910. }
  5911. array_unshift($parts, $method);
  5912. $this->routes->put($parts, $routeNumber);
  5913. }
  5914. }
  5915. public function load(Middleware $middleware) /*: void*/
  5916. {
  5917. array_push($this->middlewares, $middleware);
  5918. }
  5919. public function route(ServerRequestInterface $request): ResponseInterface
  5920. {
  5921. if ($this->registration) {
  5922. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  5923. $this->cache->set('PathTree', $data, $this->ttl);
  5924. }
  5925. return $this->handle($request);
  5926. }
  5927. private function getRouteNumbers(ServerRequestInterface $request): array
  5928. {
  5929. $method = strtoupper($request->getMethod());
  5930. $path = array();
  5931. $segment = $method;
  5932. for ($i = 1; $segment; $i++) {
  5933. array_push($path, $segment);
  5934. $segment = RequestUtils::getPathSegment($request, $i);
  5935. }
  5936. return $this->routes->match($path);
  5937. }
  5938. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  5939. {
  5940. $path = $request->getUri()->getPath();
  5941. $basePath = rtrim($this->basePath, '/');
  5942. if (substr($path, 0, strlen($basePath)) == $basePath) {
  5943. $path = substr($path, strlen($basePath));
  5944. $request = $request->withUri($request->getUri()->withPath($path));
  5945. }
  5946. return $request;
  5947. }
  5948. public function getBasePath(): string
  5949. {
  5950. return $this->basePath;
  5951. }
  5952. public function handle(ServerRequestInterface $request): ResponseInterface
  5953. {
  5954. $request = $this->removeBasePath($request);
  5955. if (count($this->middlewares)) {
  5956. $handler = array_pop($this->middlewares);
  5957. return $handler->process($request, $this);
  5958. }
  5959. $routeNumbers = $this->getRouteNumbers($request);
  5960. if (count($routeNumbers) == 0) {
  5961. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  5962. }
  5963. try {
  5964. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  5965. } catch (\PDOException $e) {
  5966. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  5967. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  5968. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  5969. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  5970. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  5971. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  5972. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  5973. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  5974. } else {
  5975. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  5976. }
  5977. if ($this->debug) {
  5978. $response = ResponseUtils::addExceptionHeaders($response, $e);
  5979. }
  5980. }
  5981. return $response;
  5982. }
  5983. }
  5984. }
  5985. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  5986. namespace Tqdev\PhpCrudApi\Middleware {
  5987. use Psr\Http\Message\ResponseInterface;
  5988. use Psr\Http\Message\ServerRequestInterface;
  5989. use Psr\Http\Server\RequestHandlerInterface;
  5990. use Tqdev\PhpCrudApi\Controller\Responder;
  5991. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  5992. use Tqdev\PhpCrudApi\Record\ErrorCode;
  5993. use Tqdev\PhpCrudApi\RequestUtils;
  5994. class AjaxOnlyMiddleware extends Middleware
  5995. {
  5996. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  5997. {
  5998. $method = $request->getMethod();
  5999. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  6000. if (!in_array($method, $excludeMethods)) {
  6001. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  6002. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  6003. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  6004. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  6005. }
  6006. }
  6007. return $next->handle($request);
  6008. }
  6009. }
  6010. }
  6011. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  6012. namespace Tqdev\PhpCrudApi\Middleware {
  6013. use Psr\Http\Message\ResponseInterface;
  6014. use Psr\Http\Message\ServerRequestInterface;
  6015. use Psr\Http\Server\RequestHandlerInterface;
  6016. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6017. use Tqdev\PhpCrudApi\Controller\Responder;
  6018. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6019. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6020. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6021. use Tqdev\PhpCrudApi\Record\FilterInfo;
  6022. use Tqdev\PhpCrudApi\RequestUtils;
  6023. class AuthorizationMiddleware extends Middleware
  6024. {
  6025. private $reflection;
  6026. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6027. {
  6028. parent::__construct($router, $responder, $properties);
  6029. $this->reflection = $reflection;
  6030. }
  6031. private function handleColumns(string $operation, string $tableName) /*: void*/
  6032. {
  6033. $columnHandler = $this->getProperty('columnHandler', '');
  6034. if ($columnHandler) {
  6035. $table = $this->reflection->getTable($tableName);
  6036. foreach ($table->getColumnNames() as $columnName) {
  6037. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  6038. if (!$allowed) {
  6039. $table->removeColumn($columnName);
  6040. }
  6041. }
  6042. }
  6043. }
  6044. private function handleTable(string $operation, string $tableName) /*: void*/
  6045. {
  6046. if (!$this->reflection->hasTable($tableName)) {
  6047. return;
  6048. }
  6049. $allowed = true;
  6050. $tableHandler = $this->getProperty('tableHandler', '');
  6051. if ($tableHandler) {
  6052. $allowed = call_user_func($tableHandler, $operation, $tableName);
  6053. }
  6054. if (!$allowed) {
  6055. $this->reflection->removeTable($tableName);
  6056. } else {
  6057. $this->handleColumns($operation, $tableName);
  6058. }
  6059. }
  6060. private function handleRecords(string $operation, string $tableName) /*: void*/
  6061. {
  6062. if (!$this->reflection->hasTable($tableName)) {
  6063. return;
  6064. }
  6065. $recordHandler = $this->getProperty('recordHandler', '');
  6066. if ($recordHandler) {
  6067. $query = call_user_func($recordHandler, $operation, $tableName);
  6068. $filters = new FilterInfo();
  6069. $table = $this->reflection->getTable($tableName);
  6070. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  6071. parse_str($query, $params);
  6072. $condition = $filters->getCombinedConditions($table, $params);
  6073. VariableStore::set("authorization.conditions.$tableName", $condition);
  6074. }
  6075. }
  6076. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6077. {
  6078. $path = RequestUtils::getPathSegment($request, 1);
  6079. $operation = RequestUtils::getOperation($request);
  6080. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  6081. foreach ($tableNames as $tableName) {
  6082. $this->handleTable($operation, $tableName);
  6083. if ($path == 'records') {
  6084. $this->handleRecords($operation, $tableName);
  6085. }
  6086. }
  6087. if ($path == 'openapi') {
  6088. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  6089. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  6090. }
  6091. return $next->handle($request);
  6092. }
  6093. }
  6094. }
  6095. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  6096. namespace Tqdev\PhpCrudApi\Middleware {
  6097. use Psr\Http\Message\ResponseInterface;
  6098. use Psr\Http\Message\ServerRequestInterface;
  6099. use Psr\Http\Server\RequestHandlerInterface;
  6100. use Tqdev\PhpCrudApi\Controller\Responder;
  6101. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6102. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6103. use Tqdev\PhpCrudApi\RequestUtils;
  6104. class BasicAuthMiddleware extends Middleware
  6105. {
  6106. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  6107. {
  6108. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  6109. if ($hash && password_verify($password, $hash)) {
  6110. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  6111. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  6112. }
  6113. return true;
  6114. }
  6115. return false;
  6116. }
  6117. private function getValidUsername(string $username, string $password, string $passwordFile): string
  6118. {
  6119. $passwords = $this->readPasswords($passwordFile);
  6120. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  6121. $this->writePasswords($passwordFile, $passwords);
  6122. return $valid ? $username : '';
  6123. }
  6124. private function readPasswords(string $passwordFile): array
  6125. {
  6126. $passwords = [];
  6127. $passwordLines = file($passwordFile);
  6128. foreach ($passwordLines as $passwordLine) {
  6129. if (strpos($passwordLine, ':') !== false) {
  6130. list($username, $hash) = explode(':', trim($passwordLine), 2);
  6131. if (strlen($hash) > 0 && $hash[0] != '$') {
  6132. $hash = password_hash($hash, PASSWORD_DEFAULT);
  6133. }
  6134. $passwords[$username] = $hash;
  6135. }
  6136. }
  6137. return $passwords;
  6138. }
  6139. private function writePasswords(string $passwordFile, array $passwords): bool
  6140. {
  6141. $success = false;
  6142. $passwordFileContents = '';
  6143. foreach ($passwords as $username => $hash) {
  6144. $passwordFileContents .= "$username:$hash\n";
  6145. }
  6146. if (file_get_contents($passwordFile) != $passwordFileContents) {
  6147. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  6148. }
  6149. return $success;
  6150. }
  6151. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  6152. {
  6153. if (isset($_SERVER['PHP_AUTH_USER'])) {
  6154. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  6155. }
  6156. $header = RequestUtils::getHeader($request, 'Authorization');
  6157. $parts = explode(' ', trim($header), 2);
  6158. if (count($parts) != 2) {
  6159. return '';
  6160. }
  6161. if ($parts[0] != 'Basic') {
  6162. return '';
  6163. }
  6164. return base64_decode(strtr($parts[1], '-_', '+/'));
  6165. }
  6166. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6167. {
  6168. if (session_status() == PHP_SESSION_NONE) {
  6169. if (!headers_sent()) {
  6170. session_start();
  6171. }
  6172. }
  6173. $credentials = $this->getAuthorizationCredentials($request);
  6174. if ($credentials) {
  6175. list($username, $password) = array('', '');
  6176. if (strpos($credentials, ':') !== false) {
  6177. list($username, $password) = explode(':', $credentials, 2);
  6178. }
  6179. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  6180. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  6181. $_SESSION['username'] = $validUser;
  6182. if (!$validUser) {
  6183. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6184. }
  6185. if (!headers_sent()) {
  6186. session_regenerate_id();
  6187. }
  6188. }
  6189. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  6190. $authenticationMode = $this->getProperty('mode', 'required');
  6191. if ($authenticationMode == 'required') {
  6192. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6193. $realm = $this->getProperty('realm', 'Username and password required');
  6194. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  6195. return $response;
  6196. }
  6197. }
  6198. return $next->handle($request);
  6199. }
  6200. }
  6201. }
  6202. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  6203. namespace Tqdev\PhpCrudApi\Middleware {
  6204. use Psr\Http\Message\ResponseInterface;
  6205. use Psr\Http\Message\ServerRequestInterface;
  6206. use Psr\Http\Server\RequestHandlerInterface;
  6207. use Tqdev\PhpCrudApi\Controller\Responder;
  6208. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6209. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6210. use Tqdev\PhpCrudApi\ResponseFactory;
  6211. class CorsMiddleware extends Middleware
  6212. {
  6213. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  6214. {
  6215. $found = false;
  6216. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  6217. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  6218. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  6219. if (preg_match($regex, $origin)) {
  6220. $found = true;
  6221. break;
  6222. }
  6223. }
  6224. return $found;
  6225. }
  6226. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6227. {
  6228. $method = $request->getMethod();
  6229. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  6230. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  6231. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  6232. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  6233. } elseif ($method == 'OPTIONS') {
  6234. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  6235. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  6236. if ($allowHeaders) {
  6237. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  6238. }
  6239. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  6240. if ($allowMethods) {
  6241. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  6242. }
  6243. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6244. if ($allowCredentials) {
  6245. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6246. }
  6247. $maxAge = $this->getProperty('maxAge', '1728000');
  6248. if ($maxAge) {
  6249. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  6250. }
  6251. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  6252. if ($exposeHeaders) {
  6253. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  6254. }
  6255. } else {
  6256. $response = $next->handle($request);
  6257. }
  6258. if ($origin) {
  6259. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6260. if ($allowCredentials) {
  6261. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6262. }
  6263. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  6264. }
  6265. return $response;
  6266. }
  6267. }
  6268. }
  6269. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  6270. namespace Tqdev\PhpCrudApi\Middleware {
  6271. use Psr\Http\Message\ResponseInterface;
  6272. use Psr\Http\Message\ServerRequestInterface;
  6273. use Psr\Http\Server\RequestHandlerInterface;
  6274. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6275. use Tqdev\PhpCrudApi\Controller\Responder;
  6276. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6277. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6278. use Tqdev\PhpCrudApi\RequestUtils;
  6279. class CustomizationMiddleware extends Middleware
  6280. {
  6281. private $reflection;
  6282. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6283. {
  6284. parent::__construct($router, $responder, $properties);
  6285. $this->reflection = $reflection;
  6286. }
  6287. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6288. {
  6289. $operation = RequestUtils::getOperation($request);
  6290. $tableName = RequestUtils::getPathSegment($request, 2);
  6291. $beforeHandler = $this->getProperty('beforeHandler', '');
  6292. $environment = (object) array();
  6293. if ($beforeHandler !== '') {
  6294. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  6295. $request = $result ?: $request;
  6296. }
  6297. $response = $next->handle($request);
  6298. $afterHandler = $this->getProperty('afterHandler', '');
  6299. if ($afterHandler !== '') {
  6300. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  6301. $response = $result ?: $response;
  6302. }
  6303. return $response;
  6304. }
  6305. }
  6306. }
  6307. // file: src/Tqdev/PhpCrudApi/Middleware/DbAuthMiddleware.php
  6308. namespace Tqdev\PhpCrudApi\Middleware {
  6309. use Psr\Http\Message\ResponseInterface;
  6310. use Psr\Http\Message\ServerRequestInterface;
  6311. use Psr\Http\Server\RequestHandlerInterface;
  6312. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6313. use Tqdev\PhpCrudApi\Controller\Responder;
  6314. use Tqdev\PhpCrudApi\Database\GenericDB;
  6315. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6316. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6317. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  6318. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6319. use Tqdev\PhpCrudApi\Record\OrderingInfo;
  6320. use Tqdev\PhpCrudApi\RequestUtils;
  6321. class DbAuthMiddleware extends Middleware
  6322. {
  6323. private $reflection;
  6324. private $db;
  6325. private $ordering;
  6326. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  6327. {
  6328. parent::__construct($router, $responder, $properties);
  6329. $this->reflection = $reflection;
  6330. $this->db = $db;
  6331. $this->ordering = new OrderingInfo();
  6332. }
  6333. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6334. {
  6335. if (session_status() == PHP_SESSION_NONE) {
  6336. if (!headers_sent()) {
  6337. session_start();
  6338. }
  6339. }
  6340. $path = RequestUtils::getPathSegment($request, 1);
  6341. $method = $request->getMethod();
  6342. if ($method == 'POST' && $path == 'login') {
  6343. $body = $request->getParsedBody();
  6344. $username = isset($body->username) ? $body->username : '';
  6345. $password = isset($body->password) ? $body->password : '';
  6346. $tableName = $this->getProperty('usersTable', 'users');
  6347. $table = $this->reflection->getTable($tableName);
  6348. $usernameColumnName = $this->getProperty('usernameColumn', 'username');
  6349. $usernameColumn = $table->getColumn($usernameColumnName);
  6350. $passwordColumnName = $this->getProperty('passwordColumn', 'password');
  6351. $passwordColumn = $table->getColumn($passwordColumnName);
  6352. $condition = new ColumnCondition($usernameColumn, 'eq', $username);
  6353. $returnedColumns = $this->getProperty('returnedColumns', '');
  6354. if (!$returnedColumns) {
  6355. $columnNames = $table->getColumnNames();
  6356. } else {
  6357. $columnNames = array_map('trim', explode(',', $returnedColumns));
  6358. $columnNames[] = $passwordColumnName;
  6359. }
  6360. $columnOrdering = $this->ordering->getDefaultColumnOrdering($table);
  6361. $users = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, 0, 1);
  6362. foreach ($users as $user) {
  6363. if (password_verify($password, $user[$passwordColumnName]) == 1) {
  6364. if (!headers_sent()) {
  6365. session_regenerate_id(true);
  6366. }
  6367. unset($user[$passwordColumnName]);
  6368. $_SESSION['user'] = $user;
  6369. return $this->responder->success($user);
  6370. }
  6371. }
  6372. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6373. }
  6374. if ($method == 'POST' && $path == 'logout') {
  6375. if (isset($_SESSION['user'])) {
  6376. $user = $_SESSION['user'];
  6377. unset($_SESSION['user']);
  6378. if (session_status() != PHP_SESSION_NONE) {
  6379. session_destroy();
  6380. }
  6381. return $this->responder->success($user);
  6382. }
  6383. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6384. }
  6385. if (!isset($_SESSION['user']) || !$_SESSION['user']) {
  6386. $authenticationMode = $this->getProperty('mode', 'required');
  6387. if ($authenticationMode == 'required') {
  6388. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6389. }
  6390. }
  6391. return $next->handle($request);
  6392. }
  6393. }
  6394. }
  6395. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  6396. namespace Tqdev\PhpCrudApi\Middleware {
  6397. use Psr\Http\Message\ResponseInterface;
  6398. use Psr\Http\Message\ServerRequestInterface;
  6399. use Psr\Http\Server\RequestHandlerInterface;
  6400. use Tqdev\PhpCrudApi\Controller\Responder;
  6401. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6402. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6403. class FirewallMiddleware extends Middleware
  6404. {
  6405. private function ipMatch(string $ip, string $cidr): bool
  6406. {
  6407. if (strpos($cidr, '/') !== false) {
  6408. list($subnet, $mask) = explode('/', trim($cidr));
  6409. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  6410. return true;
  6411. }
  6412. } else {
  6413. if (ip2long($ip) == ip2long($cidr)) {
  6414. return true;
  6415. }
  6416. }
  6417. return false;
  6418. }
  6419. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  6420. {
  6421. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  6422. if ($this->ipMatch($ipAddress, $allowedIp)) {
  6423. return true;
  6424. }
  6425. }
  6426. return false;
  6427. }
  6428. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6429. {
  6430. $reverseProxy = $this->getProperty('reverseProxy', '');
  6431. if ($reverseProxy) {
  6432. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  6433. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  6434. $ipAddress = $_SERVER['REMOTE_ADDR'];
  6435. } else {
  6436. $ipAddress = '127.0.0.1';
  6437. }
  6438. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  6439. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  6440. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  6441. } else {
  6442. $response = $next->handle($request);
  6443. }
  6444. return $response;
  6445. }
  6446. }
  6447. }
  6448. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  6449. namespace Tqdev\PhpCrudApi\Middleware {
  6450. use Psr\Http\Message\ResponseInterface;
  6451. use Psr\Http\Message\ServerRequestInterface;
  6452. use Psr\Http\Server\RequestHandlerInterface;
  6453. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6454. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6455. use Tqdev\PhpCrudApi\Controller\Responder;
  6456. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6457. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6458. use Tqdev\PhpCrudApi\RequestUtils;
  6459. class IpAddressMiddleware extends Middleware
  6460. {
  6461. private $reflection;
  6462. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6463. {
  6464. parent::__construct($router, $responder, $properties);
  6465. $this->reflection = $reflection;
  6466. }
  6467. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  6468. {
  6469. $context = (array) $record;
  6470. $columnNames = $this->getProperty('columns', '');
  6471. if ($columnNames) {
  6472. foreach (explode(',', $columnNames) as $columnName) {
  6473. if ($table->hasColumn($columnName)) {
  6474. if ($operation == 'create') {
  6475. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  6476. } else {
  6477. unset($context[$columnName]);
  6478. }
  6479. }
  6480. }
  6481. }
  6482. return (object) $context;
  6483. }
  6484. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6485. {
  6486. $operation = RequestUtils::getOperation($request);
  6487. if (in_array($operation, ['create', 'update', 'increment'])) {
  6488. $tableNames = $this->getProperty('tables', '');
  6489. $tableName = RequestUtils::getPathSegment($request, 2);
  6490. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  6491. if ($this->reflection->hasTable($tableName)) {
  6492. $record = $request->getParsedBody();
  6493. if ($record !== null) {
  6494. $table = $this->reflection->getTable($tableName);
  6495. if (is_array($record)) {
  6496. foreach ($record as &$r) {
  6497. $r = $this->callHandler($r, $operation, $table);
  6498. }
  6499. } else {
  6500. $record = $this->callHandler($record, $operation, $table);
  6501. }
  6502. $request = $request->withParsedBody($record);
  6503. }
  6504. }
  6505. }
  6506. }
  6507. return $next->handle($request);
  6508. }
  6509. }
  6510. }
  6511. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  6512. namespace Tqdev\PhpCrudApi\Middleware {
  6513. use Psr\Http\Message\ResponseInterface;
  6514. use Psr\Http\Message\ServerRequestInterface;
  6515. use Psr\Http\Server\RequestHandlerInterface;
  6516. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6517. use Tqdev\PhpCrudApi\Controller\Responder;
  6518. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6519. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6520. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6521. use Tqdev\PhpCrudApi\RequestUtils;
  6522. class JoinLimitsMiddleware extends Middleware
  6523. {
  6524. private $reflection;
  6525. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6526. {
  6527. parent::__construct($router, $responder, $properties);
  6528. $this->reflection = $reflection;
  6529. }
  6530. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6531. {
  6532. $operation = RequestUtils::getOperation($request);
  6533. $params = RequestUtils::getParams($request);
  6534. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  6535. $maxDepth = (int) $this->getProperty('depth', '3');
  6536. $maxTables = (int) $this->getProperty('tables', '10');
  6537. $maxRecords = (int) $this->getProperty('records', '1000');
  6538. $tableCount = 0;
  6539. $joinPaths = array();
  6540. for ($i = 0; $i < count($params['join']); $i++) {
  6541. $joinPath = array();
  6542. $tables = explode(',', $params['join'][$i]);
  6543. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  6544. array_push($joinPath, $tables[$depth]);
  6545. $tableCount += 1;
  6546. if ($tableCount == $maxTables) {
  6547. break;
  6548. }
  6549. }
  6550. array_push($joinPaths, implode(',', $joinPath));
  6551. if ($tableCount == $maxTables) {
  6552. break;
  6553. }
  6554. }
  6555. $params['join'] = $joinPaths;
  6556. $request = RequestUtils::setParams($request, $params);
  6557. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  6558. }
  6559. return $next->handle($request);
  6560. }
  6561. }
  6562. }
  6563. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  6564. namespace Tqdev\PhpCrudApi\Middleware {
  6565. use Psr\Http\Message\ResponseInterface;
  6566. use Psr\Http\Message\ServerRequestInterface;
  6567. use Psr\Http\Server\RequestHandlerInterface;
  6568. use Tqdev\PhpCrudApi\Controller\Responder;
  6569. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6570. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6571. use Tqdev\PhpCrudApi\RequestUtils;
  6572. class JwtAuthMiddleware extends Middleware
  6573. {
  6574. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, string $secret, array $requirements): array
  6575. {
  6576. $algorithms = array(
  6577. 'HS256' => 'sha256',
  6578. 'HS384' => 'sha384',
  6579. 'HS512' => 'sha512',
  6580. 'RS256' => 'sha256',
  6581. 'RS384' => 'sha384',
  6582. 'RS512' => 'sha512',
  6583. );
  6584. $token = explode('.', $token);
  6585. if (count($token) < 3) {
  6586. return array();
  6587. }
  6588. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  6589. if (!$secret) {
  6590. return array();
  6591. }
  6592. if ($header['typ'] != 'JWT') {
  6593. return array();
  6594. }
  6595. $algorithm = $header['alg'];
  6596. if (!isset($algorithms[$algorithm])) {
  6597. return array();
  6598. }
  6599. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  6600. return array();
  6601. }
  6602. $hmac = $algorithms[$algorithm];
  6603. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  6604. $data = "$token[0].$token[1]";
  6605. switch ($algorithm[0]) {
  6606. case 'H':
  6607. $hash = hash_hmac($hmac, $data, $secret, true);
  6608. if (function_exists('hash_equals')) {
  6609. $equals = hash_equals($signature, $hash);
  6610. } else {
  6611. $equals = $signature == $hash;
  6612. }
  6613. if (!$equals) {
  6614. return array();
  6615. }
  6616. break;
  6617. case 'R':
  6618. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  6619. if (!$equals) {
  6620. return array();
  6621. }
  6622. break;
  6623. }
  6624. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  6625. if (!$claims) {
  6626. return array();
  6627. }
  6628. foreach ($requirements as $field => $values) {
  6629. if (!empty($values)) {
  6630. if ($field != 'alg') {
  6631. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  6632. return array();
  6633. }
  6634. }
  6635. }
  6636. }
  6637. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  6638. return array();
  6639. }
  6640. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  6641. return array();
  6642. }
  6643. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  6644. return array();
  6645. }
  6646. if (isset($claims['iat']) && !isset($claims['exp'])) {
  6647. if ($time - $leeway > $claims['iat'] + $ttl) {
  6648. return array();
  6649. }
  6650. }
  6651. return $claims;
  6652. }
  6653. private function getClaims(string $token): array
  6654. {
  6655. $time = (int) $this->getProperty('time', time());
  6656. $leeway = (int) $this->getProperty('leeway', '5');
  6657. $ttl = (int) $this->getProperty('ttl', '30');
  6658. $secret = $this->getProperty('secret', '');
  6659. $requirements = array(
  6660. 'alg' => $this->getArrayProperty('algorithms', ''),
  6661. 'aud' => $this->getArrayProperty('audiences', ''),
  6662. 'iss' => $this->getArrayProperty('issuers', ''),
  6663. );
  6664. if (!$secret) {
  6665. return array();
  6666. }
  6667. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret, $requirements);
  6668. }
  6669. private function getAuthorizationToken(ServerRequestInterface $request): string
  6670. {
  6671. $headerName = $this->getProperty('header', 'X-Authorization');
  6672. $headerValue = RequestUtils::getHeader($request, $headerName);
  6673. $parts = explode(' ', trim($headerValue), 2);
  6674. if (count($parts) != 2) {
  6675. return '';
  6676. }
  6677. if ($parts[0] != 'Bearer') {
  6678. return '';
  6679. }
  6680. return $parts[1];
  6681. }
  6682. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6683. {
  6684. if (session_status() == PHP_SESSION_NONE) {
  6685. if (!headers_sent()) {
  6686. session_start();
  6687. }
  6688. }
  6689. $token = $this->getAuthorizationToken($request);
  6690. if ($token) {
  6691. $claims = $this->getClaims($token);
  6692. $_SESSION['claims'] = $claims;
  6693. if (empty($claims)) {
  6694. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  6695. }
  6696. if (!headers_sent()) {
  6697. session_regenerate_id();
  6698. }
  6699. }
  6700. if (empty($_SESSION['claims'])) {
  6701. $authenticationMode = $this->getProperty('mode', 'required');
  6702. if ($authenticationMode == 'required') {
  6703. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6704. }
  6705. }
  6706. return $next->handle($request);
  6707. }
  6708. }
  6709. }
  6710. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  6711. namespace Tqdev\PhpCrudApi\Middleware {
  6712. use Psr\Http\Message\ResponseInterface;
  6713. use Psr\Http\Message\ServerRequestInterface;
  6714. use Psr\Http\Server\RequestHandlerInterface;
  6715. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6716. use Tqdev\PhpCrudApi\Controller\Responder;
  6717. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6718. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6719. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6720. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  6721. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  6722. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  6723. use Tqdev\PhpCrudApi\RequestUtils;
  6724. class MultiTenancyMiddleware extends Middleware
  6725. {
  6726. private $reflection;
  6727. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6728. {
  6729. parent::__construct($router, $responder, $properties);
  6730. $this->reflection = $reflection;
  6731. }
  6732. private function getCondition(string $tableName, array $pairs): Condition
  6733. {
  6734. $condition = new NoCondition();
  6735. $table = $this->reflection->getTable($tableName);
  6736. foreach ($pairs as $k => $v) {
  6737. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  6738. }
  6739. return $condition;
  6740. }
  6741. private function getPairs($handler, string $operation, string $tableName): array
  6742. {
  6743. $result = array();
  6744. $pairs = call_user_func($handler, $operation, $tableName);
  6745. $table = $this->reflection->getTable($tableName);
  6746. foreach ($pairs as $k => $v) {
  6747. if ($table->hasColumn($k)) {
  6748. $result[$k] = $v;
  6749. }
  6750. }
  6751. return $result;
  6752. }
  6753. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  6754. {
  6755. $record = $request->getParsedBody();
  6756. if ($record === null) {
  6757. return $request;
  6758. }
  6759. $multi = is_array($record);
  6760. $records = $multi ? $record : [$record];
  6761. foreach ($records as &$record) {
  6762. foreach ($pairs as $column => $value) {
  6763. if ($operation == 'create') {
  6764. $record->$column = $value;
  6765. } else {
  6766. if (isset($record->$column)) {
  6767. unset($record->$column);
  6768. }
  6769. }
  6770. }
  6771. }
  6772. return $request->withParsedBody($multi ? $records : $records[0]);
  6773. }
  6774. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6775. {
  6776. $handler = $this->getProperty('handler', '');
  6777. if ($handler !== '') {
  6778. $path = RequestUtils::getPathSegment($request, 1);
  6779. if ($path == 'records') {
  6780. $operation = RequestUtils::getOperation($request);
  6781. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  6782. foreach ($tableNames as $i => $tableName) {
  6783. if (!$this->reflection->hasTable($tableName)) {
  6784. continue;
  6785. }
  6786. $pairs = $this->getPairs($handler, $operation, $tableName);
  6787. if ($i == 0) {
  6788. if (in_array($operation, ['create', 'update', 'increment'])) {
  6789. $request = $this->handleRecord($request, $operation, $pairs);
  6790. }
  6791. }
  6792. $condition = $this->getCondition($tableName, $pairs);
  6793. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  6794. }
  6795. }
  6796. }
  6797. return $next->handle($request);
  6798. }
  6799. }
  6800. }
  6801. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  6802. namespace Tqdev\PhpCrudApi\Middleware {
  6803. use Psr\Http\Message\ResponseInterface;
  6804. use Psr\Http\Message\ServerRequestInterface;
  6805. use Psr\Http\Server\RequestHandlerInterface;
  6806. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6807. use Tqdev\PhpCrudApi\Controller\Responder;
  6808. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6809. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6810. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6811. use Tqdev\PhpCrudApi\RequestUtils;
  6812. class PageLimitsMiddleware extends Middleware
  6813. {
  6814. private $reflection;
  6815. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6816. {
  6817. parent::__construct($router, $responder, $properties);
  6818. $this->reflection = $reflection;
  6819. }
  6820. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6821. {
  6822. $operation = RequestUtils::getOperation($request);
  6823. if ($operation == 'list') {
  6824. $params = RequestUtils::getParams($request);
  6825. $maxPage = (int) $this->getProperty('pages', '100');
  6826. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  6827. if (strpos($params['page'][0], ',') === false) {
  6828. $page = $params['page'][0];
  6829. } else {
  6830. list($page, $size) = explode(',', $params['page'][0], 2);
  6831. }
  6832. if ($page > $maxPage) {
  6833. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  6834. }
  6835. }
  6836. $maxSize = (int) $this->getProperty('records', '1000');
  6837. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  6838. $params['size'] = array($maxSize);
  6839. } else {
  6840. $params['size'] = array(min($params['size'][0], $maxSize));
  6841. }
  6842. $request = RequestUtils::setParams($request, $params);
  6843. }
  6844. return $next->handle($request);
  6845. }
  6846. }
  6847. }
  6848. // file: src/Tqdev/PhpCrudApi/Middleware/ReAuthMiddleware.php
  6849. namespace Tqdev\PhpCrudApi\Middleware {
  6850. use Psr\Http\Message\ResponseInterface;
  6851. use Psr\Http\Message\ServerRequestInterface;
  6852. use Psr\Http\Server\RequestHandlerInterface;
  6853. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6854. use Tqdev\PhpCrudApi\Controller\Responder;
  6855. use Tqdev\PhpCrudApi\Database\GenericDB;
  6856. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6857. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6858. class ReAuthMiddleware extends Middleware
  6859. {
  6860. private $reflection;
  6861. private $db;
  6862. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  6863. {
  6864. parent::__construct($router, $responder, $properties);
  6865. $this->reflection = $reflection;
  6866. $this->db = $db;
  6867. }
  6868. private function getUsername(): string
  6869. {
  6870. $usernameHandler = $this->getProperty('usernameHandler', '');
  6871. if ($usernameHandler) {
  6872. return call_user_func($usernameHandler);
  6873. }
  6874. return '';
  6875. }
  6876. private function getPassword(): string
  6877. {
  6878. $passwordHandler = $this->getProperty('passwordHandler', '');
  6879. if ($passwordHandler) {
  6880. return call_user_func($passwordHandler);
  6881. }
  6882. return '';
  6883. }
  6884. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6885. {
  6886. $username = $this->getUsername();
  6887. $password = $this->getPassword();
  6888. if ($username && $password) {
  6889. $this->db->pdo()->reauthenticate($username, $password);
  6890. }
  6891. return $next->handle($request);
  6892. }
  6893. }
  6894. }
  6895. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  6896. namespace Tqdev\PhpCrudApi\Middleware {
  6897. use Psr\Http\Message\ResponseInterface;
  6898. use Psr\Http\Message\ServerRequestInterface;
  6899. use Psr\Http\Server\RequestHandlerInterface;
  6900. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6901. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6902. use Tqdev\PhpCrudApi\Controller\Responder;
  6903. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6904. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6905. use Tqdev\PhpCrudApi\RequestUtils;
  6906. class SanitationMiddleware extends Middleware
  6907. {
  6908. private $reflection;
  6909. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6910. {
  6911. parent::__construct($router, $responder, $properties);
  6912. $this->reflection = $reflection;
  6913. }
  6914. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  6915. {
  6916. $context = (array) $record;
  6917. $tableName = $table->getName();
  6918. foreach ($context as $columnName => &$value) {
  6919. if ($table->hasColumn($columnName)) {
  6920. $column = $table->getColumn($columnName);
  6921. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  6922. }
  6923. }
  6924. return (object) $context;
  6925. }
  6926. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6927. {
  6928. $operation = RequestUtils::getOperation($request);
  6929. if (in_array($operation, ['create', 'update', 'increment'])) {
  6930. $tableName = RequestUtils::getPathSegment($request, 2);
  6931. if ($this->reflection->hasTable($tableName)) {
  6932. $record = $request->getParsedBody();
  6933. if ($record !== null) {
  6934. $handler = $this->getProperty('handler', '');
  6935. if ($handler !== '') {
  6936. $table = $this->reflection->getTable($tableName);
  6937. if (is_array($record)) {
  6938. foreach ($record as &$r) {
  6939. $r = $this->callHandler($handler, $r, $operation, $table);
  6940. }
  6941. } else {
  6942. $record = $this->callHandler($handler, $record, $operation, $table);
  6943. }
  6944. $request = $request->withParsedBody($record);
  6945. }
  6946. }
  6947. }
  6948. }
  6949. return $next->handle($request);
  6950. }
  6951. }
  6952. }
  6953. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  6954. namespace Tqdev\PhpCrudApi\Middleware {
  6955. use Psr\Http\Message\ResponseInterface;
  6956. use Psr\Http\Message\ServerRequestInterface;
  6957. use Psr\Http\Server\RequestHandlerInterface;
  6958. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6959. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6960. use Tqdev\PhpCrudApi\Controller\Responder;
  6961. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6962. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6963. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6964. use Tqdev\PhpCrudApi\RequestUtils;
  6965. class ValidationMiddleware extends Middleware
  6966. {
  6967. private $reflection;
  6968. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6969. {
  6970. parent::__construct($router, $responder, $properties);
  6971. $this->reflection = $reflection;
  6972. }
  6973. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  6974. {
  6975. $context = (array) $record;
  6976. $details = array();
  6977. $tableName = $table->getName();
  6978. foreach ($context as $columnName => $value) {
  6979. if ($table->hasColumn($columnName)) {
  6980. $column = $table->getColumn($columnName);
  6981. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  6982. if ($valid !== true && $valid !== '') {
  6983. $details[$columnName] = $valid;
  6984. }
  6985. }
  6986. }
  6987. if (count($details) > 0) {
  6988. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  6989. }
  6990. return null;
  6991. }
  6992. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6993. {
  6994. $operation = RequestUtils::getOperation($request);
  6995. if (in_array($operation, ['create', 'update', 'increment'])) {
  6996. $tableName = RequestUtils::getPathSegment($request, 2);
  6997. if ($this->reflection->hasTable($tableName)) {
  6998. $record = $request->getParsedBody();
  6999. if ($record !== null) {
  7000. $handler = $this->getProperty('handler', '');
  7001. if ($handler !== '') {
  7002. $table = $this->reflection->getTable($tableName);
  7003. if (is_array($record)) {
  7004. foreach ($record as $r) {
  7005. $response = $this->callHandler($handler, $r, $operation, $table);
  7006. if ($response !== null) {
  7007. return $response;
  7008. }
  7009. }
  7010. } else {
  7011. $response = $this->callHandler($handler, $record, $operation, $table);
  7012. if ($response !== null) {
  7013. return $response;
  7014. }
  7015. }
  7016. }
  7017. }
  7018. }
  7019. }
  7020. return $next->handle($request);
  7021. }
  7022. }
  7023. }
  7024. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  7025. namespace Tqdev\PhpCrudApi\Middleware {
  7026. use Psr\Http\Message\ResponseInterface;
  7027. use Psr\Http\Message\ServerRequestInterface;
  7028. use Psr\Http\Server\RequestHandlerInterface;
  7029. use Tqdev\PhpCrudApi\Controller\Responder;
  7030. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7031. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7032. class XsrfMiddleware extends Middleware
  7033. {
  7034. private function getToken(): string
  7035. {
  7036. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  7037. if (isset($_COOKIE[$cookieName])) {
  7038. $token = $_COOKIE[$cookieName];
  7039. } else {
  7040. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  7041. $token = bin2hex(random_bytes(8));
  7042. if (!headers_sent()) {
  7043. setcookie($cookieName, $token, 0, '', '', $secure);
  7044. }
  7045. }
  7046. return $token;
  7047. }
  7048. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7049. {
  7050. $token = $this->getToken();
  7051. $method = $request->getMethod();
  7052. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  7053. if (!in_array($method, $excludeMethods)) {
  7054. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  7055. if ($token != $request->getHeader($headerName)) {
  7056. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  7057. }
  7058. }
  7059. return $next->handle($request);
  7060. }
  7061. }
  7062. }
  7063. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  7064. namespace Tqdev\PhpCrudApi\OpenApi {
  7065. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7066. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  7067. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  7068. class OpenApiBuilder
  7069. {
  7070. private $openapi;
  7071. private $reflection;
  7072. private $operations = [
  7073. 'list' => 'get',
  7074. 'create' => 'post',
  7075. 'read' => 'get',
  7076. 'update' => 'put',
  7077. 'delete' => 'delete',
  7078. 'increment' => 'patch',
  7079. ];
  7080. private $types = [
  7081. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  7082. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  7083. 'varchar' => ['type' => 'string'],
  7084. 'clob' => ['type' => 'string'],
  7085. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  7086. 'blob' => ['type' => 'string', 'format' => 'byte'],
  7087. 'decimal' => ['type' => 'string'],
  7088. 'float' => ['type' => 'number', 'format' => 'float'],
  7089. 'double' => ['type' => 'number', 'format' => 'double'],
  7090. 'date' => ['type' => 'string', 'format' => 'date'],
  7091. 'time' => ['type' => 'string', 'format' => 'date-time'],
  7092. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  7093. 'geometry' => ['type' => 'string'],
  7094. 'boolean' => ['type' => 'boolean'],
  7095. ];
  7096. public function __construct(ReflectionService $reflection, $base)
  7097. {
  7098. $this->reflection = $reflection;
  7099. $this->openapi = new OpenApiDefinition($base);
  7100. }
  7101. private function getServerUrl(): string
  7102. {
  7103. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  7104. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  7105. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  7106. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  7107. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  7108. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  7109. }
  7110. private function getAllTableReferences(): array
  7111. {
  7112. $tableReferences = array();
  7113. foreach ($this->reflection->getTableNames() as $tableName) {
  7114. $table = $this->reflection->getTable($tableName);
  7115. foreach ($table->getColumnNames() as $columnName) {
  7116. $column = $table->getColumn($columnName);
  7117. $referencedTableName = $column->getFk();
  7118. if ($referencedTableName) {
  7119. if (!isset($tableReferences[$referencedTableName])) {
  7120. $tableReferences[$referencedTableName] = array();
  7121. }
  7122. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  7123. }
  7124. }
  7125. }
  7126. return $tableReferences;
  7127. }
  7128. public function build(): OpenApiDefinition
  7129. {
  7130. $this->openapi->set("openapi", "3.0.0");
  7131. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  7132. $this->openapi->set("servers|0|url", $this->getServerUrl());
  7133. }
  7134. $tableNames = $this->reflection->getTableNames();
  7135. foreach ($tableNames as $tableName) {
  7136. $this->setPath($tableName);
  7137. }
  7138. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  7139. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  7140. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  7141. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  7142. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  7143. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  7144. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  7145. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  7146. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  7147. $tableReferences = $this->getAllTableReferences();
  7148. foreach ($tableNames as $tableName) {
  7149. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  7150. $this->setComponentSchema($tableName, $references);
  7151. $this->setComponentResponse($tableName);
  7152. $this->setComponentRequestBody($tableName);
  7153. }
  7154. $this->setComponentParameters();
  7155. foreach ($tableNames as $index => $tableName) {
  7156. $this->setTag($index, $tableName);
  7157. }
  7158. return $this->openapi;
  7159. }
  7160. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  7161. {
  7162. $tableHandler = VariableStore::get('authorization.tableHandler');
  7163. if (!$tableHandler) {
  7164. return true;
  7165. }
  7166. return (bool) call_user_func($tableHandler, $operation, $tableName);
  7167. }
  7168. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  7169. {
  7170. $columnHandler = VariableStore::get('authorization.columnHandler');
  7171. if (!$columnHandler) {
  7172. return true;
  7173. }
  7174. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  7175. }
  7176. private function setPath(string $tableName) /*: void*/
  7177. {
  7178. $table = $this->reflection->getTable($tableName);
  7179. $type = $table->getType();
  7180. $pk = $table->getPk();
  7181. $pkName = $pk ? $pk->getName() : '';
  7182. foreach ($this->operations as $operation => $method) {
  7183. if (!$pkName && $operation != 'list') {
  7184. continue;
  7185. }
  7186. if ($type != 'table' && $operation != 'list') {
  7187. continue;
  7188. }
  7189. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7190. continue;
  7191. }
  7192. $parameters = [];
  7193. if (in_array($operation, ['list', 'create'])) {
  7194. $path = sprintf('/records/%s', $tableName);
  7195. if ($operation == 'list') {
  7196. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  7197. }
  7198. } else {
  7199. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  7200. if ($operation == 'read') {
  7201. $parameters = ['pk', 'include', 'exclude', 'join'];
  7202. } else {
  7203. $parameters = ['pk'];
  7204. }
  7205. }
  7206. foreach ($parameters as $p => $parameter) {
  7207. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  7208. }
  7209. if (in_array($operation, ['create', 'update', 'increment'])) {
  7210. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  7211. }
  7212. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  7213. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  7214. switch ($operation) {
  7215. case 'list':
  7216. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  7217. break;
  7218. case 'create':
  7219. if ($pk->getType() == 'integer') {
  7220. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  7221. } else {
  7222. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  7223. }
  7224. break;
  7225. case 'read':
  7226. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  7227. break;
  7228. case 'update':
  7229. case 'delete':
  7230. case 'increment':
  7231. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  7232. break;
  7233. }
  7234. }
  7235. }
  7236. private function setComponentSchema(string $tableName, array $references) /*: void*/
  7237. {
  7238. $table = $this->reflection->getTable($tableName);
  7239. $type = $table->getType();
  7240. $pk = $table->getPk();
  7241. $pkName = $pk ? $pk->getName() : '';
  7242. foreach ($this->operations as $operation => $method) {
  7243. if (!$pkName && $operation != 'list') {
  7244. continue;
  7245. }
  7246. if ($type != 'table' && $operation != 'list') {
  7247. continue;
  7248. }
  7249. if ($operation == 'delete') {
  7250. continue;
  7251. }
  7252. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7253. continue;
  7254. }
  7255. if ($operation == 'list') {
  7256. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  7257. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  7258. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  7259. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  7260. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  7261. } else {
  7262. $prefix = "components|schemas|$operation-$tableName";
  7263. }
  7264. $this->openapi->set("$prefix|type", "object");
  7265. foreach ($table->getColumnNames() as $columnName) {
  7266. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  7267. continue;
  7268. }
  7269. $column = $table->getColumn($columnName);
  7270. $properties = $this->types[$column->getType()];
  7271. foreach ($properties as $key => $value) {
  7272. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  7273. }
  7274. if ($column->getPk()) {
  7275. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  7276. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  7277. }
  7278. $fk = $column->getFk();
  7279. if ($fk) {
  7280. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  7281. }
  7282. }
  7283. }
  7284. }
  7285. private function setComponentResponse(string $tableName) /*: void*/
  7286. {
  7287. $table = $this->reflection->getTable($tableName);
  7288. $type = $table->getType();
  7289. $pk = $table->getPk();
  7290. $pkName = $pk ? $pk->getName() : '';
  7291. foreach (['list', 'read'] as $operation) {
  7292. if (!$pkName && $operation != 'list') {
  7293. continue;
  7294. }
  7295. if ($type != 'table' && $operation != 'list') {
  7296. continue;
  7297. }
  7298. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7299. continue;
  7300. }
  7301. if ($operation == 'list') {
  7302. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  7303. } else {
  7304. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  7305. }
  7306. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  7307. }
  7308. }
  7309. private function setComponentRequestBody(string $tableName) /*: void*/
  7310. {
  7311. $table = $this->reflection->getTable($tableName);
  7312. $type = $table->getType();
  7313. $pk = $table->getPk();
  7314. $pkName = $pk ? $pk->getName() : '';
  7315. if ($pkName && $type == 'table') {
  7316. foreach (['create', 'update', 'increment'] as $operation) {
  7317. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  7318. continue;
  7319. }
  7320. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  7321. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  7322. }
  7323. }
  7324. }
  7325. private function setComponentParameters() /*: void*/
  7326. {
  7327. $this->openapi->set("components|parameters|pk|name", "id");
  7328. $this->openapi->set("components|parameters|pk|in", "path");
  7329. $this->openapi->set("components|parameters|pk|schema|type", "string");
  7330. $this->openapi->set("components|parameters|pk|description", "primary key value");
  7331. $this->openapi->set("components|parameters|pk|required", true);
  7332. $this->openapi->set("components|parameters|filter|name", "filter");
  7333. $this->openapi->set("components|parameters|filter|in", "query");
  7334. $this->openapi->set("components|parameters|filter|schema|type", "array");
  7335. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  7336. $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");
  7337. $this->openapi->set("components|parameters|filter|required", false);
  7338. $this->openapi->set("components|parameters|include|name", "include");
  7339. $this->openapi->set("components|parameters|include|in", "query");
  7340. $this->openapi->set("components|parameters|include|schema|type", "string");
  7341. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  7342. $this->openapi->set("components|parameters|include|required", false);
  7343. $this->openapi->set("components|parameters|exclude|name", "exclude");
  7344. $this->openapi->set("components|parameters|exclude|in", "query");
  7345. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  7346. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  7347. $this->openapi->set("components|parameters|exclude|required", false);
  7348. $this->openapi->set("components|parameters|order|name", "order");
  7349. $this->openapi->set("components|parameters|order|in", "query");
  7350. $this->openapi->set("components|parameters|order|schema|type", "array");
  7351. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  7352. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  7353. $this->openapi->set("components|parameters|order|required", false);
  7354. $this->openapi->set("components|parameters|size|name", "size");
  7355. $this->openapi->set("components|parameters|size|in", "query");
  7356. $this->openapi->set("components|parameters|size|schema|type", "string");
  7357. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  7358. $this->openapi->set("components|parameters|size|required", false);
  7359. $this->openapi->set("components|parameters|page|name", "page");
  7360. $this->openapi->set("components|parameters|page|in", "query");
  7361. $this->openapi->set("components|parameters|page|schema|type", "string");
  7362. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  7363. $this->openapi->set("components|parameters|page|required", false);
  7364. $this->openapi->set("components|parameters|join|name", "join");
  7365. $this->openapi->set("components|parameters|join|in", "query");
  7366. $this->openapi->set("components|parameters|join|schema|type", "array");
  7367. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  7368. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  7369. $this->openapi->set("components|parameters|join|required", false);
  7370. }
  7371. private function setTag(int $index, string $tableName) /*: void*/
  7372. {
  7373. $this->openapi->set("tags|$index|name", "$tableName");
  7374. $this->openapi->set("tags|$index|description", "$tableName operations");
  7375. }
  7376. }
  7377. }
  7378. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  7379. namespace Tqdev\PhpCrudApi\OpenApi {
  7380. class OpenApiDefinition implements \JsonSerializable
  7381. {
  7382. private $root;
  7383. public function __construct($base)
  7384. {
  7385. $this->root = $base;
  7386. }
  7387. public function set(string $path, $value) /*: void*/
  7388. {
  7389. $parts = explode('|', trim($path, '|'));
  7390. $current = &$this->root;
  7391. while (count($parts) > 0) {
  7392. $part = array_shift($parts);
  7393. if (!isset($current[$part])) {
  7394. $current[$part] = [];
  7395. }
  7396. $current = &$current[$part];
  7397. }
  7398. $current = $value;
  7399. }
  7400. public function has(string $path): bool
  7401. {
  7402. $parts = explode('|', trim($path, '|'));
  7403. $current = &$this->root;
  7404. while (count($parts) > 0) {
  7405. $part = array_shift($parts);
  7406. if (!isset($current[$part])) {
  7407. return false;
  7408. }
  7409. $current = &$current[$part];
  7410. }
  7411. return true;
  7412. }
  7413. public function jsonSerialize()
  7414. {
  7415. return $this->root;
  7416. }
  7417. }
  7418. }
  7419. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  7420. namespace Tqdev\PhpCrudApi\OpenApi {
  7421. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7422. use Tqdev\PhpCrudApi\OpenApi\OpenApiBuilder;
  7423. class OpenApiService
  7424. {
  7425. private $builder;
  7426. public function __construct(ReflectionService $reflection, array $base)
  7427. {
  7428. $this->builder = new OpenApiBuilder($reflection, $base);
  7429. }
  7430. public function get(): OpenApiDefinition
  7431. {
  7432. return $this->builder->build();
  7433. }
  7434. }
  7435. }
  7436. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  7437. namespace Tqdev\PhpCrudApi\Record\Condition {
  7438. class AndCondition extends Condition
  7439. {
  7440. private $conditions;
  7441. public function __construct(Condition $condition1, Condition $condition2)
  7442. {
  7443. $this->conditions = [$condition1, $condition2];
  7444. }
  7445. public function _and(Condition $condition): Condition
  7446. {
  7447. if ($condition instanceof NoCondition) {
  7448. return $this;
  7449. }
  7450. $this->conditions[] = $condition;
  7451. return $this;
  7452. }
  7453. public function getConditions(): array
  7454. {
  7455. return $this->conditions;
  7456. }
  7457. public static function fromArray(array $conditions): Condition
  7458. {
  7459. $condition = new NoCondition();
  7460. foreach ($conditions as $c) {
  7461. $condition = $condition->_and($c);
  7462. }
  7463. return $condition;
  7464. }
  7465. }
  7466. }
  7467. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  7468. namespace Tqdev\PhpCrudApi\Record\Condition {
  7469. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  7470. class ColumnCondition extends Condition
  7471. {
  7472. private $column;
  7473. private $operator;
  7474. private $value;
  7475. public function __construct(ReflectedColumn $column, string $operator, string $value)
  7476. {
  7477. $this->column = $column;
  7478. $this->operator = $operator;
  7479. $this->value = $value;
  7480. }
  7481. public function getColumn(): ReflectedColumn
  7482. {
  7483. return $this->column;
  7484. }
  7485. public function getOperator(): string
  7486. {
  7487. return $this->operator;
  7488. }
  7489. public function getValue(): string
  7490. {
  7491. return $this->value;
  7492. }
  7493. }
  7494. }
  7495. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  7496. namespace Tqdev\PhpCrudApi\Record\Condition {
  7497. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7498. abstract class Condition
  7499. {
  7500. public function _and(Condition $condition): Condition
  7501. {
  7502. if ($condition instanceof NoCondition) {
  7503. return $this;
  7504. }
  7505. return new AndCondition($this, $condition);
  7506. }
  7507. public function _or(Condition $condition): Condition
  7508. {
  7509. if ($condition instanceof NoCondition) {
  7510. return $this;
  7511. }
  7512. return new OrCondition($this, $condition);
  7513. }
  7514. public function _not(): Condition
  7515. {
  7516. return new NotCondition($this);
  7517. }
  7518. public static function fromString(ReflectedTable $table, string $value): Condition
  7519. {
  7520. $condition = new NoCondition();
  7521. $parts = explode(',', $value, 3);
  7522. if (count($parts) < 2) {
  7523. return $condition;
  7524. }
  7525. if (count($parts) < 3) {
  7526. $parts[2] = '';
  7527. }
  7528. $field = $table->getColumn($parts[0]);
  7529. $command = $parts[1];
  7530. $negate = false;
  7531. $spatial = false;
  7532. if (strlen($command) > 2) {
  7533. if (substr($command, 0, 1) == 'n') {
  7534. $negate = true;
  7535. $command = substr($command, 1);
  7536. }
  7537. if (substr($command, 0, 1) == 's') {
  7538. $spatial = true;
  7539. $command = substr($command, 1);
  7540. }
  7541. }
  7542. if ($spatial) {
  7543. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  7544. $condition = new SpatialCondition($field, $command, $parts[2]);
  7545. }
  7546. } else {
  7547. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  7548. $condition = new ColumnCondition($field, $command, $parts[2]);
  7549. }
  7550. }
  7551. if ($negate) {
  7552. $condition = $condition->_not();
  7553. }
  7554. return $condition;
  7555. }
  7556. }
  7557. }
  7558. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  7559. namespace Tqdev\PhpCrudApi\Record\Condition {
  7560. class NoCondition extends Condition
  7561. {
  7562. public function _and(Condition $condition): Condition
  7563. {
  7564. return $condition;
  7565. }
  7566. public function _or(Condition $condition): Condition
  7567. {
  7568. return $condition;
  7569. }
  7570. public function _not(): Condition
  7571. {
  7572. return $this;
  7573. }
  7574. }
  7575. }
  7576. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  7577. namespace Tqdev\PhpCrudApi\Record\Condition {
  7578. class NotCondition extends Condition
  7579. {
  7580. private $condition;
  7581. public function __construct(Condition $condition)
  7582. {
  7583. $this->condition = $condition;
  7584. }
  7585. public function getCondition(): Condition
  7586. {
  7587. return $this->condition;
  7588. }
  7589. }
  7590. }
  7591. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  7592. namespace Tqdev\PhpCrudApi\Record\Condition {
  7593. class OrCondition extends Condition
  7594. {
  7595. private $conditions;
  7596. public function __construct(Condition $condition1, Condition $condition2)
  7597. {
  7598. $this->conditions = [$condition1, $condition2];
  7599. }
  7600. public function _or(Condition $condition): Condition
  7601. {
  7602. if ($condition instanceof NoCondition) {
  7603. return $this;
  7604. }
  7605. $this->conditions[] = $condition;
  7606. return $this;
  7607. }
  7608. public function getConditions(): array
  7609. {
  7610. return $this->conditions;
  7611. }
  7612. public static function fromArray(array $conditions): Condition
  7613. {
  7614. $condition = new NoCondition();
  7615. foreach ($conditions as $c) {
  7616. $condition = $condition->_or($c);
  7617. }
  7618. return $condition;
  7619. }
  7620. }
  7621. }
  7622. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  7623. namespace Tqdev\PhpCrudApi\Record\Condition {
  7624. class SpatialCondition extends ColumnCondition
  7625. {
  7626. }
  7627. }
  7628. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  7629. namespace Tqdev\PhpCrudApi\Record\Document {
  7630. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7631. class ErrorDocument implements \JsonSerializable
  7632. {
  7633. public $code;
  7634. public $message;
  7635. public $details;
  7636. public function __construct(ErrorCode $errorCode, string $argument, $details)
  7637. {
  7638. $this->code = $errorCode->getCode();
  7639. $this->message = $errorCode->getMessage($argument);
  7640. $this->details = $details;
  7641. }
  7642. public function getCode(): int
  7643. {
  7644. return $this->code;
  7645. }
  7646. public function getMessage(): string
  7647. {
  7648. return $this->message;
  7649. }
  7650. public function serialize()
  7651. {
  7652. return [
  7653. 'code' => $this->code,
  7654. 'message' => $this->message,
  7655. 'details' => $this->details,
  7656. ];
  7657. }
  7658. public function jsonSerialize()
  7659. {
  7660. return array_filter($this->serialize());
  7661. }
  7662. }
  7663. }
  7664. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  7665. namespace Tqdev\PhpCrudApi\Record\Document {
  7666. class ListDocument implements \JsonSerializable
  7667. {
  7668. private $records;
  7669. private $results;
  7670. public function __construct(array $records, int $results)
  7671. {
  7672. $this->records = $records;
  7673. $this->results = $results;
  7674. }
  7675. public function getRecords(): array
  7676. {
  7677. return $this->records;
  7678. }
  7679. public function getResults(): int
  7680. {
  7681. return $this->results;
  7682. }
  7683. public function serialize()
  7684. {
  7685. return [
  7686. 'records' => $this->records,
  7687. 'results' => $this->results,
  7688. ];
  7689. }
  7690. public function jsonSerialize()
  7691. {
  7692. return array_filter($this->serialize(), function ($v) {
  7693. return $v !== 0;
  7694. });
  7695. }
  7696. }
  7697. }
  7698. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  7699. namespace Tqdev\PhpCrudApi\Record {
  7700. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7701. class ColumnIncluder
  7702. {
  7703. private function isMandatory(string $tableName, string $columnName, array $params): bool
  7704. {
  7705. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  7706. }
  7707. private function select(string $tableName, bool $primaryTable, array $params, string $paramName,
  7708. array $columnNames, bool $include): array{
  7709. if (!isset($params[$paramName])) {
  7710. return $columnNames;
  7711. }
  7712. $columns = array();
  7713. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  7714. $columns[$columnName] = true;
  7715. }
  7716. $result = array();
  7717. foreach ($columnNames as $columnName) {
  7718. $match = isset($columns['*.*']);
  7719. if (!$match) {
  7720. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  7721. }
  7722. if ($primaryTable && !$match) {
  7723. $match = isset($columns['*']) || isset($columns[$columnName]);
  7724. }
  7725. if ($match) {
  7726. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  7727. $result[] = $columnName;
  7728. }
  7729. } else {
  7730. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  7731. $result[] = $columnName;
  7732. }
  7733. }
  7734. }
  7735. return $result;
  7736. }
  7737. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  7738. {
  7739. $tableName = $table->getName();
  7740. $results = $table->getColumnNames();
  7741. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  7742. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  7743. return $results;
  7744. }
  7745. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  7746. {
  7747. $results = array();
  7748. $columnNames = $this->getNames($table, $primaryTable, $params);
  7749. foreach ($columnNames as $columnName) {
  7750. if (property_exists($record, $columnName)) {
  7751. $results[$columnName] = $record->$columnName;
  7752. }
  7753. }
  7754. return $results;
  7755. }
  7756. }
  7757. }
  7758. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  7759. namespace Tqdev\PhpCrudApi\Record {
  7760. use Tqdev\PhpCrudApi\ResponseFactory;
  7761. class ErrorCode
  7762. {
  7763. private $code;
  7764. private $message;
  7765. private $status;
  7766. const ERROR_NOT_FOUND = 9999;
  7767. const ROUTE_NOT_FOUND = 1000;
  7768. const TABLE_NOT_FOUND = 1001;
  7769. const ARGUMENT_COUNT_MISMATCH = 1002;
  7770. const RECORD_NOT_FOUND = 1003;
  7771. const ORIGIN_FORBIDDEN = 1004;
  7772. const COLUMN_NOT_FOUND = 1005;
  7773. const TABLE_ALREADY_EXISTS = 1006;
  7774. const COLUMN_ALREADY_EXISTS = 1007;
  7775. const HTTP_MESSAGE_NOT_READABLE = 1008;
  7776. const DUPLICATE_KEY_EXCEPTION = 1009;
  7777. const DATA_INTEGRITY_VIOLATION = 1010;
  7778. const AUTHENTICATION_REQUIRED = 1011;
  7779. const AUTHENTICATION_FAILED = 1012;
  7780. const INPUT_VALIDATION_FAILED = 1013;
  7781. const OPERATION_FORBIDDEN = 1014;
  7782. const OPERATION_NOT_SUPPORTED = 1015;
  7783. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  7784. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  7785. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  7786. const PAGINATION_FORBIDDEN = 1019;
  7787. private $values = [
  7788. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  7789. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  7790. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  7791. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  7792. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  7793. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  7794. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  7795. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  7796. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  7797. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  7798. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  7799. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  7800. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  7801. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  7802. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  7803. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  7804. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  7805. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  7806. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  7807. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  7808. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  7809. ];
  7810. public function __construct(int $code)
  7811. {
  7812. if (!isset($this->values[$code])) {
  7813. $code = 9999;
  7814. }
  7815. $this->code = $code;
  7816. $this->message = $this->values[$code][0];
  7817. $this->status = $this->values[$code][1];
  7818. }
  7819. public function getCode(): int
  7820. {
  7821. return $this->code;
  7822. }
  7823. public function getMessage(string $argument): string
  7824. {
  7825. return sprintf($this->message, $argument);
  7826. }
  7827. public function getStatus(): int
  7828. {
  7829. return $this->status;
  7830. }
  7831. }
  7832. }
  7833. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  7834. namespace Tqdev\PhpCrudApi\Record {
  7835. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7836. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  7837. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  7838. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  7839. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  7840. class FilterInfo
  7841. {
  7842. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  7843. {
  7844. $key = 'filter' . implode('', $path);
  7845. if (isset($params[$key])) {
  7846. foreach ($params[$key] as $filter) {
  7847. $condition = Condition::fromString($table, $filter);
  7848. if (($condition instanceof NoCondition) == false) {
  7849. $conditions->put($path, $condition);
  7850. }
  7851. }
  7852. }
  7853. }
  7854. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  7855. {
  7856. $conditions = new PathTree();
  7857. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  7858. for ($n = ord('0'); $n <= ord('9'); $n++) {
  7859. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  7860. for ($l = ord('a'); $l <= ord('f'); $l++) {
  7861. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  7862. }
  7863. }
  7864. return $conditions;
  7865. }
  7866. private function combinePathTreeOfConditions(PathTree $tree): Condition
  7867. {
  7868. $andConditions = $tree->getValues();
  7869. $and = AndCondition::fromArray($andConditions);
  7870. $orConditions = [];
  7871. foreach ($tree->getKeys() as $p) {
  7872. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  7873. }
  7874. $or = OrCondition::fromArray($orConditions);
  7875. return $and->_and($or);
  7876. }
  7877. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  7878. {
  7879. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  7880. }
  7881. }
  7882. }
  7883. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  7884. namespace Tqdev\PhpCrudApi\Record {
  7885. class HabtmValues
  7886. {
  7887. public $pkValues;
  7888. public $fkValues;
  7889. public function __construct(array $pkValues, array $fkValues)
  7890. {
  7891. $this->pkValues = $pkValues;
  7892. $this->fkValues = $fkValues;
  7893. }
  7894. }
  7895. }
  7896. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  7897. namespace Tqdev\PhpCrudApi\Record {
  7898. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7899. class OrderingInfo
  7900. {
  7901. public function getColumnOrdering(ReflectedTable $table, array $params): array
  7902. {
  7903. $fields = array();
  7904. if (isset($params['order'])) {
  7905. foreach ($params['order'] as $order) {
  7906. $parts = explode(',', $order, 3);
  7907. $columnName = $parts[0];
  7908. if (!$table->hasColumn($columnName)) {
  7909. continue;
  7910. }
  7911. $ascending = 'ASC';
  7912. if (count($parts) > 1) {
  7913. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  7914. $ascending = 'DESC';
  7915. }
  7916. }
  7917. $fields[] = [$columnName, $ascending];
  7918. }
  7919. }
  7920. if (count($fields) == 0) {
  7921. return $this->getDefaultColumnOrdering($table);
  7922. }
  7923. return $fields;
  7924. }
  7925. public function getDefaultColumnOrdering(ReflectedTable $table): array
  7926. {
  7927. $fields = array();
  7928. $pk = $table->getPk();
  7929. if ($pk) {
  7930. $fields[] = [$pk->getName(), 'ASC'];
  7931. } else {
  7932. foreach ($table->getColumnNames() as $columnName) {
  7933. $fields[] = [$columnName, 'ASC'];
  7934. }
  7935. }
  7936. return $fields;
  7937. }
  7938. }
  7939. }
  7940. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  7941. namespace Tqdev\PhpCrudApi\Record {
  7942. class PaginationInfo
  7943. {
  7944. public $DEFAULT_PAGE_SIZE = 20;
  7945. public function hasPage(array $params): bool
  7946. {
  7947. return isset($params['page']);
  7948. }
  7949. public function getPageOffset(array $params): int
  7950. {
  7951. $offset = 0;
  7952. $pageSize = $this->getPageSize($params);
  7953. if (isset($params['page'])) {
  7954. foreach ($params['page'] as $page) {
  7955. $parts = explode(',', $page, 2);
  7956. $page = intval($parts[0]) - 1;
  7957. $offset = $page * $pageSize;
  7958. }
  7959. }
  7960. return $offset;
  7961. }
  7962. private function getPageSize(array $params): int
  7963. {
  7964. $pageSize = $this->DEFAULT_PAGE_SIZE;
  7965. if (isset($params['page'])) {
  7966. foreach ($params['page'] as $page) {
  7967. $parts = explode(',', $page, 2);
  7968. if (count($parts) > 1) {
  7969. $pageSize = intval($parts[1]);
  7970. }
  7971. }
  7972. }
  7973. return $pageSize;
  7974. }
  7975. public function getResultSize(array $params): int
  7976. {
  7977. $numberOfRows = -1;
  7978. if (isset($params['size'])) {
  7979. foreach ($params['size'] as $size) {
  7980. $numberOfRows = intval($size);
  7981. }
  7982. }
  7983. return $numberOfRows;
  7984. }
  7985. public function getPageLimit(array $params): int
  7986. {
  7987. $pageLimit = -1;
  7988. if ($this->hasPage($params)) {
  7989. $pageLimit = $this->getPageSize($params);
  7990. }
  7991. $resultSize = $this->getResultSize($params);
  7992. if ($resultSize >= 0) {
  7993. if ($pageLimit >= 0) {
  7994. $pageLimit = min($pageLimit, $resultSize);
  7995. } else {
  7996. $pageLimit = $resultSize;
  7997. }
  7998. }
  7999. return $pageLimit;
  8000. }
  8001. }
  8002. }
  8003. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  8004. namespace Tqdev\PhpCrudApi\Record {
  8005. class PathTree implements \JsonSerializable
  8006. {
  8007. const WILDCARD = '*';
  8008. private $tree;
  8009. public function __construct( /* object */&$tree = null)
  8010. {
  8011. if (!$tree) {
  8012. $tree = $this->newTree();
  8013. }
  8014. $this->tree = &$tree;
  8015. }
  8016. public function newTree()
  8017. {
  8018. return (object) ['values' => [], 'branches' => (object) []];
  8019. }
  8020. public function getKeys(): array
  8021. {
  8022. $branches = (array) $this->tree->branches;
  8023. return array_keys($branches);
  8024. }
  8025. public function getValues(): array
  8026. {
  8027. return $this->tree->values;
  8028. }
  8029. public function get(string $key): PathTree
  8030. {
  8031. if (!isset($this->tree->branches->$key)) {
  8032. return null;
  8033. }
  8034. return new PathTree($this->tree->branches->$key);
  8035. }
  8036. public function put(array $path, $value)
  8037. {
  8038. $tree = &$this->tree;
  8039. foreach ($path as $key) {
  8040. if (!isset($tree->branches->$key)) {
  8041. $tree->branches->$key = $this->newTree();
  8042. }
  8043. $tree = &$tree->branches->$key;
  8044. }
  8045. $tree->values[] = $value;
  8046. }
  8047. public function match(array $path): array
  8048. {
  8049. $star = self::WILDCARD;
  8050. $tree = &$this->tree;
  8051. foreach ($path as $key) {
  8052. if (isset($tree->branches->$key)) {
  8053. $tree = &$tree->branches->$key;
  8054. } else if (isset($tree->branches->$star)) {
  8055. $tree = &$tree->branches->$star;
  8056. } else {
  8057. return [];
  8058. }
  8059. }
  8060. return $tree->values;
  8061. }
  8062. public static function fromJson( /* object */$tree): PathTree
  8063. {
  8064. return new PathTree($tree);
  8065. }
  8066. public function jsonSerialize()
  8067. {
  8068. return $this->tree;
  8069. }
  8070. }
  8071. }
  8072. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  8073. namespace Tqdev\PhpCrudApi\Record {
  8074. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8075. use Tqdev\PhpCrudApi\Database\GenericDB;
  8076. use Tqdev\PhpCrudApi\Record\Document\ListDocument;
  8077. class RecordService
  8078. {
  8079. private $db;
  8080. private $reflection;
  8081. private $columns;
  8082. private $joiner;
  8083. private $filters;
  8084. private $ordering;
  8085. private $pagination;
  8086. public function __construct(GenericDB $db, ReflectionService $reflection)
  8087. {
  8088. $this->db = $db;
  8089. $this->reflection = $reflection;
  8090. $this->columns = new ColumnIncluder();
  8091. $this->joiner = new RelationJoiner($reflection, $this->columns);
  8092. $this->filters = new FilterInfo();
  8093. $this->ordering = new OrderingInfo();
  8094. $this->pagination = new PaginationInfo();
  8095. }
  8096. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  8097. {
  8098. $keyset = array_keys((array) $record);
  8099. foreach ($keyset as $key) {
  8100. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  8101. unset($record->$key);
  8102. }
  8103. }
  8104. if ($id != '') {
  8105. $pk = $this->reflection->getTable($tableName)->getPk();
  8106. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  8107. $field = $this->reflection->getTable($tableName)->getColumn($key);
  8108. if ($field->getName() == $pk->getName()) {
  8109. unset($record->$key);
  8110. }
  8111. }
  8112. }
  8113. }
  8114. public function hasTable(string $table): bool
  8115. {
  8116. return $this->reflection->hasTable($table);
  8117. }
  8118. public function getType(string $table): string
  8119. {
  8120. return $this->reflection->getType($table);
  8121. }
  8122. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  8123. {
  8124. $this->sanitizeRecord($tableName, $record, '');
  8125. $table = $this->reflection->getTable($tableName);
  8126. $columnValues = $this->columns->getValues($table, true, $record, $params);
  8127. return $this->db->createSingle($table, $columnValues);
  8128. }
  8129. public function read(string $tableName, string $id, array $params) /*: ?object*/
  8130. {
  8131. $table = $this->reflection->getTable($tableName);
  8132. $this->joiner->addMandatoryColumns($table, $params);
  8133. $columnNames = $this->columns->getNames($table, true, $params);
  8134. $record = $this->db->selectSingle($table, $columnNames, $id);
  8135. if ($record == null) {
  8136. return null;
  8137. }
  8138. $records = array($record);
  8139. $this->joiner->addJoins($table, $records, $params, $this->db);
  8140. return $records[0];
  8141. }
  8142. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  8143. {
  8144. $this->sanitizeRecord($tableName, $record, $id);
  8145. $table = $this->reflection->getTable($tableName);
  8146. $columnValues = $this->columns->getValues($table, true, $record, $params);
  8147. return $this->db->updateSingle($table, $columnValues, $id);
  8148. }
  8149. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  8150. {
  8151. $table = $this->reflection->getTable($tableName);
  8152. return $this->db->deleteSingle($table, $id);
  8153. }
  8154. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  8155. {
  8156. $this->sanitizeRecord($tableName, $record, $id);
  8157. $table = $this->reflection->getTable($tableName);
  8158. $columnValues = $this->columns->getValues($table, true, $record, $params);
  8159. return $this->db->incrementSingle($table, $columnValues, $id);
  8160. }
  8161. public function _list(string $tableName, array $params): ListDocument
  8162. {
  8163. $table = $this->reflection->getTable($tableName);
  8164. $this->joiner->addMandatoryColumns($table, $params);
  8165. $columnNames = $this->columns->getNames($table, true, $params);
  8166. $condition = $this->filters->getCombinedConditions($table, $params);
  8167. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  8168. if (!$this->pagination->hasPage($params)) {
  8169. $offset = 0;
  8170. $limit = $this->pagination->getPageLimit($params);
  8171. $count = 0;
  8172. } else {
  8173. $offset = $this->pagination->getPageOffset($params);
  8174. $limit = $this->pagination->getPageLimit($params);
  8175. $count = $this->db->selectCount($table, $condition);
  8176. }
  8177. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  8178. $this->joiner->addJoins($table, $records, $params, $this->db);
  8179. return new ListDocument($records, $count);
  8180. }
  8181. }
  8182. }
  8183. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  8184. namespace Tqdev\PhpCrudApi\Record {
  8185. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8186. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8187. use Tqdev\PhpCrudApi\Database\GenericDB;
  8188. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  8189. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  8190. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  8191. class RelationJoiner
  8192. {
  8193. private $reflection;
  8194. private $ordering;
  8195. private $columns;
  8196. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  8197. {
  8198. $this->reflection = $reflection;
  8199. $this->ordering = new OrderingInfo();
  8200. $this->columns = $columns;
  8201. }
  8202. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  8203. {
  8204. if (!isset($params['join']) || !isset($params['include'])) {
  8205. return;
  8206. }
  8207. $params['mandatory'] = array();
  8208. foreach ($params['join'] as $tableNames) {
  8209. $t1 = $table;
  8210. foreach (explode(',', $tableNames) as $tableName) {
  8211. if (!$this->reflection->hasTable($tableName)) {
  8212. continue;
  8213. }
  8214. $t2 = $this->reflection->getTable($tableName);
  8215. $fks1 = $t1->getFksTo($t2->getName());
  8216. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  8217. if ($t3 != null || count($fks1) > 0) {
  8218. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  8219. }
  8220. foreach ($fks1 as $fk) {
  8221. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  8222. }
  8223. $fks2 = $t2->getFksTo($t1->getName());
  8224. if ($t3 != null || count($fks2) > 0) {
  8225. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  8226. }
  8227. foreach ($fks2 as $fk) {
  8228. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  8229. }
  8230. $t1 = $t2;
  8231. }
  8232. }
  8233. }
  8234. private function getJoinsAsPathTree(array $params): PathTree
  8235. {
  8236. $joins = new PathTree();
  8237. if (isset($params['join'])) {
  8238. foreach ($params['join'] as $tableNames) {
  8239. $path = array();
  8240. foreach (explode(',', $tableNames) as $tableName) {
  8241. $t = $this->reflection->getTable($tableName);
  8242. if ($t != null) {
  8243. $path[] = $t->getName();
  8244. }
  8245. }
  8246. $joins->put($path, true);
  8247. }
  8248. }
  8249. return $joins;
  8250. }
  8251. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  8252. {
  8253. $joins = $this->getJoinsAsPathTree($params);
  8254. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  8255. }
  8256. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  8257. {
  8258. foreach ($this->reflection->getTableNames() as $tableName) {
  8259. $t3 = $this->reflection->getTable($tableName);
  8260. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  8261. return $t3;
  8262. }
  8263. }
  8264. return null;
  8265. }
  8266. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  8267. {
  8268. foreach ($joins->getKeys() as $t2Name) {
  8269. $t2 = $this->reflection->getTable($t2Name);
  8270. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  8271. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  8272. if (!$belongsTo && !$hasMany) {
  8273. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  8274. } else {
  8275. $t3 = null;
  8276. }
  8277. $hasAndBelongsToMany = ($t3 != null);
  8278. $newRecords = array();
  8279. $fkValues = null;
  8280. $pkValues = null;
  8281. $habtmValues = null;
  8282. if ($belongsTo) {
  8283. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  8284. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  8285. }
  8286. if ($hasMany) {
  8287. $pkValues = $this->getPkEmptyValues($t1, $records);
  8288. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  8289. }
  8290. if ($hasAndBelongsToMany) {
  8291. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  8292. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  8293. }
  8294. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  8295. if ($fkValues != null) {
  8296. $this->fillFkValues($t2, $newRecords, $fkValues);
  8297. $this->setFkValues($t1, $t2, $records, $fkValues);
  8298. }
  8299. if ($pkValues != null) {
  8300. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  8301. $this->setPkValues($t1, $t2, $records, $pkValues);
  8302. }
  8303. if ($habtmValues != null) {
  8304. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  8305. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  8306. }
  8307. }
  8308. }
  8309. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  8310. {
  8311. $fkValues = array();
  8312. $fks = $t1->getFksTo($t2->getName());
  8313. foreach ($fks as $fk) {
  8314. $fkName = $fk->getName();
  8315. foreach ($records as $record) {
  8316. if (isset($record[$fkName])) {
  8317. $fkValue = $record[$fkName];
  8318. $fkValues[$fkValue] = null;
  8319. }
  8320. }
  8321. }
  8322. return $fkValues;
  8323. }
  8324. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  8325. {
  8326. $columnNames = $this->columns->getNames($t2, false, $params);
  8327. $fkIds = array_keys($fkValues);
  8328. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  8329. $records[] = $record;
  8330. }
  8331. }
  8332. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  8333. {
  8334. $pkName = $t2->getPk()->getName();
  8335. foreach ($fkRecords as $fkRecord) {
  8336. $pkValue = $fkRecord[$pkName];
  8337. $fkValues[$pkValue] = $fkRecord;
  8338. }
  8339. }
  8340. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  8341. {
  8342. $fks = $t1->getFksTo($t2->getName());
  8343. foreach ($fks as $fk) {
  8344. $fkName = $fk->getName();
  8345. foreach ($records as $i => $record) {
  8346. if (isset($record[$fkName])) {
  8347. $key = $record[$fkName];
  8348. $records[$i][$fkName] = $fkValues[$key];
  8349. }
  8350. }
  8351. }
  8352. }
  8353. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  8354. {
  8355. $pkValues = array();
  8356. $pkName = $t1->getPk()->getName();
  8357. foreach ($records as $record) {
  8358. $key = $record[$pkName];
  8359. $pkValues[$key] = array();
  8360. }
  8361. return $pkValues;
  8362. }
  8363. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  8364. {
  8365. $fks = $t2->getFksTo($t1->getName());
  8366. $columnNames = $this->columns->getNames($t2, false, $params);
  8367. $pkValueKeys = implode(',', array_keys($pkValues));
  8368. $conditions = array();
  8369. foreach ($fks as $fk) {
  8370. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  8371. }
  8372. $condition = OrCondition::fromArray($conditions);
  8373. $columnOrdering = array();
  8374. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  8375. if ($limit != -1) {
  8376. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  8377. }
  8378. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  8379. $records[] = $record;
  8380. }
  8381. }
  8382. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  8383. {
  8384. $fks = $t2->getFksTo($t1->getName());
  8385. foreach ($fks as $fk) {
  8386. $fkName = $fk->getName();
  8387. foreach ($pkRecords as $pkRecord) {
  8388. $key = $pkRecord[$fkName];
  8389. if (isset($pkValues[$key])) {
  8390. $pkValues[$key][] = $pkRecord;
  8391. }
  8392. }
  8393. }
  8394. }
  8395. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  8396. {
  8397. $pkName = $t1->getPk()->getName();
  8398. $t2Name = $t2->getName();
  8399. foreach ($records as $i => $record) {
  8400. $key = $record[$pkName];
  8401. $records[$i][$t2Name] = $pkValues[$key];
  8402. }
  8403. }
  8404. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  8405. {
  8406. $pkValues = $this->getPkEmptyValues($t1, $records);
  8407. $fkValues = array();
  8408. $fk1 = $t3->getFksTo($t1->getName())[0];
  8409. $fk2 = $t3->getFksTo($t2->getName())[0];
  8410. $fk1Name = $fk1->getName();
  8411. $fk2Name = $fk2->getName();
  8412. $columnNames = array($fk1Name, $fk2Name);
  8413. $pkIds = implode(',', array_keys($pkValues));
  8414. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  8415. $columnOrdering = array();
  8416. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  8417. if ($limit != -1) {
  8418. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  8419. }
  8420. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  8421. foreach ($records as $record) {
  8422. $val1 = $record[$fk1Name];
  8423. $val2 = $record[$fk2Name];
  8424. $pkValues[$val1][] = $val2;
  8425. $fkValues[$val2] = null;
  8426. }
  8427. return new HabtmValues($pkValues, $fkValues);
  8428. }
  8429. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  8430. {
  8431. $pkName = $t1->getPk()->getName();
  8432. $t2Name = $t2->getName();
  8433. foreach ($records as $i => $record) {
  8434. $key = $record[$pkName];
  8435. $val = array();
  8436. $fks = $habtmValues->pkValues[$key];
  8437. foreach ($fks as $fk) {
  8438. $val[] = $habtmValues->fkValues[$fk];
  8439. }
  8440. $records[$i][$t2Name] = $val;
  8441. }
  8442. }
  8443. }
  8444. }
  8445. // file: src/Tqdev/PhpCrudApi/Api.php
  8446. namespace Tqdev\PhpCrudApi {
  8447. use Psr\Http\Message\ResponseInterface;
  8448. use Psr\Http\Message\ServerRequestInterface;
  8449. use Psr\Http\Server\RequestHandlerInterface;
  8450. use Tqdev\PhpCrudApi\Cache\CacheFactory;
  8451. use Tqdev\PhpCrudApi\Column\DefinitionService;
  8452. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8453. use Tqdev\PhpCrudApi\Controller\CacheController;
  8454. use Tqdev\PhpCrudApi\Controller\ColumnController;
  8455. use Tqdev\PhpCrudApi\Controller\GeoJsonController;
  8456. use Tqdev\PhpCrudApi\Controller\JsonResponder;
  8457. use Tqdev\PhpCrudApi\Controller\OpenApiController;
  8458. use Tqdev\PhpCrudApi\Controller\RecordController;
  8459. use Tqdev\PhpCrudApi\Database\GenericDB;
  8460. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  8461. use Tqdev\PhpCrudApi\Middleware\AuthorizationMiddleware;
  8462. use Tqdev\PhpCrudApi\Middleware\BasicAuthMiddleware;
  8463. use Tqdev\PhpCrudApi\Middleware\CorsMiddleware;
  8464. use Tqdev\PhpCrudApi\Middleware\CustomizationMiddleware;
  8465. use Tqdev\PhpCrudApi\Middleware\DbAuthMiddleware;
  8466. use Tqdev\PhpCrudApi\Middleware\FirewallMiddleware;
  8467. use Tqdev\PhpCrudApi\Middleware\IpAddressMiddleware;
  8468. use Tqdev\PhpCrudApi\Middleware\JoinLimitsMiddleware;
  8469. use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware;
  8470. use Tqdev\PhpCrudApi\Middleware\ReAuthMiddleware;
  8471. use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware;
  8472. use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware;
  8473. use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter;
  8474. use Tqdev\PhpCrudApi\Middleware\SanitationMiddleware;
  8475. use Tqdev\PhpCrudApi\Middleware\ValidationMiddleware;
  8476. use Tqdev\PhpCrudApi\Middleware\XsrfMiddleware;
  8477. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  8478. use Tqdev\PhpCrudApi\Record\ErrorCode;
  8479. use Tqdev\PhpCrudApi\Record\RecordService;
  8480. use Tqdev\PhpCrudApi\ResponseUtils;
  8481. class Api implements RequestHandlerInterface
  8482. {
  8483. private $router;
  8484. private $responder;
  8485. private $debug;
  8486. public function __construct(Config $config)
  8487. {
  8488. $db = new GenericDB(
  8489. $config->getDriver(),
  8490. $config->getAddress(),
  8491. $config->getPort(),
  8492. $config->getDatabase(),
  8493. $config->getUsername(),
  8494. $config->getPassword()
  8495. );
  8496. $prefix = sprintf('phpcrudapi-%s-%s-%s-', $config->getDriver(), $config->getDatabase(), substr(md5(__FILE__), 0, 8));
  8497. $cache = CacheFactory::create($config->getCacheType(), $prefix, $config->getCachePath());
  8498. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  8499. $responder = new JsonResponder();
  8500. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  8501. foreach ($config->getMiddlewares() as $middleware => $properties) {
  8502. switch ($middleware) {
  8503. case 'cors':
  8504. new CorsMiddleware($router, $responder, $properties);
  8505. break;
  8506. case 'firewall':
  8507. new FirewallMiddleware($router, $responder, $properties);
  8508. break;
  8509. case 'basicAuth':
  8510. new BasicAuthMiddleware($router, $responder, $properties);
  8511. break;
  8512. case 'jwtAuth':
  8513. new JwtAuthMiddleware($router, $responder, $properties);
  8514. break;
  8515. case 'dbAuth':
  8516. new DbAuthMiddleware($router, $responder, $properties, $reflection, $db);
  8517. break;
  8518. case 'reAuth':
  8519. new ReAuthMiddleware($router, $responder, $properties, $reflection, $db);
  8520. break;
  8521. case 'validation':
  8522. new ValidationMiddleware($router, $responder, $properties, $reflection);
  8523. break;
  8524. case 'ipAddress':
  8525. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  8526. break;
  8527. case 'sanitation':
  8528. new SanitationMiddleware($router, $responder, $properties, $reflection);
  8529. break;
  8530. case 'multiTenancy':
  8531. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  8532. break;
  8533. case 'authorization':
  8534. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  8535. break;
  8536. case 'xsrf':
  8537. new XsrfMiddleware($router, $responder, $properties);
  8538. break;
  8539. case 'pageLimits':
  8540. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  8541. break;
  8542. case 'joinLimits':
  8543. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  8544. break;
  8545. case 'customization':
  8546. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  8547. break;
  8548. }
  8549. }
  8550. foreach ($config->getControllers() as $controller) {
  8551. switch ($controller) {
  8552. case 'records':
  8553. $records = new RecordService($db, $reflection);
  8554. new RecordController($router, $responder, $records);
  8555. break;
  8556. case 'columns':
  8557. $definition = new DefinitionService($db, $reflection);
  8558. new ColumnController($router, $responder, $reflection, $definition);
  8559. break;
  8560. case 'cache':
  8561. new CacheController($router, $responder, $cache);
  8562. break;
  8563. case 'openapi':
  8564. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  8565. new OpenApiController($router, $responder, $openApi);
  8566. break;
  8567. case 'geojson':
  8568. $records = new RecordService($db, $reflection);
  8569. $geoJson = new GeoJsonService($reflection, $records);
  8570. new GeoJsonController($router, $responder, $geoJson);
  8571. break;
  8572. }
  8573. }
  8574. $this->router = $router;
  8575. $this->responder = $responder;
  8576. $this->debug = $config->getDebug();
  8577. }
  8578. private function parseBody(string $body) /*: ?object*/
  8579. {
  8580. $first = substr($body, 0, 1);
  8581. if ($first == '[' || $first == '{') {
  8582. $object = json_decode($body);
  8583. $causeCode = json_last_error();
  8584. if ($causeCode !== JSON_ERROR_NONE) {
  8585. $object = null;
  8586. }
  8587. } else {
  8588. parse_str($body, $input);
  8589. foreach ($input as $key => $value) {
  8590. if (substr($key, -9) == '__is_null') {
  8591. $input[substr($key, 0, -9)] = null;
  8592. unset($input[$key]);
  8593. }
  8594. }
  8595. $object = (object) $input;
  8596. }
  8597. return $object;
  8598. }
  8599. private function addParsedBody(ServerRequestInterface $request): ServerRequestInterface
  8600. {
  8601. $body = $request->getBody();
  8602. if ($body->isReadable() && $body->isSeekable()) {
  8603. $contents = $body->getContents();
  8604. $body->rewind();
  8605. if ($contents) {
  8606. $parsedBody = $this->parseBody($contents);
  8607. $request = $request->withParsedBody($parsedBody);
  8608. }
  8609. }
  8610. return $request;
  8611. }
  8612. public function handle(ServerRequestInterface $request): ResponseInterface
  8613. {
  8614. $response = null;
  8615. try {
  8616. $response = $this->router->route($this->addParsedBody($request));
  8617. } catch (\Throwable $e) {
  8618. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  8619. if ($this->debug) {
  8620. $response = ResponseUtils::addExceptionHeaders($response, $e);
  8621. }
  8622. }
  8623. return $response;
  8624. }
  8625. }
  8626. }
  8627. // file: src/Tqdev/PhpCrudApi/Config.php
  8628. namespace Tqdev\PhpCrudApi {
  8629. class Config
  8630. {
  8631. private $values = [
  8632. 'driver' => null,
  8633. 'address' => 'localhost',
  8634. 'port' => null,
  8635. 'username' => null,
  8636. 'password' => null,
  8637. 'database' => null,
  8638. 'middlewares' => 'cors',
  8639. 'controllers' => 'records,geojson,openapi',
  8640. 'cacheType' => 'TempFile',
  8641. 'cachePath' => '',
  8642. 'cacheTime' => 10,
  8643. 'debug' => false,
  8644. 'basePath' => '',
  8645. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  8646. ];
  8647. private function getDefaultDriver(array $values): string
  8648. {
  8649. if (isset($values['driver'])) {
  8650. return $values['driver'];
  8651. }
  8652. return 'mysql';
  8653. }
  8654. private function getDefaultPort(string $driver): int
  8655. {
  8656. switch ($driver) {
  8657. case 'mysql':return 3306;
  8658. case 'pgsql':return 5432;
  8659. case 'sqlsrv':return 1433;
  8660. }
  8661. }
  8662. private function getDefaultAddress(string $driver): string
  8663. {
  8664. switch ($driver) {
  8665. case 'mysql':return 'localhost';
  8666. case 'pgsql':return 'localhost';
  8667. case 'sqlsrv':return 'localhost';
  8668. }
  8669. }
  8670. private function getDriverDefaults(string $driver): array
  8671. {
  8672. return [
  8673. 'driver' => $driver,
  8674. 'address' => $this->getDefaultAddress($driver),
  8675. 'port' => $this->getDefaultPort($driver),
  8676. ];
  8677. }
  8678. public function __construct(array $values)
  8679. {
  8680. $driver = $this->getDefaultDriver($values);
  8681. $defaults = $this->getDriverDefaults($driver);
  8682. $newValues = array_merge($this->values, $defaults, $values);
  8683. $newValues = $this->parseMiddlewares($newValues);
  8684. $diff = array_diff_key($newValues, $this->values);
  8685. if (!empty($diff)) {
  8686. $key = array_keys($diff)[0];
  8687. throw new \Exception("Config has invalid value '$key'");
  8688. }
  8689. $this->values = $newValues;
  8690. }
  8691. private function parseMiddlewares(array $values): array
  8692. {
  8693. $newValues = array();
  8694. $properties = array();
  8695. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  8696. foreach ($middlewares as $middleware) {
  8697. $properties[$middleware] = [];
  8698. }
  8699. foreach ($values as $key => $value) {
  8700. if (strpos($key, '.') === false) {
  8701. $newValues[$key] = $value;
  8702. } else {
  8703. list($middleware, $key2) = explode('.', $key, 2);
  8704. if (isset($properties[$middleware])) {
  8705. $properties[$middleware][$key2] = $value;
  8706. } else {
  8707. throw new \Exception("Config has invalid value '$key'");
  8708. }
  8709. }
  8710. }
  8711. $newValues['middlewares'] = array_reverse($properties, true);
  8712. return $newValues;
  8713. }
  8714. public function getDriver(): string
  8715. {
  8716. return $this->values['driver'];
  8717. }
  8718. public function getAddress(): string
  8719. {
  8720. return $this->values['address'];
  8721. }
  8722. public function getPort(): int
  8723. {
  8724. return $this->values['port'];
  8725. }
  8726. public function getUsername(): string
  8727. {
  8728. return $this->values['username'];
  8729. }
  8730. public function getPassword(): string
  8731. {
  8732. return $this->values['password'];
  8733. }
  8734. public function getDatabase(): string
  8735. {
  8736. return $this->values['database'];
  8737. }
  8738. public function getMiddlewares(): array
  8739. {
  8740. return $this->values['middlewares'];
  8741. }
  8742. public function getControllers(): array
  8743. {
  8744. return array_map('trim', explode(',', $this->values['controllers']));
  8745. }
  8746. public function getCacheType(): string
  8747. {
  8748. return $this->values['cacheType'];
  8749. }
  8750. public function getCachePath(): string
  8751. {
  8752. return $this->values['cachePath'];
  8753. }
  8754. public function getCacheTime(): int
  8755. {
  8756. return $this->values['cacheTime'];
  8757. }
  8758. public function getDebug(): bool
  8759. {
  8760. return $this->values['debug'];
  8761. }
  8762. public function getBasePath(): string
  8763. {
  8764. return $this->values['basePath'];
  8765. }
  8766. public function getOpenApiBase(): array
  8767. {
  8768. return json_decode($this->values['openApiBase'], true);
  8769. }
  8770. }
  8771. }
  8772. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  8773. namespace Tqdev\PhpCrudApi {
  8774. use Nyholm\Psr7Server\ServerRequestCreator;
  8775. use Nyholm\Psr7\Factory\Psr17Factory;
  8776. use Psr\Http\Message\ServerRequestInterface;
  8777. class RequestFactory
  8778. {
  8779. public static function fromGlobals(): ServerRequestInterface
  8780. {
  8781. $psr17Factory = new Psr17Factory();
  8782. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  8783. $serverRequest = $creator->fromGlobals();
  8784. $stream = $psr17Factory->createStreamFromFile('php://input');
  8785. $serverRequest = $serverRequest->withBody($stream);
  8786. return $serverRequest;
  8787. }
  8788. public static function fromString(string $request): ServerRequestInterface
  8789. {
  8790. $parts = explode("\n\n", trim($request), 2);
  8791. $lines = explode("\n", $parts[0]);
  8792. $first = explode(' ', trim(array_shift($lines)), 2);
  8793. $method = $first[0];
  8794. $body = isset($parts[1]) ? $parts[1] : '';
  8795. $url = isset($first[1]) ? $first[1] : '';
  8796. $psr17Factory = new Psr17Factory();
  8797. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  8798. foreach ($lines as $line) {
  8799. list($key, $value) = explode(':', $line, 2);
  8800. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  8801. }
  8802. if ($body) {
  8803. $stream = $psr17Factory->createStream($body);
  8804. $stream->rewind();
  8805. $serverRequest = $serverRequest->withBody($stream);
  8806. }
  8807. return $serverRequest;
  8808. }
  8809. }
  8810. }
  8811. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  8812. namespace Tqdev\PhpCrudApi {
  8813. use Psr\Http\Message\ServerRequestInterface;
  8814. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8815. class RequestUtils
  8816. {
  8817. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  8818. {
  8819. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  8820. return $request->withUri($request->getUri()->withQuery($query));
  8821. }
  8822. public static function getHeader(ServerRequestInterface $request, string $header): string
  8823. {
  8824. $headers = $request->getHeader($header);
  8825. return isset($headers[0]) ? $headers[0] : '';
  8826. }
  8827. public static function getParams(ServerRequestInterface $request): array
  8828. {
  8829. $params = array();
  8830. $query = $request->getUri()->getQuery();
  8831. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  8832. parse_str($query, $params);
  8833. return $params;
  8834. }
  8835. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  8836. {
  8837. $path = $request->getUri()->getPath();
  8838. $pathSegments = explode('/', rtrim($path, '/'));
  8839. if ($part < 0 || $part >= count($pathSegments)) {
  8840. return '';
  8841. }
  8842. return urldecode($pathSegments[$part]);
  8843. }
  8844. public static function getOperation(ServerRequestInterface $request): string
  8845. {
  8846. $method = $request->getMethod();
  8847. $path = RequestUtils::getPathSegment($request, 1);
  8848. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  8849. switch ($path) {
  8850. case 'openapi':
  8851. return 'document';
  8852. case 'columns':
  8853. return $method == 'get' ? 'reflect' : 'remodel';
  8854. case 'records':
  8855. switch ($method) {
  8856. case 'POST':
  8857. return 'create';
  8858. case 'GET':
  8859. return $hasPk ? 'read' : 'list';
  8860. case 'PUT':
  8861. return 'update';
  8862. case 'DELETE':
  8863. return 'delete';
  8864. case 'PATCH':
  8865. return 'increment';
  8866. }
  8867. }
  8868. return 'unknown';
  8869. }
  8870. private static function getJoinTables(string $tableName, array $parameters): array
  8871. {
  8872. $uniqueTableNames = array();
  8873. $uniqueTableNames[$tableName] = true;
  8874. if (isset($parameters['join'])) {
  8875. foreach ($parameters['join'] as $parameter) {
  8876. $tableNames = explode(',', trim($parameter));
  8877. foreach ($tableNames as $tableName) {
  8878. $uniqueTableNames[$tableName] = true;
  8879. }
  8880. }
  8881. }
  8882. return array_keys($uniqueTableNames);
  8883. }
  8884. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  8885. {
  8886. $path = RequestUtils::getPathSegment($request, 1);
  8887. $tableName = RequestUtils::getPathSegment($request, 2);
  8888. $allTableNames = $reflection->getTableNames();
  8889. switch ($path) {
  8890. case 'openapi':
  8891. return $allTableNames;
  8892. case 'columns':
  8893. return $tableName ? [$tableName] : $allTableNames;
  8894. case 'records':
  8895. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  8896. }
  8897. return $allTableNames;
  8898. }
  8899. }
  8900. }
  8901. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  8902. namespace Tqdev\PhpCrudApi {
  8903. use Nyholm\Psr7\Factory\Psr17Factory;
  8904. use Psr\Http\Message\ResponseInterface;
  8905. class ResponseFactory
  8906. {
  8907. const OK = 200;
  8908. const UNAUTHORIZED = 401;
  8909. const FORBIDDEN = 403;
  8910. const NOT_FOUND = 404;
  8911. const METHOD_NOT_ALLOWED = 405;
  8912. const CONFLICT = 409;
  8913. const UNPROCESSABLE_ENTITY = 422;
  8914. const INTERNAL_SERVER_ERROR = 500;
  8915. public static function fromHtml(int $status, string $html): ResponseInterface
  8916. {
  8917. return self::from($status, 'text/html', $html);
  8918. }
  8919. public static function fromObject(int $status, $body): ResponseInterface
  8920. {
  8921. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  8922. return self::from($status, 'application/json', $content);
  8923. }
  8924. private static function from(int $status, string $contentType, string $content): ResponseInterface
  8925. {
  8926. $psr17Factory = new Psr17Factory();
  8927. $response = $psr17Factory->createResponse($status);
  8928. $stream = $psr17Factory->createStream($content);
  8929. $stream->rewind();
  8930. $response = $response->withBody($stream);
  8931. $response = $response->withHeader('Content-Type', $contentType);
  8932. $response = $response->withHeader('Content-Length', strlen($content));
  8933. return $response;
  8934. }
  8935. public static function fromStatus(int $status): ResponseInterface
  8936. {
  8937. $psr17Factory = new Psr17Factory();
  8938. return $psr17Factory->createResponse($status);
  8939. }
  8940. }
  8941. }
  8942. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  8943. namespace Tqdev\PhpCrudApi {
  8944. use Psr\Http\Message\ResponseInterface;
  8945. class ResponseUtils
  8946. {
  8947. public static function output(ResponseInterface $response)
  8948. {
  8949. $status = $response->getStatusCode();
  8950. $headers = $response->getHeaders();
  8951. $body = $response->getBody()->getContents();
  8952. http_response_code($status);
  8953. foreach ($headers as $key => $values) {
  8954. foreach ($values as $value) {
  8955. header("$key: $value");
  8956. }
  8957. }
  8958. echo $body;
  8959. }
  8960. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  8961. {
  8962. $response = $response->withHeader('X-Exception-Name', get_class($e));
  8963. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  8964. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  8965. return $response;
  8966. }
  8967. public static function toString(ResponseInterface $response): string
  8968. {
  8969. $status = $response->getStatusCode();
  8970. $headers = $response->getHeaders();
  8971. $body = $response->getBody()->getContents();
  8972. $str = "$status\n";
  8973. foreach ($headers as $key => $values) {
  8974. foreach ($values as $value) {
  8975. $str .= "$key: $value\n";
  8976. }
  8977. }
  8978. if ($body !== '') {
  8979. $str .= "\n";
  8980. $str .= "$body\n";
  8981. }
  8982. return $str;
  8983. }
  8984. }
  8985. }
  8986. // file: src/index.php
  8987. namespace Tqdev\PhpCrudApi {
  8988. use Tqdev\PhpCrudApi\Api;
  8989. use Tqdev\PhpCrudApi\Config;
  8990. use Tqdev\PhpCrudApi\RequestFactory;
  8991. use Tqdev\PhpCrudApi\ResponseUtils;
  8992. $config = new Config([
  8993. 'username' => 'php-crud-api',
  8994. 'password' => 'php-crud-api',
  8995. 'database' => 'php-crud-api',
  8996. ]);
  8997. $request = RequestFactory::fromGlobals();
  8998. $api = new Api($config);
  8999. $response = $api->handle($request);
  9000. ResponseUtils::output($response);
  9001. }