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

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