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

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