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
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

api.php 420KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294
  1. <?php
  2. /**
  3. * PHP-CRUD-API v2 License: MIT
  4. * Maurits van der Schee: maurits@vdschee.nl
  5. * https://github.com/mevdschee/php-crud-api
  6. *
  7. * Dependencies:
  8. * - vendor/psr/*: PHP-FIG
  9. * https://github.com/php-fig
  10. * - vendor/nyholm/*: Tobias Nyholm
  11. * https://github.com/Nyholm
  12. **/
  13. // file: vendor/psr/http-factory/src/RequestFactoryInterface.php
  14. namespace Psr\Http\Message {
  15. interface RequestFactoryInterface
  16. {
  17. /**
  18. * Create a new request.
  19. *
  20. * @param string $method The HTTP method associated with the request.
  21. * @param UriInterface|string $uri The URI associated with the request. If
  22. * the value is a string, the factory MUST create a UriInterface
  23. * instance based on it.
  24. *
  25. * @return RequestInterface
  26. */
  27. public function createRequest(string $method, $uri): RequestInterface;
  28. }
  29. }
  30. // file: vendor/psr/http-factory/src/ResponseFactoryInterface.php
  31. namespace Psr\Http\Message {
  32. interface ResponseFactoryInterface
  33. {
  34. /**
  35. * Create a new response.
  36. *
  37. * @param int $code HTTP status code; defaults to 200
  38. * @param string $reasonPhrase Reason phrase to associate with status code
  39. * in generated response; if none is provided implementations MAY use
  40. * the defaults as suggested in the HTTP specification.
  41. *
  42. * @return ResponseInterface
  43. */
  44. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface;
  45. }
  46. }
  47. // file: vendor/psr/http-factory/src/ServerRequestFactoryInterface.php
  48. namespace Psr\Http\Message {
  49. interface ServerRequestFactoryInterface
  50. {
  51. /**
  52. * Create a new server request.
  53. *
  54. * Note that server-params are taken precisely as given - no parsing/processing
  55. * of the given values is performed, and, in particular, no attempt is made to
  56. * determine the HTTP method or URI, which must be provided explicitly.
  57. *
  58. * @param string $method The HTTP method associated with the request.
  59. * @param UriInterface|string $uri The URI associated with the request. If
  60. * the value is a string, the factory MUST create a UriInterface
  61. * instance based on it.
  62. * @param array $serverParams Array of SAPI parameters with which to seed
  63. * the generated request instance.
  64. *
  65. * @return ServerRequestInterface
  66. */
  67. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface;
  68. }
  69. }
  70. // file: vendor/psr/http-factory/src/StreamFactoryInterface.php
  71. namespace Psr\Http\Message {
  72. interface StreamFactoryInterface
  73. {
  74. /**
  75. * Create a new stream from a string.
  76. *
  77. * The stream SHOULD be created with a temporary resource.
  78. *
  79. * @param string $content String content with which to populate the stream.
  80. *
  81. * @return StreamInterface
  82. */
  83. public function createStream(string $content = ''): StreamInterface;
  84. /**
  85. * Create a stream from an existing file.
  86. *
  87. * The file MUST be opened using the given mode, which may be any mode
  88. * supported by the `fopen` function.
  89. *
  90. * The `$filename` MAY be any string supported by `fopen()`.
  91. *
  92. * @param string $filename Filename or stream URI to use as basis of stream.
  93. * @param string $mode Mode with which to open the underlying filename/stream.
  94. *
  95. * @return StreamInterface
  96. * @throws \RuntimeException If the file cannot be opened.
  97. * @throws \InvalidArgumentException If the mode is invalid.
  98. */
  99. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface;
  100. /**
  101. * Create a new stream from an existing resource.
  102. *
  103. * The stream MUST be readable and may be writable.
  104. *
  105. * @param resource $resource PHP resource to use as basis of stream.
  106. *
  107. * @return StreamInterface
  108. */
  109. public function createStreamFromResource($resource): StreamInterface;
  110. }
  111. }
  112. // file: vendor/psr/http-factory/src/UploadedFileFactoryInterface.php
  113. namespace Psr\Http\Message {
  114. interface UploadedFileFactoryInterface
  115. {
  116. /**
  117. * Create a new uploaded file.
  118. *
  119. * If a size is not provided it will be determined by checking the size of
  120. * the file.
  121. *
  122. * @see http://php.net/manual/features.file-upload.post-method.php
  123. * @see http://php.net/manual/features.file-upload.errors.php
  124. *
  125. * @param StreamInterface $stream Underlying stream representing the
  126. * uploaded file content.
  127. * @param int $size in bytes
  128. * @param int $error PHP file upload error
  129. * @param string $clientFilename Filename as provided by the client, if any.
  130. * @param string $clientMediaType Media type as provided by the client, if any.
  131. *
  132. * @return UploadedFileInterface
  133. *
  134. * @throws \InvalidArgumentException If the file resource is not readable.
  135. */
  136. public function createUploadedFile(
  137. StreamInterface $stream,
  138. int $size = null,
  139. int $error = \UPLOAD_ERR_OK,
  140. string $clientFilename = null,
  141. string $clientMediaType = null
  142. ): UploadedFileInterface;
  143. }
  144. }
  145. // file: vendor/psr/http-factory/src/UriFactoryInterface.php
  146. namespace Psr\Http\Message {
  147. interface UriFactoryInterface
  148. {
  149. /**
  150. * Create a new URI.
  151. *
  152. * @param string $uri
  153. *
  154. * @return UriInterface
  155. *
  156. * @throws \InvalidArgumentException If the given URI cannot be parsed.
  157. */
  158. public function createUri(string $uri = ''): UriInterface;
  159. }
  160. }
  161. // file: vendor/psr/http-message/src/MessageInterface.php
  162. namespace Psr\Http\Message {
  163. /**
  164. * HTTP messages consist of requests from a client to a server and responses
  165. * from a server to a client. This interface defines the methods common to
  166. * each.
  167. *
  168. * Messages are considered immutable; all methods that might change state MUST
  169. * be implemented such that they retain the internal state of the current
  170. * message and return an instance that contains the changed state.
  171. *
  172. * @link http://www.ietf.org/rfc/rfc7230.txt
  173. * @link http://www.ietf.org/rfc/rfc7231.txt
  174. */
  175. interface MessageInterface
  176. {
  177. /**
  178. * Retrieves the HTTP protocol version as a string.
  179. *
  180. * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
  181. *
  182. * @return string HTTP protocol version.
  183. */
  184. public function getProtocolVersion();
  185. /**
  186. * Return an instance with the specified HTTP protocol version.
  187. *
  188. * The version string MUST contain only the HTTP version number (e.g.,
  189. * "1.1", "1.0").
  190. *
  191. * This method MUST be implemented in such a way as to retain the
  192. * immutability of the message, and MUST return an instance that has the
  193. * new protocol version.
  194. *
  195. * @param string $version HTTP protocol version
  196. * @return static
  197. */
  198. public function withProtocolVersion($version);
  199. /**
  200. * Retrieves all message header values.
  201. *
  202. * The keys represent the header name as it will be sent over the wire, and
  203. * each value is an array of strings associated with the header.
  204. *
  205. * // Represent the headers as a string
  206. * foreach ($message->getHeaders() as $name => $values) {
  207. * echo $name . ": " . implode(", ", $values);
  208. * }
  209. *
  210. * // Emit headers iteratively:
  211. * foreach ($message->getHeaders() as $name => $values) {
  212. * foreach ($values as $value) {
  213. * header(sprintf('%s: %s', $name, $value), false);
  214. * }
  215. * }
  216. *
  217. * While header names are not case-sensitive, getHeaders() will preserve the
  218. * exact case in which headers were originally specified.
  219. *
  220. * @return string[][] Returns an associative array of the message's headers. Each
  221. * key MUST be a header name, and each value MUST be an array of strings
  222. * for that header.
  223. */
  224. public function getHeaders();
  225. /**
  226. * Checks if a header exists by the given case-insensitive name.
  227. *
  228. * @param string $name Case-insensitive header field name.
  229. * @return bool Returns true if any header names match the given header
  230. * name using a case-insensitive string comparison. Returns false if
  231. * no matching header name is found in the message.
  232. */
  233. public function hasHeader($name);
  234. /**
  235. * Retrieves a message header value by the given case-insensitive name.
  236. *
  237. * This method returns an array of all the header values of the given
  238. * case-insensitive header name.
  239. *
  240. * If the header does not appear in the message, this method MUST return an
  241. * empty array.
  242. *
  243. * @param string $name Case-insensitive header field name.
  244. * @return string[] An array of string values as provided for the given
  245. * header. If the header does not appear in the message, this method MUST
  246. * return an empty array.
  247. */
  248. public function getHeader($name);
  249. /**
  250. * Retrieves a comma-separated string of the values for a single header.
  251. *
  252. * This method returns all of the header values of the given
  253. * case-insensitive header name as a string concatenated together using
  254. * a comma.
  255. *
  256. * NOTE: Not all header values may be appropriately represented using
  257. * comma concatenation. For such headers, use getHeader() instead
  258. * and supply your own delimiter when concatenating.
  259. *
  260. * If the header does not appear in the message, this method MUST return
  261. * an empty string.
  262. *
  263. * @param string $name Case-insensitive header field name.
  264. * @return string A string of values as provided for the given header
  265. * concatenated together using a comma. If the header does not appear in
  266. * the message, this method MUST return an empty string.
  267. */
  268. public function getHeaderLine($name);
  269. /**
  270. * Return an instance with the provided value replacing the specified header.
  271. *
  272. * While header names are case-insensitive, the casing of the header will
  273. * be preserved by this function, and returned from getHeaders().
  274. *
  275. * This method MUST be implemented in such a way as to retain the
  276. * immutability of the message, and MUST return an instance that has the
  277. * new and/or updated header and value.
  278. *
  279. * @param string $name Case-insensitive header field name.
  280. * @param string|string[] $value Header value(s).
  281. * @return static
  282. * @throws \InvalidArgumentException for invalid header names or values.
  283. */
  284. public function withHeader($name, $value);
  285. /**
  286. * Return an instance with the specified header appended with the given value.
  287. *
  288. * Existing values for the specified header will be maintained. The new
  289. * value(s) will be appended to the existing list. If the header did not
  290. * exist previously, it will be added.
  291. *
  292. * This method MUST be implemented in such a way as to retain the
  293. * immutability of the message, and MUST return an instance that has the
  294. * new header and/or value.
  295. *
  296. * @param string $name Case-insensitive header field name to add.
  297. * @param string|string[] $value Header value(s).
  298. * @return static
  299. * @throws \InvalidArgumentException for invalid header names or values.
  300. */
  301. public function withAddedHeader($name, $value);
  302. /**
  303. * Return an instance without the specified header.
  304. *
  305. * Header resolution MUST be done without case-sensitivity.
  306. *
  307. * This method MUST be implemented in such a way as to retain the
  308. * immutability of the message, and MUST return an instance that removes
  309. * the named header.
  310. *
  311. * @param string $name Case-insensitive header field name to remove.
  312. * @return static
  313. */
  314. public function withoutHeader($name);
  315. /**
  316. * Gets the body of the message.
  317. *
  318. * @return StreamInterface Returns the body as a stream.
  319. */
  320. public function getBody();
  321. /**
  322. * Return an instance with the specified message body.
  323. *
  324. * The body MUST be a StreamInterface object.
  325. *
  326. * This method MUST be implemented in such a way as to retain the
  327. * immutability of the message, and MUST return a new instance that has the
  328. * new body stream.
  329. *
  330. * @param StreamInterface $body Body.
  331. * @return static
  332. * @throws \InvalidArgumentException When the body is not valid.
  333. */
  334. public function withBody(StreamInterface $body);
  335. }
  336. }
  337. // file: vendor/psr/http-message/src/RequestInterface.php
  338. namespace Psr\Http\Message {
  339. /**
  340. * Representation of an outgoing, client-side request.
  341. *
  342. * Per the HTTP specification, this interface includes properties for
  343. * each of the following:
  344. *
  345. * - Protocol version
  346. * - HTTP method
  347. * - URI
  348. * - Headers
  349. * - Message body
  350. *
  351. * During construction, implementations MUST attempt to set the Host header from
  352. * a provided URI if no Host header is provided.
  353. *
  354. * Requests are considered immutable; all methods that might change state MUST
  355. * be implemented such that they retain the internal state of the current
  356. * message and return an instance that contains the changed state.
  357. */
  358. interface RequestInterface extends MessageInterface
  359. {
  360. /**
  361. * Retrieves the message's request target.
  362. *
  363. * Retrieves the message's request-target either as it will appear (for
  364. * clients), as it appeared at request (for servers), or as it was
  365. * specified for the instance (see withRequestTarget()).
  366. *
  367. * In most cases, this will be the origin-form of the composed URI,
  368. * unless a value was provided to the concrete implementation (see
  369. * withRequestTarget() below).
  370. *
  371. * If no URI is available, and no request-target has been specifically
  372. * provided, this method MUST return the string "/".
  373. *
  374. * @return string
  375. */
  376. public function getRequestTarget();
  377. /**
  378. * Return an instance with the specific request-target.
  379. *
  380. * If the request needs a non-origin-form request-target — e.g., for
  381. * specifying an absolute-form, authority-form, or asterisk-form —
  382. * this method may be used to create an instance with the specified
  383. * request-target, verbatim.
  384. *
  385. * This method MUST be implemented in such a way as to retain the
  386. * immutability of the message, and MUST return an instance that has the
  387. * changed request target.
  388. *
  389. * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various
  390. * request-target forms allowed in request messages)
  391. * @param mixed $requestTarget
  392. * @return static
  393. */
  394. public function withRequestTarget($requestTarget);
  395. /**
  396. * Retrieves the HTTP method of the request.
  397. *
  398. * @return string Returns the request method.
  399. */
  400. public function getMethod();
  401. /**
  402. * Return an instance with the provided HTTP method.
  403. *
  404. * While HTTP method names are typically all uppercase characters, HTTP
  405. * method names are case-sensitive and thus implementations SHOULD NOT
  406. * modify the given string.
  407. *
  408. * This method MUST be implemented in such a way as to retain the
  409. * immutability of the message, and MUST return an instance that has the
  410. * changed request method.
  411. *
  412. * @param string $method Case-sensitive method.
  413. * @return static
  414. * @throws \InvalidArgumentException for invalid HTTP methods.
  415. */
  416. public function withMethod($method);
  417. /**
  418. * Retrieves the URI instance.
  419. *
  420. * This method MUST return a UriInterface instance.
  421. *
  422. * @link http://tools.ietf.org/html/rfc3986#section-4.3
  423. * @return UriInterface Returns a UriInterface instance
  424. * representing the URI of the request.
  425. */
  426. public function getUri();
  427. /**
  428. * Returns an instance with the provided URI.
  429. *
  430. * This method MUST update the Host header of the returned request by
  431. * default if the URI contains a host component. If the URI does not
  432. * contain a host component, any pre-existing Host header MUST be carried
  433. * over to the returned request.
  434. *
  435. * You can opt-in to preserving the original state of the Host header by
  436. * setting `$preserveHost` to `true`. When `$preserveHost` is set to
  437. * `true`, this method interacts with the Host header in the following ways:
  438. *
  439. * - If the Host header is missing or empty, and the new URI contains
  440. * a host component, this method MUST update the Host header in the returned
  441. * request.
  442. * - If the Host header is missing or empty, and the new URI does not contain a
  443. * host component, this method MUST NOT update the Host header in the returned
  444. * request.
  445. * - If a Host header is present and non-empty, this method MUST NOT update
  446. * the Host header in the returned request.
  447. *
  448. * This method MUST be implemented in such a way as to retain the
  449. * immutability of the message, and MUST return an instance that has the
  450. * new UriInterface instance.
  451. *
  452. * @link http://tools.ietf.org/html/rfc3986#section-4.3
  453. * @param UriInterface $uri New request URI to use.
  454. * @param bool $preserveHost Preserve the original state of the Host header.
  455. * @return static
  456. */
  457. public function withUri(UriInterface $uri, $preserveHost = false);
  458. }
  459. }
  460. // file: vendor/psr/http-message/src/ResponseInterface.php
  461. namespace Psr\Http\Message {
  462. /**
  463. * Representation of an outgoing, server-side response.
  464. *
  465. * Per the HTTP specification, this interface includes properties for
  466. * each of the following:
  467. *
  468. * - Protocol version
  469. * - Status code and reason phrase
  470. * - Headers
  471. * - Message body
  472. *
  473. * Responses are considered immutable; all methods that might change state MUST
  474. * be implemented such that they retain the internal state of the current
  475. * message and return an instance that contains the changed state.
  476. */
  477. interface ResponseInterface extends MessageInterface
  478. {
  479. /**
  480. * Gets the response status code.
  481. *
  482. * The status code is a 3-digit integer result code of the server's attempt
  483. * to understand and satisfy the request.
  484. *
  485. * @return int Status code.
  486. */
  487. public function getStatusCode();
  488. /**
  489. * Return an instance with the specified status code and, optionally, reason phrase.
  490. *
  491. * If no reason phrase is specified, implementations MAY choose to default
  492. * to the RFC 7231 or IANA recommended reason phrase for the response's
  493. * status code.
  494. *
  495. * This method MUST be implemented in such a way as to retain the
  496. * immutability of the message, and MUST return an instance that has the
  497. * updated status and reason phrase.
  498. *
  499. * @link http://tools.ietf.org/html/rfc7231#section-6
  500. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  501. * @param int $code The 3-digit integer result code to set.
  502. * @param string $reasonPhrase The reason phrase to use with the
  503. * provided status code; if none is provided, implementations MAY
  504. * use the defaults as suggested in the HTTP specification.
  505. * @return static
  506. * @throws \InvalidArgumentException For invalid status code arguments.
  507. */
  508. public function withStatus($code, $reasonPhrase = '');
  509. /**
  510. * Gets the response reason phrase associated with the status code.
  511. *
  512. * Because a reason phrase is not a required element in a response
  513. * status line, the reason phrase value MAY be null. Implementations MAY
  514. * choose to return the default RFC 7231 recommended reason phrase (or those
  515. * listed in the IANA HTTP Status Code Registry) for the response's
  516. * status code.
  517. *
  518. * @link http://tools.ietf.org/html/rfc7231#section-6
  519. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  520. * @return string Reason phrase; must return an empty string if none present.
  521. */
  522. public function getReasonPhrase();
  523. }
  524. }
  525. // file: vendor/psr/http-message/src/ServerRequestInterface.php
  526. namespace Psr\Http\Message {
  527. /**
  528. * Representation of an incoming, server-side HTTP request.
  529. *
  530. * Per the HTTP specification, this interface includes properties for
  531. * each of the following:
  532. *
  533. * - Protocol version
  534. * - HTTP method
  535. * - URI
  536. * - Headers
  537. * - Message body
  538. *
  539. * Additionally, it encapsulates all data as it has arrived to the
  540. * application from the CGI and/or PHP environment, including:
  541. *
  542. * - The values represented in $_SERVER.
  543. * - Any cookies provided (generally via $_COOKIE)
  544. * - Query string arguments (generally via $_GET, or as parsed via parse_str())
  545. * - Upload files, if any (as represented by $_FILES)
  546. * - Deserialized body parameters (generally from $_POST)
  547. *
  548. * $_SERVER values MUST be treated as immutable, as they represent application
  549. * state at the time of request; as such, no methods are provided to allow
  550. * modification of those values. The other values provide such methods, as they
  551. * can be restored from $_SERVER or the request body, and may need treatment
  552. * during the application (e.g., body parameters may be deserialized based on
  553. * content type).
  554. *
  555. * Additionally, this interface recognizes the utility of introspecting a
  556. * request to derive and match additional parameters (e.g., via URI path
  557. * matching, decrypting cookie values, deserializing non-form-encoded body
  558. * content, matching authorization headers to users, etc). These parameters
  559. * are stored in an "attributes" property.
  560. *
  561. * Requests are considered immutable; all methods that might change state MUST
  562. * be implemented such that they retain the internal state of the current
  563. * message and return an instance that contains the changed state.
  564. */
  565. interface ServerRequestInterface extends RequestInterface
  566. {
  567. /**
  568. * Retrieve server parameters.
  569. *
  570. * Retrieves data related to the incoming request environment,
  571. * typically derived from PHP's $_SERVER superglobal. The data IS NOT
  572. * REQUIRED to originate from $_SERVER.
  573. *
  574. * @return array
  575. */
  576. public function getServerParams();
  577. /**
  578. * Retrieve cookies.
  579. *
  580. * Retrieves cookies sent by the client to the server.
  581. *
  582. * The data MUST be compatible with the structure of the $_COOKIE
  583. * superglobal.
  584. *
  585. * @return array
  586. */
  587. public function getCookieParams();
  588. /**
  589. * Return an instance with the specified cookies.
  590. *
  591. * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
  592. * be compatible with the structure of $_COOKIE. Typically, this data will
  593. * be injected at instantiation.
  594. *
  595. * This method MUST NOT update the related Cookie header of the request
  596. * instance, nor related values in the server params.
  597. *
  598. * This method MUST be implemented in such a way as to retain the
  599. * immutability of the message, and MUST return an instance that has the
  600. * updated cookie values.
  601. *
  602. * @param array $cookies Array of key/value pairs representing cookies.
  603. * @return static
  604. */
  605. public function withCookieParams(array $cookies);
  606. /**
  607. * Retrieve query string arguments.
  608. *
  609. * Retrieves the deserialized query string arguments, if any.
  610. *
  611. * Note: the query params might not be in sync with the URI or server
  612. * params. If you need to ensure you are only getting the original
  613. * values, you may need to parse the query string from `getUri()->getQuery()`
  614. * or from the `QUERY_STRING` server param.
  615. *
  616. * @return array
  617. */
  618. public function getQueryParams();
  619. /**
  620. * Return an instance with the specified query string arguments.
  621. *
  622. * These values SHOULD remain immutable over the course of the incoming
  623. * request. They MAY be injected during instantiation, such as from PHP's
  624. * $_GET superglobal, or MAY be derived from some other value such as the
  625. * URI. In cases where the arguments are parsed from the URI, the data
  626. * MUST be compatible with what PHP's parse_str() would return for
  627. * purposes of how duplicate query parameters are handled, and how nested
  628. * sets are handled.
  629. *
  630. * Setting query string arguments MUST NOT change the URI stored by the
  631. * request, nor the values in the server params.
  632. *
  633. * This method MUST be implemented in such a way as to retain the
  634. * immutability of the message, and MUST return an instance that has the
  635. * updated query string arguments.
  636. *
  637. * @param array $query Array of query string arguments, typically from
  638. * $_GET.
  639. * @return static
  640. */
  641. public function withQueryParams(array $query);
  642. /**
  643. * Retrieve normalized file upload data.
  644. *
  645. * This method returns upload metadata in a normalized tree, with each leaf
  646. * an instance of Psr\Http\Message\UploadedFileInterface.
  647. *
  648. * These values MAY be prepared from $_FILES or the message body during
  649. * instantiation, or MAY be injected via withUploadedFiles().
  650. *
  651. * @return array An array tree of UploadedFileInterface instances; an empty
  652. * array MUST be returned if no data is present.
  653. */
  654. public function getUploadedFiles();
  655. /**
  656. * Create a new instance with the specified uploaded files.
  657. *
  658. * This method MUST be implemented in such a way as to retain the
  659. * immutability of the message, and MUST return an instance that has the
  660. * updated body parameters.
  661. *
  662. * @param array $uploadedFiles An array tree of UploadedFileInterface instances.
  663. * @return static
  664. * @throws \InvalidArgumentException if an invalid structure is provided.
  665. */
  666. public function withUploadedFiles(array $uploadedFiles);
  667. /**
  668. * Retrieve any parameters provided in the request body.
  669. *
  670. * If the request Content-Type is either application/x-www-form-urlencoded
  671. * or multipart/form-data, and the request method is POST, this method MUST
  672. * return the contents of $_POST.
  673. *
  674. * Otherwise, this method may return any results of deserializing
  675. * the request body content; as parsing returns structured content, the
  676. * potential types MUST be arrays or objects only. A null value indicates
  677. * the absence of body content.
  678. *
  679. * @return null|array|object The deserialized body parameters, if any.
  680. * These will typically be an array or object.
  681. */
  682. public function getParsedBody();
  683. /**
  684. * Return an instance with the specified body parameters.
  685. *
  686. * These MAY be injected during instantiation.
  687. *
  688. * If the request Content-Type is either application/x-www-form-urlencoded
  689. * or multipart/form-data, and the request method is POST, use this method
  690. * ONLY to inject the contents of $_POST.
  691. *
  692. * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
  693. * deserializing the request body content. Deserialization/parsing returns
  694. * structured data, and, as such, this method ONLY accepts arrays or objects,
  695. * or a null value if nothing was available to parse.
  696. *
  697. * As an example, if content negotiation determines that the request data
  698. * is a JSON payload, this method could be used to create a request
  699. * instance with the deserialized parameters.
  700. *
  701. * This method MUST be implemented in such a way as to retain the
  702. * immutability of the message, and MUST return an instance that has the
  703. * updated body parameters.
  704. *
  705. * @param null|array|object $data The deserialized body data. This will
  706. * typically be in an array or object.
  707. * @return static
  708. * @throws \InvalidArgumentException if an unsupported argument type is
  709. * provided.
  710. */
  711. public function withParsedBody($data);
  712. /**
  713. * Retrieve attributes derived from the request.
  714. *
  715. * The request "attributes" may be used to allow injection of any
  716. * parameters derived from the request: e.g., the results of path
  717. * match operations; the results of decrypting cookies; the results of
  718. * deserializing non-form-encoded message bodies; etc. Attributes
  719. * will be application and request specific, and CAN be mutable.
  720. *
  721. * @return array Attributes derived from the request.
  722. */
  723. public function getAttributes();
  724. /**
  725. * Retrieve a single derived request attribute.
  726. *
  727. * Retrieves a single derived request attribute as described in
  728. * getAttributes(). If the attribute has not been previously set, returns
  729. * the default value as provided.
  730. *
  731. * This method obviates the need for a hasAttribute() method, as it allows
  732. * specifying a default value to return if the attribute is not found.
  733. *
  734. * @see getAttributes()
  735. * @param string $name The attribute name.
  736. * @param mixed $default Default value to return if the attribute does not exist.
  737. * @return mixed
  738. */
  739. public function getAttribute($name, $default = null);
  740. /**
  741. * Return an instance with the specified derived request attribute.
  742. *
  743. * This method allows setting a single derived request attribute as
  744. * described in getAttributes().
  745. *
  746. * This method MUST be implemented in such a way as to retain the
  747. * immutability of the message, and MUST return an instance that has the
  748. * updated attribute.
  749. *
  750. * @see getAttributes()
  751. * @param string $name The attribute name.
  752. * @param mixed $value The value of the attribute.
  753. * @return static
  754. */
  755. public function withAttribute($name, $value);
  756. /**
  757. * Return an instance that removes the specified derived request attribute.
  758. *
  759. * This method allows removing a single derived request attribute as
  760. * described in getAttributes().
  761. *
  762. * This method MUST be implemented in such a way as to retain the
  763. * immutability of the message, and MUST return an instance that removes
  764. * the attribute.
  765. *
  766. * @see getAttributes()
  767. * @param string $name The attribute name.
  768. * @return static
  769. */
  770. public function withoutAttribute($name);
  771. }
  772. }
  773. // file: vendor/psr/http-message/src/StreamInterface.php
  774. namespace Psr\Http\Message {
  775. /**
  776. * Describes a data stream.
  777. *
  778. * Typically, an instance will wrap a PHP stream; this interface provides
  779. * a wrapper around the most common operations, including serialization of
  780. * the entire stream to a string.
  781. */
  782. interface StreamInterface
  783. {
  784. /**
  785. * Reads all data from the stream into a string, from the beginning to end.
  786. *
  787. * This method MUST attempt to seek to the beginning of the stream before
  788. * reading data and read the stream until the end is reached.
  789. *
  790. * Warning: This could attempt to load a large amount of data into memory.
  791. *
  792. * This method MUST NOT raise an exception in order to conform with PHP's
  793. * string casting operations.
  794. *
  795. * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
  796. * @return string
  797. */
  798. public function __toString();
  799. /**
  800. * Closes the stream and any underlying resources.
  801. *
  802. * @return void
  803. */
  804. public function close();
  805. /**
  806. * Separates any underlying resources from the stream.
  807. *
  808. * After the stream has been detached, the stream is in an unusable state.
  809. *
  810. * @return resource|null Underlying PHP stream, if any
  811. */
  812. public function detach();
  813. /**
  814. * Get the size of the stream if known.
  815. *
  816. * @return int|null Returns the size in bytes if known, or null if unknown.
  817. */
  818. public function getSize();
  819. /**
  820. * Returns the current position of the file read/write pointer
  821. *
  822. * @return int Position of the file pointer
  823. * @throws \RuntimeException on error.
  824. */
  825. public function tell();
  826. /**
  827. * Returns true if the stream is at the end of the stream.
  828. *
  829. * @return bool
  830. */
  831. public function eof();
  832. /**
  833. * Returns whether or not the stream is seekable.
  834. *
  835. * @return bool
  836. */
  837. public function isSeekable();
  838. /**
  839. * Seek to a position in the stream.
  840. *
  841. * @link http://www.php.net/manual/en/function.fseek.php
  842. * @param int $offset Stream offset
  843. * @param int $whence Specifies how the cursor position will be calculated
  844. * based on the seek offset. Valid values are identical to the built-in
  845. * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
  846. * offset bytes SEEK_CUR: Set position to current location plus offset
  847. * SEEK_END: Set position to end-of-stream plus offset.
  848. * @throws \RuntimeException on failure.
  849. */
  850. public function seek($offset, $whence = SEEK_SET);
  851. /**
  852. * Seek to the beginning of the stream.
  853. *
  854. * If the stream is not seekable, this method will raise an exception;
  855. * otherwise, it will perform a seek(0).
  856. *
  857. * @see seek()
  858. * @link http://www.php.net/manual/en/function.fseek.php
  859. * @throws \RuntimeException on failure.
  860. */
  861. public function rewind();
  862. /**
  863. * Returns whether or not the stream is writable.
  864. *
  865. * @return bool
  866. */
  867. public function isWritable();
  868. /**
  869. * Write data to the stream.
  870. *
  871. * @param string $string The string that is to be written.
  872. * @return int Returns the number of bytes written to the stream.
  873. * @throws \RuntimeException on failure.
  874. */
  875. public function write($string);
  876. /**
  877. * Returns whether or not the stream is readable.
  878. *
  879. * @return bool
  880. */
  881. public function isReadable();
  882. /**
  883. * Read data from the stream.
  884. *
  885. * @param int $length Read up to $length bytes from the object and return
  886. * them. Fewer than $length bytes may be returned if underlying stream
  887. * call returns fewer bytes.
  888. * @return string Returns the data read from the stream, or an empty string
  889. * if no bytes are available.
  890. * @throws \RuntimeException if an error occurs.
  891. */
  892. public function read($length);
  893. /**
  894. * Returns the remaining contents in a string
  895. *
  896. * @return string
  897. * @throws \RuntimeException if unable to read or an error occurs while
  898. * reading.
  899. */
  900. public function getContents();
  901. /**
  902. * Get stream metadata as an associative array or retrieve a specific key.
  903. *
  904. * The keys returned are identical to the keys returned from PHP's
  905. * stream_get_meta_data() function.
  906. *
  907. * @link http://php.net/manual/en/function.stream-get-meta-data.php
  908. * @param string $key Specific metadata to retrieve.
  909. * @return array|mixed|null Returns an associative array if no key is
  910. * provided. Returns a specific key value if a key is provided and the
  911. * value is found, or null if the key is not found.
  912. */
  913. public function getMetadata($key = null);
  914. }
  915. }
  916. // file: vendor/psr/http-message/src/UploadedFileInterface.php
  917. namespace Psr\Http\Message {
  918. /**
  919. * Value object representing a file uploaded through an HTTP request.
  920. *
  921. * Instances of this interface are considered immutable; all methods that
  922. * might change state MUST be implemented such that they retain the internal
  923. * state of the current instance and return an instance that contains the
  924. * changed state.
  925. */
  926. interface UploadedFileInterface
  927. {
  928. /**
  929. * Retrieve a stream representing the uploaded file.
  930. *
  931. * This method MUST return a StreamInterface instance, representing the
  932. * uploaded file. The purpose of this method is to allow utilizing native PHP
  933. * stream functionality to manipulate the file upload, such as
  934. * stream_copy_to_stream() (though the result will need to be decorated in a
  935. * native PHP stream wrapper to work with such functions).
  936. *
  937. * If the moveTo() method has been called previously, this method MUST raise
  938. * an exception.
  939. *
  940. * @return StreamInterface Stream representation of the uploaded file.
  941. * @throws \RuntimeException in cases when no stream is available or can be
  942. * created.
  943. */
  944. public function getStream();
  945. /**
  946. * Move the uploaded file to a new location.
  947. *
  948. * Use this method as an alternative to move_uploaded_file(). This method is
  949. * guaranteed to work in both SAPI and non-SAPI environments.
  950. * Implementations must determine which environment they are in, and use the
  951. * appropriate method (move_uploaded_file(), rename(), or a stream
  952. * operation) to perform the operation.
  953. *
  954. * $targetPath may be an absolute path, or a relative path. If it is a
  955. * relative path, resolution should be the same as used by PHP's rename()
  956. * function.
  957. *
  958. * The original file or stream MUST be removed on completion.
  959. *
  960. * If this method is called more than once, any subsequent calls MUST raise
  961. * an exception.
  962. *
  963. * When used in an SAPI environment where $_FILES is populated, when writing
  964. * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
  965. * used to ensure permissions and upload status are verified correctly.
  966. *
  967. * If you wish to move to a stream, use getStream(), as SAPI operations
  968. * cannot guarantee writing to stream destinations.
  969. *
  970. * @see http://php.net/is_uploaded_file
  971. * @see http://php.net/move_uploaded_file
  972. * @param string $targetPath Path to which to move the uploaded file.
  973. * @throws \InvalidArgumentException if the $targetPath specified is invalid.
  974. * @throws \RuntimeException on any error during the move operation, or on
  975. * the second or subsequent call to the method.
  976. */
  977. public function moveTo($targetPath);
  978. /**
  979. * Retrieve the file size.
  980. *
  981. * Implementations SHOULD return the value stored in the "size" key of
  982. * the file in the $_FILES array if available, as PHP calculates this based
  983. * on the actual size transmitted.
  984. *
  985. * @return int|null The file size in bytes or null if unknown.
  986. */
  987. public function getSize();
  988. /**
  989. * Retrieve the error associated with the uploaded file.
  990. *
  991. * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
  992. *
  993. * If the file was uploaded successfully, this method MUST return
  994. * UPLOAD_ERR_OK.
  995. *
  996. * Implementations SHOULD return the value stored in the "error" key of
  997. * the file in the $_FILES array.
  998. *
  999. * @see http://php.net/manual/en/features.file-upload.errors.php
  1000. * @return int One of PHP's UPLOAD_ERR_XXX constants.
  1001. */
  1002. public function getError();
  1003. /**
  1004. * Retrieve the filename sent by the client.
  1005. *
  1006. * Do not trust the value returned by this method. A client could send
  1007. * a malicious filename with the intention to corrupt or hack your
  1008. * application.
  1009. *
  1010. * Implementations SHOULD return the value stored in the "name" key of
  1011. * the file in the $_FILES array.
  1012. *
  1013. * @return string|null The filename sent by the client or null if none
  1014. * was provided.
  1015. */
  1016. public function getClientFilename();
  1017. /**
  1018. * Retrieve the media type sent by the client.
  1019. *
  1020. * Do not trust the value returned by this method. A client could send
  1021. * a malicious media type with the intention to corrupt or hack your
  1022. * application.
  1023. *
  1024. * Implementations SHOULD return the value stored in the "type" key of
  1025. * the file in the $_FILES array.
  1026. *
  1027. * @return string|null The media type sent by the client or null if none
  1028. * was provided.
  1029. */
  1030. public function getClientMediaType();
  1031. }
  1032. }
  1033. // file: vendor/psr/http-message/src/UriInterface.php
  1034. namespace Psr\Http\Message {
  1035. /**
  1036. * Value object representing a URI.
  1037. *
  1038. * This interface is meant to represent URIs according to RFC 3986 and to
  1039. * provide methods for most common operations. Additional functionality for
  1040. * working with URIs can be provided on top of the interface or externally.
  1041. * Its primary use is for HTTP requests, but may also be used in other
  1042. * contexts.
  1043. *
  1044. * Instances of this interface are considered immutable; all methods that
  1045. * might change state MUST be implemented such that they retain the internal
  1046. * state of the current instance and return an instance that contains the
  1047. * changed state.
  1048. *
  1049. * Typically the Host header will be also be present in the request message.
  1050. * For server-side requests, the scheme will typically be discoverable in the
  1051. * server parameters.
  1052. *
  1053. * @link http://tools.ietf.org/html/rfc3986 (the URI specification)
  1054. */
  1055. interface UriInterface
  1056. {
  1057. /**
  1058. * Retrieve the scheme component of the URI.
  1059. *
  1060. * If no scheme is present, this method MUST return an empty string.
  1061. *
  1062. * The value returned MUST be normalized to lowercase, per RFC 3986
  1063. * Section 3.1.
  1064. *
  1065. * The trailing ":" character is not part of the scheme and MUST NOT be
  1066. * added.
  1067. *
  1068. * @see https://tools.ietf.org/html/rfc3986#section-3.1
  1069. * @return string The URI scheme.
  1070. */
  1071. public function getScheme();
  1072. /**
  1073. * Retrieve the authority component of the URI.
  1074. *
  1075. * If no authority information is present, this method MUST return an empty
  1076. * string.
  1077. *
  1078. * The authority syntax of the URI is:
  1079. *
  1080. * <pre>
  1081. * [user-info@]host[:port]
  1082. * </pre>
  1083. *
  1084. * If the port component is not set or is the standard port for the current
  1085. * scheme, it SHOULD NOT be included.
  1086. *
  1087. * @see https://tools.ietf.org/html/rfc3986#section-3.2
  1088. * @return string The URI authority, in "[user-info@]host[:port]" format.
  1089. */
  1090. public function getAuthority();
  1091. /**
  1092. * Retrieve the user information component of the URI.
  1093. *
  1094. * If no user information is present, this method MUST return an empty
  1095. * string.
  1096. *
  1097. * If a user is present in the URI, this will return that value;
  1098. * additionally, if the password is also present, it will be appended to the
  1099. * user value, with a colon (":") separating the values.
  1100. *
  1101. * The trailing "@" character is not part of the user information and MUST
  1102. * NOT be added.
  1103. *
  1104. * @return string The URI user information, in "username[:password]" format.
  1105. */
  1106. public function getUserInfo();
  1107. /**
  1108. * Retrieve the host component of the URI.
  1109. *
  1110. * If no host is present, this method MUST return an empty string.
  1111. *
  1112. * The value returned MUST be normalized to lowercase, per RFC 3986
  1113. * Section 3.2.2.
  1114. *
  1115. * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
  1116. * @return string The URI host.
  1117. */
  1118. public function getHost();
  1119. /**
  1120. * Retrieve the port component of the URI.
  1121. *
  1122. * If a port is present, and it is non-standard for the current scheme,
  1123. * this method MUST return it as an integer. If the port is the standard port
  1124. * used with the current scheme, this method SHOULD return null.
  1125. *
  1126. * If no port is present, and no scheme is present, this method MUST return
  1127. * a null value.
  1128. *
  1129. * If no port is present, but a scheme is present, this method MAY return
  1130. * the standard port for that scheme, but SHOULD return null.
  1131. *
  1132. * @return null|int The URI port.
  1133. */
  1134. public function getPort();
  1135. /**
  1136. * Retrieve the path component of the URI.
  1137. *
  1138. * The path can either be empty or absolute (starting with a slash) or
  1139. * rootless (not starting with a slash). Implementations MUST support all
  1140. * three syntaxes.
  1141. *
  1142. * Normally, the empty path "" and absolute path "/" are considered equal as
  1143. * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
  1144. * do this normalization because in contexts with a trimmed base path, e.g.
  1145. * the front controller, this difference becomes significant. It's the task
  1146. * of the user to handle both "" and "/".
  1147. *
  1148. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1149. * any characters. To determine what characters to encode, please refer to
  1150. * RFC 3986, Sections 2 and 3.3.
  1151. *
  1152. * As an example, if the value should include a slash ("/") not intended as
  1153. * delimiter between path segments, that value MUST be passed in encoded
  1154. * form (e.g., "%2F") to the instance.
  1155. *
  1156. * @see https://tools.ietf.org/html/rfc3986#section-2
  1157. * @see https://tools.ietf.org/html/rfc3986#section-3.3
  1158. * @return string The URI path.
  1159. */
  1160. public function getPath();
  1161. /**
  1162. * Retrieve the query string of the URI.
  1163. *
  1164. * If no query string is present, this method MUST return an empty string.
  1165. *
  1166. * The leading "?" character is not part of the query and MUST NOT be
  1167. * added.
  1168. *
  1169. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1170. * any characters. To determine what characters to encode, please refer to
  1171. * RFC 3986, Sections 2 and 3.4.
  1172. *
  1173. * As an example, if a value in a key/value pair of the query string should
  1174. * include an ampersand ("&") not intended as a delimiter between values,
  1175. * that value MUST be passed in encoded form (e.g., "%26") to the instance.
  1176. *
  1177. * @see https://tools.ietf.org/html/rfc3986#section-2
  1178. * @see https://tools.ietf.org/html/rfc3986#section-3.4
  1179. * @return string The URI query string.
  1180. */
  1181. public function getQuery();
  1182. /**
  1183. * Retrieve the fragment component of the URI.
  1184. *
  1185. * If no fragment is present, this method MUST return an empty string.
  1186. *
  1187. * The leading "#" character is not part of the fragment and MUST NOT be
  1188. * added.
  1189. *
  1190. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  1191. * any characters. To determine what characters to encode, please refer to
  1192. * RFC 3986, Sections 2 and 3.5.
  1193. *
  1194. * @see https://tools.ietf.org/html/rfc3986#section-2
  1195. * @see https://tools.ietf.org/html/rfc3986#section-3.5
  1196. * @return string The URI fragment.
  1197. */
  1198. public function getFragment();
  1199. /**
  1200. * Return an instance with the specified scheme.
  1201. *
  1202. * This method MUST retain the state of the current instance, and return
  1203. * an instance that contains the specified scheme.
  1204. *
  1205. * Implementations MUST support the schemes "http" and "https" case
  1206. * insensitively, and MAY accommodate other schemes if required.
  1207. *
  1208. * An empty scheme is equivalent to removing the scheme.
  1209. *
  1210. * @param string $scheme The scheme to use with the new instance.
  1211. * @return static A new instance with the specified scheme.
  1212. * @throws \InvalidArgumentException for invalid or unsupported schemes.
  1213. */
  1214. public function withScheme($scheme);
  1215. /**
  1216. * Return an instance with the specified user information.
  1217. *
  1218. * This method MUST retain the state of the current instance, and return
  1219. * an instance that contains the specified user information.
  1220. *
  1221. * Password is optional, but the user information MUST include the
  1222. * user; an empty string for the user is equivalent to removing user
  1223. * information.
  1224. *
  1225. * @param string $user The user name to use for authority.
  1226. * @param null|string $password The password associated with $user.
  1227. * @return static A new instance with the specified user information.
  1228. */
  1229. public function withUserInfo($user, $password = null);
  1230. /**
  1231. * Return an instance with the specified host.
  1232. *
  1233. * This method MUST retain the state of the current instance, and return
  1234. * an instance that contains the specified host.
  1235. *
  1236. * An empty host value is equivalent to removing the host.
  1237. *
  1238. * @param string $host The hostname to use with the new instance.
  1239. * @return static A new instance with the specified host.
  1240. * @throws \InvalidArgumentException for invalid hostnames.
  1241. */
  1242. public function withHost($host);
  1243. /**
  1244. * Return an instance with the specified port.
  1245. *
  1246. * This method MUST retain the state of the current instance, and return
  1247. * an instance that contains the specified port.
  1248. *
  1249. * Implementations MUST raise an exception for ports outside the
  1250. * established TCP and UDP port ranges.
  1251. *
  1252. * A null value provided for the port is equivalent to removing the port
  1253. * information.
  1254. *
  1255. * @param null|int $port The port to use with the new instance; a null value
  1256. * removes the port information.
  1257. * @return static A new instance with the specified port.
  1258. * @throws \InvalidArgumentException for invalid ports.
  1259. */
  1260. public function withPort($port);
  1261. /**
  1262. * Return an instance with the specified path.
  1263. *
  1264. * This method MUST retain the state of the current instance, and return
  1265. * an instance that contains the specified path.
  1266. *
  1267. * The path can either be empty or absolute (starting with a slash) or
  1268. * rootless (not starting with a slash). Implementations MUST support all
  1269. * three syntaxes.
  1270. *
  1271. * If the path is intended to be domain-relative rather than path relative then
  1272. * it must begin with a slash ("/"). Paths not starting with a slash ("/")
  1273. * are assumed to be relative to some base path known to the application or
  1274. * consumer.
  1275. *
  1276. * Users can provide both encoded and decoded path characters.
  1277. * Implementations ensure the correct encoding as outlined in getPath().
  1278. *
  1279. * @param string $path The path to use with the new instance.
  1280. * @return static A new instance with the specified path.
  1281. * @throws \InvalidArgumentException for invalid paths.
  1282. */
  1283. public function withPath($path);
  1284. /**
  1285. * Return an instance with the specified query string.
  1286. *
  1287. * This method MUST retain the state of the current instance, and return
  1288. * an instance that contains the specified query string.
  1289. *
  1290. * Users can provide both encoded and decoded query characters.
  1291. * Implementations ensure the correct encoding as outlined in getQuery().
  1292. *
  1293. * An empty query string value is equivalent to removing the query string.
  1294. *
  1295. * @param string $query The query string to use with the new instance.
  1296. * @return static A new instance with the specified query string.
  1297. * @throws \InvalidArgumentException for invalid query strings.
  1298. */
  1299. public function withQuery($query);
  1300. /**
  1301. * Return an instance with the specified URI fragment.
  1302. *
  1303. * This method MUST retain the state of the current instance, and return
  1304. * an instance that contains the specified URI fragment.
  1305. *
  1306. * Users can provide both encoded and decoded fragment characters.
  1307. * Implementations ensure the correct encoding as outlined in getFragment().
  1308. *
  1309. * An empty fragment value is equivalent to removing the fragment.
  1310. *
  1311. * @param string $fragment The fragment to use with the new instance.
  1312. * @return static A new instance with the specified fragment.
  1313. */
  1314. public function withFragment($fragment);
  1315. /**
  1316. * Return the string representation as a URI reference.
  1317. *
  1318. * Depending on which components of the URI are present, the resulting
  1319. * string is either a full URI or relative reference according to RFC 3986,
  1320. * Section 4.1. The method concatenates the various components of the URI,
  1321. * using the appropriate delimiters:
  1322. *
  1323. * - If a scheme is present, it MUST be suffixed by ":".
  1324. * - If an authority is present, it MUST be prefixed by "//".
  1325. * - The path can be concatenated without delimiters. But there are two
  1326. * cases where the path has to be adjusted to make the URI reference
  1327. * valid as PHP does not allow to throw an exception in __toString():
  1328. * - If the path is rootless and an authority is present, the path MUST
  1329. * be prefixed by "/".
  1330. * - If the path is starting with more than one "/" and no authority is
  1331. * present, the starting slashes MUST be reduced to one.
  1332. * - If a query is present, it MUST be prefixed by "?".
  1333. * - If a fragment is present, it MUST be prefixed by "#".
  1334. *
  1335. * @see http://tools.ietf.org/html/rfc3986#section-4.1
  1336. * @return string
  1337. */
  1338. public function __toString();
  1339. }
  1340. }
  1341. // file: vendor/psr/http-server-handler/src/RequestHandlerInterface.php
  1342. namespace Psr\Http\Server {
  1343. use Psr\Http\Message\ResponseInterface;
  1344. use Psr\Http\Message\ServerRequestInterface;
  1345. /**
  1346. * Handles a server request and produces a response.
  1347. *
  1348. * An HTTP request handler process an HTTP request in order to produce an
  1349. * HTTP response.
  1350. */
  1351. interface RequestHandlerInterface
  1352. {
  1353. /**
  1354. * Handles a request and produces a response.
  1355. *
  1356. * May call other collaborating code to generate the response.
  1357. */
  1358. public function handle(ServerRequestInterface $request): ResponseInterface;
  1359. }
  1360. }
  1361. // file: vendor/psr/http-server-middleware/src/MiddlewareInterface.php
  1362. namespace Psr\Http\Server {
  1363. use Psr\Http\Message\ResponseInterface;
  1364. use Psr\Http\Message\ServerRequestInterface;
  1365. /**
  1366. * Participant in processing a server request and response.
  1367. *
  1368. * An HTTP middleware component participates in processing an HTTP message:
  1369. * by acting on the request, generating the response, or forwarding the
  1370. * request to a subsequent middleware and possibly acting on its response.
  1371. */
  1372. interface MiddlewareInterface
  1373. {
  1374. /**
  1375. * Process an incoming server request.
  1376. *
  1377. * Processes an incoming server request in order to produce a response.
  1378. * If unable to produce the response itself, it may delegate to the provided
  1379. * request handler to do so.
  1380. */
  1381. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
  1382. }
  1383. }
  1384. // file: vendor/nyholm/psr7/src/Factory/Psr17Factory.php
  1385. namespace Nyholm\Psr7\Factory {
  1386. use Nyholm\Psr7\{Request, Response, ServerRequest, Stream, UploadedFile, Uri};
  1387. use Psr\Http\Message\{RequestFactoryInterface, RequestInterface, ResponseFactoryInterface, ResponseInterface, ServerRequestFactoryInterface, ServerRequestInterface, StreamFactoryInterface, StreamInterface, UploadedFileFactoryInterface, UploadedFileInterface, UriFactoryInterface, UriInterface};
  1388. /**
  1389. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1390. * @author Martijn van der Ven <martijn@vanderven.se>
  1391. */
  1392. final class Psr17Factory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
  1393. {
  1394. public function createRequest(string $method, $uri): RequestInterface
  1395. {
  1396. return new Request($method, $uri);
  1397. }
  1398. public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface
  1399. {
  1400. if (2 > \func_num_args()) {
  1401. // This will make the Response class to use a custom reasonPhrase
  1402. $reasonPhrase = null;
  1403. }
  1404. return new Response($code, [], null, '1.1', $reasonPhrase);
  1405. }
  1406. public function createStream(string $content = ''): StreamInterface
  1407. {
  1408. return Stream::create($content);
  1409. }
  1410. public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
  1411. {
  1412. $resource = @\fopen($filename, $mode);
  1413. if (false === $resource) {
  1414. if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'])) {
  1415. throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.');
  1416. }
  1417. throw new \RuntimeException('The file ' . $filename . ' cannot be opened.');
  1418. }
  1419. return Stream::create($resource);
  1420. }
  1421. public function createStreamFromResource($resource): StreamInterface
  1422. {
  1423. return Stream::create($resource);
  1424. }
  1425. public function createUploadedFile(StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null): UploadedFileInterface
  1426. {
  1427. if (null === $size) {
  1428. $size = $stream->getSize();
  1429. }
  1430. return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);
  1431. }
  1432. public function createUri(string $uri = ''): UriInterface
  1433. {
  1434. return new Uri($uri);
  1435. }
  1436. public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  1437. {
  1438. return new ServerRequest($method, $uri, [], null, '1.1', $serverParams);
  1439. }
  1440. }
  1441. }
  1442. // file: vendor/nyholm/psr7/src/MessageTrait.php
  1443. namespace Nyholm\Psr7 {
  1444. use Psr\Http\Message\StreamInterface;
  1445. /**
  1446. * Trait implementing functionality common to requests and responses.
  1447. *
  1448. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1449. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1450. * @author Martijn van der Ven <martijn@vanderven.se>
  1451. *
  1452. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1453. */
  1454. trait MessageTrait
  1455. {
  1456. /** @var array Map of all registered headers, as original name => array of values */
  1457. private $headers = [];
  1458. /** @var array Map of lowercase header name => original name at registration */
  1459. private $headerNames = [];
  1460. /** @var string */
  1461. private $protocol = '1.1';
  1462. /** @var StreamInterface|null */
  1463. private $stream;
  1464. public function getProtocolVersion(): string
  1465. {
  1466. return $this->protocol;
  1467. }
  1468. public function withProtocolVersion($version): self
  1469. {
  1470. if ($this->protocol === $version) {
  1471. return $this;
  1472. }
  1473. $new = clone $this;
  1474. $new->protocol = $version;
  1475. return $new;
  1476. }
  1477. public function getHeaders(): array
  1478. {
  1479. return $this->headers;
  1480. }
  1481. public function hasHeader($header): bool
  1482. {
  1483. return isset($this->headerNames[\strtolower($header)]);
  1484. }
  1485. public function getHeader($header): array
  1486. {
  1487. $header = \strtolower($header);
  1488. if (!isset($this->headerNames[$header])) {
  1489. return [];
  1490. }
  1491. $header = $this->headerNames[$header];
  1492. return $this->headers[$header];
  1493. }
  1494. public function getHeaderLine($header): string
  1495. {
  1496. return \implode(', ', $this->getHeader($header));
  1497. }
  1498. public function withHeader($header, $value): self
  1499. {
  1500. $value = $this->validateAndTrimHeader($header, $value);
  1501. $normalized = \strtolower($header);
  1502. $new = clone $this;
  1503. if (isset($new->headerNames[$normalized])) {
  1504. unset($new->headers[$new->headerNames[$normalized]]);
  1505. }
  1506. $new->headerNames[$normalized] = $header;
  1507. $new->headers[$header] = $value;
  1508. return $new;
  1509. }
  1510. public function withAddedHeader($header, $value): self
  1511. {
  1512. if (!\is_string($header) || '' === $header) {
  1513. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1514. }
  1515. $new = clone $this;
  1516. $new->setHeaders([$header => $value]);
  1517. return $new;
  1518. }
  1519. public function withoutHeader($header): self
  1520. {
  1521. $normalized = \strtolower($header);
  1522. if (!isset($this->headerNames[$normalized])) {
  1523. return $this;
  1524. }
  1525. $header = $this->headerNames[$normalized];
  1526. $new = clone $this;
  1527. unset($new->headers[$header], $new->headerNames[$normalized]);
  1528. return $new;
  1529. }
  1530. public function getBody(): StreamInterface
  1531. {
  1532. if (null === $this->stream) {
  1533. $this->stream = Stream::create('');
  1534. }
  1535. return $this->stream;
  1536. }
  1537. public function withBody(StreamInterface $body): self
  1538. {
  1539. if ($body === $this->stream) {
  1540. return $this;
  1541. }
  1542. $new = clone $this;
  1543. $new->stream = $body;
  1544. return $new;
  1545. }
  1546. private function setHeaders(array $headers) /*:void*/
  1547. {
  1548. foreach ($headers as $header => $value) {
  1549. $value = $this->validateAndTrimHeader($header, $value);
  1550. $normalized = \strtolower($header);
  1551. if (isset($this->headerNames[$normalized])) {
  1552. $header = $this->headerNames[$normalized];
  1553. $this->headers[$header] = \array_merge($this->headers[$header], $value);
  1554. } else {
  1555. $this->headerNames[$normalized] = $header;
  1556. $this->headers[$header] = $value;
  1557. }
  1558. }
  1559. }
  1560. /**
  1561. * Make sure the header complies with RFC 7230.
  1562. *
  1563. * Header names must be a non-empty string consisting of token characters.
  1564. *
  1565. * Header values must be strings consisting of visible characters with all optional
  1566. * leading and trailing whitespace stripped. This method will always strip such
  1567. * optional whitespace. Note that the method does not allow folding whitespace within
  1568. * the values as this was deprecated for almost all instances by the RFC.
  1569. *
  1570. * header-field = field-name ":" OWS field-value OWS
  1571. * field-name = 1*( "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^"
  1572. * / "_" / "`" / "|" / "~" / %x30-39 / ( %x41-5A / %x61-7A ) )
  1573. * OWS = *( SP / HTAB )
  1574. * field-value = *( ( %x21-7E / %x80-FF ) [ 1*( SP / HTAB ) ( %x21-7E / %x80-FF ) ] )
  1575. *
  1576. * @see https://tools.ietf.org/html/rfc7230#section-3.2.4
  1577. */
  1578. private function validateAndTrimHeader($header, $values): array
  1579. {
  1580. if (!\is_string($header) || 1 !== \preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@", $header)) {
  1581. throw new \InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
  1582. }
  1583. if (!\is_array($values)) {
  1584. // This is simple, just one value.
  1585. if ((!\is_numeric($values) && !\is_string($values)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $values)) {
  1586. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1587. }
  1588. return [\trim((string) $values, " \t")];
  1589. }
  1590. if (empty($values)) {
  1591. throw new \InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
  1592. }
  1593. // Assert Non empty array
  1594. $returnValues = [];
  1595. foreach ($values as $v) {
  1596. if ((!\is_numeric($v) && !\is_string($v)) || 1 !== \preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", (string) $v)) {
  1597. throw new \InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
  1598. }
  1599. $returnValues[] = \trim((string) $v, " \t");
  1600. }
  1601. return $returnValues;
  1602. }
  1603. }
  1604. }
  1605. // file: vendor/nyholm/psr7/src/Request.php
  1606. namespace Nyholm\Psr7 {
  1607. use Psr\Http\Message\{RequestInterface, StreamInterface, UriInterface};
  1608. /**
  1609. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1610. * @author Martijn van der Ven <martijn@vanderven.se>
  1611. */
  1612. final class Request implements RequestInterface
  1613. {
  1614. use MessageTrait;
  1615. use RequestTrait;
  1616. /**
  1617. * @param string $method HTTP method
  1618. * @param string|UriInterface $uri URI
  1619. * @param array $headers Request headers
  1620. * @param string|resource|StreamInterface|null $body Request body
  1621. * @param string $version Protocol version
  1622. */
  1623. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
  1624. {
  1625. if (!($uri instanceof UriInterface)) {
  1626. $uri = new Uri($uri);
  1627. }
  1628. $this->method = $method;
  1629. $this->uri = $uri;
  1630. $this->setHeaders($headers);
  1631. $this->protocol = $version;
  1632. if (!$this->hasHeader('Host')) {
  1633. $this->updateHostFromUri();
  1634. }
  1635. // If we got no body, defer initialization of the stream until Request::getBody()
  1636. if ('' !== $body && null !== $body) {
  1637. $this->stream = Stream::create($body);
  1638. }
  1639. }
  1640. }
  1641. }
  1642. // file: vendor/nyholm/psr7/src/RequestTrait.php
  1643. namespace Nyholm\Psr7 {
  1644. use Psr\Http\Message\UriInterface;
  1645. /**
  1646. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1647. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1648. * @author Martijn van der Ven <martijn@vanderven.se>
  1649. *
  1650. * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
  1651. */
  1652. trait RequestTrait
  1653. {
  1654. /** @var string */
  1655. private $method;
  1656. /** @var string|null */
  1657. private $requestTarget;
  1658. /** @var UriInterface|null */
  1659. private $uri;
  1660. public function getRequestTarget(): string
  1661. {
  1662. if (null !== $this->requestTarget) {
  1663. return $this->requestTarget;
  1664. }
  1665. if ('' === $target = $this->uri->getPath()) {
  1666. $target = '/';
  1667. }
  1668. if ('' !== $this->uri->getQuery()) {
  1669. $target .= '?' . $this->uri->getQuery();
  1670. }
  1671. return $target;
  1672. }
  1673. public function withRequestTarget($requestTarget): self
  1674. {
  1675. if (\preg_match('#\s#', $requestTarget)) {
  1676. throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
  1677. }
  1678. $new = clone $this;
  1679. $new->requestTarget = $requestTarget;
  1680. return $new;
  1681. }
  1682. public function getMethod(): string
  1683. {
  1684. return $this->method;
  1685. }
  1686. public function withMethod($method): self
  1687. {
  1688. if (!\is_string($method)) {
  1689. throw new \InvalidArgumentException('Method must be a string');
  1690. }
  1691. $new = clone $this;
  1692. $new->method = $method;
  1693. return $new;
  1694. }
  1695. public function getUri(): UriInterface
  1696. {
  1697. return $this->uri;
  1698. }
  1699. public function withUri(UriInterface $uri, $preserveHost = false): self
  1700. {
  1701. if ($uri === $this->uri) {
  1702. return $this;
  1703. }
  1704. $new = clone $this;
  1705. $new->uri = $uri;
  1706. if (!$preserveHost || !$this->hasHeader('Host')) {
  1707. $new->updateHostFromUri();
  1708. }
  1709. return $new;
  1710. }
  1711. private function updateHostFromUri() /*:void*/
  1712. {
  1713. if ('' === $host = $this->uri->getHost()) {
  1714. return;
  1715. }
  1716. if (null !== ($port = $this->uri->getPort())) {
  1717. $host .= ':' . $port;
  1718. }
  1719. if (isset($this->headerNames['host'])) {
  1720. $header = $this->headerNames['host'];
  1721. } else {
  1722. $this->headerNames['host'] = $header = 'Host';
  1723. }
  1724. // Ensure Host is the first header.
  1725. // See: http://tools.ietf.org/html/rfc7230#section-5.4
  1726. $this->headers = [$header => [$host]] + $this->headers;
  1727. }
  1728. }
  1729. }
  1730. // file: vendor/nyholm/psr7/src/Response.php
  1731. namespace Nyholm\Psr7 {
  1732. use Psr\Http\Message\{ResponseInterface, StreamInterface};
  1733. /**
  1734. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1735. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1736. * @author Martijn van der Ven <martijn@vanderven.se>
  1737. */
  1738. final class Response implements ResponseInterface
  1739. {
  1740. use MessageTrait;
  1741. /** @var array Map of standard HTTP status code/reason phrases */
  1742. /*private*/ const PHRASES = [
  1743. 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing',
  1744. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported',
  1745. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect',
  1746. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons',
  1747. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 511 => 'Network Authentication Required',
  1748. ];
  1749. /** @var string */
  1750. private $reasonPhrase = '';
  1751. /** @var int */
  1752. private $statusCode;
  1753. /**
  1754. * @param int $status Status code
  1755. * @param array $headers Response headers
  1756. * @param string|resource|StreamInterface|null $body Response body
  1757. * @param string $version Protocol version
  1758. * @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
  1759. */
  1760. public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
  1761. {
  1762. // If we got no body, defer initialization of the stream until Response::getBody()
  1763. if ('' !== $body && null !== $body) {
  1764. $this->stream = Stream::create($body);
  1765. }
  1766. $this->statusCode = $status;
  1767. $this->setHeaders($headers);
  1768. if (null === $reason && isset(self::PHRASES[$this->statusCode])) {
  1769. $this->reasonPhrase = self::PHRASES[$status];
  1770. } else {
  1771. $this->reasonPhrase = $reason ?? '';
  1772. }
  1773. $this->protocol = $version;
  1774. }
  1775. public function getStatusCode(): int
  1776. {
  1777. return $this->statusCode;
  1778. }
  1779. public function getReasonPhrase(): string
  1780. {
  1781. return $this->reasonPhrase;
  1782. }
  1783. public function withStatus($code, $reasonPhrase = ''): self
  1784. {
  1785. if (!\is_int($code) && !\is_string($code)) {
  1786. throw new \InvalidArgumentException('Status code has to be an integer');
  1787. }
  1788. $code = (int) $code;
  1789. if ($code < 100 || $code > 599) {
  1790. throw new \InvalidArgumentException('Status code has to be an integer between 100 and 599');
  1791. }
  1792. $new = clone $this;
  1793. $new->statusCode = $code;
  1794. if ((null === $reasonPhrase || '' === $reasonPhrase) && isset(self::PHRASES[$new->statusCode])) {
  1795. $reasonPhrase = self::PHRASES[$new->statusCode];
  1796. }
  1797. $new->reasonPhrase = $reasonPhrase;
  1798. return $new;
  1799. }
  1800. }
  1801. }
  1802. // file: vendor/nyholm/psr7/src/ServerRequest.php
  1803. namespace Nyholm\Psr7 {
  1804. use Psr\Http\Message\{ServerRequestInterface, StreamInterface, UploadedFileInterface, UriInterface};
  1805. /**
  1806. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1807. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1808. * @author Martijn van der Ven <martijn@vanderven.se>
  1809. */
  1810. final class ServerRequest implements ServerRequestInterface
  1811. {
  1812. use MessageTrait;
  1813. use RequestTrait;
  1814. /** @var array */
  1815. private $attributes = [];
  1816. /** @var array */
  1817. private $cookieParams = [];
  1818. /** @var array|object|null */
  1819. private $parsedBody;
  1820. /** @var array */
  1821. private $queryParams = [];
  1822. /** @var array */
  1823. private $serverParams;
  1824. /** @var UploadedFileInterface[] */
  1825. private $uploadedFiles = [];
  1826. /**
  1827. * @param string $method HTTP method
  1828. * @param string|UriInterface $uri URI
  1829. * @param array $headers Request headers
  1830. * @param string|resource|StreamInterface|null $body Request body
  1831. * @param string $version Protocol version
  1832. * @param array $serverParams Typically the $_SERVER superglobal
  1833. */
  1834. public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
  1835. {
  1836. $this->serverParams = $serverParams;
  1837. if (!($uri instanceof UriInterface)) {
  1838. $uri = new Uri($uri);
  1839. }
  1840. $this->method = $method;
  1841. $this->uri = $uri;
  1842. $this->setHeaders($headers);
  1843. $this->protocol = $version;
  1844. if (!$this->hasHeader('Host')) {
  1845. $this->updateHostFromUri();
  1846. }
  1847. // If we got no body, defer initialization of the stream until ServerRequest::getBody()
  1848. if ('' !== $body && null !== $body) {
  1849. $this->stream = Stream::create($body);
  1850. }
  1851. }
  1852. public function getServerParams(): array
  1853. {
  1854. return $this->serverParams;
  1855. }
  1856. public function getUploadedFiles(): array
  1857. {
  1858. return $this->uploadedFiles;
  1859. }
  1860. public function withUploadedFiles(array $uploadedFiles)
  1861. {
  1862. $new = clone $this;
  1863. $new->uploadedFiles = $uploadedFiles;
  1864. return $new;
  1865. }
  1866. public function getCookieParams(): array
  1867. {
  1868. return $this->cookieParams;
  1869. }
  1870. public function withCookieParams(array $cookies)
  1871. {
  1872. $new = clone $this;
  1873. $new->cookieParams = $cookies;
  1874. return $new;
  1875. }
  1876. public function getQueryParams(): array
  1877. {
  1878. return $this->queryParams;
  1879. }
  1880. public function withQueryParams(array $query)
  1881. {
  1882. $new = clone $this;
  1883. $new->queryParams = $query;
  1884. return $new;
  1885. }
  1886. public function getParsedBody()
  1887. {
  1888. return $this->parsedBody;
  1889. }
  1890. public function withParsedBody($data)
  1891. {
  1892. if (!\is_array($data) && !\is_object($data) && null !== $data) {
  1893. throw new \InvalidArgumentException('First parameter to withParsedBody MUST be object, array or null');
  1894. }
  1895. $new = clone $this;
  1896. $new->parsedBody = $data;
  1897. return $new;
  1898. }
  1899. public function getAttributes(): array
  1900. {
  1901. return $this->attributes;
  1902. }
  1903. public function getAttribute($attribute, $default = null)
  1904. {
  1905. if (false === \array_key_exists($attribute, $this->attributes)) {
  1906. return $default;
  1907. }
  1908. return $this->attributes[$attribute];
  1909. }
  1910. public function withAttribute($attribute, $value): self
  1911. {
  1912. $new = clone $this;
  1913. $new->attributes[$attribute] = $value;
  1914. return $new;
  1915. }
  1916. public function withoutAttribute($attribute): self
  1917. {
  1918. if (false === \array_key_exists($attribute, $this->attributes)) {
  1919. return $this;
  1920. }
  1921. $new = clone $this;
  1922. unset($new->attributes[$attribute]);
  1923. return $new;
  1924. }
  1925. }
  1926. }
  1927. // file: vendor/nyholm/psr7/src/Stream.php
  1928. namespace Nyholm\Psr7 {
  1929. use Psr\Http\Message\StreamInterface;
  1930. /**
  1931. * @author Michael Dowling and contributors to guzzlehttp/psr7
  1932. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  1933. * @author Martijn van der Ven <martijn@vanderven.se>
  1934. */
  1935. final class Stream implements StreamInterface
  1936. {
  1937. /** @var resource|null A resource reference */
  1938. private $stream;
  1939. /** @var bool */
  1940. private $seekable;
  1941. /** @var bool */
  1942. private $readable;
  1943. /** @var bool */
  1944. private $writable;
  1945. /** @var array|mixed|void|null */
  1946. private $uri;
  1947. /** @var int|null */
  1948. private $size;
  1949. /** @var array Hash of readable and writable stream types */
  1950. /*private*/ const READ_WRITE_HASH = [
  1951. 'read' => [
  1952. 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
  1953. 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
  1954. 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
  1955. 'x+t' => true, 'c+t' => true, 'a+' => true,
  1956. ],
  1957. 'write' => [
  1958. 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
  1959. 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
  1960. 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
  1961. 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
  1962. ],
  1963. ];
  1964. private function __construct()
  1965. {
  1966. }
  1967. /**
  1968. * Creates a new PSR-7 stream.
  1969. *
  1970. * @param string|resource|StreamInterface $body
  1971. *
  1972. * @return StreamInterface
  1973. *
  1974. * @throws \InvalidArgumentException
  1975. */
  1976. public static function create($body = ''): StreamInterface
  1977. {
  1978. if ($body instanceof StreamInterface) {
  1979. return $body;
  1980. }
  1981. if (\is_string($body)) {
  1982. $resource = \fopen('php://temp', 'rw+');
  1983. \fwrite($resource, $body);
  1984. $body = $resource;
  1985. }
  1986. if (\is_resource($body)) {
  1987. $new = new self();
  1988. $new->stream = $body;
  1989. $meta = \stream_get_meta_data($new->stream);
  1990. $new->seekable = $meta['seekable'] && 0 === \fseek($new->stream, 0, \SEEK_CUR);
  1991. $new->readable = isset(self::READ_WRITE_HASH['read'][$meta['mode']]);
  1992. $new->writable = isset(self::READ_WRITE_HASH['write'][$meta['mode']]);
  1993. $new->uri = $new->getMetadata('uri');
  1994. return $new;
  1995. }
  1996. throw new \InvalidArgumentException('First argument to Stream::create() must be a string, resource or StreamInterface.');
  1997. }
  1998. /**
  1999. * Closes the stream when the destructed.
  2000. */
  2001. public function __destruct()
  2002. {
  2003. $this->close();
  2004. }
  2005. public function __toString(): string
  2006. {
  2007. try {
  2008. if ($this->isSeekable()) {
  2009. $this->seek(0);
  2010. }
  2011. return $this->getContents();
  2012. } catch (\Exception $e) {
  2013. return '';
  2014. }
  2015. }
  2016. public function close() /*:void*/
  2017. {
  2018. if (isset($this->stream)) {
  2019. if (\is_resource($this->stream)) {
  2020. \fclose($this->stream);
  2021. }
  2022. $this->detach();
  2023. }
  2024. }
  2025. public function detach()
  2026. {
  2027. if (!isset($this->stream)) {
  2028. return null;
  2029. }
  2030. $result = $this->stream;
  2031. unset($this->stream);
  2032. $this->size = $this->uri = null;
  2033. $this->readable = $this->writable = $this->seekable = false;
  2034. return $result;
  2035. }
  2036. public function getSize() /*:?int*/
  2037. {
  2038. if (null !== $this->size) {
  2039. return $this->size;
  2040. }
  2041. if (!isset($this->stream)) {
  2042. return null;
  2043. }
  2044. // Clear the stat cache if the stream has a URI
  2045. if ($this->uri) {
  2046. \clearstatcache(true, $this->uri);
  2047. }
  2048. $stats = \fstat($this->stream);
  2049. if (isset($stats['size'])) {
  2050. $this->size = $stats['size'];
  2051. return $this->size;
  2052. }
  2053. return null;
  2054. }
  2055. public function tell(): int
  2056. {
  2057. if (false === $result = \ftell($this->stream)) {
  2058. throw new \RuntimeException('Unable to determine stream position');
  2059. }
  2060. return $result;
  2061. }
  2062. public function eof(): bool
  2063. {
  2064. return !$this->stream || \feof($this->stream);
  2065. }
  2066. public function isSeekable(): bool
  2067. {
  2068. return $this->seekable;
  2069. }
  2070. public function seek($offset, $whence = \SEEK_SET) /*:void*/
  2071. {
  2072. if (!$this->seekable) {
  2073. throw new \RuntimeException('Stream is not seekable');
  2074. }
  2075. if (-1 === \fseek($this->stream, $offset, $whence)) {
  2076. throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, true));
  2077. }
  2078. }
  2079. public function rewind() /*:void*/
  2080. {
  2081. $this->seek(0);
  2082. }
  2083. public function isWritable(): bool
  2084. {
  2085. return $this->writable;
  2086. }
  2087. public function write($string): int
  2088. {
  2089. if (!$this->writable) {
  2090. throw new \RuntimeException('Cannot write to a non-writable stream');
  2091. }
  2092. // We can't know the size after writing anything
  2093. $this->size = null;
  2094. if (false === $result = \fwrite($this->stream, $string)) {
  2095. throw new \RuntimeException('Unable to write to stream');
  2096. }
  2097. return $result;
  2098. }
  2099. public function isReadable(): bool
  2100. {
  2101. return $this->readable;
  2102. }
  2103. public function read($length): string
  2104. {
  2105. if (!$this->readable) {
  2106. throw new \RuntimeException('Cannot read from non-readable stream');
  2107. }
  2108. return \fread($this->stream, $length);
  2109. }
  2110. public function getContents(): string
  2111. {
  2112. if (!isset($this->stream)) {
  2113. throw new \RuntimeException('Unable to read stream contents');
  2114. }
  2115. if (false === $contents = \stream_get_contents($this->stream)) {
  2116. throw new \RuntimeException('Unable to read stream contents');
  2117. }
  2118. return $contents;
  2119. }
  2120. public function getMetadata($key = null)
  2121. {
  2122. if (!isset($this->stream)) {
  2123. return $key ? null : [];
  2124. }
  2125. $meta = \stream_get_meta_data($this->stream);
  2126. if (null === $key) {
  2127. return $meta;
  2128. }
  2129. return $meta[$key] ?? null;
  2130. }
  2131. }
  2132. }
  2133. // file: vendor/nyholm/psr7/src/UploadedFile.php
  2134. namespace Nyholm\Psr7 {
  2135. use Psr\Http\Message\{StreamInterface, UploadedFileInterface};
  2136. /**
  2137. * @author Michael Dowling and contributors to guzzlehttp/psr7
  2138. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2139. * @author Martijn van der Ven <martijn@vanderven.se>
  2140. */
  2141. final class UploadedFile implements UploadedFileInterface
  2142. {
  2143. /** @var array */
  2144. /*private*/ const ERRORS = [
  2145. \UPLOAD_ERR_OK => 1,
  2146. \UPLOAD_ERR_INI_SIZE => 1,
  2147. \UPLOAD_ERR_FORM_SIZE => 1,
  2148. \UPLOAD_ERR_PARTIAL => 1,
  2149. \UPLOAD_ERR_NO_FILE => 1,
  2150. \UPLOAD_ERR_NO_TMP_DIR => 1,
  2151. \UPLOAD_ERR_CANT_WRITE => 1,
  2152. \UPLOAD_ERR_EXTENSION => 1,
  2153. ];
  2154. /** @var string */
  2155. private $clientFilename;
  2156. /** @var string */
  2157. private $clientMediaType;
  2158. /** @var int */
  2159. private $error;
  2160. /** @var string|null */
  2161. private $file;
  2162. /** @var bool */
  2163. private $moved = false;
  2164. /** @var int */
  2165. private $size;
  2166. /** @var StreamInterface|null */
  2167. private $stream;
  2168. /**
  2169. * @param StreamInterface|string|resource $streamOrFile
  2170. * @param int $size
  2171. * @param int $errorStatus
  2172. * @param string|null $clientFilename
  2173. * @param string|null $clientMediaType
  2174. */
  2175. public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
  2176. {
  2177. if (false === \is_int($errorStatus) || !isset(self::ERRORS[$errorStatus])) {
  2178. throw new \InvalidArgumentException('Upload file error status must be an integer value and one of the "UPLOAD_ERR_*" constants.');
  2179. }
  2180. if (false === \is_int($size)) {
  2181. throw new \InvalidArgumentException('Upload file size must be an integer');
  2182. }
  2183. if (null !== $clientFilename && !\is_string($clientFilename)) {
  2184. throw new \InvalidArgumentException('Upload file client filename must be a string or null');
  2185. }
  2186. if (null !== $clientMediaType && !\is_string($clientMediaType)) {
  2187. throw new \InvalidArgumentException('Upload file client media type must be a string or null');
  2188. }
  2189. $this->error = $errorStatus;
  2190. $this->size = $size;
  2191. $this->clientFilename = $clientFilename;
  2192. $this->clientMediaType = $clientMediaType;
  2193. if (\UPLOAD_ERR_OK === $this->error) {
  2194. // Depending on the value set file or stream variable.
  2195. if (\is_string($streamOrFile)) {
  2196. $this->file = $streamOrFile;
  2197. } elseif (\is_resource($streamOrFile)) {
  2198. $this->stream = Stream::create($streamOrFile);
  2199. } elseif ($streamOrFile instanceof StreamInterface) {
  2200. $this->stream = $streamOrFile;
  2201. } else {
  2202. throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile');
  2203. }
  2204. }
  2205. }
  2206. /**
  2207. * @throws \RuntimeException if is moved or not ok
  2208. */
  2209. private function validateActive() /*:void*/
  2210. {
  2211. if (\UPLOAD_ERR_OK !== $this->error) {
  2212. throw new \RuntimeException('Cannot retrieve stream due to upload error');
  2213. }
  2214. if ($this->moved) {
  2215. throw new \RuntimeException('Cannot retrieve stream after it has already been moved');
  2216. }
  2217. }
  2218. public function getStream(): StreamInterface
  2219. {
  2220. $this->validateActive();
  2221. if ($this->stream instanceof StreamInterface) {
  2222. return $this->stream;
  2223. }
  2224. $resource = \fopen($this->file, 'r');
  2225. return Stream::create($resource);
  2226. }
  2227. public function moveTo($targetPath) /*:void*/
  2228. {
  2229. $this->validateActive();
  2230. if (!\is_string($targetPath) || '' === $targetPath) {
  2231. throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
  2232. }
  2233. if (null !== $this->file) {
  2234. $this->moved = 'cli' === \PHP_SAPI ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath);
  2235. } else {
  2236. $stream = $this->getStream();
  2237. if ($stream->isSeekable()) {
  2238. $stream->rewind();
  2239. }
  2240. // Copy the contents of a stream into another stream until end-of-file.
  2241. $dest = Stream::create(\fopen($targetPath, 'w'));
  2242. while (!$stream->eof()) {
  2243. if (!$dest->write($stream->read(1048576))) {
  2244. break;
  2245. }
  2246. }
  2247. $this->moved = true;
  2248. }
  2249. if (false === $this->moved) {
  2250. throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath));
  2251. }
  2252. }
  2253. public function getSize(): int
  2254. {
  2255. return $this->size;
  2256. }
  2257. public function getError(): int
  2258. {
  2259. return $this->error;
  2260. }
  2261. public function getClientFilename() /*:?string*/
  2262. {
  2263. return $this->clientFilename;
  2264. }
  2265. public function getClientMediaType() /*:?string*/
  2266. {
  2267. return $this->clientMediaType;
  2268. }
  2269. }
  2270. }
  2271. // file: vendor/nyholm/psr7/src/Uri.php
  2272. namespace Nyholm\Psr7 {
  2273. use Psr\Http\Message\UriInterface;
  2274. /**
  2275. * PSR-7 URI implementation.
  2276. *
  2277. * @author Michael Dowling
  2278. * @author Tobias Schultze
  2279. * @author Matthew Weier O'Phinney
  2280. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2281. * @author Martijn van der Ven <martijn@vanderven.se>
  2282. */
  2283. final class Uri implements UriInterface
  2284. {
  2285. /*private*/ const SCHEMES = ['http' => 80, 'https' => 443];
  2286. /*private*/ const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
  2287. /*private*/ const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
  2288. /** @var string Uri scheme. */
  2289. private $scheme = '';
  2290. /** @var string Uri user info. */
  2291. private $userInfo = '';
  2292. /** @var string Uri host. */
  2293. private $host = '';
  2294. /** @var int|null Uri port. */
  2295. private $port;
  2296. /** @var string Uri path. */
  2297. private $path = '';
  2298. /** @var string Uri query string. */
  2299. private $query = '';
  2300. /** @var string Uri fragment. */
  2301. private $fragment = '';
  2302. public function __construct(string $uri = '')
  2303. {
  2304. if ('' !== $uri) {
  2305. if (false === $parts = \parse_url($uri)) {
  2306. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  2307. }
  2308. // Apply parse_url parts to a URI.
  2309. $this->scheme = isset($parts['scheme']) ? \strtolower($parts['scheme']) : '';
  2310. $this->userInfo = $parts['user'] ?? '';
  2311. $this->host = isset($parts['host']) ? \strtolower($parts['host']) : '';
  2312. $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null;
  2313. $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : '';
  2314. $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : '';
  2315. $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : '';
  2316. if (isset($parts['pass'])) {
  2317. $this->userInfo .= ':' . $parts['pass'];
  2318. }
  2319. }
  2320. }
  2321. public function __toString(): string
  2322. {
  2323. return self::createUriString($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment);
  2324. }
  2325. public function getScheme(): string
  2326. {
  2327. return $this->scheme;
  2328. }
  2329. public function getAuthority(): string
  2330. {
  2331. if ('' === $this->host) {
  2332. return '';
  2333. }
  2334. $authority = $this->host;
  2335. if ('' !== $this->userInfo) {
  2336. $authority = $this->userInfo . '@' . $authority;
  2337. }
  2338. if (null !== $this->port) {
  2339. $authority .= ':' . $this->port;
  2340. }
  2341. return $authority;
  2342. }
  2343. public function getUserInfo(): string
  2344. {
  2345. return $this->userInfo;
  2346. }
  2347. public function getHost(): string
  2348. {
  2349. return $this->host;
  2350. }
  2351. public function getPort() /*:?int*/
  2352. {
  2353. return $this->port;
  2354. }
  2355. public function getPath(): string
  2356. {
  2357. return $this->path;
  2358. }
  2359. public function getQuery(): string
  2360. {
  2361. return $this->query;
  2362. }
  2363. public function getFragment(): string
  2364. {
  2365. return $this->fragment;
  2366. }
  2367. public function withScheme($scheme): self
  2368. {
  2369. if (!\is_string($scheme)) {
  2370. throw new \InvalidArgumentException('Scheme must be a string');
  2371. }
  2372. if ($this->scheme === $scheme = \strtolower($scheme)) {
  2373. return $this;
  2374. }
  2375. $new = clone $this;
  2376. $new->scheme = $scheme;
  2377. $new->port = $new->filterPort($new->port);
  2378. return $new;
  2379. }
  2380. public function withUserInfo($user, $password = null): self
  2381. {
  2382. $info = $user;
  2383. if (null !== $password && '' !== $password) {
  2384. $info .= ':' . $password;
  2385. }
  2386. if ($this->userInfo === $info) {
  2387. return $this;
  2388. }
  2389. $new = clone $this;
  2390. $new->userInfo = $info;
  2391. return $new;
  2392. }
  2393. public function withHost($host): self
  2394. {
  2395. if (!\is_string($host)) {
  2396. throw new \InvalidArgumentException('Host must be a string');
  2397. }
  2398. if ($this->host === $host = \strtolower($host)) {
  2399. return $this;
  2400. }
  2401. $new = clone $this;
  2402. $new->host = $host;
  2403. return $new;
  2404. }
  2405. public function withPort($port): self
  2406. {
  2407. if ($this->port === $port = $this->filterPort($port)) {
  2408. return $this;
  2409. }
  2410. $new = clone $this;
  2411. $new->port = $port;
  2412. return $new;
  2413. }
  2414. public function withPath($path): self
  2415. {
  2416. if ($this->path === $path = $this->filterPath($path)) {
  2417. return $this;
  2418. }
  2419. $new = clone $this;
  2420. $new->path = $path;
  2421. return $new;
  2422. }
  2423. public function withQuery($query): self
  2424. {
  2425. if ($this->query === $query = $this->filterQueryAndFragment($query)) {
  2426. return $this;
  2427. }
  2428. $new = clone $this;
  2429. $new->query = $query;
  2430. return $new;
  2431. }
  2432. public function withFragment($fragment): self
  2433. {
  2434. if ($this->fragment === $fragment = $this->filterQueryAndFragment($fragment)) {
  2435. return $this;
  2436. }
  2437. $new = clone $this;
  2438. $new->fragment = $fragment;
  2439. return $new;
  2440. }
  2441. /**
  2442. * Create a URI string from its various parts.
  2443. */
  2444. private static function createUriString(string $scheme, string $authority, string $path, string $query, string $fragment): string
  2445. {
  2446. $uri = '';
  2447. if ('' !== $scheme) {
  2448. $uri .= $scheme . ':';
  2449. }
  2450. if ('' !== $authority) {
  2451. $uri .= '//' . $authority;
  2452. }
  2453. if ('' !== $path) {
  2454. if ('/' !== $path[0]) {
  2455. if ('' !== $authority) {
  2456. // If the path is rootless and an authority is present, the path MUST be prefixed by "/"
  2457. $path = '/' . $path;
  2458. }
  2459. } elseif (isset($path[1]) && '/' === $path[1]) {
  2460. if ('' === $authority) {
  2461. // If the path is starting with more than one "/" and no authority is present, the
  2462. // starting slashes MUST be reduced to one.
  2463. $path = '/' . \ltrim($path, '/');
  2464. }
  2465. }
  2466. $uri .= $path;
  2467. }
  2468. if ('' !== $query) {
  2469. $uri .= '?' . $query;
  2470. }
  2471. if ('' !== $fragment) {
  2472. $uri .= '#' . $fragment;
  2473. }
  2474. return $uri;
  2475. }
  2476. /**
  2477. * Is a given port non-standard for the current scheme?
  2478. */
  2479. private static function isNonStandardPort(string $scheme, int $port): bool
  2480. {
  2481. return !isset(self::SCHEMES[$scheme]) || $port !== self::SCHEMES[$scheme];
  2482. }
  2483. private function filterPort($port) /*:?int*/
  2484. {
  2485. if (null === $port) {
  2486. return null;
  2487. }
  2488. $port = (int) $port;
  2489. if (0 > $port || 0xffff < $port) {
  2490. throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 0 and 65535', $port));
  2491. }
  2492. return self::isNonStandardPort($this->scheme, $port) ? $port : null;
  2493. }
  2494. private function filterPath($path): string
  2495. {
  2496. if (!\is_string($path)) {
  2497. throw new \InvalidArgumentException('Path must be a string');
  2498. }
  2499. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $path);
  2500. }
  2501. private function filterQueryAndFragment($str): string
  2502. {
  2503. if (!\is_string($str)) {
  2504. throw new \InvalidArgumentException('Query and fragment must be a string');
  2505. }
  2506. return \preg_replace_callback('/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', [__CLASS__, 'rawurlencodeMatchZero'], $str);
  2507. }
  2508. private static function rawurlencodeMatchZero(array $match): string
  2509. {
  2510. return \rawurlencode($match[0]);
  2511. }
  2512. }
  2513. }
  2514. // file: vendor/nyholm/psr7-server/src/ServerRequestCreator.php
  2515. namespace Nyholm\Psr7Server {
  2516. use Psr\Http\Message\ServerRequestFactoryInterface;
  2517. use Psr\Http\Message\ServerRequestInterface;
  2518. use Psr\Http\Message\StreamFactoryInterface;
  2519. use Psr\Http\Message\StreamInterface;
  2520. use Psr\Http\Message\UploadedFileFactoryInterface;
  2521. use Psr\Http\Message\UploadedFileInterface;
  2522. use Psr\Http\Message\UriFactoryInterface;
  2523. use Psr\Http\Message\UriInterface;
  2524. /**
  2525. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2526. * @author Martijn van der Ven <martijn@vanderven.se>
  2527. */
  2528. final class ServerRequestCreator implements ServerRequestCreatorInterface
  2529. {
  2530. private $serverRequestFactory;
  2531. private $uriFactory;
  2532. private $uploadedFileFactory;
  2533. private $streamFactory;
  2534. public function __construct(
  2535. ServerRequestFactoryInterface $serverRequestFactory,
  2536. UriFactoryInterface $uriFactory,
  2537. UploadedFileFactoryInterface $uploadedFileFactory,
  2538. StreamFactoryInterface $streamFactory
  2539. ) {
  2540. $this->serverRequestFactory = $serverRequestFactory;
  2541. $this->uriFactory = $uriFactory;
  2542. $this->uploadedFileFactory = $uploadedFileFactory;
  2543. $this->streamFactory = $streamFactory;
  2544. }
  2545. /**
  2546. * {@inheritdoc}
  2547. */
  2548. public function fromGlobals(): ServerRequestInterface
  2549. {
  2550. $server = $_SERVER;
  2551. if (false === isset($server['REQUEST_METHOD'])) {
  2552. $server['REQUEST_METHOD'] = 'GET';
  2553. }
  2554. $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
  2555. return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $_POST, $_FILES, \fopen('php://input', 'r') ?: null);
  2556. }
  2557. /**
  2558. * {@inheritdoc}
  2559. */
  2560. public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
  2561. {
  2562. $method = $this->getMethodFromEnv($server);
  2563. $uri = $this->getUriFromEnvWithHTTP($server);
  2564. $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
  2565. $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
  2566. foreach ($headers as $name => $value) {
  2567. $serverRequest = $serverRequest->withAddedHeader($name, $value);
  2568. }
  2569. $serverRequest = $serverRequest
  2570. ->withProtocolVersion($protocol)
  2571. ->withCookieParams($cookie)
  2572. ->withQueryParams($get)
  2573. ->withParsedBody($post)
  2574. ->withUploadedFiles($this->normalizeFiles($files));
  2575. if (null === $body) {
  2576. return $serverRequest;
  2577. }
  2578. if (\is_resource($body)) {
  2579. $body = $this->streamFactory->createStreamFromResource($body);
  2580. } elseif (\is_string($body)) {
  2581. $body = $this->streamFactory->createStream($body);
  2582. } elseif (!$body instanceof StreamInterface) {
  2583. throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
  2584. }
  2585. return $serverRequest->withBody($body);
  2586. }
  2587. /**
  2588. * Implementation from Zend\Diactoros\marshalHeadersFromSapi().
  2589. */
  2590. public static function getHeadersFromServer(array $server): array
  2591. {
  2592. $headers = [];
  2593. foreach ($server as $key => $value) {
  2594. // Apache prefixes environment variables with REDIRECT_
  2595. // if they are added by rewrite rules
  2596. if (0 === \strpos($key, 'REDIRECT_')) {
  2597. $key = \substr($key, 9);
  2598. // We will not overwrite existing variables with the
  2599. // prefixed versions, though
  2600. if (\array_key_exists($key, $server)) {
  2601. continue;
  2602. }
  2603. }
  2604. if ($value && 0 === \strpos($key, 'HTTP_')) {
  2605. $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
  2606. $headers[$name] = $value;
  2607. continue;
  2608. }
  2609. if ($value && 0 === \strpos($key, 'CONTENT_')) {
  2610. $name = 'content-'.\strtolower(\substr($key, 8));
  2611. $headers[$name] = $value;
  2612. continue;
  2613. }
  2614. }
  2615. return $headers;
  2616. }
  2617. private function getMethodFromEnv(array $environment): string
  2618. {
  2619. if (false === isset($environment['REQUEST_METHOD'])) {
  2620. throw new \InvalidArgumentException('Cannot determine HTTP method');
  2621. }
  2622. return $environment['REQUEST_METHOD'];
  2623. }
  2624. private function getUriFromEnvWithHTTP(array $environment): UriInterface
  2625. {
  2626. $uri = $this->createUriFromArray($environment);
  2627. if (empty($uri->getScheme())) {
  2628. $uri = $uri->withScheme('http');
  2629. }
  2630. return $uri;
  2631. }
  2632. /**
  2633. * Return an UploadedFile instance array.
  2634. *
  2635. * @param array $files A array which respect $_FILES structure
  2636. *
  2637. * @return UploadedFileInterface[]
  2638. *
  2639. * @throws \InvalidArgumentException for unrecognized values
  2640. */
  2641. private function normalizeFiles(array $files): array
  2642. {
  2643. $normalized = [];
  2644. foreach ($files as $key => $value) {
  2645. if ($value instanceof UploadedFileInterface) {
  2646. $normalized[$key] = $value;
  2647. } elseif (\is_array($value) && isset($value['tmp_name'])) {
  2648. $normalized[$key] = $this->createUploadedFileFromSpec($value);
  2649. } elseif (\is_array($value)) {
  2650. $normalized[$key] = $this->normalizeFiles($value);
  2651. } else {
  2652. throw new \InvalidArgumentException('Invalid value in files specification');
  2653. }
  2654. }
  2655. return $normalized;
  2656. }
  2657. /**
  2658. * Create and return an UploadedFile instance from a $_FILES specification.
  2659. *
  2660. * If the specification represents an array of values, this method will
  2661. * delegate to normalizeNestedFileSpec() and return that return value.
  2662. *
  2663. * @param array $value $_FILES struct
  2664. *
  2665. * @return array|UploadedFileInterface
  2666. */
  2667. private function createUploadedFileFromSpec(array $value)
  2668. {
  2669. if (\is_array($value['tmp_name'])) {
  2670. return $this->normalizeNestedFileSpec($value);
  2671. }
  2672. try {
  2673. $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
  2674. } catch (\RuntimeException $e) {
  2675. $stream = $this->streamFactory->createStream();
  2676. }
  2677. return $this->uploadedFileFactory->createUploadedFile(
  2678. $stream,
  2679. (int) $value['size'],
  2680. (int) $value['error'],
  2681. $value['name'],
  2682. $value['type']
  2683. );
  2684. }
  2685. /**
  2686. * Normalize an array of file specifications.
  2687. *
  2688. * Loops through all nested files and returns a normalized array of
  2689. * UploadedFileInterface instances.
  2690. *
  2691. * @param array $files
  2692. *
  2693. * @return UploadedFileInterface[]
  2694. */
  2695. private function normalizeNestedFileSpec(array $files = []): array
  2696. {
  2697. $normalizedFiles = [];
  2698. foreach (\array_keys($files['tmp_name']) as $key) {
  2699. $spec = [
  2700. 'tmp_name' => $files['tmp_name'][$key],
  2701. 'size' => $files['size'][$key],
  2702. 'error' => $files['error'][$key],
  2703. 'name' => $files['name'][$key],
  2704. 'type' => $files['type'][$key],
  2705. ];
  2706. $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
  2707. }
  2708. return $normalizedFiles;
  2709. }
  2710. /**
  2711. * Create a new uri from server variable.
  2712. *
  2713. * @param array $server typically $_SERVER or similar structure
  2714. */
  2715. private function createUriFromArray(array $server): UriInterface
  2716. {
  2717. $uri = $this->uriFactory->createUri('');
  2718. if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
  2719. $uri = $uri->withScheme($server['HTTP_X_FORWARDED_PROTO']);
  2720. } else {
  2721. if (isset($server['REQUEST_SCHEME'])) {
  2722. $uri = $uri->withScheme($server['REQUEST_SCHEME']);
  2723. } elseif (isset($server['HTTPS'])) {
  2724. $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
  2725. }
  2726. if (isset($server['SERVER_PORT'])) {
  2727. $uri = $uri->withPort($server['SERVER_PORT']);
  2728. }
  2729. }
  2730. if (isset($server['HTTP_HOST'])) {
  2731. if (1 === \preg_match('/^(.+)\:(\d+)$/', $server['HTTP_HOST'], $matches)) {
  2732. $uri = $uri->withHost($matches[1])->withPort($matches[2]);
  2733. } else {
  2734. $uri = $uri->withHost($server['HTTP_HOST']);
  2735. }
  2736. } elseif (isset($server['SERVER_NAME'])) {
  2737. $uri = $uri->withHost($server['SERVER_NAME']);
  2738. }
  2739. if (isset($server['REQUEST_URI'])) {
  2740. $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
  2741. }
  2742. if (isset($server['QUERY_STRING'])) {
  2743. $uri = $uri->withQuery($server['QUERY_STRING']);
  2744. }
  2745. return $uri;
  2746. }
  2747. }
  2748. }
  2749. // file: vendor/nyholm/psr7-server/src/ServerRequestCreatorInterface.php
  2750. namespace Nyholm\Psr7Server {
  2751. use Psr\Http\Message\ServerRequestInterface;
  2752. use Psr\Http\Message\StreamInterface;
  2753. /**
  2754. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  2755. * @author Martijn van der Ven <martijn@vanderven.se>
  2756. */
  2757. interface ServerRequestCreatorInterface
  2758. {
  2759. /**
  2760. * Create a new server request from the current environment variables.
  2761. * Defaults to a GET request to minimise the risk of an \InvalidArgumentException.
  2762. * Includes the current request headers as supplied by the server through `getallheaders()`.
  2763. * If `getallheaders()` is unavailable on the current server it will fallback to its own `getHeadersFromServer()` method.
  2764. * Defaults to php://input for the request body.
  2765. *
  2766. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2767. */
  2768. public function fromGlobals(): ServerRequestInterface;
  2769. /**
  2770. * Create a new server request from a set of arrays.
  2771. *
  2772. * @param array $server typically $_SERVER or similar structure
  2773. * @param array $headers typically the output of getallheaders() or similar structure
  2774. * @param array $cookie typically $_COOKIE or similar structure
  2775. * @param array $get typically $_GET or similar structure
  2776. * @param array $post typically $_POST or similar structure
  2777. * @param array $files typically $_FILES or similar structure
  2778. * @param StreamInterface|resource|string|null $body Typically stdIn
  2779. *
  2780. * @throws \InvalidArgumentException if no valid method or URI can be determined
  2781. */
  2782. public function fromArrays(
  2783. array $server,
  2784. array $headers = [],
  2785. array $cookie = [],
  2786. array $get = [],
  2787. array $post = [],
  2788. array $files = [],
  2789. $body = null
  2790. ): ServerRequestInterface;
  2791. /**
  2792. * Get parsed headers from ($_SERVER) array.
  2793. *
  2794. * @param array $server typically $_SERVER or similar structure
  2795. *
  2796. * @return array
  2797. */
  2798. public static function getHeadersFromServer(array $server): array;
  2799. }
  2800. }
  2801. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  2802. namespace Tqdev\PhpCrudApi\Cache {
  2803. interface Cache
  2804. {
  2805. public function set(string $key, string $value, int $ttl = 0): bool;
  2806. public function get(string $key): string;
  2807. public function clear(): bool;
  2808. }
  2809. }
  2810. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  2811. namespace Tqdev\PhpCrudApi\Cache {
  2812. class CacheFactory
  2813. {
  2814. public static function create(string $type, string $prefix, string $config): Cache
  2815. {
  2816. switch ($type) {
  2817. case 'TempFile':
  2818. $cache = new TempFileCache($prefix, $config);
  2819. break;
  2820. case 'Redis':
  2821. $cache = new RedisCache($prefix, $config);
  2822. break;
  2823. case 'Memcache':
  2824. $cache = new MemcacheCache($prefix, $config);
  2825. break;
  2826. case 'Memcached':
  2827. $cache = new MemcachedCache($prefix, $config);
  2828. break;
  2829. default:
  2830. $cache = new NoCache();
  2831. }
  2832. return $cache;
  2833. }
  2834. }
  2835. }
  2836. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  2837. namespace Tqdev\PhpCrudApi\Cache {
  2838. class MemcacheCache implements Cache
  2839. {
  2840. protected $prefix;
  2841. protected $memcache;
  2842. public function __construct(string $prefix, string $config)
  2843. {
  2844. $this->prefix = $prefix;
  2845. if ($config == '') {
  2846. $address = 'localhost';
  2847. $port = 11211;
  2848. } elseif (strpos($config, ':') === false) {
  2849. $address = $config;
  2850. $port = 11211;
  2851. } else {
  2852. list($address, $port) = explode(':', $config);
  2853. }
  2854. $this->memcache = $this->create();
  2855. $this->memcache->addServer($address, $port);
  2856. }
  2857. protected function create() /*: \Memcache*/
  2858. {
  2859. return new \Memcache();
  2860. }
  2861. public function set(string $key, string $value, int $ttl = 0): bool
  2862. {
  2863. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  2864. }
  2865. public function get(string $key): string
  2866. {
  2867. return $this->memcache->get($this->prefix . $key) ?: '';
  2868. }
  2869. public function clear(): bool
  2870. {
  2871. return $this->memcache->flush();
  2872. }
  2873. }
  2874. }
  2875. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  2876. namespace Tqdev\PhpCrudApi\Cache {
  2877. class MemcachedCache extends MemcacheCache
  2878. {
  2879. protected function create() /*: \Memcached*/
  2880. {
  2881. return new \Memcached();
  2882. }
  2883. public function set(string $key, string $value, int $ttl = 0): bool
  2884. {
  2885. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  2886. }
  2887. }
  2888. }
  2889. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  2890. namespace Tqdev\PhpCrudApi\Cache {
  2891. class NoCache implements Cache
  2892. {
  2893. public function __construct()
  2894. {
  2895. }
  2896. public function set(string $key, string $value, int $ttl = 0): bool
  2897. {
  2898. return true;
  2899. }
  2900. public function get(string $key): string
  2901. {
  2902. return '';
  2903. }
  2904. public function clear(): bool
  2905. {
  2906. return true;
  2907. }
  2908. }
  2909. }
  2910. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  2911. namespace Tqdev\PhpCrudApi\Cache {
  2912. class RedisCache implements Cache
  2913. {
  2914. protected $prefix;
  2915. protected $redis;
  2916. public function __construct(string $prefix, string $config)
  2917. {
  2918. $this->prefix = $prefix;
  2919. if ($config == '') {
  2920. $config = '127.0.0.1';
  2921. }
  2922. $params = explode(':', $config, 6);
  2923. if (isset($params[3])) {
  2924. $params[3] = null;
  2925. }
  2926. $this->redis = new \Redis();
  2927. call_user_func_array(array($this->redis, 'pconnect'), $params);
  2928. }
  2929. public function set(string $key, string $value, int $ttl = 0): bool
  2930. {
  2931. return $this->redis->set($this->prefix . $key, $value, $ttl);
  2932. }
  2933. public function get(string $key): string
  2934. {
  2935. return $this->redis->get($this->prefix . $key) ?: '';
  2936. }
  2937. public function clear(): bool
  2938. {
  2939. return $this->redis->flushDb();
  2940. }
  2941. }
  2942. }
  2943. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  2944. namespace Tqdev\PhpCrudApi\Cache {
  2945. class TempFileCache implements Cache
  2946. {
  2947. const SUFFIX = 'cache';
  2948. private $path;
  2949. private $segments;
  2950. public function __construct(string $prefix, string $config)
  2951. {
  2952. $this->segments = [];
  2953. $s = DIRECTORY_SEPARATOR;
  2954. $ps = PATH_SEPARATOR;
  2955. if ($config == '') {
  2956. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  2957. } elseif (strpos($config, $ps) === false) {
  2958. $this->path = $config;
  2959. } else {
  2960. list($path, $segments) = explode($ps, $config);
  2961. $this->path = $path;
  2962. $this->segments = explode(',', $segments);
  2963. }
  2964. if (file_exists($this->path) && is_dir($this->path)) {
  2965. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  2966. }
  2967. }
  2968. private function getFileName(string $key): string
  2969. {
  2970. $s = DIRECTORY_SEPARATOR;
  2971. $md5 = md5($key);
  2972. $filename = rtrim($this->path, $s) . $s;
  2973. $i = 0;
  2974. foreach ($this->segments as $segment) {
  2975. $filename .= substr($md5, $i, $segment) . $s;
  2976. $i += $segment;
  2977. }
  2978. $filename .= substr($md5, $i);
  2979. return $filename;
  2980. }
  2981. public function set(string $key, string $value, int $ttl = 0): bool
  2982. {
  2983. $filename = $this->getFileName($key);
  2984. $dirname = dirname($filename);
  2985. if (!file_exists($dirname)) {
  2986. if (!mkdir($dirname, 0755, true)) {
  2987. return false;
  2988. }
  2989. }
  2990. $string = $ttl . '|' . $value;
  2991. return $this->filePutContents($filename, $string) !== false;
  2992. }
  2993. private function filePutContents($filename, $string)
  2994. {
  2995. return file_put_contents($filename, $string, LOCK_EX);
  2996. }
  2997. private function fileGetContents($filename)
  2998. {
  2999. $file = fopen($filename, 'rb');
  3000. if ($file === false) {
  3001. return false;
  3002. }
  3003. $lock = flock($file, LOCK_SH);
  3004. if (!$lock) {
  3005. fclose($file);
  3006. return false;
  3007. }
  3008. $string = '';
  3009. while (!feof($file)) {
  3010. $string .= fread($file, 8192);
  3011. }
  3012. flock($file, LOCK_UN);
  3013. fclose($file);
  3014. return $string;
  3015. }
  3016. private function getString($filename): string
  3017. {
  3018. $data = $this->fileGetContents($filename);
  3019. if ($data === false) {
  3020. return '';
  3021. }
  3022. if (strpos($data, '|') === false) {
  3023. return '';
  3024. }
  3025. list($ttl, $string) = explode('|', $data, 2);
  3026. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  3027. return '';
  3028. }
  3029. return $string;
  3030. }
  3031. public function get(string $key): string
  3032. {
  3033. $filename = $this->getFileName($key);
  3034. if (!file_exists($filename)) {
  3035. return '';
  3036. }
  3037. $string = $this->getString($filename);
  3038. if ($string == null) {
  3039. return '';
  3040. }
  3041. return $string;
  3042. }
  3043. private function clean(string $path, array $segments, int $len, bool $all) /*: void*/
  3044. {
  3045. $entries = scandir($path);
  3046. foreach ($entries as $entry) {
  3047. if ($entry === '.' || $entry === '..') {
  3048. continue;
  3049. }
  3050. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  3051. if (count($segments) == 0) {
  3052. if (strlen($entry) != $len) {
  3053. continue;
  3054. }
  3055. if (file_exists($filename) && is_file($filename)) {
  3056. if ($all || $this->getString($filename) == null) {
  3057. @unlink($filename);
  3058. }
  3059. }
  3060. } else {
  3061. if (strlen($entry) != $segments[0]) {
  3062. continue;
  3063. }
  3064. if (file_exists($filename) && is_dir($filename)) {
  3065. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  3066. @rmdir($filename);
  3067. }
  3068. }
  3069. }
  3070. }
  3071. public function clear(): bool
  3072. {
  3073. if (!file_exists($this->path) || !is_dir($this->path)) {
  3074. return false;
  3075. }
  3076. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  3077. return true;
  3078. }
  3079. }
  3080. }
  3081. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  3082. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3083. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3084. class ReflectedColumn implements \JsonSerializable
  3085. {
  3086. const DEFAULT_LENGTH = 255;
  3087. const DEFAULT_PRECISION = 19;
  3088. const DEFAULT_SCALE = 4;
  3089. private $name;
  3090. private $type;
  3091. private $length;
  3092. private $precision;
  3093. private $scale;
  3094. private $nullable;
  3095. private $pk;
  3096. private $fk;
  3097. public function __construct(string $name, string $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, string $fk)
  3098. {
  3099. $this->name = $name;
  3100. $this->type = $type;
  3101. $this->length = $length;
  3102. $this->precision = $precision;
  3103. $this->scale = $scale;
  3104. $this->nullable = $nullable;
  3105. $this->pk = $pk;
  3106. $this->fk = $fk;
  3107. $this->sanitize();
  3108. }
  3109. private static function parseColumnType(string $columnType, int &$length, int &$precision, int &$scale) /*: void*/
  3110. {
  3111. if (!$columnType) {
  3112. return;
  3113. }
  3114. $pos = strpos($columnType, '(');
  3115. if ($pos) {
  3116. $dataSize = rtrim(substr($columnType, $pos + 1), ')');
  3117. if ($length) {
  3118. $length = (int) $dataSize;
  3119. } else {
  3120. $pos = strpos($dataSize, ',');
  3121. if ($pos) {
  3122. $precision = (int) substr($dataSize, 0, $pos);
  3123. $scale = (int) substr($dataSize, $pos + 1);
  3124. } else {
  3125. $precision = (int) $dataSize;
  3126. $scale = 0;
  3127. }
  3128. }
  3129. }
  3130. }
  3131. private static function getDataSize(int $length, int $precision, int $scale): string
  3132. {
  3133. $dataSize = '';
  3134. if ($length) {
  3135. $dataSize = $length;
  3136. } elseif ($precision) {
  3137. if ($scale) {
  3138. $dataSize = $precision . ',' . $scale;
  3139. } else {
  3140. $dataSize = $precision;
  3141. }
  3142. }
  3143. return $dataSize;
  3144. }
  3145. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  3146. {
  3147. $name = $columnResult['COLUMN_NAME'];
  3148. $dataType = $columnResult['DATA_TYPE'];
  3149. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  3150. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  3151. $scale = (int) $columnResult['NUMERIC_SCALE'];
  3152. $columnType = $columnResult['COLUMN_TYPE'];
  3153. self::parseColumnType($columnType, $length, $precision, $scale);
  3154. $dataSize = self::getDataSize($length, $precision, $scale);
  3155. $type = $reflection->toJdbcType($dataType, $dataSize);
  3156. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  3157. $pk = false;
  3158. $fk = '';
  3159. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3160. }
  3161. public static function fromJson(/* object */$json): ReflectedColumn
  3162. {
  3163. $name = $json->name;
  3164. $type = $json->type;
  3165. $length = isset($json->length) ? (int) $json->length : 0;
  3166. $precision = isset($json->precision) ? (int) $json->precision : 0;
  3167. $scale = isset($json->scale) ? (int) $json->scale : 0;
  3168. $nullable = isset($json->nullable) ? (bool) $json->nullable : false;
  3169. $pk = isset($json->pk) ? (bool) $json->pk : false;
  3170. $fk = isset($json->fk) ? $json->fk : '';
  3171. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  3172. }
  3173. private function sanitize()
  3174. {
  3175. $this->length = $this->hasLength() ? $this->getLength() : 0;
  3176. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  3177. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  3178. }
  3179. public function getName(): string
  3180. {
  3181. return $this->name;
  3182. }
  3183. public function getNullable(): bool
  3184. {
  3185. return $this->nullable;
  3186. }
  3187. public function getType(): string
  3188. {
  3189. return $this->type;
  3190. }
  3191. public function getLength(): int
  3192. {
  3193. return $this->length ?: self::DEFAULT_LENGTH;
  3194. }
  3195. public function getPrecision(): int
  3196. {
  3197. return $this->precision ?: self::DEFAULT_PRECISION;
  3198. }
  3199. public function getScale(): int
  3200. {
  3201. return $this->scale ?: self::DEFAULT_SCALE;
  3202. }
  3203. public function hasLength(): bool
  3204. {
  3205. return in_array($this->type, ['varchar', 'varbinary']);
  3206. }
  3207. public function hasPrecision(): bool
  3208. {
  3209. return $this->type == 'decimal';
  3210. }
  3211. public function hasScale(): bool
  3212. {
  3213. return $this->type == 'decimal';
  3214. }
  3215. public function isBinary(): bool
  3216. {
  3217. return in_array($this->type, ['blob', 'varbinary']);
  3218. }
  3219. public function isBoolean(): bool
  3220. {
  3221. return $this->type == 'boolean';
  3222. }
  3223. public function isGeometry(): bool
  3224. {
  3225. return $this->type == 'geometry';
  3226. }
  3227. public function isInteger(): bool
  3228. {
  3229. return in_array($this->type, ['integer', 'bigint', 'smallint', 'tinyint']);
  3230. }
  3231. public function setPk($value) /*: void*/
  3232. {
  3233. $this->pk = $value;
  3234. }
  3235. public function getPk(): bool
  3236. {
  3237. return $this->pk;
  3238. }
  3239. public function setFk($value) /*: void*/
  3240. {
  3241. $this->fk = $value;
  3242. }
  3243. public function getFk(): string
  3244. {
  3245. return $this->fk;
  3246. }
  3247. public function serialize()
  3248. {
  3249. return [
  3250. 'name' => $this->name,
  3251. 'type' => $this->type,
  3252. 'length' => $this->length,
  3253. 'precision' => $this->precision,
  3254. 'scale' => $this->scale,
  3255. 'nullable' => $this->nullable,
  3256. 'pk' => $this->pk,
  3257. 'fk' => $this->fk,
  3258. ];
  3259. }
  3260. public function jsonSerialize()
  3261. {
  3262. return array_filter($this->serialize());
  3263. }
  3264. }
  3265. }
  3266. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  3267. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3268. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3269. class ReflectedDatabase implements \JsonSerializable
  3270. {
  3271. private $tableTypes;
  3272. public function __construct(array $tableTypes)
  3273. {
  3274. $this->tableTypes = $tableTypes;
  3275. }
  3276. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  3277. {
  3278. $tableTypes = [];
  3279. foreach ($reflection->getTables() as $table) {
  3280. $tableName = $table['TABLE_NAME'];
  3281. $tableType = $table['TABLE_TYPE'];
  3282. if (in_array($tableName, $reflection->getIgnoredTables())) {
  3283. continue;
  3284. }
  3285. $tableTypes[$tableName] = $tableType;
  3286. }
  3287. return new ReflectedDatabase($tableTypes);
  3288. }
  3289. public static function fromJson(/* object */$json): ReflectedDatabase
  3290. {
  3291. $tableTypes = (array) $json->tables;
  3292. return new ReflectedDatabase($tableTypes);
  3293. }
  3294. public function hasTable(string $tableName): bool
  3295. {
  3296. return isset($this->tableTypes[$tableName]);
  3297. }
  3298. public function getType(string $tableName): string
  3299. {
  3300. return isset($this->tableTypes[$tableName]) ? $this->tableTypes[$tableName] : '';
  3301. }
  3302. public function getTableNames(): array
  3303. {
  3304. return array_keys($this->tableTypes);
  3305. }
  3306. public function removeTable(string $tableName): bool
  3307. {
  3308. if (!isset($this->tableTypes[$tableName])) {
  3309. return false;
  3310. }
  3311. unset($this->tableTypes[$tableName]);
  3312. return true;
  3313. }
  3314. public function serialize()
  3315. {
  3316. return [
  3317. 'tables' => $this->tableTypes,
  3318. ];
  3319. }
  3320. public function jsonSerialize()
  3321. {
  3322. return $this->serialize();
  3323. }
  3324. }
  3325. }
  3326. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  3327. namespace Tqdev\PhpCrudApi\Column\Reflection {
  3328. use Tqdev\PhpCrudApi\Database\GenericReflection;
  3329. class ReflectedTable implements \JsonSerializable
  3330. {
  3331. private $name;
  3332. private $type;
  3333. private $columns;
  3334. private $pk;
  3335. private $fks;
  3336. public function __construct(string $name, string $type, array $columns)
  3337. {
  3338. $this->name = $name;
  3339. $this->type = $type;
  3340. // set columns
  3341. $this->columns = [];
  3342. foreach ($columns as $column) {
  3343. $columnName = $column->getName();
  3344. $this->columns[$columnName] = $column;
  3345. }
  3346. // set primary key
  3347. $this->pk = null;
  3348. foreach ($columns as $column) {
  3349. if ($column->getPk() == true) {
  3350. $this->pk = $column;
  3351. }
  3352. }
  3353. // set foreign keys
  3354. $this->fks = [];
  3355. foreach ($columns as $column) {
  3356. $columnName = $column->getName();
  3357. $referencedTableName = $column->getFk();
  3358. if ($referencedTableName != '') {
  3359. $this->fks[$columnName] = $referencedTableName;
  3360. }
  3361. }
  3362. }
  3363. public static function fromReflection(GenericReflection $reflection, string $name, string $type): ReflectedTable
  3364. {
  3365. // set columns
  3366. $columns = [];
  3367. foreach ($reflection->getTableColumns($name, $type) as $tableColumn) {
  3368. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  3369. $columns[$column->getName()] = $column;
  3370. }
  3371. // set primary key
  3372. $columnNames = $reflection->getTablePrimaryKeys($name);
  3373. if (count($columnNames) == 1) {
  3374. $columnName = $columnNames[0];
  3375. if (isset($columns[$columnName])) {
  3376. $pk = $columns[$columnName];
  3377. $pk->setPk(true);
  3378. }
  3379. }
  3380. // set foreign keys
  3381. $fks = $reflection->getTableForeignKeys($name);
  3382. foreach ($fks as $columnName => $table) {
  3383. $columns[$columnName]->setFk($table);
  3384. }
  3385. return new ReflectedTable($name, $type, array_values($columns));
  3386. }
  3387. public static function fromJson(/* object */$json): ReflectedTable
  3388. {
  3389. $name = $json->name;
  3390. $type = isset($json->type) ? $json->type : 'table';
  3391. $columns = [];
  3392. if (isset($json->columns) && is_array($json->columns)) {
  3393. foreach ($json->columns as $column) {
  3394. $columns[] = ReflectedColumn::fromJson($column);
  3395. }
  3396. }
  3397. return new ReflectedTable($name, $type, $columns);
  3398. }
  3399. public function hasColumn(string $columnName): bool
  3400. {
  3401. return isset($this->columns[$columnName]);
  3402. }
  3403. public function hasPk(): bool
  3404. {
  3405. return $this->pk != null;
  3406. }
  3407. public function getPk() /*: ?ReflectedColumn */
  3408. {
  3409. return $this->pk;
  3410. }
  3411. public function getName(): string
  3412. {
  3413. return $this->name;
  3414. }
  3415. public function getType(): string
  3416. {
  3417. return $this->type;
  3418. }
  3419. public function getColumnNames(): array
  3420. {
  3421. return array_keys($this->columns);
  3422. }
  3423. public function getColumn($columnName): ReflectedColumn
  3424. {
  3425. return $this->columns[$columnName];
  3426. }
  3427. public function getFksTo(string $tableName): array
  3428. {
  3429. $columns = array();
  3430. foreach ($this->fks as $columnName => $referencedTableName) {
  3431. if ($tableName == $referencedTableName) {
  3432. $columns[] = $this->columns[$columnName];
  3433. }
  3434. }
  3435. return $columns;
  3436. }
  3437. public function removeColumn(string $columnName): bool
  3438. {
  3439. if (!isset($this->columns[$columnName])) {
  3440. return false;
  3441. }
  3442. unset($this->columns[$columnName]);
  3443. return true;
  3444. }
  3445. public function serialize()
  3446. {
  3447. return [
  3448. 'name' => $this->name,
  3449. 'type' => $this->type,
  3450. 'columns' => array_values($this->columns),
  3451. ];
  3452. }
  3453. public function jsonSerialize()
  3454. {
  3455. return $this->serialize();
  3456. }
  3457. }
  3458. }
  3459. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  3460. namespace Tqdev\PhpCrudApi\Column {
  3461. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  3462. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3463. use Tqdev\PhpCrudApi\Database\GenericDB;
  3464. class DefinitionService
  3465. {
  3466. private $db;
  3467. private $reflection;
  3468. public function __construct(GenericDB $db, ReflectionService $reflection)
  3469. {
  3470. $this->db = $db;
  3471. $this->reflection = $reflection;
  3472. }
  3473. public function updateTable(string $tableName, /* object */ $changes): bool
  3474. {
  3475. $table = $this->reflection->getTable($tableName);
  3476. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  3477. if ($table->getName() != $newTable->getName()) {
  3478. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  3479. return false;
  3480. }
  3481. }
  3482. return true;
  3483. }
  3484. public function updateColumn(string $tableName, string $columnName, /* object */ $changes): bool
  3485. {
  3486. $table = $this->reflection->getTable($tableName);
  3487. $column = $table->getColumn($columnName);
  3488. // remove constraints on other column
  3489. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3490. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  3491. $oldColumn = $table->getPk();
  3492. if ($oldColumn->getName() != $columnName) {
  3493. $oldColumn->setPk(false);
  3494. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  3495. return false;
  3496. }
  3497. }
  3498. }
  3499. // remove constraints
  3500. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  3501. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  3502. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  3503. return false;
  3504. }
  3505. }
  3506. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  3507. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  3508. return false;
  3509. }
  3510. }
  3511. // name and type
  3512. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3513. $newColumn->setPk(false);
  3514. $newColumn->setFk('');
  3515. if ($newColumn->getName() != $column->getName()) {
  3516. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  3517. return false;
  3518. }
  3519. }
  3520. if (
  3521. $newColumn->getType() != $column->getType() ||
  3522. $newColumn->getLength() != $column->getLength() ||
  3523. $newColumn->getPrecision() != $column->getPrecision() ||
  3524. $newColumn->getScale() != $column->getScale()
  3525. ) {
  3526. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  3527. return false;
  3528. }
  3529. }
  3530. if ($newColumn->getNullable() != $column->getNullable()) {
  3531. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  3532. return false;
  3533. }
  3534. }
  3535. // add constraints
  3536. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  3537. if ($newColumn->getFk()) {
  3538. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3539. return false;
  3540. }
  3541. }
  3542. if ($newColumn->getPk()) {
  3543. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3544. return false;
  3545. }
  3546. }
  3547. return true;
  3548. }
  3549. public function addTable(/* object */$definition)
  3550. {
  3551. $newTable = ReflectedTable::fromJson($definition);
  3552. if (!$this->db->definition()->addTable($newTable)) {
  3553. return false;
  3554. }
  3555. return true;
  3556. }
  3557. public function addColumn(string $tableName, /* object */ $definition)
  3558. {
  3559. $newColumn = ReflectedColumn::fromJson($definition);
  3560. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  3561. return false;
  3562. }
  3563. if ($newColumn->getFk()) {
  3564. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  3565. return false;
  3566. }
  3567. }
  3568. if ($newColumn->getPk()) {
  3569. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  3570. return false;
  3571. }
  3572. }
  3573. return true;
  3574. }
  3575. public function removeTable(string $tableName)
  3576. {
  3577. if (!$this->db->definition()->removeTable($tableName)) {
  3578. return false;
  3579. }
  3580. return true;
  3581. }
  3582. public function removeColumn(string $tableName, string $columnName)
  3583. {
  3584. $table = $this->reflection->getTable($tableName);
  3585. $newColumn = $table->getColumn($columnName);
  3586. if ($newColumn->getPk()) {
  3587. $newColumn->setPk(false);
  3588. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  3589. return false;
  3590. }
  3591. }
  3592. if ($newColumn->getFk()) {
  3593. $newColumn->setFk("");
  3594. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  3595. return false;
  3596. }
  3597. }
  3598. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  3599. return false;
  3600. }
  3601. return true;
  3602. }
  3603. }
  3604. }
  3605. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  3606. namespace Tqdev\PhpCrudApi\Column {
  3607. use Tqdev\PhpCrudApi\Cache\Cache;
  3608. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedDatabase;
  3609. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  3610. use Tqdev\PhpCrudApi\Database\GenericDB;
  3611. class ReflectionService
  3612. {
  3613. private $db;
  3614. private $cache;
  3615. private $ttl;
  3616. private $database;
  3617. private $tables;
  3618. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  3619. {
  3620. $this->db = $db;
  3621. $this->cache = $cache;
  3622. $this->ttl = $ttl;
  3623. $this->database = null;
  3624. $this->tables = [];
  3625. }
  3626. private function database(): ReflectedDatabase
  3627. {
  3628. if ($this->database) {
  3629. return $this->database;
  3630. }
  3631. $this->database = $this->loadDatabase(true);
  3632. return $this->database;
  3633. }
  3634. private function loadDatabase(bool $useCache): ReflectedDatabase
  3635. {
  3636. $key = sprintf('%s-ReflectedDatabase', $this->db->getCacheKey());
  3637. $data = $useCache ? $this->cache->get($key) : '';
  3638. if ($data != '') {
  3639. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  3640. } else {
  3641. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  3642. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  3643. $this->cache->set($key, $data, $this->ttl);
  3644. }
  3645. return $database;
  3646. }
  3647. private function loadTable(string $tableName, bool $useCache): ReflectedTable
  3648. {
  3649. $key = sprintf('%s-ReflectedTable(%s)', $this->db->getCacheKey(), $tableName);
  3650. $data = $useCache ? $this->cache->get($key) : '';
  3651. if ($data != '') {
  3652. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  3653. } else {
  3654. $tableType = $this->database()->getType($tableName);
  3655. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
  3656. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  3657. $this->cache->set($key, $data, $this->ttl);
  3658. }
  3659. return $table;
  3660. }
  3661. public function refreshTables()
  3662. {
  3663. $this->database = $this->loadDatabase(false);
  3664. }
  3665. public function refreshTable(string $tableName)
  3666. {
  3667. $this->tables[$tableName] = $this->loadTable($tableName, false);
  3668. }
  3669. public function hasTable(string $tableName): bool
  3670. {
  3671. return $this->database()->hasTable($tableName);
  3672. }
  3673. public function getType(string $tableName): string
  3674. {
  3675. return $this->database()->getType($tableName);
  3676. }
  3677. public function getTable(string $tableName): ReflectedTable
  3678. {
  3679. if (!isset($this->tables[$tableName])) {
  3680. $this->tables[$tableName] = $this->loadTable($tableName, true);
  3681. }
  3682. return $this->tables[$tableName];
  3683. }
  3684. public function getTableNames(): array
  3685. {
  3686. return $this->database()->getTableNames();
  3687. }
  3688. public function removeTable(string $tableName): bool
  3689. {
  3690. unset($this->tables[$tableName]);
  3691. return $this->database()->removeTable($tableName);
  3692. }
  3693. }
  3694. }
  3695. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  3696. namespace Tqdev\PhpCrudApi\Controller {
  3697. use Psr\Http\Message\ResponseInterface;
  3698. use Psr\Http\Message\ServerRequestInterface;
  3699. use Tqdev\PhpCrudApi\Cache\Cache;
  3700. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3701. class CacheController
  3702. {
  3703. private $cache;
  3704. private $responder;
  3705. public function __construct(Router $router, Responder $responder, Cache $cache)
  3706. {
  3707. $router->register('GET', '/cache/clear', array($this, 'clear'));
  3708. $this->cache = $cache;
  3709. $this->responder = $responder;
  3710. }
  3711. public function clear(ServerRequestInterface $request): ResponseInterface
  3712. {
  3713. return $this->responder->success($this->cache->clear());
  3714. }
  3715. }
  3716. }
  3717. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  3718. namespace Tqdev\PhpCrudApi\Controller {
  3719. use Psr\Http\Message\ResponseInterface;
  3720. use Psr\Http\Message\ServerRequestInterface;
  3721. use Tqdev\PhpCrudApi\Column\DefinitionService;
  3722. use Tqdev\PhpCrudApi\Column\ReflectionService;
  3723. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3724. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3725. use Tqdev\PhpCrudApi\RequestUtils;
  3726. class ColumnController
  3727. {
  3728. private $responder;
  3729. private $reflection;
  3730. private $definition;
  3731. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  3732. {
  3733. $router->register('GET', '/columns', array($this, 'getDatabase'));
  3734. $router->register('GET', '/columns/*', array($this, 'getTable'));
  3735. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  3736. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  3737. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  3738. $router->register('POST', '/columns', array($this, 'addTable'));
  3739. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  3740. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  3741. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  3742. $this->responder = $responder;
  3743. $this->reflection = $reflection;
  3744. $this->definition = $definition;
  3745. }
  3746. public function getDatabase(ServerRequestInterface $request): ResponseInterface
  3747. {
  3748. $tables = [];
  3749. foreach ($this->reflection->getTableNames() as $table) {
  3750. $tables[] = $this->reflection->getTable($table);
  3751. }
  3752. $database = ['tables' => $tables];
  3753. return $this->responder->success($database);
  3754. }
  3755. public function getTable(ServerRequestInterface $request): ResponseInterface
  3756. {
  3757. $tableName = RequestUtils::getPathSegment($request, 2);
  3758. if (!$this->reflection->hasTable($tableName)) {
  3759. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3760. }
  3761. $table = $this->reflection->getTable($tableName);
  3762. return $this->responder->success($table);
  3763. }
  3764. public function getColumn(ServerRequestInterface $request): ResponseInterface
  3765. {
  3766. $tableName = RequestUtils::getPathSegment($request, 2);
  3767. $columnName = RequestUtils::getPathSegment($request, 3);
  3768. if (!$this->reflection->hasTable($tableName)) {
  3769. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3770. }
  3771. $table = $this->reflection->getTable($tableName);
  3772. if (!$table->hasColumn($columnName)) {
  3773. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3774. }
  3775. $column = $table->getColumn($columnName);
  3776. return $this->responder->success($column);
  3777. }
  3778. public function updateTable(ServerRequestInterface $request): ResponseInterface
  3779. {
  3780. $tableName = RequestUtils::getPathSegment($request, 2);
  3781. if (!$this->reflection->hasTable($tableName)) {
  3782. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3783. }
  3784. $success = $this->definition->updateTable($tableName, $request->getParsedBody());
  3785. if ($success) {
  3786. $this->reflection->refreshTables();
  3787. }
  3788. return $this->responder->success($success);
  3789. }
  3790. public function updateColumn(ServerRequestInterface $request): ResponseInterface
  3791. {
  3792. $tableName = RequestUtils::getPathSegment($request, 2);
  3793. $columnName = RequestUtils::getPathSegment($request, 3);
  3794. if (!$this->reflection->hasTable($tableName)) {
  3795. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3796. }
  3797. $table = $this->reflection->getTable($tableName);
  3798. if (!$table->hasColumn($columnName)) {
  3799. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3800. }
  3801. $success = $this->definition->updateColumn($tableName, $columnName, $request->getParsedBody());
  3802. if ($success) {
  3803. $this->reflection->refreshTable($tableName);
  3804. }
  3805. return $this->responder->success($success);
  3806. }
  3807. public function addTable(ServerRequestInterface $request): ResponseInterface
  3808. {
  3809. $tableName = $request->getParsedBody()->name;
  3810. if ($this->reflection->hasTable($tableName)) {
  3811. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  3812. }
  3813. $success = $this->definition->addTable($request->getParsedBody());
  3814. if ($success) {
  3815. $this->reflection->refreshTables();
  3816. }
  3817. return $this->responder->success($success);
  3818. }
  3819. public function addColumn(ServerRequestInterface $request): ResponseInterface
  3820. {
  3821. $tableName = RequestUtils::getPathSegment($request, 2);
  3822. if (!$this->reflection->hasTable($tableName)) {
  3823. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3824. }
  3825. $columnName = $request->getParsedBody()->name;
  3826. $table = $this->reflection->getTable($tableName);
  3827. if ($table->hasColumn($columnName)) {
  3828. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  3829. }
  3830. $success = $this->definition->addColumn($tableName, $request->getParsedBody());
  3831. if ($success) {
  3832. $this->reflection->refreshTable($tableName);
  3833. }
  3834. return $this->responder->success($success);
  3835. }
  3836. public function removeTable(ServerRequestInterface $request): ResponseInterface
  3837. {
  3838. $tableName = RequestUtils::getPathSegment($request, 2);
  3839. if (!$this->reflection->hasTable($tableName)) {
  3840. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3841. }
  3842. $success = $this->definition->removeTable($tableName);
  3843. if ($success) {
  3844. $this->reflection->refreshTables();
  3845. }
  3846. return $this->responder->success($success);
  3847. }
  3848. public function removeColumn(ServerRequestInterface $request): ResponseInterface
  3849. {
  3850. $tableName = RequestUtils::getPathSegment($request, 2);
  3851. $columnName = RequestUtils::getPathSegment($request, 3);
  3852. if (!$this->reflection->hasTable($tableName)) {
  3853. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  3854. }
  3855. $table = $this->reflection->getTable($tableName);
  3856. if (!$table->hasColumn($columnName)) {
  3857. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  3858. }
  3859. $success = $this->definition->removeColumn($tableName, $columnName);
  3860. if ($success) {
  3861. $this->reflection->refreshTable($tableName);
  3862. }
  3863. return $this->responder->success($success);
  3864. }
  3865. }
  3866. }
  3867. // file: src/Tqdev/PhpCrudApi/Controller/GeoJsonController.php
  3868. namespace Tqdev\PhpCrudApi\Controller {
  3869. use Psr\Http\Message\ResponseInterface;
  3870. use Psr\Http\Message\ServerRequestInterface;
  3871. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  3872. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3873. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3874. use Tqdev\PhpCrudApi\RequestUtils;
  3875. class GeoJsonController
  3876. {
  3877. private $service;
  3878. private $responder;
  3879. public function __construct(Router $router, Responder $responder, GeoJsonService $service)
  3880. {
  3881. $router->register('GET', '/geojson/*', array($this, '_list'));
  3882. $router->register('GET', '/geojson/*/*', array($this, 'read'));
  3883. $this->service = $service;
  3884. $this->responder = $responder;
  3885. }
  3886. public function _list(ServerRequestInterface $request): ResponseInterface
  3887. {
  3888. $table = RequestUtils::getPathSegment($request, 2);
  3889. $params = RequestUtils::getParams($request);
  3890. if (!$this->service->hasTable($table)) {
  3891. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3892. }
  3893. return $this->responder->success($this->service->_list($table, $params));
  3894. }
  3895. public function read(ServerRequestInterface $request): ResponseInterface
  3896. {
  3897. $table = RequestUtils::getPathSegment($request, 2);
  3898. if (!$this->service->hasTable($table)) {
  3899. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3900. }
  3901. if ($this->service->getType($table) != 'table') {
  3902. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  3903. }
  3904. $id = RequestUtils::getPathSegment($request, 3);
  3905. $params = RequestUtils::getParams($request);
  3906. if (strpos($id, ',') !== false) {
  3907. $ids = explode(',', $id);
  3908. $result = (object) array('type' => 'FeatureCollection', 'features' => array());
  3909. for ($i = 0; $i < count($ids); $i++) {
  3910. array_push($result->features, $this->service->read($table, $ids[$i], $params));
  3911. }
  3912. return $this->responder->success($result);
  3913. } else {
  3914. $response = $this->service->read($table, $id, $params);
  3915. if ($response === null) {
  3916. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  3917. }
  3918. return $this->responder->success($response);
  3919. }
  3920. }
  3921. }
  3922. }
  3923. // file: src/Tqdev/PhpCrudApi/Controller/JsonResponder.php
  3924. namespace Tqdev\PhpCrudApi\Controller {
  3925. use Psr\Http\Message\ResponseInterface;
  3926. use Tqdev\PhpCrudApi\Record\Document\ErrorDocument;
  3927. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3928. use Tqdev\PhpCrudApi\ResponseFactory;
  3929. class JsonResponder implements Responder
  3930. {
  3931. public function error(int $error, string $argument, $details = null): ResponseInterface
  3932. {
  3933. $errorCode = new ErrorCode($error);
  3934. $status = $errorCode->getStatus();
  3935. $document = new ErrorDocument($errorCode, $argument, $details);
  3936. return ResponseFactory::fromObject($status, $document);
  3937. }
  3938. public function success($result): ResponseInterface
  3939. {
  3940. return ResponseFactory::fromObject(ResponseFactory::OK, $result);
  3941. }
  3942. }
  3943. }
  3944. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  3945. namespace Tqdev\PhpCrudApi\Controller {
  3946. use Psr\Http\Message\ResponseInterface;
  3947. use Psr\Http\Message\ServerRequestInterface;
  3948. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3949. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  3950. class OpenApiController
  3951. {
  3952. private $openApi;
  3953. private $responder;
  3954. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  3955. {
  3956. $router->register('GET', '/openapi', array($this, 'openapi'));
  3957. $this->openApi = $openApi;
  3958. $this->responder = $responder;
  3959. }
  3960. public function openapi(ServerRequestInterface $request): ResponseInterface
  3961. {
  3962. return $this->responder->success($this->openApi->get());
  3963. }
  3964. }
  3965. }
  3966. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  3967. namespace Tqdev\PhpCrudApi\Controller {
  3968. use Psr\Http\Message\ResponseInterface;
  3969. use Psr\Http\Message\ServerRequestInterface;
  3970. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  3971. use Tqdev\PhpCrudApi\Record\ErrorCode;
  3972. use Tqdev\PhpCrudApi\Record\RecordService;
  3973. use Tqdev\PhpCrudApi\RequestUtils;
  3974. class RecordController
  3975. {
  3976. private $service;
  3977. private $responder;
  3978. public function __construct(Router $router, Responder $responder, RecordService $service)
  3979. {
  3980. $router->register('GET', '/records/*', array($this, '_list'));
  3981. $router->register('POST', '/records/*', array($this, 'create'));
  3982. $router->register('GET', '/records/*/*', array($this, 'read'));
  3983. $router->register('PUT', '/records/*/*', array($this, 'update'));
  3984. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  3985. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  3986. $this->service = $service;
  3987. $this->responder = $responder;
  3988. }
  3989. public function _list(ServerRequestInterface $request): ResponseInterface
  3990. {
  3991. $table = RequestUtils::getPathSegment($request, 2);
  3992. $params = RequestUtils::getParams($request);
  3993. if (!$this->service->hasTable($table)) {
  3994. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  3995. }
  3996. return $this->responder->success($this->service->_list($table, $params));
  3997. }
  3998. public function read(ServerRequestInterface $request): ResponseInterface
  3999. {
  4000. $table = RequestUtils::getPathSegment($request, 2);
  4001. if (!$this->service->hasTable($table)) {
  4002. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4003. }
  4004. if ($this->service->getType($table) != 'table') {
  4005. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4006. }
  4007. $id = RequestUtils::getPathSegment($request, 3);
  4008. $params = RequestUtils::getParams($request);
  4009. if (strpos($id, ',') !== false) {
  4010. $ids = explode(',', $id);
  4011. $result = [];
  4012. for ($i = 0; $i < count($ids); $i++) {
  4013. array_push($result, $this->service->read($table, $ids[$i], $params));
  4014. }
  4015. return $this->responder->success($result);
  4016. } else {
  4017. $response = $this->service->read($table, $id, $params);
  4018. if ($response === null) {
  4019. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  4020. }
  4021. return $this->responder->success($response);
  4022. }
  4023. }
  4024. public function create(ServerRequestInterface $request): ResponseInterface
  4025. {
  4026. $table = RequestUtils::getPathSegment($request, 2);
  4027. if (!$this->service->hasTable($table)) {
  4028. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4029. }
  4030. if ($this->service->getType($table) != 'table') {
  4031. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4032. }
  4033. $record = $request->getParsedBody();
  4034. if ($record === null) {
  4035. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4036. }
  4037. $params = RequestUtils::getParams($request);
  4038. if (is_array($record)) {
  4039. $result = array();
  4040. foreach ($record as $r) {
  4041. $result[] = $this->service->create($table, $r, $params);
  4042. }
  4043. return $this->responder->success($result);
  4044. } else {
  4045. return $this->responder->success($this->service->create($table, $record, $params));
  4046. }
  4047. }
  4048. public function update(ServerRequestInterface $request): ResponseInterface
  4049. {
  4050. $table = RequestUtils::getPathSegment($request, 2);
  4051. if (!$this->service->hasTable($table)) {
  4052. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4053. }
  4054. if ($this->service->getType($table) != 'table') {
  4055. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4056. }
  4057. $id = RequestUtils::getPathSegment($request, 3);
  4058. $params = RequestUtils::getParams($request);
  4059. $record = $request->getParsedBody();
  4060. if ($record === null) {
  4061. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4062. }
  4063. $ids = explode(',', $id);
  4064. if (is_array($record)) {
  4065. if (count($ids) != count($record)) {
  4066. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4067. }
  4068. $result = array();
  4069. for ($i = 0; $i < count($ids); $i++) {
  4070. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  4071. }
  4072. return $this->responder->success($result);
  4073. } else {
  4074. if (count($ids) != 1) {
  4075. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4076. }
  4077. return $this->responder->success($this->service->update($table, $id, $record, $params));
  4078. }
  4079. }
  4080. public function delete(ServerRequestInterface $request): ResponseInterface
  4081. {
  4082. $table = RequestUtils::getPathSegment($request, 2);
  4083. if (!$this->service->hasTable($table)) {
  4084. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4085. }
  4086. if ($this->service->getType($table) != 'table') {
  4087. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4088. }
  4089. $id = RequestUtils::getPathSegment($request, 3);
  4090. $params = RequestUtils::getParams($request);
  4091. $ids = explode(',', $id);
  4092. if (count($ids) > 1) {
  4093. $result = array();
  4094. for ($i = 0; $i < count($ids); $i++) {
  4095. $result[] = $this->service->delete($table, $ids[$i], $params);
  4096. }
  4097. return $this->responder->success($result);
  4098. } else {
  4099. return $this->responder->success($this->service->delete($table, $id, $params));
  4100. }
  4101. }
  4102. public function increment(ServerRequestInterface $request): ResponseInterface
  4103. {
  4104. $table = RequestUtils::getPathSegment($request, 2);
  4105. if (!$this->service->hasTable($table)) {
  4106. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  4107. }
  4108. if ($this->service->getType($table) != 'table') {
  4109. return $this->responder->error(ErrorCode::OPERATION_NOT_SUPPORTED, __FUNCTION__);
  4110. }
  4111. $id = RequestUtils::getPathSegment($request, 3);
  4112. $record = $request->getParsedBody();
  4113. if ($record === null) {
  4114. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  4115. }
  4116. $params = RequestUtils::getParams($request);
  4117. $ids = explode(',', $id);
  4118. if (is_array($record)) {
  4119. if (count($ids) != count($record)) {
  4120. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4121. }
  4122. $result = array();
  4123. for ($i = 0; $i < count($ids); $i++) {
  4124. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  4125. }
  4126. return $this->responder->success($result);
  4127. } else {
  4128. if (count($ids) != 1) {
  4129. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  4130. }
  4131. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  4132. }
  4133. }
  4134. }
  4135. }
  4136. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  4137. namespace Tqdev\PhpCrudApi\Controller {
  4138. use Psr\Http\Message\ResponseInterface;
  4139. interface Responder
  4140. {
  4141. public function error(int $error, string $argument, $details = null): ResponseInterface;
  4142. public function success($result): ResponseInterface;
  4143. }
  4144. }
  4145. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  4146. namespace Tqdev\PhpCrudApi\Database {
  4147. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4148. class ColumnConverter
  4149. {
  4150. private $driver;
  4151. public function __construct(string $driver)
  4152. {
  4153. $this->driver = $driver;
  4154. }
  4155. public function convertColumnValue(ReflectedColumn $column): string
  4156. {
  4157. if ($column->isBoolean()) {
  4158. switch ($this->driver) {
  4159. case 'mysql':
  4160. return "IFNULL(IF(?,TRUE,FALSE),NULL)";
  4161. case 'pgsql':
  4162. return "?";
  4163. case 'sqlsrv':
  4164. return "?";
  4165. }
  4166. }
  4167. if ($column->isBinary()) {
  4168. switch ($this->driver) {
  4169. case 'mysql':
  4170. return "FROM_BASE64(?)";
  4171. case 'pgsql':
  4172. return "decode(?, 'base64')";
  4173. case 'sqlsrv':
  4174. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  4175. }
  4176. }
  4177. if ($column->isGeometry()) {
  4178. switch ($this->driver) {
  4179. case 'mysql':
  4180. case 'pgsql':
  4181. return "ST_GeomFromText(?)";
  4182. case 'sqlsrv':
  4183. return "geometry::STGeomFromText(?,0)";
  4184. }
  4185. }
  4186. return '?';
  4187. }
  4188. public function convertColumnName(ReflectedColumn $column, $value): string
  4189. {
  4190. if ($column->isBinary()) {
  4191. switch ($this->driver) {
  4192. case 'mysql':
  4193. return "TO_BASE64($value) as $value";
  4194. case 'pgsql':
  4195. return "encode($value::bytea, 'base64') as $value";
  4196. case 'sqlsrv':
  4197. return "CASE WHEN $value IS NULL THEN NULL ELSE (SELECT CAST($value as varbinary(max)) FOR XML PATH(''), BINARY BASE64) END as $value";
  4198. }
  4199. }
  4200. if ($column->isGeometry()) {
  4201. switch ($this->driver) {
  4202. case 'mysql':
  4203. case 'pgsql':
  4204. return "ST_AsText($value) as $value";
  4205. case 'sqlsrv':
  4206. return "REPLACE($value.STAsText(),' (','(') as $value";
  4207. }
  4208. }
  4209. return $value;
  4210. }
  4211. }
  4212. }
  4213. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  4214. namespace Tqdev\PhpCrudApi\Database {
  4215. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4216. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4217. class ColumnsBuilder
  4218. {
  4219. private $driver;
  4220. private $converter;
  4221. public function __construct(string $driver)
  4222. {
  4223. $this->driver = $driver;
  4224. $this->converter = new ColumnConverter($driver);
  4225. }
  4226. public function getOffsetLimit(int $offset, int $limit): string
  4227. {
  4228. if ($limit < 0 || $offset < 0) {
  4229. return '';
  4230. }
  4231. switch ($this->driver) {
  4232. case 'mysql':
  4233. return " LIMIT $offset, $limit";
  4234. case 'pgsql':
  4235. return " LIMIT $limit OFFSET $offset";
  4236. case 'sqlsrv':
  4237. return " OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  4238. case 'sqlite':
  4239. return " LIMIT $limit OFFSET $offset";
  4240. }
  4241. }
  4242. private function quoteColumnName(ReflectedColumn $column): string
  4243. {
  4244. return '"' . $column->getName() . '"';
  4245. }
  4246. public function getOrderBy(ReflectedTable $table, array $columnOrdering): string
  4247. {
  4248. if (count($columnOrdering) == 0) {
  4249. return '';
  4250. }
  4251. $results = array();
  4252. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  4253. $column = $table->getColumn($columnName);
  4254. $quotedColumnName = $this->quoteColumnName($column);
  4255. $results[] = $quotedColumnName . ' ' . $ordering;
  4256. }
  4257. return ' ORDER BY ' . implode(',', $results);
  4258. }
  4259. public function getSelect(ReflectedTable $table, array $columnNames): string
  4260. {
  4261. $results = array();
  4262. foreach ($columnNames as $columnName) {
  4263. $column = $table->getColumn($columnName);
  4264. $quotedColumnName = $this->quoteColumnName($column);
  4265. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  4266. $results[] = $quotedColumnName;
  4267. }
  4268. return implode(',', $results);
  4269. }
  4270. public function getInsert(ReflectedTable $table, array $columnValues): string
  4271. {
  4272. $columns = array();
  4273. $values = array();
  4274. foreach ($columnValues as $columnName => $columnValue) {
  4275. $column = $table->getColumn($columnName);
  4276. $quotedColumnName = $this->quoteColumnName($column);
  4277. $columns[] = $quotedColumnName;
  4278. $columnValue = $this->converter->convertColumnValue($column);
  4279. $values[] = $columnValue;
  4280. }
  4281. $columnsSql = '(' . implode(',', $columns) . ')';
  4282. $valuesSql = '(' . implode(',', $values) . ')';
  4283. $outputColumn = $this->quoteColumnName($table->getPk());
  4284. switch ($this->driver) {
  4285. case 'mysql':
  4286. return "$columnsSql VALUES $valuesSql";
  4287. case 'pgsql':
  4288. return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  4289. case 'sqlsrv':
  4290. return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  4291. case 'sqlite':
  4292. return "$columnsSql VALUES $valuesSql";
  4293. }
  4294. }
  4295. public function getUpdate(ReflectedTable $table, array $columnValues): string
  4296. {
  4297. $results = array();
  4298. foreach ($columnValues as $columnName => $columnValue) {
  4299. $column = $table->getColumn($columnName);
  4300. $quotedColumnName = $this->quoteColumnName($column);
  4301. $columnValue = $this->converter->convertColumnValue($column);
  4302. $results[] = $quotedColumnName . '=' . $columnValue;
  4303. }
  4304. return implode(',', $results);
  4305. }
  4306. public function getIncrement(ReflectedTable $table, array $columnValues): string
  4307. {
  4308. $results = array();
  4309. foreach ($columnValues as $columnName => $columnValue) {
  4310. if (!is_numeric($columnValue)) {
  4311. continue;
  4312. }
  4313. $column = $table->getColumn($columnName);
  4314. $quotedColumnName = $this->quoteColumnName($column);
  4315. $columnValue = $this->converter->convertColumnValue($column);
  4316. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  4317. }
  4318. return implode(',', $results);
  4319. }
  4320. }
  4321. }
  4322. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  4323. namespace Tqdev\PhpCrudApi\Database {
  4324. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4325. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  4326. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4327. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4328. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  4329. use Tqdev\PhpCrudApi\Record\Condition\NotCondition;
  4330. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  4331. use Tqdev\PhpCrudApi\Record\Condition\SpatialCondition;
  4332. class ConditionsBuilder
  4333. {
  4334. private $driver;
  4335. public function __construct(string $driver)
  4336. {
  4337. $this->driver = $driver;
  4338. }
  4339. private function getConditionSql(Condition $condition, array &$arguments): string
  4340. {
  4341. if ($condition instanceof AndCondition) {
  4342. return $this->getAndConditionSql($condition, $arguments);
  4343. }
  4344. if ($condition instanceof OrCondition) {
  4345. return $this->getOrConditionSql($condition, $arguments);
  4346. }
  4347. if ($condition instanceof NotCondition) {
  4348. return $this->getNotConditionSql($condition, $arguments);
  4349. }
  4350. if ($condition instanceof SpatialCondition) {
  4351. return $this->getSpatialConditionSql($condition, $arguments);
  4352. }
  4353. if ($condition instanceof ColumnCondition) {
  4354. return $this->getColumnConditionSql($condition, $arguments);
  4355. }
  4356. throw new \Exception('Unknown Condition: ' . get_class($condition));
  4357. }
  4358. private function getAndConditionSql(AndCondition $and, array &$arguments): string
  4359. {
  4360. $parts = [];
  4361. foreach ($and->getConditions() as $condition) {
  4362. $parts[] = $this->getConditionSql($condition, $arguments);
  4363. }
  4364. return '(' . implode(' AND ', $parts) . ')';
  4365. }
  4366. private function getOrConditionSql(OrCondition $or, array &$arguments): string
  4367. {
  4368. $parts = [];
  4369. foreach ($or->getConditions() as $condition) {
  4370. $parts[] = $this->getConditionSql($condition, $arguments);
  4371. }
  4372. return '(' . implode(' OR ', $parts) . ')';
  4373. }
  4374. private function getNotConditionSql(NotCondition $not, array &$arguments): string
  4375. {
  4376. $condition = $not->getCondition();
  4377. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  4378. }
  4379. private function quoteColumnName(ReflectedColumn $column): string
  4380. {
  4381. return '"' . $column->getName() . '"';
  4382. }
  4383. private function escapeLikeValue(string $value): string
  4384. {
  4385. return addcslashes($value, '%_');
  4386. }
  4387. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): string
  4388. {
  4389. $column = $this->quoteColumnName($condition->getColumn());
  4390. $operator = $condition->getOperator();
  4391. $value = $condition->getValue();
  4392. switch ($operator) {
  4393. case 'cs':
  4394. $sql = "$column LIKE ?";
  4395. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  4396. break;
  4397. case 'sw':
  4398. $sql = "$column LIKE ?";
  4399. $arguments[] = $this->escapeLikeValue($value) . '%';
  4400. break;
  4401. case 'ew':
  4402. $sql = "$column LIKE ?";
  4403. $arguments[] = '%' . $this->escapeLikeValue($value);
  4404. break;
  4405. case 'eq':
  4406. $sql = "$column = ?";
  4407. $arguments[] = $value;
  4408. break;
  4409. case 'lt':
  4410. $sql = "$column < ?";
  4411. $arguments[] = $value;
  4412. break;
  4413. case 'le':
  4414. $sql = "$column <= ?";
  4415. $arguments[] = $value;
  4416. break;
  4417. case 'ge':
  4418. $sql = "$column >= ?";
  4419. $arguments[] = $value;
  4420. break;
  4421. case 'gt':
  4422. $sql = "$column > ?";
  4423. $arguments[] = $value;
  4424. break;
  4425. case 'bt':
  4426. $parts = explode(',', $value, 2);
  4427. $count = count($parts);
  4428. if ($count == 2) {
  4429. $sql = "($column >= ? AND $column <= ?)";
  4430. $arguments[] = $parts[0];
  4431. $arguments[] = $parts[1];
  4432. } else {
  4433. $sql = "FALSE";
  4434. }
  4435. break;
  4436. case 'in':
  4437. $parts = explode(',', $value);
  4438. $count = count($parts);
  4439. if ($count > 0) {
  4440. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  4441. $sql = "$column IN ($qmarks)";
  4442. for ($i = 0; $i < $count; $i++) {
  4443. $arguments[] = $parts[$i];
  4444. }
  4445. } else {
  4446. $sql = "FALSE";
  4447. }
  4448. break;
  4449. case 'is':
  4450. $sql = "$column IS NULL";
  4451. break;
  4452. }
  4453. return $sql;
  4454. }
  4455. private function getSpatialFunctionName(string $operator): string
  4456. {
  4457. switch ($operator) {
  4458. case 'co':
  4459. return 'ST_Contains';
  4460. case 'cr':
  4461. return 'ST_Crosses';
  4462. case 'di':
  4463. return 'ST_Disjoint';
  4464. case 'eq':
  4465. return 'ST_Equals';
  4466. case 'in':
  4467. return 'ST_Intersects';
  4468. case 'ov':
  4469. return 'ST_Overlaps';
  4470. case 'to':
  4471. return 'ST_Touches';
  4472. case 'wi':
  4473. return 'ST_Within';
  4474. case 'ic':
  4475. return 'ST_IsClosed';
  4476. case 'is':
  4477. return 'ST_IsSimple';
  4478. case 'iv':
  4479. return 'ST_IsValid';
  4480. }
  4481. }
  4482. private function hasSpatialArgument(string $operator): bool
  4483. {
  4484. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  4485. }
  4486. private function getSpatialFunctionCall(string $functionName, string $column, bool $hasArgument): string
  4487. {
  4488. switch ($this->driver) {
  4489. case 'mysql':
  4490. case 'pgsql':
  4491. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  4492. return "$functionName($column, $argument)=TRUE";
  4493. case 'sqlsrv':
  4494. $functionName = str_replace('ST_', 'ST', $functionName);
  4495. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  4496. return "$column.$functionName($argument)=1";
  4497. case 'sqlite':
  4498. $argument = $hasArgument ? '?' : '0';
  4499. return "$functionName($column, $argument)=1";
  4500. }
  4501. }
  4502. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): string
  4503. {
  4504. $column = $this->quoteColumnName($condition->getColumn());
  4505. $operator = $condition->getOperator();
  4506. $value = $condition->getValue();
  4507. $functionName = $this->getSpatialFunctionName($operator);
  4508. $hasArgument = $this->hasSpatialArgument($operator);
  4509. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  4510. if ($hasArgument) {
  4511. $arguments[] = $value;
  4512. }
  4513. return $sql;
  4514. }
  4515. public function getWhereClause(Condition $condition, array &$arguments): string
  4516. {
  4517. if ($condition instanceof NoCondition) {
  4518. return '';
  4519. }
  4520. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  4521. }
  4522. }
  4523. }
  4524. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  4525. namespace Tqdev\PhpCrudApi\Database {
  4526. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4527. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4528. class DataConverter
  4529. {
  4530. private $driver;
  4531. public function __construct(string $driver)
  4532. {
  4533. $this->driver = $driver;
  4534. }
  4535. private function convertRecordValue($conversion, $value)
  4536. {
  4537. $args = explode('|', $conversion);
  4538. $type = array_shift($args);
  4539. switch ($type) {
  4540. case 'boolean':
  4541. return $value ? true : false;
  4542. case 'integer':
  4543. return (int) $value;
  4544. case 'float':
  4545. return (float) $value;
  4546. case 'decimal':
  4547. return number_format($value, $args[0], '.', '');
  4548. }
  4549. return $value;
  4550. }
  4551. private function getRecordValueConversion(ReflectedColumn $column): string
  4552. {
  4553. if (in_array($this->driver, ['mysql', 'sqlsrv', 'sqlite']) && $column->isBoolean()) {
  4554. return 'boolean';
  4555. }
  4556. if (in_array($this->driver, ['sqlsrv', 'sqlite']) && in_array($column->getType(), ['integer', 'bigint'])) {
  4557. return 'integer';
  4558. }
  4559. if (in_array($this->driver, ['sqlite', 'pgsql']) && in_array($column->getType(), ['float', 'double'])) {
  4560. return 'float';
  4561. }
  4562. if (in_array($this->driver, ['sqlite']) && in_array($column->getType(), ['decimal'])) {
  4563. return 'decimal|' . $column->getScale();
  4564. }
  4565. return 'none';
  4566. }
  4567. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  4568. {
  4569. foreach ($columnNames as $columnName) {
  4570. $column = $table->getColumn($columnName);
  4571. $conversion = $this->getRecordValueConversion($column);
  4572. if ($conversion != 'none') {
  4573. foreach ($records as $i => $record) {
  4574. $value = $records[$i][$columnName];
  4575. if ($value === null) {
  4576. continue;
  4577. }
  4578. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  4579. }
  4580. }
  4581. }
  4582. }
  4583. private function convertInputValue($conversion, $value)
  4584. {
  4585. switch ($conversion) {
  4586. case 'boolean':
  4587. return $value ? 1 : 0;
  4588. case 'base64url_to_base64':
  4589. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  4590. }
  4591. return $value;
  4592. }
  4593. private function getInputValueConversion(ReflectedColumn $column): string
  4594. {
  4595. if ($column->isBoolean()) {
  4596. return 'boolean';
  4597. }
  4598. if ($column->isBinary()) {
  4599. return 'base64url_to_base64';
  4600. }
  4601. return 'none';
  4602. }
  4603. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  4604. {
  4605. $columnNames = array_keys($columnValues);
  4606. foreach ($columnNames as $columnName) {
  4607. $column = $table->getColumn($columnName);
  4608. $conversion = $this->getInputValueConversion($column);
  4609. if ($conversion != 'none') {
  4610. $value = $columnValues[$columnName];
  4611. if ($value !== null) {
  4612. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  4613. }
  4614. }
  4615. }
  4616. }
  4617. }
  4618. }
  4619. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  4620. namespace Tqdev\PhpCrudApi\Database {
  4621. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4622. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  4623. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  4624. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  4625. class GenericDB
  4626. {
  4627. private $driver;
  4628. private $address;
  4629. private $port;
  4630. private $database;
  4631. private $tables;
  4632. private $username;
  4633. private $password;
  4634. private $pdo;
  4635. private $reflection;
  4636. private $definition;
  4637. private $conditions;
  4638. private $columns;
  4639. private $converter;
  4640. private function getDsn(): string
  4641. {
  4642. switch ($this->driver) {
  4643. case 'mysql':
  4644. return "$this->driver:host=$this->address;port=$this->port;dbname=$this->database;charset=utf8mb4";
  4645. case 'pgsql':
  4646. return "$this->driver:host=$this->address port=$this->port dbname=$this->database options='--client_encoding=UTF8'";
  4647. case 'sqlsrv':
  4648. return "$this->driver:Server=$this->address,$this->port;Database=$this->database";
  4649. case 'sqlite':
  4650. return "$this->driver:$this->address";
  4651. }
  4652. }
  4653. private function getCommands(): array
  4654. {
  4655. switch ($this->driver) {
  4656. case 'mysql':
  4657. return [
  4658. 'SET SESSION sql_warnings=1;',
  4659. 'SET NAMES utf8mb4;',
  4660. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  4661. ];
  4662. case 'pgsql':
  4663. return [
  4664. "SET NAMES 'UTF8';",
  4665. ];
  4666. case 'sqlsrv':
  4667. return [];
  4668. case 'sqlite':
  4669. return [
  4670. 'PRAGMA foreign_keys = on;',
  4671. ];
  4672. }
  4673. }
  4674. private function getOptions(): array
  4675. {
  4676. $options = array(
  4677. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  4678. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  4679. );
  4680. switch ($this->driver) {
  4681. case 'mysql':
  4682. return $options + [
  4683. \PDO::ATTR_EMULATE_PREPARES => false,
  4684. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  4685. \PDO::ATTR_PERSISTENT => true,
  4686. ];
  4687. case 'pgsql':
  4688. return $options + [
  4689. \PDO::ATTR_EMULATE_PREPARES => false,
  4690. \PDO::ATTR_PERSISTENT => true,
  4691. ];
  4692. case 'sqlsrv':
  4693. return $options + [
  4694. \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
  4695. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  4696. ];
  4697. case 'sqlite':
  4698. return $options + [];
  4699. }
  4700. }
  4701. private function initPdo(): bool
  4702. {
  4703. if ($this->pdo) {
  4704. $result = $this->pdo->reconstruct($this->getDsn(), $this->username, $this->password, $this->getOptions());
  4705. } else {
  4706. $this->pdo = new LazyPdo($this->getDsn(), $this->username, $this->password, $this->getOptions());
  4707. $result = true;
  4708. }
  4709. $commands = $this->getCommands();
  4710. foreach ($commands as $command) {
  4711. $this->pdo->addInitCommand($command);
  4712. }
  4713. $this->reflection = new GenericReflection($this->pdo, $this->driver, $this->database, $this->tables);
  4714. $this->definition = new GenericDefinition($this->pdo, $this->driver, $this->database, $this->tables);
  4715. $this->conditions = new ConditionsBuilder($this->driver);
  4716. $this->columns = new ColumnsBuilder($this->driver);
  4717. $this->converter = new DataConverter($this->driver);
  4718. return $result;
  4719. }
  4720. public function __construct(string $driver, string $address, int $port, string $database, array $tables, string $username, string $password)
  4721. {
  4722. $this->driver = $driver;
  4723. $this->address = $address;
  4724. $this->port = $port;
  4725. $this->database = $database;
  4726. $this->tables = $tables;
  4727. $this->username = $username;
  4728. $this->password = $password;
  4729. $this->initPdo();
  4730. }
  4731. public function reconstruct(string $driver, string $address, int $port, string $database, array $tables, string $username, string $password): bool
  4732. {
  4733. if ($driver) {
  4734. $this->driver = $driver;
  4735. }
  4736. if ($address) {
  4737. $this->address = $address;
  4738. }
  4739. if ($port) {
  4740. $this->port = $port;
  4741. }
  4742. if ($database) {
  4743. $this->database = $database;
  4744. }
  4745. if ($tables) {
  4746. $this->tables = $tables;
  4747. }
  4748. if ($username) {
  4749. $this->username = $username;
  4750. }
  4751. if ($password) {
  4752. $this->password = $password;
  4753. }
  4754. return $this->initPdo();
  4755. }
  4756. public function pdo(): LazyPdo
  4757. {
  4758. return $this->pdo;
  4759. }
  4760. public function reflection(): GenericReflection
  4761. {
  4762. return $this->reflection;
  4763. }
  4764. public function definition(): GenericDefinition
  4765. {
  4766. return $this->definition;
  4767. }
  4768. private function addMiddlewareConditions(string $tableName, Condition $condition): Condition
  4769. {
  4770. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  4771. if ($condition1) {
  4772. $condition = $condition->_and($condition1);
  4773. }
  4774. $condition2 = VariableStore::get("multiTenancy.conditions.$tableName");
  4775. if ($condition2) {
  4776. $condition = $condition->_and($condition2);
  4777. }
  4778. return $condition;
  4779. }
  4780. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  4781. {
  4782. $this->converter->convertColumnValues($table, $columnValues);
  4783. $insertColumns = $this->columns->getInsert($table, $columnValues);
  4784. $tableName = $table->getName();
  4785. $pkName = $table->getPk()->getName();
  4786. $parameters = array_values($columnValues);
  4787. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  4788. $stmt = $this->query($sql, $parameters);
  4789. // return primary key value if specified in the input
  4790. if (isset($columnValues[$pkName])) {
  4791. return $columnValues[$pkName];
  4792. }
  4793. // work around missing "returning" or "output" in mysql
  4794. switch ($this->driver) {
  4795. case 'mysql':
  4796. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  4797. break;
  4798. case 'sqlite':
  4799. $stmt = $this->query('SELECT LAST_INSERT_ROWID()', []);
  4800. break;
  4801. }
  4802. $pkValue = $stmt->fetchColumn(0);
  4803. if ($this->driver == 'sqlsrv' && $table->getPk()->getType() == 'bigint') {
  4804. return (int) $pkValue;
  4805. }
  4806. if ($this->driver == 'sqlite' && in_array($table->getPk()->getType(), ['integer', 'bigint'])) {
  4807. return (int) $pkValue;
  4808. }
  4809. return $pkValue;
  4810. }
  4811. public function selectSingle(ReflectedTable $table, array $columnNames, string $id) /*: ?array*/
  4812. {
  4813. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4814. $tableName = $table->getName();
  4815. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4816. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4817. $parameters = array();
  4818. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4819. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4820. $stmt = $this->query($sql, $parameters);
  4821. $record = $stmt->fetch() ?: null;
  4822. if ($record === null) {
  4823. return null;
  4824. }
  4825. $records = array($record);
  4826. $this->converter->convertRecords($table, $columnNames, $records);
  4827. return $records[0];
  4828. }
  4829. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  4830. {
  4831. if (count($ids) == 0) {
  4832. return [];
  4833. }
  4834. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4835. $tableName = $table->getName();
  4836. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  4837. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4838. $parameters = array();
  4839. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4840. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  4841. $stmt = $this->query($sql, $parameters);
  4842. $records = $stmt->fetchAll();
  4843. $this->converter->convertRecords($table, $columnNames, $records);
  4844. return $records;
  4845. }
  4846. public function selectCount(ReflectedTable $table, Condition $condition): int
  4847. {
  4848. $tableName = $table->getName();
  4849. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4850. $parameters = array();
  4851. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4852. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  4853. $stmt = $this->query($sql, $parameters);
  4854. return $stmt->fetchColumn(0);
  4855. }
  4856. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  4857. {
  4858. if ($limit == 0) {
  4859. return array();
  4860. }
  4861. $selectColumns = $this->columns->getSelect($table, $columnNames);
  4862. $tableName = $table->getName();
  4863. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4864. $parameters = array();
  4865. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4866. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  4867. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  4868. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . $orderBy . $offsetLimit;
  4869. $stmt = $this->query($sql, $parameters);
  4870. $records = $stmt->fetchAll();
  4871. $this->converter->convertRecords($table, $columnNames, $records);
  4872. return $records;
  4873. }
  4874. public function updateSingle(ReflectedTable $table, array $columnValues, string $id)
  4875. {
  4876. if (count($columnValues) == 0) {
  4877. return 0;
  4878. }
  4879. $this->converter->convertColumnValues($table, $columnValues);
  4880. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  4881. $tableName = $table->getName();
  4882. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4883. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4884. $parameters = array_values($columnValues);
  4885. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4886. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4887. $stmt = $this->query($sql, $parameters);
  4888. return $stmt->rowCount();
  4889. }
  4890. public function deleteSingle(ReflectedTable $table, string $id)
  4891. {
  4892. $tableName = $table->getName();
  4893. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4894. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4895. $parameters = array();
  4896. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4897. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  4898. $stmt = $this->query($sql, $parameters);
  4899. return $stmt->rowCount();
  4900. }
  4901. public function incrementSingle(ReflectedTable $table, array $columnValues, string $id)
  4902. {
  4903. if (count($columnValues) == 0) {
  4904. return 0;
  4905. }
  4906. $this->converter->convertColumnValues($table, $columnValues);
  4907. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  4908. $tableName = $table->getName();
  4909. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  4910. $condition = $this->addMiddlewareConditions($tableName, $condition);
  4911. $parameters = array_values($columnValues);
  4912. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  4913. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  4914. $stmt = $this->query($sql, $parameters);
  4915. return $stmt->rowCount();
  4916. }
  4917. private function query(string $sql, array $parameters): \PDOStatement
  4918. {
  4919. $stmt = $this->pdo->prepare($sql);
  4920. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  4921. $stmt->execute($parameters);
  4922. return $stmt;
  4923. }
  4924. public function getCacheKey(): string
  4925. {
  4926. return md5(json_encode([
  4927. $this->driver,
  4928. $this->address,
  4929. $this->port,
  4930. $this->database,
  4931. $this->tables,
  4932. $this->username
  4933. ]));
  4934. }
  4935. }
  4936. }
  4937. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  4938. namespace Tqdev\PhpCrudApi\Database {
  4939. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  4940. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  4941. use Tqdev\PhpCrudApi\Database\LazyPdo;
  4942. class GenericDefinition
  4943. {
  4944. private $pdo;
  4945. private $driver;
  4946. private $database;
  4947. private $typeConverter;
  4948. private $reflection;
  4949. public function __construct(LazyPdo $pdo, string $driver, string $database, array $tables)
  4950. {
  4951. $this->pdo = $pdo;
  4952. $this->driver = $driver;
  4953. $this->database = $database;
  4954. $this->typeConverter = new TypeConverter($driver);
  4955. $this->reflection = new GenericReflection($pdo, $driver, $database, $tables);
  4956. }
  4957. private function quote(string $identifier): string
  4958. {
  4959. return '"' . str_replace('"', '', $identifier) . '"';
  4960. }
  4961. public function getColumnType(ReflectedColumn $column, bool $update): string
  4962. {
  4963. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  4964. return 'serial';
  4965. }
  4966. $type = $this->typeConverter->fromJdbc($column->getType());
  4967. if ($column->hasPrecision() && $column->hasScale()) {
  4968. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  4969. } elseif ($column->hasPrecision()) {
  4970. $size = '(' . $column->getPrecision() . ')';
  4971. } elseif ($column->hasLength()) {
  4972. $size = '(' . $column->getLength() . ')';
  4973. } else {
  4974. $size = '';
  4975. }
  4976. $null = $this->getColumnNullType($column, $update);
  4977. $auto = $this->getColumnAutoIncrement($column, $update);
  4978. return $type . $size . $null . $auto;
  4979. }
  4980. private function getPrimaryKey(string $tableName): string
  4981. {
  4982. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  4983. if (count($pks) == 1) {
  4984. return $pks[0];
  4985. }
  4986. return "";
  4987. }
  4988. private function canAutoIncrement(ReflectedColumn $column): bool
  4989. {
  4990. return in_array($column->getType(), ['integer', 'bigint']);
  4991. }
  4992. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): string
  4993. {
  4994. if (!$this->canAutoIncrement($column)) {
  4995. return '';
  4996. }
  4997. switch ($this->driver) {
  4998. case 'mysql':
  4999. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  5000. case 'pgsql':
  5001. case 'sqlsrv':
  5002. return $column->getPk() ? ' IDENTITY(1,1)' : '';
  5003. case 'sqlite':
  5004. return $column->getPk() ? ' AUTOINCREMENT' : '';
  5005. }
  5006. }
  5007. private function getColumnNullType(ReflectedColumn $column, bool $update): string
  5008. {
  5009. if ($this->driver == 'pgsql' && $update) {
  5010. return '';
  5011. }
  5012. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  5013. }
  5014. private function getTableRenameSQL(string $tableName, string $newTableName): string
  5015. {
  5016. $p1 = $this->quote($tableName);
  5017. $p2 = $this->quote($newTableName);
  5018. switch ($this->driver) {
  5019. case 'mysql':
  5020. return "RENAME TABLE $p1 TO $p2";
  5021. case 'pgsql':
  5022. return "ALTER TABLE $p1 RENAME TO $p2";
  5023. case 'sqlsrv':
  5024. return "EXEC sp_rename $p1, $p2";
  5025. case 'sqlite':
  5026. return "ALTER TABLE $p1 RENAME TO $p2";
  5027. }
  5028. }
  5029. private function getColumnRenameSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5030. {
  5031. $p1 = $this->quote($tableName);
  5032. $p2 = $this->quote($columnName);
  5033. $p3 = $this->quote($newColumn->getName());
  5034. switch ($this->driver) {
  5035. case 'mysql':
  5036. $p4 = $this->getColumnType($newColumn, true);
  5037. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5038. case 'pgsql':
  5039. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  5040. case 'sqlsrv':
  5041. $p4 = $this->quote($tableName . '.' . $columnName);
  5042. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  5043. case 'sqlite':
  5044. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  5045. }
  5046. }
  5047. private function getColumnRetypeSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5048. {
  5049. $p1 = $this->quote($tableName);
  5050. $p2 = $this->quote($columnName);
  5051. $p3 = $this->quote($newColumn->getName());
  5052. $p4 = $this->getColumnType($newColumn, true);
  5053. switch ($this->driver) {
  5054. case 'mysql':
  5055. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5056. case 'pgsql':
  5057. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  5058. case 'sqlsrv':
  5059. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  5060. }
  5061. }
  5062. private function getSetColumnNullableSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5063. {
  5064. $p1 = $this->quote($tableName);
  5065. $p2 = $this->quote($columnName);
  5066. $p3 = $this->quote($newColumn->getName());
  5067. $p4 = $this->getColumnType($newColumn, true);
  5068. switch ($this->driver) {
  5069. case 'mysql':
  5070. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5071. case 'pgsql':
  5072. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  5073. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  5074. case 'sqlsrv':
  5075. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  5076. }
  5077. }
  5078. private function getSetColumnPkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5079. {
  5080. $p1 = $this->quote($tableName);
  5081. $p2 = $this->quote($columnName);
  5082. $p3 = $this->quote($tableName . '_pkey');
  5083. switch ($this->driver) {
  5084. case 'mysql':
  5085. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  5086. return "ALTER TABLE $p1 $p4";
  5087. case 'pgsql':
  5088. case 'sqlsrv':
  5089. $p4 = $newColumn->getPk() ? "ADD CONSTRAINT $p3 PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  5090. return "ALTER TABLE $p1 $p4";
  5091. }
  5092. }
  5093. private function getSetColumnPkSequenceSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5094. {
  5095. $p1 = $this->quote($tableName);
  5096. $p2 = $this->quote($columnName);
  5097. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  5098. switch ($this->driver) {
  5099. case 'mysql':
  5100. return "select 1";
  5101. case 'pgsql':
  5102. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  5103. case 'sqlsrv':
  5104. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  5105. }
  5106. }
  5107. private function getSetColumnPkSequenceStartSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5108. {
  5109. $p1 = $this->quote($tableName);
  5110. $p2 = $this->quote($columnName);
  5111. switch ($this->driver) {
  5112. case 'mysql':
  5113. return "select 1";
  5114. case 'pgsql':
  5115. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  5116. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  5117. case 'sqlsrv':
  5118. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  5119. $p4 = $this->pdo->query("SELECT max($p2)+1 FROM $p1")->fetchColumn();
  5120. return "ALTER SEQUENCE $p3 RESTART WITH $p4";
  5121. }
  5122. }
  5123. private function getSetColumnPkDefaultSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5124. {
  5125. $p1 = $this->quote($tableName);
  5126. $p2 = $this->quote($columnName);
  5127. switch ($this->driver) {
  5128. case 'mysql':
  5129. $p3 = $this->quote($newColumn->getName());
  5130. $p4 = $this->getColumnType($newColumn, true);
  5131. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  5132. case 'pgsql':
  5133. if ($newColumn->getPk()) {
  5134. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  5135. $p4 = "SET DEFAULT nextval($p3)";
  5136. } else {
  5137. $p4 = 'DROP DEFAULT';
  5138. }
  5139. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  5140. case 'sqlsrv':
  5141. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  5142. $p4 = $this->quote($tableName . '_' . $columnName . '_def');
  5143. if ($newColumn->getPk()) {
  5144. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  5145. } else {
  5146. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  5147. }
  5148. }
  5149. }
  5150. private function getAddColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5151. {
  5152. $p1 = $this->quote($tableName);
  5153. $p2 = $this->quote($columnName);
  5154. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5155. $p4 = $this->quote($newColumn->getFk());
  5156. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  5157. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  5158. }
  5159. private function getRemoveColumnFkConstraintSQL(string $tableName, string $columnName, ReflectedColumn $newColumn): string
  5160. {
  5161. $p1 = $this->quote($tableName);
  5162. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5163. switch ($this->driver) {
  5164. case 'mysql':
  5165. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  5166. case 'pgsql':
  5167. case 'sqlsrv':
  5168. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  5169. }
  5170. }
  5171. private function getAddTableSQL(ReflectedTable $newTable): string
  5172. {
  5173. $tableName = $newTable->getName();
  5174. $p1 = $this->quote($tableName);
  5175. $fields = [];
  5176. $constraints = [];
  5177. foreach ($newTable->getColumnNames() as $columnName) {
  5178. $pkColumn = $this->getPrimaryKey($tableName);
  5179. $newColumn = $newTable->getColumn($columnName);
  5180. $f1 = $this->quote($columnName);
  5181. $f2 = $this->getColumnType($newColumn, false);
  5182. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  5183. $f4 = $this->quote($newColumn->getFk());
  5184. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  5185. $f6 = $this->quote($tableName . '_' . $pkColumn . '_pkey');
  5186. if ($this->driver == 'sqlite') {
  5187. if ($newColumn->getPk()) {
  5188. $f2 = str_replace('NULL', 'NULL PRIMARY KEY', $f2);
  5189. }
  5190. $fields[] = "$f1 $f2";
  5191. if ($newColumn->getFk()) {
  5192. $constraints[] = "FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  5193. }
  5194. } else {
  5195. $fields[] = "$f1 $f2";
  5196. if ($newColumn->getPk()) {
  5197. $constraints[] = "CONSTRAINT $f6 PRIMARY KEY ($f1)";
  5198. }
  5199. if ($newColumn->getFk()) {
  5200. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  5201. }
  5202. }
  5203. }
  5204. $p2 = implode(',', array_merge($fields, $constraints));
  5205. return "CREATE TABLE $p1 ($p2);";
  5206. }
  5207. private function getAddColumnSQL(string $tableName, ReflectedColumn $newColumn): string
  5208. {
  5209. $p1 = $this->quote($tableName);
  5210. $p2 = $this->quote($newColumn->getName());
  5211. $p3 = $this->getColumnType($newColumn, false);
  5212. switch ($this->driver) {
  5213. case 'mysql':
  5214. case 'pgsql':
  5215. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  5216. case 'sqlsrv':
  5217. return "ALTER TABLE $p1 ADD $p2 $p3";
  5218. case 'sqlite':
  5219. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  5220. }
  5221. }
  5222. private function getRemoveTableSQL(string $tableName): string
  5223. {
  5224. $p1 = $this->quote($tableName);
  5225. switch ($this->driver) {
  5226. case 'mysql':
  5227. case 'pgsql':
  5228. return "DROP TABLE $p1 CASCADE;";
  5229. case 'sqlsrv':
  5230. return "DROP TABLE $p1;";
  5231. case 'sqlite':
  5232. return "DROP TABLE $p1;";
  5233. }
  5234. }
  5235. private function getRemoveColumnSQL(string $tableName, string $columnName): string
  5236. {
  5237. $p1 = $this->quote($tableName);
  5238. $p2 = $this->quote($columnName);
  5239. switch ($this->driver) {
  5240. case 'mysql':
  5241. case 'pgsql':
  5242. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  5243. case 'sqlsrv':
  5244. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  5245. case 'sqlite':
  5246. return "ALTER TABLE $p1 DROP COLUMN $p2;";
  5247. }
  5248. }
  5249. public function renameTable(string $tableName, string $newTableName)
  5250. {
  5251. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  5252. return $this->query($sql, []);
  5253. }
  5254. public function renameColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5255. {
  5256. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  5257. return $this->query($sql, []);
  5258. }
  5259. public function retypeColumn(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5260. {
  5261. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  5262. return $this->query($sql, []);
  5263. }
  5264. public function setColumnNullable(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5265. {
  5266. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  5267. return $this->query($sql, []);
  5268. }
  5269. public function addColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5270. {
  5271. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5272. $this->query($sql, []);
  5273. if ($this->canAutoIncrement($newColumn)) {
  5274. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5275. $this->query($sql, []);
  5276. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  5277. $this->query($sql, []);
  5278. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5279. $this->query($sql, []);
  5280. }
  5281. return true;
  5282. }
  5283. public function removeColumnPrimaryKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5284. {
  5285. if ($this->canAutoIncrement($newColumn)) {
  5286. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  5287. $this->query($sql, []);
  5288. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  5289. $this->query($sql, []);
  5290. }
  5291. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  5292. $this->query($sql, []);
  5293. return true;
  5294. }
  5295. public function addColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5296. {
  5297. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5298. return $this->query($sql, []);
  5299. }
  5300. public function removeColumnForeignKey(string $tableName, string $columnName, ReflectedColumn $newColumn)
  5301. {
  5302. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  5303. return $this->query($sql, []);
  5304. }
  5305. public function addTable(ReflectedTable $newTable)
  5306. {
  5307. $sql = $this->getAddTableSQL($newTable);
  5308. return $this->query($sql, []);
  5309. }
  5310. public function addColumn(string $tableName, ReflectedColumn $newColumn)
  5311. {
  5312. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  5313. return $this->query($sql, []);
  5314. }
  5315. public function removeTable(string $tableName)
  5316. {
  5317. $sql = $this->getRemoveTableSQL($tableName);
  5318. return $this->query($sql, []);
  5319. }
  5320. public function removeColumn(string $tableName, string $columnName)
  5321. {
  5322. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  5323. return $this->query($sql, []);
  5324. }
  5325. private function query(string $sql, array $arguments): bool
  5326. {
  5327. $stmt = $this->pdo->prepare($sql);
  5328. // echo "- $sql -- " . json_encode($arguments) . "\n";
  5329. return $stmt->execute($arguments);
  5330. }
  5331. }
  5332. }
  5333. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  5334. namespace Tqdev\PhpCrudApi\Database {
  5335. use Tqdev\PhpCrudApi\Database\LazyPdo;
  5336. class GenericReflection
  5337. {
  5338. private $pdo;
  5339. private $driver;
  5340. private $database;
  5341. private $tables;
  5342. private $typeConverter;
  5343. public function __construct(LazyPdo $pdo, string $driver, string $database, array $tables)
  5344. {
  5345. $this->pdo = $pdo;
  5346. $this->driver = $driver;
  5347. $this->database = $database;
  5348. $this->tables = $tables;
  5349. $this->typeConverter = new TypeConverter($driver);
  5350. }
  5351. public function getIgnoredTables(): array
  5352. {
  5353. switch ($this->driver) {
  5354. case 'mysql':
  5355. return [];
  5356. case 'pgsql':
  5357. return ['spatial_ref_sys', 'raster_columns', 'raster_overviews', 'geography_columns', 'geometry_columns'];
  5358. case 'sqlsrv':
  5359. return [];
  5360. case 'sqlite':
  5361. return [];
  5362. }
  5363. }
  5364. private function getTablesSQL(): string
  5365. {
  5366. switch ($this->driver) {
  5367. case 'mysql':
  5368. 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"';
  5369. case 'pgsql':
  5370. 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";';
  5371. case 'sqlsrv':
  5372. 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"';
  5373. case 'sqlite':
  5374. return 'SELECT t.name as "TABLE_NAME", t.type as "TABLE_TYPE" FROM sqlite_master t WHERE t.type IN (\'table\', \'view\') AND \'\' <> ? ORDER BY "TABLE_NAME"';
  5375. }
  5376. }
  5377. private function getTableColumnsSQL(): string
  5378. {
  5379. switch ($this->driver) {
  5380. case 'mysql':
  5381. return 'SELECT "COLUMN_NAME", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH" as "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ? ORDER BY "ORDINAL_POSITION"';
  5382. case 'pgsql':
  5383. return 'SELECT a.attname AS "COLUMN_NAME", case when a.attnotnull then \'NO\' else \'YES\' end as "IS_NULLABLE", pg_catalog.format_type(a.atttypid, -1) as "DATA_TYPE", case when a.atttypmod < 0 then NULL else a.atttypmod-4 end as "CHARACTER_MAXIMUM_LENGTH", case when a.atttypid != 1700 then NULL else ((a.atttypmod - 4) >> 16) & 65535 end as "NUMERIC_PRECISION", case when a.atttypid != 1700 then NULL else (a.atttypmod - 4) & 65535 end as "NUMERIC_SCALE", \'\' AS "COLUMN_TYPE" FROM pg_attribute a JOIN pg_class pgc ON pgc.oid = a.attrelid WHERE pgc.relname = ? AND \'\' <> ? AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum;';
  5384. case 'sqlsrv':
  5385. return 'SELECT c.name AS "COLUMN_NAME", c.is_nullable AS "IS_NULLABLE", t.Name AS "DATA_TYPE", (c.max_length/2) AS "CHARACTER_MAXIMUM_LENGTH", c.precision AS "NUMERIC_PRECISION", c.scale AS "NUMERIC_SCALE", \'\' AS "COLUMN_TYPE" FROM sys.columns c INNER JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE c.object_id = OBJECT_ID(?) AND \'\' <> ? ORDER BY c.column_id';
  5386. case 'sqlite':
  5387. return 'SELECT "name" AS "COLUMN_NAME", case when "notnull"==1 then \'no\' else \'yes\' end as "IS_NULLABLE", lower("type") AS "DATA_TYPE", 2147483647 AS "CHARACTER_MAXIMUM_LENGTH", 0 AS "NUMERIC_PRECISION", 0 AS "NUMERIC_SCALE", \'\' AS "COLUMN_TYPE" FROM pragma_table_info(?) WHERE \'\' <> ? ORDER BY "cid"';
  5388. }
  5389. }
  5390. private function getTablePrimaryKeysSQL(): string
  5391. {
  5392. switch ($this->driver) {
  5393. case 'mysql':
  5394. return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  5395. case 'pgsql':
  5396. 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\'';
  5397. case 'sqlsrv':
  5398. 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 \'\' <> ?';
  5399. case 'sqlite':
  5400. return 'SELECT "name" as "COLUMN_NAME" FROM pragma_table_info(?) WHERE "pk"=1 AND \'\' <> ?';
  5401. }
  5402. }
  5403. private function getTableForeignKeysSQL(): string
  5404. {
  5405. switch ($this->driver) {
  5406. case 'mysql':
  5407. 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" = ?';
  5408. case 'pgsql':
  5409. 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\'';
  5410. case 'sqlsrv':
  5411. 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 \'\' <> ?';
  5412. case 'sqlite':
  5413. return 'SELECT "from" AS "COLUMN_NAME", "table" AS "REFERENCED_TABLE_NAME" FROM pragma_foreign_key_list(?) WHERE \'\' <> ?';
  5414. }
  5415. }
  5416. public function getDatabaseName(): string
  5417. {
  5418. return $this->database;
  5419. }
  5420. public function getTables(): array
  5421. {
  5422. $sql = $this->getTablesSQL();
  5423. $results = $this->query($sql, [$this->database]);
  5424. $tables = $this->tables;
  5425. $results = array_filter($results, function ($v) use ($tables) {
  5426. return !$tables || in_array($v['TABLE_NAME'], $tables);
  5427. });
  5428. foreach ($results as &$result) {
  5429. $map = [];
  5430. switch ($this->driver) {
  5431. case 'mysql':
  5432. $map = ['BASE TABLE' => 'table', 'VIEW' => 'view'];
  5433. break;
  5434. case 'pgsql':
  5435. $map = ['r' => 'table', 'v' => 'view'];
  5436. break;
  5437. case 'sqlsrv':
  5438. $map = ['U' => 'table', 'V' => 'view'];
  5439. break;
  5440. case 'sqlite':
  5441. $map = ['table' => 'table', 'view' => 'view'];
  5442. break;
  5443. }
  5444. $result['TABLE_TYPE'] = $map[trim($result['TABLE_TYPE'])];
  5445. }
  5446. return $results;
  5447. }
  5448. public function getTableColumns(string $tableName, string $type): array
  5449. {
  5450. $sql = $this->getTableColumnsSQL();
  5451. $results = $this->query($sql, [$tableName, $this->database]);
  5452. if ($type == 'view') {
  5453. foreach ($results as &$result) {
  5454. $result['IS_NULLABLE'] = false;
  5455. }
  5456. }
  5457. if ($this->driver == 'mysql') {
  5458. foreach ($results as &$result) {
  5459. // mysql does not properly reflect display width of types
  5460. preg_match('|([a-z]+)(\(([0-9]+)(,([0-9]+))?\))?|', $result['DATA_TYPE'], $matches);
  5461. $result['DATA_TYPE'] = $matches[1];
  5462. if (!$result['CHARACTER_MAXIMUM_LENGTH']) {
  5463. if (isset($matches[3])) {
  5464. $result['NUMERIC_PRECISION'] = $matches[3];
  5465. }
  5466. if (isset($matches[5])) {
  5467. $result['NUMERIC_SCALE'] = $matches[5];
  5468. }
  5469. }
  5470. }
  5471. }
  5472. if ($this->driver == 'sqlite') {
  5473. foreach ($results as &$result) {
  5474. // sqlite does not properly reflect display width of types
  5475. preg_match('|([a-z]+)(\(([0-9]+)(,([0-9]+))?\))?|', $result['DATA_TYPE'], $matches);
  5476. if (isset($matches[1])) {
  5477. $result['DATA_TYPE'] = $matches[1];
  5478. } else {
  5479. $result['DATA_TYPE'] = 'integer';
  5480. }
  5481. if (isset($matches[5])) {
  5482. $result['NUMERIC_PRECISION'] = $matches[3];
  5483. $result['NUMERIC_SCALE'] = $matches[5];
  5484. } else if (isset($matches[3])) {
  5485. $result['CHARACTER_MAXIMUM_LENGTH'] = $matches[3];
  5486. }
  5487. }
  5488. }
  5489. return $results;
  5490. }
  5491. public function getTablePrimaryKeys(string $tableName): array
  5492. {
  5493. $sql = $this->getTablePrimaryKeysSQL();
  5494. $results = $this->query($sql, [$tableName, $this->database]);
  5495. $primaryKeys = [];
  5496. foreach ($results as $result) {
  5497. $primaryKeys[] = $result['COLUMN_NAME'];
  5498. }
  5499. return $primaryKeys;
  5500. }
  5501. public function getTableForeignKeys(string $tableName): array
  5502. {
  5503. $sql = $this->getTableForeignKeysSQL();
  5504. $results = $this->query($sql, [$tableName, $this->database]);
  5505. $foreignKeys = [];
  5506. foreach ($results as $result) {
  5507. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  5508. }
  5509. return $foreignKeys;
  5510. }
  5511. public function toJdbcType(string $type, string $size): string
  5512. {
  5513. return $this->typeConverter->toJdbc($type, $size);
  5514. }
  5515. private function query(string $sql, array $parameters): array
  5516. {
  5517. $stmt = $this->pdo->prepare($sql);
  5518. //echo "- $sql -- " . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\n";
  5519. $stmt->execute($parameters);
  5520. return $stmt->fetchAll();
  5521. }
  5522. }
  5523. }
  5524. // file: src/Tqdev/PhpCrudApi/Database/LazyPdo.php
  5525. namespace Tqdev\PhpCrudApi\Database {
  5526. class LazyPdo extends \PDO
  5527. {
  5528. private $dsn;
  5529. private $user;
  5530. private $password;
  5531. private $options;
  5532. private $commands;
  5533. private $pdo = null;
  5534. public function __construct(string $dsn, /*?string*/ $user = null, /*?string*/ $password = null, array $options = array())
  5535. {
  5536. $this->dsn = $dsn;
  5537. $this->user = $user;
  5538. $this->password = $password;
  5539. $this->options = $options;
  5540. $this->commands = array();
  5541. // explicitly NOT calling super::__construct
  5542. }
  5543. public function addInitCommand(string $command)/*: void*/
  5544. {
  5545. $this->commands[] = $command;
  5546. }
  5547. private function pdo()
  5548. {
  5549. if (!$this->pdo) {
  5550. $this->pdo = new \PDO($this->dsn, $this->user, $this->password, $this->options);
  5551. foreach ($this->commands as $command) {
  5552. $this->pdo->query($command);
  5553. }
  5554. }
  5555. return $this->pdo;
  5556. }
  5557. public function reconstruct(string $dsn, /*?string*/ $user = null, /*?string*/ $password = null, array $options = array()): bool
  5558. {
  5559. $this->dsn = $dsn;
  5560. $this->user = $user;
  5561. $this->password = $password;
  5562. $this->options = $options;
  5563. $this->commands = array();
  5564. if ($this->pdo) {
  5565. $this->pdo = null;
  5566. return true;
  5567. }
  5568. return false;
  5569. }
  5570. public function inTransaction(): bool
  5571. {
  5572. // Do not call parent method if there is no pdo object
  5573. return $this->pdo && parent::inTransaction();
  5574. }
  5575. public function setAttribute($attribute, $value): bool
  5576. {
  5577. if ($this->pdo) {
  5578. return $this->pdo()->setAttribute($attribute, $value);
  5579. }
  5580. $this->options[$attribute] = $value;
  5581. return true;
  5582. }
  5583. public function getAttribute($attribute): mixed
  5584. {
  5585. return $this->pdo()->getAttribute($attribute);
  5586. }
  5587. public function beginTransaction(): bool
  5588. {
  5589. return $this->pdo()->beginTransaction();
  5590. }
  5591. public function commit(): bool
  5592. {
  5593. return $this->pdo()->commit();
  5594. }
  5595. public function rollBack(): bool
  5596. {
  5597. return $this->pdo()->rollBack();
  5598. }
  5599. public function errorCode(): mixed
  5600. {
  5601. return $this->pdo()->errorCode();
  5602. }
  5603. public function errorInfo(): array
  5604. {
  5605. return $this->pdo()->errorInfo();
  5606. }
  5607. public function exec($query): int
  5608. {
  5609. return $this->pdo()->exec($query);
  5610. }
  5611. public function prepare($statement, $options = array())
  5612. {
  5613. return $this->pdo()->prepare($statement, $options);
  5614. }
  5615. public function quote($string, $parameter_type = null): string
  5616. {
  5617. return $this->pdo()->quote($string, $parameter_type);
  5618. }
  5619. public function lastInsertId(/* ?string */$name = null): string
  5620. {
  5621. return $this->pdo()->lastInsertId($name);
  5622. }
  5623. public function query(string $statement): \PDOStatement
  5624. {
  5625. return call_user_func_array(array($this->pdo(), 'query'), func_get_args());
  5626. }
  5627. }
  5628. }
  5629. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  5630. namespace Tqdev\PhpCrudApi\Database {
  5631. class TypeConverter
  5632. {
  5633. private $driver;
  5634. public function __construct(string $driver)
  5635. {
  5636. $this->driver = $driver;
  5637. }
  5638. private $fromJdbc = [
  5639. 'mysql' => [
  5640. 'clob' => 'longtext',
  5641. 'boolean' => 'tinyint(1)',
  5642. 'blob' => 'longblob',
  5643. 'timestamp' => 'datetime',
  5644. ],
  5645. 'pgsql' => [
  5646. 'clob' => 'text',
  5647. 'blob' => 'bytea',
  5648. 'float' => 'real',
  5649. 'double' => 'double precision',
  5650. 'varbinary' => 'bytea',
  5651. ],
  5652. 'sqlsrv' => [
  5653. 'boolean' => 'bit',
  5654. 'varchar' => 'nvarchar',
  5655. 'clob' => 'ntext',
  5656. 'blob' => 'image',
  5657. 'time' => 'time(0)',
  5658. 'timestamp' => 'datetime2(0)',
  5659. 'double' => 'float',
  5660. 'float' => 'real',
  5661. ],
  5662. ];
  5663. private $toJdbc = [
  5664. 'simplified' => [
  5665. 'char' => 'varchar',
  5666. 'longvarchar' => 'clob',
  5667. 'nchar' => 'varchar',
  5668. 'nvarchar' => 'varchar',
  5669. 'longnvarchar' => 'clob',
  5670. 'binary' => 'varbinary',
  5671. 'longvarbinary' => 'blob',
  5672. 'tinyint' => 'integer',
  5673. 'smallint' => 'integer',
  5674. 'real' => 'float',
  5675. 'numeric' => 'decimal',
  5676. 'nclob' => 'clob',
  5677. 'time_with_timezone' => 'time',
  5678. 'timestamp_with_timezone' => 'timestamp',
  5679. ],
  5680. 'mysql' => [
  5681. 'tinyint(1)' => 'boolean',
  5682. 'bit(1)' => 'boolean',
  5683. 'tinyblob' => 'blob',
  5684. 'mediumblob' => 'blob',
  5685. 'longblob' => 'blob',
  5686. 'tinytext' => 'clob',
  5687. 'mediumtext' => 'clob',
  5688. 'longtext' => 'clob',
  5689. 'text' => 'clob',
  5690. 'mediumint' => 'integer',
  5691. 'int' => 'integer',
  5692. 'polygon' => 'geometry',
  5693. 'point' => 'geometry',
  5694. 'datetime' => 'timestamp',
  5695. 'year' => 'integer',
  5696. 'enum' => 'varchar',
  5697. 'set' => 'varchar',
  5698. 'json' => 'clob',
  5699. ],
  5700. 'pgsql' => [
  5701. 'bigserial' => 'bigint',
  5702. 'bit varying' => 'bit',
  5703. 'box' => 'geometry',
  5704. 'bytea' => 'blob',
  5705. 'bpchar' => 'char',
  5706. 'character varying' => 'varchar',
  5707. 'character' => 'char',
  5708. 'cidr' => 'varchar',
  5709. 'circle' => 'geometry',
  5710. 'double precision' => 'double',
  5711. 'inet' => 'integer',
  5712. //'interval [ fields ]'
  5713. 'json' => 'clob',
  5714. 'jsonb' => 'clob',
  5715. 'line' => 'geometry',
  5716. 'lseg' => 'geometry',
  5717. 'macaddr' => 'varchar',
  5718. 'money' => 'decimal',
  5719. 'path' => 'geometry',
  5720. 'point' => 'geometry',
  5721. 'polygon' => 'geometry',
  5722. 'real' => 'float',
  5723. 'serial' => 'integer',
  5724. 'text' => 'clob',
  5725. 'time without time zone' => 'time',
  5726. 'time with time zone' => 'time_with_timezone',
  5727. 'timestamp without time zone' => 'timestamp',
  5728. 'timestamp with time zone' => 'timestamp_with_timezone',
  5729. //'tsquery'=
  5730. //'tsvector'
  5731. //'txid_snapshot'
  5732. 'uuid' => 'char',
  5733. 'xml' => 'clob',
  5734. ],
  5735. // source: https://docs.microsoft.com/en-us/sql/connect/jdbc/using-basic-data-types?view=sql-server-2017
  5736. 'sqlsrv' => [
  5737. 'varbinary()' => 'blob',
  5738. 'bit' => 'boolean',
  5739. 'datetime' => 'timestamp',
  5740. 'datetime2' => 'timestamp',
  5741. 'float' => 'double',
  5742. 'image' => 'blob',
  5743. 'int' => 'integer',
  5744. 'money' => 'decimal',
  5745. 'ntext' => 'clob',
  5746. 'smalldatetime' => 'timestamp',
  5747. 'smallmoney' => 'decimal',
  5748. 'text' => 'clob',
  5749. 'timestamp' => 'binary',
  5750. 'udt' => 'varbinary',
  5751. 'uniqueidentifier' => 'char',
  5752. 'xml' => 'clob',
  5753. ],
  5754. 'sqlite' => [
  5755. 'tinytext' => 'clob',
  5756. 'text' => 'clob',
  5757. 'mediumtext' => 'clob',
  5758. 'longtext' => 'clob',
  5759. 'mediumint' => 'integer',
  5760. 'int' => 'integer',
  5761. 'bigint' => 'bigint',
  5762. 'int2' => 'smallint',
  5763. 'int4' => 'integer',
  5764. 'int8' => 'bigint',
  5765. 'double precision' => 'double',
  5766. 'datetime' => 'timestamp'
  5767. ],
  5768. ];
  5769. // source: https://docs.oracle.com/javase/9/docs/api/java/sql/Types.html
  5770. private $valid = [
  5771. //'array' => true,
  5772. 'bigint' => true,
  5773. 'binary' => true,
  5774. 'bit' => true,
  5775. 'blob' => true,
  5776. 'boolean' => true,
  5777. 'char' => true,
  5778. 'clob' => true,
  5779. //'datalink' => true,
  5780. 'date' => true,
  5781. 'decimal' => true,
  5782. //'distinct' => true,
  5783. 'double' => true,
  5784. 'float' => true,
  5785. 'integer' => true,
  5786. //'java_object' => true,
  5787. 'longnvarchar' => true,
  5788. 'longvarbinary' => true,
  5789. 'longvarchar' => true,
  5790. 'nchar' => true,
  5791. 'nclob' => true,
  5792. //'null' => true,
  5793. 'numeric' => true,
  5794. 'nvarchar' => true,
  5795. //'other' => true,
  5796. 'real' => true,
  5797. //'ref' => true,
  5798. //'ref_cursor' => true,
  5799. //'rowid' => true,
  5800. 'smallint' => true,
  5801. //'sqlxml' => true,
  5802. //'struct' => true,
  5803. 'time' => true,
  5804. 'time_with_timezone' => true,
  5805. 'timestamp' => true,
  5806. 'timestamp_with_timezone' => true,
  5807. 'tinyint' => true,
  5808. 'varbinary' => true,
  5809. 'varchar' => true,
  5810. // extra:
  5811. 'geometry' => true,
  5812. ];
  5813. public function toJdbc(string $type, string $size): string
  5814. {
  5815. $jdbcType = strtolower($type);
  5816. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  5817. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  5818. }
  5819. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  5820. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  5821. }
  5822. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  5823. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  5824. }
  5825. if (!isset($this->valid[$jdbcType])) {
  5826. //throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  5827. $jdbcType = 'clob';
  5828. }
  5829. return $jdbcType;
  5830. }
  5831. public function fromJdbc(string $type): string
  5832. {
  5833. $jdbcType = strtolower($type);
  5834. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  5835. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  5836. }
  5837. return $jdbcType;
  5838. }
  5839. }
  5840. }
  5841. // file: src/Tqdev/PhpCrudApi/GeoJson/Feature.php
  5842. namespace Tqdev\PhpCrudApi\GeoJson {
  5843. class Feature implements \JsonSerializable
  5844. {
  5845. private $id;
  5846. private $properties;
  5847. private $geometry;
  5848. public function __construct($id, array $properties, /*?Geometry*/ $geometry)
  5849. {
  5850. $this->id = $id;
  5851. $this->properties = $properties;
  5852. $this->geometry = $geometry;
  5853. }
  5854. public function serialize()
  5855. {
  5856. return [
  5857. 'type' => 'Feature',
  5858. 'id' => $this->id,
  5859. 'properties' => $this->properties,
  5860. 'geometry' => $this->geometry,
  5861. ];
  5862. }
  5863. public function jsonSerialize()
  5864. {
  5865. return $this->serialize();
  5866. }
  5867. }
  5868. }
  5869. // file: src/Tqdev/PhpCrudApi/GeoJson/FeatureCollection.php
  5870. namespace Tqdev\PhpCrudApi\GeoJson {
  5871. class FeatureCollection implements \JsonSerializable
  5872. {
  5873. private $features;
  5874. private $results;
  5875. public function __construct(array $features, int $results)
  5876. {
  5877. $this->features = $features;
  5878. $this->results = $results;
  5879. }
  5880. public function serialize()
  5881. {
  5882. return [
  5883. 'type' => 'FeatureCollection',
  5884. 'features' => $this->features,
  5885. 'results' => $this->results,
  5886. ];
  5887. }
  5888. public function jsonSerialize()
  5889. {
  5890. return array_filter($this->serialize(), function ($v) {
  5891. return $v !== 0;
  5892. });
  5893. }
  5894. }
  5895. }
  5896. // file: src/Tqdev/PhpCrudApi/GeoJson/GeoJsonService.php
  5897. namespace Tqdev\PhpCrudApi\GeoJson {
  5898. use Tqdev\PhpCrudApi\Column\ReflectionService;
  5899. use Tqdev\PhpCrudApi\GeoJson\FeatureCollection;
  5900. use Tqdev\PhpCrudApi\Record\RecordService;
  5901. class GeoJsonService
  5902. {
  5903. private $reflection;
  5904. private $records;
  5905. public function __construct(ReflectionService $reflection, RecordService $records)
  5906. {
  5907. $this->reflection = $reflection;
  5908. $this->records = $records;
  5909. }
  5910. public function hasTable(string $table): bool
  5911. {
  5912. return $this->reflection->hasTable($table);
  5913. }
  5914. public function getType(string $table): string
  5915. {
  5916. return $this->reflection->getType($table);
  5917. }
  5918. private function getGeometryColumnName(string $tableName, array &$params): string
  5919. {
  5920. $geometryParam = isset($params['geometry']) ? $params['geometry'][0] : '';
  5921. $table = $this->reflection->getTable($tableName);
  5922. $geometryColumnName = '';
  5923. foreach ($table->getColumnNames() as $columnName) {
  5924. if ($geometryParam && $geometryParam != $columnName) {
  5925. continue;
  5926. }
  5927. $column = $table->getColumn($columnName);
  5928. if ($column->isGeometry()) {
  5929. $geometryColumnName = $columnName;
  5930. break;
  5931. }
  5932. }
  5933. if ($geometryColumnName) {
  5934. $params['mandatory'][] = $tableName . "." . $geometryColumnName;
  5935. }
  5936. return $geometryColumnName;
  5937. }
  5938. private function setBoudingBoxFilter(string $geometryColumnName, array &$params)
  5939. {
  5940. $boundingBox = isset($params['bbox']) ? $params['bbox'][0] : '';
  5941. if ($boundingBox) {
  5942. $c = explode(',', $boundingBox);
  5943. if (!isset($params['filter'])) {
  5944. $params['filter'] = array();
  5945. }
  5946. $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]))";
  5947. }
  5948. $tile = isset($params['tile']) ? $params['tile'][0] : '';
  5949. if ($tile) {
  5950. $zxy = explode(',', $tile);
  5951. if (count($zxy) == 3) {
  5952. list($z, $x, $y) = $zxy;
  5953. $c = array();
  5954. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x, $y));
  5955. $c = array_merge($c, $this->convertTileToLatLonOfUpperLeftCorner($z, $x + 1, $y + 1));
  5956. $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]))";
  5957. }
  5958. }
  5959. }
  5960. private function convertTileToLatLonOfUpperLeftCorner($z, $x, $y): array
  5961. {
  5962. $n = pow(2, $z);
  5963. $lon = $x / $n * 360.0 - 180.0;
  5964. $lat = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n))));
  5965. return [$lon, $lat];
  5966. }
  5967. private function convertRecordToFeature(/*object*/$record, string $primaryKeyColumnName, string $geometryColumnName)
  5968. {
  5969. $id = null;
  5970. if ($primaryKeyColumnName) {
  5971. $id = $record[$primaryKeyColumnName];
  5972. }
  5973. $geometry = null;
  5974. if (isset($record[$geometryColumnName])) {
  5975. $geometry = Geometry::fromWkt($record[$geometryColumnName]);
  5976. }
  5977. $properties = array_diff_key($record, [$primaryKeyColumnName => true, $geometryColumnName => true]);
  5978. return new Feature($id, $properties, $geometry);
  5979. }
  5980. private function getPrimaryKeyColumnName(string $tableName, array &$params): string
  5981. {
  5982. $primaryKeyColumn = $this->reflection->getTable($tableName)->getPk();
  5983. if (!$primaryKeyColumn) {
  5984. return '';
  5985. }
  5986. $primaryKeyColumnName = $primaryKeyColumn->getName();
  5987. $params['mandatory'][] = $tableName . "." . $primaryKeyColumnName;
  5988. return $primaryKeyColumnName;
  5989. }
  5990. public function _list(string $tableName, array $params): FeatureCollection
  5991. {
  5992. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  5993. $this->setBoudingBoxFilter($geometryColumnName, $params);
  5994. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  5995. $records = $this->records->_list($tableName, $params);
  5996. $features = array();
  5997. foreach ($records->getRecords() as $record) {
  5998. $features[] = $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  5999. }
  6000. return new FeatureCollection($features, $records->getResults());
  6001. }
  6002. public function read(string $tableName, string $id, array $params): Feature
  6003. {
  6004. $geometryColumnName = $this->getGeometryColumnName($tableName, $params);
  6005. $primaryKeyColumnName = $this->getPrimaryKeyColumnName($tableName, $params);
  6006. $record = $this->records->read($tableName, $id, $params);
  6007. return $this->convertRecordToFeature($record, $primaryKeyColumnName, $geometryColumnName);
  6008. }
  6009. }
  6010. }
  6011. // file: src/Tqdev/PhpCrudApi/GeoJson/Geometry.php
  6012. namespace Tqdev\PhpCrudApi\GeoJson {
  6013. class Geometry implements \JsonSerializable
  6014. {
  6015. private $type;
  6016. private $geometry;
  6017. public static $types = [
  6018. "Point",
  6019. "MultiPoint",
  6020. "LineString",
  6021. "MultiLineString",
  6022. "Polygon",
  6023. "MultiPolygon",
  6024. //"GeometryCollection",
  6025. ];
  6026. public function __construct(string $type, array $coordinates)
  6027. {
  6028. $this->type = $type;
  6029. $this->coordinates = $coordinates;
  6030. }
  6031. public static function fromWkt(string $wkt): Geometry
  6032. {
  6033. $bracket = strpos($wkt, '(');
  6034. $type = strtoupper(trim(substr($wkt, 0, $bracket)));
  6035. $supported = false;
  6036. foreach (Geometry::$types as $typeName) {
  6037. if (strtoupper($typeName) == $type) {
  6038. $type = $typeName;
  6039. $supported = true;
  6040. }
  6041. }
  6042. if (!$supported) {
  6043. throw new \Exception('Geometry type not supported: ' . $type);
  6044. }
  6045. $coordinates = substr($wkt, $bracket);
  6046. if (substr($type, -5) != 'Point' || ($type == 'MultiPoint' && $coordinates[1] != '(')) {
  6047. $coordinates = preg_replace('|([0-9\-\.]+ )+([0-9\-\.]+)|', '[\1\2]', $coordinates);
  6048. }
  6049. $coordinates = str_replace(['(', ')', ', ', ' '], ['[', ']', ',', ','], $coordinates);
  6050. $coordinates = json_decode($coordinates);
  6051. if (!$coordinates) {
  6052. throw new \Exception('Could not decode WKT: ' . $wkt);
  6053. }
  6054. return new Geometry($type, $coordinates);
  6055. }
  6056. public function serialize()
  6057. {
  6058. return [
  6059. 'type' => $this->type,
  6060. 'coordinates' => $this->coordinates,
  6061. ];
  6062. }
  6063. public function jsonSerialize()
  6064. {
  6065. return $this->serialize();
  6066. }
  6067. }
  6068. }
  6069. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  6070. namespace Tqdev\PhpCrudApi\Middleware\Base {
  6071. use Psr\Http\Server\MiddlewareInterface;
  6072. use Tqdev\PhpCrudApi\Controller\Responder;
  6073. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6074. abstract class Middleware implements MiddlewareInterface
  6075. {
  6076. protected $next;
  6077. protected $responder;
  6078. private $properties;
  6079. public function __construct(Router $router, Responder $responder, array $properties)
  6080. {
  6081. $router->load($this);
  6082. $this->responder = $responder;
  6083. $this->properties = $properties;
  6084. }
  6085. protected function getArrayProperty(string $key, string $default): array
  6086. {
  6087. return array_filter(array_map('trim', explode(',', $this->getProperty($key, $default))));
  6088. }
  6089. protected function getMapProperty(string $key, string $default): array
  6090. {
  6091. $pairs = $this->getArrayProperty($key, $default);
  6092. $result = array();
  6093. foreach ($pairs as $pair) {
  6094. if (strpos($pair, ':')) {
  6095. list($k, $v) = explode(':', $pair, 2);
  6096. $result[trim($k)] = trim($v);
  6097. } else {
  6098. $result[] = trim($pair);
  6099. }
  6100. }
  6101. return $result;
  6102. }
  6103. protected function getProperty(string $key, $default)
  6104. {
  6105. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  6106. }
  6107. }
  6108. }
  6109. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  6110. namespace Tqdev\PhpCrudApi\Middleware\Communication {
  6111. class VariableStore
  6112. {
  6113. public static $values = array();
  6114. public static function get(string $key)
  6115. {
  6116. if (isset(self::$values[$key])) {
  6117. return self::$values[$key];
  6118. }
  6119. return null;
  6120. }
  6121. public static function set(string $key, /* object */ $value)
  6122. {
  6123. self::$values[$key] = $value;
  6124. }
  6125. }
  6126. }
  6127. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  6128. namespace Tqdev\PhpCrudApi\Middleware\Router {
  6129. use Psr\Http\Message\ResponseInterface;
  6130. use Psr\Http\Message\ServerRequestInterface;
  6131. use Psr\Http\Server\RequestHandlerInterface;
  6132. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6133. interface Router extends RequestHandlerInterface
  6134. {
  6135. public function register(string $method, string $path, array $handler);
  6136. public function load(Middleware $middleware);
  6137. public function route(ServerRequestInterface $request): ResponseInterface;
  6138. }
  6139. }
  6140. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  6141. namespace Tqdev\PhpCrudApi\Middleware\Router {
  6142. use Psr\Http\Message\ResponseInterface;
  6143. use Psr\Http\Message\ServerRequestInterface;
  6144. use Tqdev\PhpCrudApi\Cache\Cache;
  6145. use Tqdev\PhpCrudApi\Controller\Responder;
  6146. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6147. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6148. use Tqdev\PhpCrudApi\Record\PathTree;
  6149. use Tqdev\PhpCrudApi\RequestUtils;
  6150. use Tqdev\PhpCrudApi\ResponseUtils;
  6151. class SimpleRouter implements Router
  6152. {
  6153. private $basePath;
  6154. private $responder;
  6155. private $cache;
  6156. private $ttl;
  6157. private $debug;
  6158. private $registration;
  6159. private $routes;
  6160. private $routeHandlers;
  6161. private $middlewares;
  6162. public function __construct(string $basePath, Responder $responder, Cache $cache, int $ttl, bool $debug)
  6163. {
  6164. $this->basePath = rtrim($this->detectBasePath($basePath), '/');
  6165. $this->responder = $responder;
  6166. $this->cache = $cache;
  6167. $this->ttl = $ttl;
  6168. $this->debug = $debug;
  6169. $this->registration = true;
  6170. $this->routes = $this->loadPathTree();
  6171. $this->routeHandlers = [];
  6172. $this->middlewares = array();
  6173. }
  6174. private function detectBasePath(string $basePath): string
  6175. {
  6176. if ($basePath) {
  6177. return $basePath;
  6178. }
  6179. if (isset($_SERVER['REQUEST_URI'])) {
  6180. $fullPath = urldecode(explode('?', $_SERVER['REQUEST_URI'])[0]);
  6181. if (isset($_SERVER['PATH_INFO'])) {
  6182. $path = $_SERVER['PATH_INFO'];
  6183. if (substr($fullPath, -1 * strlen($path)) == $path) {
  6184. return substr($fullPath, 0, -1 * strlen($path));
  6185. }
  6186. }
  6187. return $fullPath;
  6188. }
  6189. return '/';
  6190. }
  6191. private function loadPathTree(): PathTree
  6192. {
  6193. $data = $this->cache->get('PathTree');
  6194. if ($data != '') {
  6195. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  6196. $this->registration = false;
  6197. } else {
  6198. $tree = new PathTree();
  6199. }
  6200. return $tree;
  6201. }
  6202. public function register(string $method, string $path, array $handler)
  6203. {
  6204. $routeNumber = count($this->routeHandlers);
  6205. $this->routeHandlers[$routeNumber] = $handler;
  6206. if ($this->registration) {
  6207. $path = trim($path, '/');
  6208. $parts = array();
  6209. if ($path) {
  6210. $parts = explode('/', $path);
  6211. }
  6212. array_unshift($parts, $method);
  6213. $this->routes->put($parts, $routeNumber);
  6214. }
  6215. }
  6216. public function load(Middleware $middleware) /*: void*/
  6217. {
  6218. array_push($this->middlewares, $middleware);
  6219. }
  6220. public function route(ServerRequestInterface $request): ResponseInterface
  6221. {
  6222. if ($this->registration) {
  6223. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  6224. $this->cache->set('PathTree', $data, $this->ttl);
  6225. }
  6226. return $this->handle($request);
  6227. }
  6228. private function getRouteNumbers(ServerRequestInterface $request): array
  6229. {
  6230. $method = strtoupper($request->getMethod());
  6231. $path = array();
  6232. $segment = $method;
  6233. for ($i = 1; $segment; $i++) {
  6234. array_push($path, $segment);
  6235. $segment = RequestUtils::getPathSegment($request, $i);
  6236. }
  6237. return $this->routes->match($path);
  6238. }
  6239. private function removeBasePath(ServerRequestInterface $request): ServerRequestInterface
  6240. {
  6241. $path = $request->getUri()->getPath();
  6242. if (substr($path, 0, strlen($this->basePath)) == $this->basePath) {
  6243. $path = substr($path, strlen($this->basePath));
  6244. $request = $request->withUri($request->getUri()->withPath($path));
  6245. }
  6246. return $request;
  6247. }
  6248. public function getBasePath(): string
  6249. {
  6250. return $this->basePath;
  6251. }
  6252. public function handle(ServerRequestInterface $request): ResponseInterface
  6253. {
  6254. $request = $this->removeBasePath($request);
  6255. if (count($this->middlewares)) {
  6256. $handler = array_pop($this->middlewares);
  6257. return $handler->process($request, $this);
  6258. }
  6259. $routeNumbers = $this->getRouteNumbers($request);
  6260. if (count($routeNumbers) == 0) {
  6261. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getUri()->getPath());
  6262. }
  6263. try {
  6264. $response = call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  6265. } catch (\PDOException $e) {
  6266. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  6267. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  6268. } elseif (strpos(strtolower($e->getMessage()), 'unique constraint') !== false) {
  6269. $response = $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  6270. } elseif (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  6271. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  6272. } elseif (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  6273. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  6274. } elseif (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  6275. $response = $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  6276. } else {
  6277. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, '');
  6278. }
  6279. if ($this->debug) {
  6280. $response = ResponseUtils::addExceptionHeaders($response, $e);
  6281. }
  6282. }
  6283. return $response;
  6284. }
  6285. }
  6286. }
  6287. // file: src/Tqdev/PhpCrudApi/Middleware/AjaxOnlyMiddleware.php
  6288. namespace Tqdev\PhpCrudApi\Middleware {
  6289. use Psr\Http\Message\ResponseInterface;
  6290. use Psr\Http\Message\ServerRequestInterface;
  6291. use Psr\Http\Server\RequestHandlerInterface;
  6292. use Tqdev\PhpCrudApi\Controller\Responder;
  6293. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6294. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6295. use Tqdev\PhpCrudApi\RequestUtils;
  6296. class AjaxOnlyMiddleware extends Middleware
  6297. {
  6298. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6299. {
  6300. $method = $request->getMethod();
  6301. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  6302. if (!in_array($method, $excludeMethods)) {
  6303. $headerName = $this->getProperty('headerName', 'X-Requested-With');
  6304. $headerValue = $this->getProperty('headerValue', 'XMLHttpRequest');
  6305. if ($headerValue != RequestUtils::getHeader($request, $headerName)) {
  6306. return $this->responder->error(ErrorCode::ONLY_AJAX_REQUESTS_ALLOWED, $method);
  6307. }
  6308. }
  6309. return $next->handle($request);
  6310. }
  6311. }
  6312. }
  6313. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  6314. namespace Tqdev\PhpCrudApi\Middleware {
  6315. use Psr\Http\Message\ResponseInterface;
  6316. use Psr\Http\Message\ServerRequestInterface;
  6317. use Psr\Http\Server\RequestHandlerInterface;
  6318. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6319. use Tqdev\PhpCrudApi\Controller\Responder;
  6320. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6321. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6322. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6323. use Tqdev\PhpCrudApi\Record\FilterInfo;
  6324. use Tqdev\PhpCrudApi\RequestUtils;
  6325. class AuthorizationMiddleware extends Middleware
  6326. {
  6327. private $reflection;
  6328. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6329. {
  6330. parent::__construct($router, $responder, $properties);
  6331. $this->reflection = $reflection;
  6332. }
  6333. private function handleColumns(string $operation, string $tableName) /*: void*/
  6334. {
  6335. $columnHandler = $this->getProperty('columnHandler', '');
  6336. if ($columnHandler) {
  6337. $table = $this->reflection->getTable($tableName);
  6338. foreach ($table->getColumnNames() as $columnName) {
  6339. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  6340. if (!$allowed) {
  6341. $table->removeColumn($columnName);
  6342. }
  6343. }
  6344. }
  6345. }
  6346. private function handleTable(string $operation, string $tableName) /*: void*/
  6347. {
  6348. if (!$this->reflection->hasTable($tableName)) {
  6349. return;
  6350. }
  6351. $allowed = true;
  6352. $tableHandler = $this->getProperty('tableHandler', '');
  6353. if ($tableHandler) {
  6354. $allowed = call_user_func($tableHandler, $operation, $tableName);
  6355. }
  6356. if (!$allowed) {
  6357. $this->reflection->removeTable($tableName);
  6358. } else {
  6359. $this->handleColumns($operation, $tableName);
  6360. }
  6361. }
  6362. private function handleRecords(string $operation, string $tableName) /*: void*/
  6363. {
  6364. if (!$this->reflection->hasTable($tableName)) {
  6365. return;
  6366. }
  6367. $recordHandler = $this->getProperty('recordHandler', '');
  6368. if ($recordHandler) {
  6369. $query = call_user_func($recordHandler, $operation, $tableName);
  6370. $filters = new FilterInfo();
  6371. $table = $this->reflection->getTable($tableName);
  6372. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  6373. parse_str($query, $params);
  6374. $condition = $filters->getCombinedConditions($table, $params);
  6375. VariableStore::set("authorization.conditions.$tableName", $condition);
  6376. }
  6377. }
  6378. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6379. {
  6380. $path = RequestUtils::getPathSegment($request, 1);
  6381. $operation = RequestUtils::getOperation($request);
  6382. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  6383. foreach ($tableNames as $tableName) {
  6384. $this->handleTable($operation, $tableName);
  6385. if ($path == 'records') {
  6386. $this->handleRecords($operation, $tableName);
  6387. }
  6388. }
  6389. if ($path == 'openapi') {
  6390. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  6391. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  6392. }
  6393. return $next->handle($request);
  6394. }
  6395. }
  6396. }
  6397. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  6398. namespace Tqdev\PhpCrudApi\Middleware {
  6399. use Psr\Http\Message\ResponseInterface;
  6400. use Psr\Http\Message\ServerRequestInterface;
  6401. use Psr\Http\Server\RequestHandlerInterface;
  6402. use Tqdev\PhpCrudApi\Controller\Responder;
  6403. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6404. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6405. use Tqdev\PhpCrudApi\RequestUtils;
  6406. class BasicAuthMiddleware extends Middleware
  6407. {
  6408. private function hasCorrectPassword(string $username, string $password, array &$passwords): bool
  6409. {
  6410. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  6411. if ($hash && password_verify($password, $hash)) {
  6412. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  6413. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  6414. }
  6415. return true;
  6416. }
  6417. return false;
  6418. }
  6419. private function getValidUsername(string $username, string $password, string $passwordFile): string
  6420. {
  6421. $passwords = $this->readPasswords($passwordFile);
  6422. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  6423. $this->writePasswords($passwordFile, $passwords);
  6424. return $valid ? $username : '';
  6425. }
  6426. private function readPasswords(string $passwordFile): array
  6427. {
  6428. $passwords = [];
  6429. $passwordLines = file($passwordFile);
  6430. foreach ($passwordLines as $passwordLine) {
  6431. if (strpos($passwordLine, ':') !== false) {
  6432. list($username, $hash) = explode(':', trim($passwordLine), 2);
  6433. if (strlen($hash) > 0 && $hash[0] != '$') {
  6434. $hash = password_hash($hash, PASSWORD_DEFAULT);
  6435. }
  6436. $passwords[$username] = $hash;
  6437. }
  6438. }
  6439. return $passwords;
  6440. }
  6441. private function writePasswords(string $passwordFile, array $passwords): bool
  6442. {
  6443. $success = false;
  6444. $passwordFileContents = '';
  6445. foreach ($passwords as $username => $hash) {
  6446. $passwordFileContents .= "$username:$hash\n";
  6447. }
  6448. if (file_get_contents($passwordFile) != $passwordFileContents) {
  6449. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  6450. }
  6451. return $success;
  6452. }
  6453. private function getAuthorizationCredentials(ServerRequestInterface $request): string
  6454. {
  6455. if (isset($_SERVER['PHP_AUTH_USER'])) {
  6456. return $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'];
  6457. }
  6458. $header = RequestUtils::getHeader($request, 'Authorization');
  6459. $parts = explode(' ', trim($header), 2);
  6460. if (count($parts) != 2) {
  6461. return '';
  6462. }
  6463. if ($parts[0] != 'Basic') {
  6464. return '';
  6465. }
  6466. return base64_decode(strtr($parts[1], '-_', '+/'));
  6467. }
  6468. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6469. {
  6470. if (session_status() == PHP_SESSION_NONE) {
  6471. if (!headers_sent()) {
  6472. $sessionName = $this->getProperty('sessionName', '');
  6473. if ($sessionName) {
  6474. session_name($sessionName);
  6475. }
  6476. session_start();
  6477. }
  6478. }
  6479. $credentials = $this->getAuthorizationCredentials($request);
  6480. if ($credentials) {
  6481. list($username, $password) = array('', '');
  6482. if (strpos($credentials, ':') !== false) {
  6483. list($username, $password) = explode(':', $credentials, 2);
  6484. }
  6485. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  6486. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  6487. $_SESSION['username'] = $validUser;
  6488. if (!$validUser) {
  6489. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6490. }
  6491. if (!headers_sent()) {
  6492. session_regenerate_id();
  6493. }
  6494. }
  6495. if (!isset($_SESSION['username']) || !$_SESSION['username']) {
  6496. $authenticationMode = $this->getProperty('mode', 'required');
  6497. if ($authenticationMode == 'required') {
  6498. $response = $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6499. $realm = $this->getProperty('realm', 'Username and password required');
  6500. $response = $response->withHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
  6501. return $response;
  6502. }
  6503. }
  6504. return $next->handle($request);
  6505. }
  6506. }
  6507. }
  6508. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  6509. namespace Tqdev\PhpCrudApi\Middleware {
  6510. use Psr\Http\Message\ResponseInterface;
  6511. use Psr\Http\Message\ServerRequestInterface;
  6512. use Psr\Http\Server\RequestHandlerInterface;
  6513. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6514. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6515. use Tqdev\PhpCrudApi\ResponseFactory;
  6516. class CorsMiddleware extends Middleware
  6517. {
  6518. private function isOriginAllowed(string $origin, string $allowedOrigins): bool
  6519. {
  6520. $found = false;
  6521. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  6522. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  6523. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  6524. if (preg_match($regex, $origin)) {
  6525. $found = true;
  6526. break;
  6527. }
  6528. }
  6529. return $found;
  6530. }
  6531. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6532. {
  6533. $method = $request->getMethod();
  6534. $origin = count($request->getHeader('Origin')) ? $request->getHeader('Origin')[0] : '';
  6535. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  6536. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  6537. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  6538. } elseif ($method == 'OPTIONS') {
  6539. $response = ResponseFactory::fromStatus(ResponseFactory::OK);
  6540. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN, X-Authorization');
  6541. if ($allowHeaders) {
  6542. $response = $response->withHeader('Access-Control-Allow-Headers', $allowHeaders);
  6543. }
  6544. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  6545. if ($allowMethods) {
  6546. $response = $response->withHeader('Access-Control-Allow-Methods', $allowMethods);
  6547. }
  6548. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6549. if ($allowCredentials) {
  6550. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6551. }
  6552. $maxAge = $this->getProperty('maxAge', '1728000');
  6553. if ($maxAge) {
  6554. $response = $response->withHeader('Access-Control-Max-Age', $maxAge);
  6555. }
  6556. $exposeHeaders = $this->getProperty('exposeHeaders', '');
  6557. if ($exposeHeaders) {
  6558. $response = $response->withHeader('Access-Control-Expose-Headers', $exposeHeaders);
  6559. }
  6560. } else {
  6561. $response = $next->handle($request);
  6562. }
  6563. if ($origin) {
  6564. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  6565. if ($allowCredentials) {
  6566. $response = $response->withHeader('Access-Control-Allow-Credentials', $allowCredentials);
  6567. }
  6568. $response = $response->withHeader('Access-Control-Allow-Origin', $origin);
  6569. }
  6570. return $response;
  6571. }
  6572. }
  6573. }
  6574. // file: src/Tqdev/PhpCrudApi/Middleware/CustomizationMiddleware.php
  6575. namespace Tqdev\PhpCrudApi\Middleware {
  6576. use Psr\Http\Message\ResponseInterface;
  6577. use Psr\Http\Message\ServerRequestInterface;
  6578. use Psr\Http\Server\RequestHandlerInterface;
  6579. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6580. use Tqdev\PhpCrudApi\Controller\Responder;
  6581. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6582. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6583. use Tqdev\PhpCrudApi\RequestUtils;
  6584. class CustomizationMiddleware extends Middleware
  6585. {
  6586. private $reflection;
  6587. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6588. {
  6589. parent::__construct($router, $responder, $properties);
  6590. $this->reflection = $reflection;
  6591. }
  6592. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6593. {
  6594. $operation = RequestUtils::getOperation($request);
  6595. $tableName = RequestUtils::getPathSegment($request, 2);
  6596. $beforeHandler = $this->getProperty('beforeHandler', '');
  6597. $environment = (object) array();
  6598. if ($beforeHandler !== '') {
  6599. $result = call_user_func($beforeHandler, $operation, $tableName, $request, $environment);
  6600. $request = $result ?: $request;
  6601. }
  6602. $response = $next->handle($request);
  6603. $afterHandler = $this->getProperty('afterHandler', '');
  6604. if ($afterHandler !== '') {
  6605. $result = call_user_func($afterHandler, $operation, $tableName, $response, $environment);
  6606. $response = $result ?: $response;
  6607. }
  6608. return $response;
  6609. }
  6610. }
  6611. }
  6612. // file: src/Tqdev/PhpCrudApi/Middleware/DbAuthMiddleware.php
  6613. namespace Tqdev\PhpCrudApi\Middleware {
  6614. use Psr\Http\Message\ResponseInterface;
  6615. use Psr\Http\Message\ServerRequestInterface;
  6616. use Psr\Http\Server\RequestHandlerInterface;
  6617. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6618. use Tqdev\PhpCrudApi\Controller\Responder;
  6619. use Tqdev\PhpCrudApi\Database\GenericDB;
  6620. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6621. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6622. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  6623. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6624. use Tqdev\PhpCrudApi\Record\OrderingInfo;
  6625. use Tqdev\PhpCrudApi\RequestUtils;
  6626. class DbAuthMiddleware extends Middleware
  6627. {
  6628. private $reflection;
  6629. private $db;
  6630. private $ordering;
  6631. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  6632. {
  6633. parent::__construct($router, $responder, $properties);
  6634. $this->reflection = $reflection;
  6635. $this->db = $db;
  6636. $this->ordering = new OrderingInfo();
  6637. }
  6638. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6639. {
  6640. if (session_status() == PHP_SESSION_NONE) {
  6641. if (!headers_sent()) {
  6642. $sessionName = $this->getProperty('sessionName', '');
  6643. if ($sessionName) {
  6644. session_name($sessionName);
  6645. }
  6646. session_start();
  6647. }
  6648. }
  6649. $path = RequestUtils::getPathSegment($request, 1);
  6650. $method = $request->getMethod();
  6651. if ($method == 'POST' && $path == 'login') {
  6652. $body = $request->getParsedBody();
  6653. $username = isset($body->username) ? $body->username : '';
  6654. $password = isset($body->password) ? $body->password : '';
  6655. $tableName = $this->getProperty('usersTable', 'users');
  6656. $table = $this->reflection->getTable($tableName);
  6657. $usernameColumnName = $this->getProperty('usernameColumn', 'username');
  6658. $usernameColumn = $table->getColumn($usernameColumnName);
  6659. $passwordColumnName = $this->getProperty('passwordColumn', 'password');
  6660. $passwordColumn = $table->getColumn($passwordColumnName);
  6661. $condition = new ColumnCondition($usernameColumn, 'eq', $username);
  6662. $returnedColumns = $this->getProperty('returnedColumns', '');
  6663. if (!$returnedColumns) {
  6664. $columnNames = $table->getColumnNames();
  6665. } else {
  6666. $columnNames = array_map('trim', explode(',', $returnedColumns));
  6667. $columnNames[] = $passwordColumnName;
  6668. }
  6669. $columnOrdering = $this->ordering->getDefaultColumnOrdering($table);
  6670. $users = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, 0, 1);
  6671. foreach ($users as $user) {
  6672. if (password_verify($password, $user[$passwordColumnName]) == 1) {
  6673. if (!headers_sent()) {
  6674. session_regenerate_id(true);
  6675. }
  6676. unset($user[$passwordColumnName]);
  6677. $_SESSION['user'] = $user;
  6678. return $this->responder->success($user);
  6679. }
  6680. }
  6681. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, $username);
  6682. }
  6683. if ($method == 'POST' && $path == 'logout') {
  6684. if (isset($_SESSION['user'])) {
  6685. $user = $_SESSION['user'];
  6686. unset($_SESSION['user']);
  6687. if (session_status() != PHP_SESSION_NONE) {
  6688. session_destroy();
  6689. }
  6690. return $this->responder->success($user);
  6691. }
  6692. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6693. }
  6694. if (!isset($_SESSION['user']) || !$_SESSION['user']) {
  6695. $authenticationMode = $this->getProperty('mode', 'required');
  6696. if ($authenticationMode == 'required') {
  6697. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  6698. }
  6699. }
  6700. return $next->handle($request);
  6701. }
  6702. }
  6703. }
  6704. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  6705. namespace Tqdev\PhpCrudApi\Middleware {
  6706. use Psr\Http\Message\ResponseInterface;
  6707. use Psr\Http\Message\ServerRequestInterface;
  6708. use Psr\Http\Server\RequestHandlerInterface;
  6709. use Tqdev\PhpCrudApi\Controller\Responder;
  6710. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6711. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6712. class FirewallMiddleware extends Middleware
  6713. {
  6714. private function ipMatch(string $ip, string $cidr): bool
  6715. {
  6716. if (strpos($cidr, '/') !== false) {
  6717. list($subnet, $mask) = explode('/', trim($cidr));
  6718. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  6719. return true;
  6720. }
  6721. } else {
  6722. if (ip2long($ip) == ip2long($cidr)) {
  6723. return true;
  6724. }
  6725. }
  6726. return false;
  6727. }
  6728. private function isIpAllowed(string $ipAddress, string $allowedIpAddresses): bool
  6729. {
  6730. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  6731. if ($this->ipMatch($ipAddress, $allowedIp)) {
  6732. return true;
  6733. }
  6734. }
  6735. return false;
  6736. }
  6737. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6738. {
  6739. $reverseProxy = $this->getProperty('reverseProxy', '');
  6740. if ($reverseProxy) {
  6741. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  6742. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  6743. $ipAddress = $_SERVER['REMOTE_ADDR'];
  6744. } else {
  6745. $ipAddress = '127.0.0.1';
  6746. }
  6747. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  6748. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  6749. $response = $this->responder->error(ErrorCode::TEMPORARY_OR_PERMANENTLY_BLOCKED, '');
  6750. } else {
  6751. $response = $next->handle($request);
  6752. }
  6753. return $response;
  6754. }
  6755. }
  6756. }
  6757. // file: src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php
  6758. namespace Tqdev\PhpCrudApi\Middleware {
  6759. use Psr\Http\Message\ResponseInterface;
  6760. use Psr\Http\Message\ServerRequestInterface;
  6761. use Psr\Http\Server\RequestHandlerInterface;
  6762. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  6763. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6764. use Tqdev\PhpCrudApi\Controller\Responder;
  6765. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6766. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6767. use Tqdev\PhpCrudApi\RequestUtils;
  6768. class IpAddressMiddleware extends Middleware
  6769. {
  6770. private $reflection;
  6771. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6772. {
  6773. parent::__construct($router, $responder, $properties);
  6774. $this->reflection = $reflection;
  6775. }
  6776. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  6777. {
  6778. $context = (array) $record;
  6779. $columnNames = $this->getProperty('columns', '');
  6780. if ($columnNames) {
  6781. foreach (explode(',', $columnNames) as $columnName) {
  6782. if ($table->hasColumn($columnName)) {
  6783. if ($operation == 'create') {
  6784. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  6785. } else {
  6786. unset($context[$columnName]);
  6787. }
  6788. }
  6789. }
  6790. }
  6791. return (object) $context;
  6792. }
  6793. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6794. {
  6795. $operation = RequestUtils::getOperation($request);
  6796. if (in_array($operation, ['create', 'update', 'increment'])) {
  6797. $tableNames = $this->getProperty('tables', '');
  6798. $tableName = RequestUtils::getPathSegment($request, 2);
  6799. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  6800. if ($this->reflection->hasTable($tableName)) {
  6801. $record = $request->getParsedBody();
  6802. if ($record !== null) {
  6803. $table = $this->reflection->getTable($tableName);
  6804. if (is_array($record)) {
  6805. foreach ($record as &$r) {
  6806. $r = $this->callHandler($r, $operation, $table);
  6807. }
  6808. } else {
  6809. $record = $this->callHandler($record, $operation, $table);
  6810. }
  6811. $request = $request->withParsedBody($record);
  6812. }
  6813. }
  6814. }
  6815. }
  6816. return $next->handle($request);
  6817. }
  6818. }
  6819. }
  6820. // file: src/Tqdev/PhpCrudApi/Middleware/JoinLimitsMiddleware.php
  6821. namespace Tqdev\PhpCrudApi\Middleware {
  6822. use Psr\Http\Message\ResponseInterface;
  6823. use Psr\Http\Message\ServerRequestInterface;
  6824. use Psr\Http\Server\RequestHandlerInterface;
  6825. use Tqdev\PhpCrudApi\Column\ReflectionService;
  6826. use Tqdev\PhpCrudApi\Controller\Responder;
  6827. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6828. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  6829. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  6830. use Tqdev\PhpCrudApi\RequestUtils;
  6831. class JoinLimitsMiddleware extends Middleware
  6832. {
  6833. private $reflection;
  6834. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  6835. {
  6836. parent::__construct($router, $responder, $properties);
  6837. $this->reflection = $reflection;
  6838. }
  6839. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6840. {
  6841. $operation = RequestUtils::getOperation($request);
  6842. $params = RequestUtils::getParams($request);
  6843. if (in_array($operation, ['read', 'list']) && isset($params['join'])) {
  6844. $maxDepth = (int) $this->getProperty('depth', '3');
  6845. $maxTables = (int) $this->getProperty('tables', '10');
  6846. $maxRecords = (int) $this->getProperty('records', '1000');
  6847. $tableCount = 0;
  6848. $joinPaths = array();
  6849. for ($i = 0; $i < count($params['join']); $i++) {
  6850. $joinPath = array();
  6851. $tables = explode(',', $params['join'][$i]);
  6852. for ($depth = 0; $depth < min($maxDepth, count($tables)); $depth++) {
  6853. array_push($joinPath, $tables[$depth]);
  6854. $tableCount += 1;
  6855. if ($tableCount == $maxTables) {
  6856. break;
  6857. }
  6858. }
  6859. array_push($joinPaths, implode(',', $joinPath));
  6860. if ($tableCount == $maxTables) {
  6861. break;
  6862. }
  6863. }
  6864. $params['join'] = $joinPaths;
  6865. $request = RequestUtils::setParams($request, $params);
  6866. VariableStore::set("joinLimits.maxRecords", $maxRecords);
  6867. }
  6868. return $next->handle($request);
  6869. }
  6870. }
  6871. }
  6872. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  6873. namespace Tqdev\PhpCrudApi\Middleware {
  6874. use Psr\Http\Message\ResponseInterface;
  6875. use Psr\Http\Message\ServerRequestInterface;
  6876. use Psr\Http\Server\RequestHandlerInterface;
  6877. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  6878. use Tqdev\PhpCrudApi\Record\ErrorCode;
  6879. use Tqdev\PhpCrudApi\RequestUtils;
  6880. class JwtAuthMiddleware extends Middleware
  6881. {
  6882. private function getVerifiedClaims(string $token, int $time, int $leeway, int $ttl, array $secrets, array $requirements): array
  6883. {
  6884. $algorithms = array(
  6885. 'HS256' => 'sha256',
  6886. 'HS384' => 'sha384',
  6887. 'HS512' => 'sha512',
  6888. 'RS256' => 'sha256',
  6889. 'RS384' => 'sha384',
  6890. 'RS512' => 'sha512',
  6891. );
  6892. $token = explode('.', $token);
  6893. if (count($token) < 3) {
  6894. return array();
  6895. }
  6896. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  6897. $kid = 0;
  6898. if (isset($header['kid'])) {
  6899. $kid = $header['kid'];
  6900. }
  6901. if (!isset($secrets[$kid])) {
  6902. return array();
  6903. }
  6904. $secret = $secrets[$kid];
  6905. if ($header['typ'] != 'JWT') {
  6906. return array();
  6907. }
  6908. $algorithm = $header['alg'];
  6909. if (!isset($algorithms[$algorithm])) {
  6910. return array();
  6911. }
  6912. if (!empty($requirements['alg']) && !in_array($algorithm, $requirements['alg'])) {
  6913. return array();
  6914. }
  6915. $hmac = $algorithms[$algorithm];
  6916. $signature = base64_decode(strtr($token[2], '-_', '+/'));
  6917. $data = "$token[0].$token[1]";
  6918. switch ($algorithm[0]) {
  6919. case 'H':
  6920. $hash = hash_hmac($hmac, $data, $secret, true);
  6921. $equals = hash_equals($hash, $signature);
  6922. if (!$equals) {
  6923. return array();
  6924. }
  6925. break;
  6926. case 'R':
  6927. $equals = openssl_verify($data, $signature, $secret, $hmac) == 1;
  6928. if (!$equals) {
  6929. return array();
  6930. }
  6931. break;
  6932. }
  6933. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  6934. if (!$claims) {
  6935. return array();
  6936. }
  6937. foreach ($requirements as $field => $values) {
  6938. if (!empty($values)) {
  6939. if ($field != 'alg') {
  6940. if (!isset($claims[$field]) || !in_array($claims[$field], $values)) {
  6941. return array();
  6942. }
  6943. }
  6944. }
  6945. }
  6946. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  6947. return array();
  6948. }
  6949. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  6950. return array();
  6951. }
  6952. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  6953. return array();
  6954. }
  6955. if (isset($claims['iat']) && !isset($claims['exp'])) {
  6956. if ($time - $leeway > $claims['iat'] + $ttl) {
  6957. return array();
  6958. }
  6959. }
  6960. return $claims;
  6961. }
  6962. private function getClaims(string $token): array
  6963. {
  6964. $time = (int) $this->getProperty('time', time());
  6965. $leeway = (int) $this->getProperty('leeway', '5');
  6966. $ttl = (int) $this->getProperty('ttl', '30');
  6967. $secrets = $this->getMapProperty('secrets', '');
  6968. if (!$secrets) {
  6969. $secrets = [$this->getProperty('secret', '')];
  6970. }
  6971. $requirements = array(
  6972. 'alg' => $this->getArrayProperty('algorithms', ''),
  6973. 'aud' => $this->getArrayProperty('audiences', ''),
  6974. 'iss' => $this->getArrayProperty('issuers', ''),
  6975. );
  6976. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secrets, $requirements);
  6977. }
  6978. private function getAuthorizationToken(ServerRequestInterface $request): string
  6979. {
  6980. $headerName = $this->getProperty('header', 'X-Authorization');
  6981. $headerValue = RequestUtils::getHeader($request, $headerName);
  6982. $parts = explode(' ', trim($headerValue), 2);
  6983. if (count($parts) != 2) {
  6984. return '';
  6985. }
  6986. if ($parts[0] != 'Bearer') {
  6987. return '';
  6988. }
  6989. return $parts[1];
  6990. }
  6991. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  6992. {
  6993. if (session_status() == PHP_SESSION_NONE) {
  6994. if (!headers_sent()) {
  6995. $sessionName = $this->getProperty('sessionName', '');
  6996. if ($sessionName) {
  6997. session_name($sessionName);
  6998. }
  6999. session_start();
  7000. }
  7001. }
  7002. $token = $this->getAuthorizationToken($request);
  7003. if ($token) {
  7004. $claims = $this->getClaims($token);
  7005. $_SESSION['claims'] = $claims;
  7006. if (empty($claims)) {
  7007. return $this->responder->error(ErrorCode::AUTHENTICATION_FAILED, 'JWT');
  7008. }
  7009. if (!headers_sent()) {
  7010. session_regenerate_id();
  7011. }
  7012. }
  7013. if (empty($_SESSION['claims'])) {
  7014. $authenticationMode = $this->getProperty('mode', 'required');
  7015. if ($authenticationMode == 'required') {
  7016. return $this->responder->error(ErrorCode::AUTHENTICATION_REQUIRED, '');
  7017. }
  7018. }
  7019. return $next->handle($request);
  7020. }
  7021. }
  7022. }
  7023. // file: src/Tqdev/PhpCrudApi/Middleware/MultiTenancyMiddleware.php
  7024. namespace Tqdev\PhpCrudApi\Middleware {
  7025. use Psr\Http\Message\ResponseInterface;
  7026. use Psr\Http\Message\ServerRequestInterface;
  7027. use Psr\Http\Server\RequestHandlerInterface;
  7028. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7029. use Tqdev\PhpCrudApi\Controller\Responder;
  7030. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7031. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  7032. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7033. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  7034. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  7035. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  7036. use Tqdev\PhpCrudApi\RequestUtils;
  7037. class MultiTenancyMiddleware extends Middleware
  7038. {
  7039. private $reflection;
  7040. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7041. {
  7042. parent::__construct($router, $responder, $properties);
  7043. $this->reflection = $reflection;
  7044. }
  7045. private function getCondition(string $tableName, array $pairs): Condition
  7046. {
  7047. $condition = new NoCondition();
  7048. $table = $this->reflection->getTable($tableName);
  7049. foreach ($pairs as $k => $v) {
  7050. $condition = $condition->_and(new ColumnCondition($table->getColumn($k), 'eq', $v));
  7051. }
  7052. return $condition;
  7053. }
  7054. private function getPairs($handler, string $operation, string $tableName): array
  7055. {
  7056. $result = array();
  7057. $pairs = call_user_func($handler, $operation, $tableName);
  7058. $table = $this->reflection->getTable($tableName);
  7059. foreach ($pairs as $k => $v) {
  7060. if ($table->hasColumn($k)) {
  7061. $result[$k] = $v;
  7062. }
  7063. }
  7064. return $result;
  7065. }
  7066. private function handleRecord(ServerRequestInterface $request, string $operation, array $pairs): ServerRequestInterface
  7067. {
  7068. $record = $request->getParsedBody();
  7069. if ($record === null) {
  7070. return $request;
  7071. }
  7072. $multi = is_array($record);
  7073. $records = $multi ? $record : [$record];
  7074. foreach ($records as &$record) {
  7075. foreach ($pairs as $column => $value) {
  7076. if ($operation == 'create') {
  7077. $record->$column = $value;
  7078. } else {
  7079. if (isset($record->$column)) {
  7080. unset($record->$column);
  7081. }
  7082. }
  7083. }
  7084. }
  7085. return $request->withParsedBody($multi ? $records : $records[0]);
  7086. }
  7087. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7088. {
  7089. $handler = $this->getProperty('handler', '');
  7090. if ($handler !== '') {
  7091. $path = RequestUtils::getPathSegment($request, 1);
  7092. if ($path == 'records') {
  7093. $operation = RequestUtils::getOperation($request);
  7094. $tableNames = RequestUtils::getTableNames($request, $this->reflection);
  7095. foreach ($tableNames as $i => $tableName) {
  7096. if (!$this->reflection->hasTable($tableName)) {
  7097. continue;
  7098. }
  7099. $pairs = $this->getPairs($handler, $operation, $tableName);
  7100. if ($i == 0) {
  7101. if (in_array($operation, ['create', 'update', 'increment'])) {
  7102. $request = $this->handleRecord($request, $operation, $pairs);
  7103. }
  7104. }
  7105. $condition = $this->getCondition($tableName, $pairs);
  7106. VariableStore::set("multiTenancy.conditions.$tableName", $condition);
  7107. }
  7108. }
  7109. }
  7110. return $next->handle($request);
  7111. }
  7112. }
  7113. }
  7114. // file: src/Tqdev/PhpCrudApi/Middleware/PageLimitsMiddleware.php
  7115. namespace Tqdev\PhpCrudApi\Middleware {
  7116. use Psr\Http\Message\ResponseInterface;
  7117. use Psr\Http\Message\ServerRequestInterface;
  7118. use Psr\Http\Server\RequestHandlerInterface;
  7119. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7120. use Tqdev\PhpCrudApi\Controller\Responder;
  7121. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7122. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7123. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7124. use Tqdev\PhpCrudApi\RequestUtils;
  7125. class PageLimitsMiddleware extends Middleware
  7126. {
  7127. private $reflection;
  7128. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7129. {
  7130. parent::__construct($router, $responder, $properties);
  7131. $this->reflection = $reflection;
  7132. }
  7133. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7134. {
  7135. $operation = RequestUtils::getOperation($request);
  7136. if ($operation == 'list') {
  7137. $params = RequestUtils::getParams($request);
  7138. $maxPage = (int) $this->getProperty('pages', '100');
  7139. if (isset($params['page']) && $params['page'] && $maxPage > 0) {
  7140. if (strpos($params['page'][0], ',') === false) {
  7141. $page = $params['page'][0];
  7142. } else {
  7143. list($page, $size) = explode(',', $params['page'][0], 2);
  7144. }
  7145. if ($page > $maxPage) {
  7146. return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
  7147. }
  7148. }
  7149. $maxSize = (int) $this->getProperty('records', '1000');
  7150. if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
  7151. $params['size'] = array($maxSize);
  7152. } else {
  7153. $params['size'] = array(min($params['size'][0], $maxSize));
  7154. }
  7155. $request = RequestUtils::setParams($request, $params);
  7156. }
  7157. return $next->handle($request);
  7158. }
  7159. }
  7160. }
  7161. // file: src/Tqdev/PhpCrudApi/Middleware/ReconnectMiddleware.php
  7162. namespace Tqdev\PhpCrudApi\Middleware {
  7163. use Psr\Http\Message\ResponseInterface;
  7164. use Psr\Http\Message\ServerRequestInterface;
  7165. use Psr\Http\Server\RequestHandlerInterface;
  7166. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7167. use Tqdev\PhpCrudApi\Controller\Responder;
  7168. use Tqdev\PhpCrudApi\Database\GenericDB;
  7169. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7170. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7171. class ReconnectMiddleware extends Middleware
  7172. {
  7173. private $reflection;
  7174. private $db;
  7175. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
  7176. {
  7177. parent::__construct($router, $responder, $properties);
  7178. $this->reflection = $reflection;
  7179. $this->db = $db;
  7180. }
  7181. private function getDriver(): string
  7182. {
  7183. $driverHandler = $this->getProperty('driverHandler', '');
  7184. if ($driverHandler) {
  7185. return call_user_func($driverHandler);
  7186. }
  7187. return '';
  7188. }
  7189. private function getAddress(): string
  7190. {
  7191. $addressHandler = $this->getProperty('addressHandler', '');
  7192. if ($addressHandler) {
  7193. return call_user_func($addressHandler);
  7194. }
  7195. return '';
  7196. }
  7197. private function getPort(): int
  7198. {
  7199. $portHandler = $this->getProperty('portHandler', '');
  7200. if ($portHandler) {
  7201. return call_user_func($portHandler);
  7202. }
  7203. return 0;
  7204. }
  7205. private function getDatabase(): string
  7206. {
  7207. $databaseHandler = $this->getProperty('databaseHandler', '');
  7208. if ($databaseHandler) {
  7209. return call_user_func($databaseHandler);
  7210. }
  7211. return '';
  7212. }
  7213. private function getTables(): array
  7214. {
  7215. $tablesHandler = $this->getProperty('tablesHandler', '');
  7216. if ($tablesHandler) {
  7217. return call_user_func($tablesHandler);
  7218. }
  7219. return [];
  7220. }
  7221. private function getUsername(): string
  7222. {
  7223. $usernameHandler = $this->getProperty('usernameHandler', '');
  7224. if ($usernameHandler) {
  7225. return call_user_func($usernameHandler);
  7226. }
  7227. return '';
  7228. }
  7229. private function getPassword(): string
  7230. {
  7231. $passwordHandler = $this->getProperty('passwordHandler', '');
  7232. if ($passwordHandler) {
  7233. return call_user_func($passwordHandler);
  7234. }
  7235. return '';
  7236. }
  7237. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7238. {
  7239. $driver = $this->getDriver();
  7240. $address = $this->getAddress();
  7241. $port = $this->getPort();
  7242. $database = $this->getDatabase();
  7243. $tables = $this->getTables();
  7244. $username = $this->getUsername();
  7245. $password = $this->getPassword();
  7246. if ($driver || $address || $port || $database || $tables || $username || $password) {
  7247. $this->db->reconstruct($driver, $address, $port, $database, $tables, $username, $password);
  7248. }
  7249. return $next->handle($request);
  7250. }
  7251. }
  7252. }
  7253. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  7254. namespace Tqdev\PhpCrudApi\Middleware {
  7255. use Psr\Http\Message\ResponseInterface;
  7256. use Psr\Http\Message\ServerRequestInterface;
  7257. use Psr\Http\Server\RequestHandlerInterface;
  7258. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7259. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  7260. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7261. use Tqdev\PhpCrudApi\Controller\Responder;
  7262. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7263. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7264. use Tqdev\PhpCrudApi\RequestUtils;
  7265. class SanitationMiddleware extends Middleware
  7266. {
  7267. private $reflection;
  7268. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7269. {
  7270. parent::__construct($router, $responder, $properties);
  7271. $this->reflection = $reflection;
  7272. }
  7273. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: object */
  7274. {
  7275. $context = (array) $record;
  7276. $tableName = $table->getName();
  7277. foreach ($context as $columnName => &$value) {
  7278. if ($table->hasColumn($columnName)) {
  7279. $column = $table->getColumn($columnName);
  7280. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  7281. $value = $this->sanitizeType($table, $column, $value);
  7282. }
  7283. }
  7284. return (object) $context;
  7285. }
  7286. private function sanitizeType(ReflectedTable $table, ReflectedColumn $column, $value)
  7287. {
  7288. $tables = $this->getArrayProperty('tables', 'all');
  7289. $types = $this->getArrayProperty('types', 'all');
  7290. if (
  7291. (in_array('all', $tables) || in_array($table->getName(), $tables)) &&
  7292. (in_array('all', $types) || in_array($column->getType(), $types))
  7293. ) {
  7294. if (is_null($value)) {
  7295. return $value;
  7296. }
  7297. if (is_string($value)) {
  7298. $newValue = null;
  7299. switch ($column->getType()) {
  7300. case 'integer':
  7301. case 'bigint':
  7302. $newValue = filter_var(trim($value), FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
  7303. break;
  7304. case 'decimal':
  7305. $newValue = filter_var(trim($value), FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
  7306. if (is_float($newValue)) {
  7307. $newValue = number_format($newValue, $column->getScale(), '.', '');
  7308. }
  7309. break;
  7310. case 'float':
  7311. case 'double':
  7312. $newValue = filter_var(trim($value), FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
  7313. break;
  7314. case 'boolean':
  7315. $newValue = filter_var(trim($value), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  7316. break;
  7317. case 'date':
  7318. $time = strtotime(trim($value));
  7319. if ($time !== false) {
  7320. $newValue = date('Y-m-d', $time);
  7321. }
  7322. break;
  7323. case 'time':
  7324. $time = strtotime(trim($value));
  7325. if ($time !== false) {
  7326. $newValue = date('H:i:s', $time);
  7327. }
  7328. break;
  7329. case 'timestamp':
  7330. $time = strtotime(trim($value));
  7331. if ($time !== false) {
  7332. $newValue = date('Y-m-d H:i:s', $time);
  7333. }
  7334. break;
  7335. case 'blob':
  7336. case 'varbinary':
  7337. // allow base64url format
  7338. $newValue = strtr(trim($value), '-_', '+/');
  7339. break;
  7340. case 'clob':
  7341. case 'varchar':
  7342. $newValue = $value;
  7343. break;
  7344. case 'geometry':
  7345. $newValue = trim($value);
  7346. break;
  7347. }
  7348. if (!is_null($newValue)) {
  7349. $value = $newValue;
  7350. }
  7351. } else {
  7352. switch ($column->getType()) {
  7353. case 'integer':
  7354. case 'bigint':
  7355. if (is_float($value)) {
  7356. $value = (int) round($value);
  7357. }
  7358. break;
  7359. case 'decimal':
  7360. if (is_float($value) || is_int($value)) {
  7361. $value = number_format((float) $value, $column->getScale(), '.', '');
  7362. }
  7363. break;
  7364. }
  7365. }
  7366. // post process
  7367. }
  7368. return $value;
  7369. }
  7370. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7371. {
  7372. $operation = RequestUtils::getOperation($request);
  7373. if (in_array($operation, ['create', 'update', 'increment'])) {
  7374. $tableName = RequestUtils::getPathSegment($request, 2);
  7375. if ($this->reflection->hasTable($tableName)) {
  7376. $record = $request->getParsedBody();
  7377. if ($record !== null) {
  7378. $handler = $this->getProperty('handler', '');
  7379. if ($handler !== '') {
  7380. $table = $this->reflection->getTable($tableName);
  7381. if (is_array($record)) {
  7382. foreach ($record as &$r) {
  7383. $r = $this->callHandler($handler, $r, $operation, $table);
  7384. }
  7385. } else {
  7386. $record = $this->callHandler($handler, $record, $operation, $table);
  7387. }
  7388. $request = $request->withParsedBody($record);
  7389. }
  7390. }
  7391. }
  7392. }
  7393. return $next->handle($request);
  7394. }
  7395. }
  7396. }
  7397. // file: src/Tqdev/PhpCrudApi/Middleware/SslRedirectMiddleware.php
  7398. namespace Tqdev\PhpCrudApi\Middleware {
  7399. use Psr\Http\Message\ResponseInterface;
  7400. use Psr\Http\Message\ServerRequestInterface;
  7401. use Psr\Http\Server\RequestHandlerInterface;
  7402. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7403. use Tqdev\PhpCrudApi\ResponseFactory;
  7404. class SslRedirectMiddleware extends Middleware
  7405. {
  7406. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7407. {
  7408. $uri = $request->getUri();
  7409. $scheme = $uri->getScheme();
  7410. if ($scheme == 'http') {
  7411. $uri = $request->getUri();
  7412. $uri = $uri->withScheme('https');
  7413. $response = ResponseFactory::fromStatus(301);
  7414. $response = $response->withHeader('Location', $uri->__toString());
  7415. } else {
  7416. $response = $next->handle($request);
  7417. }
  7418. return $response;
  7419. }
  7420. }
  7421. }
  7422. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  7423. namespace Tqdev\PhpCrudApi\Middleware {
  7424. use Psr\Http\Message\ResponseInterface;
  7425. use Psr\Http\Message\ServerRequestInterface;
  7426. use Psr\Http\Server\RequestHandlerInterface;
  7427. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7428. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7429. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  7430. use Tqdev\PhpCrudApi\Controller\Responder;
  7431. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7432. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7433. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7434. use Tqdev\PhpCrudApi\RequestUtils;
  7435. class ValidationMiddleware extends Middleware
  7436. {
  7437. private $reflection;
  7438. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7439. {
  7440. parent::__construct($router, $responder, $properties);
  7441. $this->reflection = $reflection;
  7442. }
  7443. private function callHandler($handler, $record, string $operation, ReflectedTable $table) /*: ResponseInterface?*/
  7444. {
  7445. $context = (array) $record;
  7446. $details = array();
  7447. $tableName = $table->getName();
  7448. foreach ($context as $columnName => $value) {
  7449. if ($table->hasColumn($columnName)) {
  7450. $column = $table->getColumn($columnName);
  7451. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  7452. if ($valid === true || $valid === '') {
  7453. $valid = $this->validateType($table, $column, $value);
  7454. }
  7455. if ($valid !== true && $valid !== '') {
  7456. $details[$columnName] = $valid;
  7457. }
  7458. }
  7459. }
  7460. if (count($details) > 0) {
  7461. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  7462. }
  7463. return null;
  7464. }
  7465. private function validateType(ReflectedTable $table, ReflectedColumn $column, $value)
  7466. {
  7467. $tables = $this->getArrayProperty('tables', 'all');
  7468. $types = $this->getArrayProperty('types', 'all');
  7469. if (
  7470. (in_array('all', $tables) || in_array($table->getName(), $tables)) &&
  7471. (in_array('all', $types) || in_array($column->getType(), $types))
  7472. ) {
  7473. if (is_null($value)) {
  7474. return ($column->getNullable() ? true : "cannot be null");
  7475. }
  7476. if (is_string($value)) {
  7477. // check for whitespace
  7478. switch ($column->getType()) {
  7479. case 'varchar':
  7480. case 'clob':
  7481. break;
  7482. default:
  7483. if (strlen(trim($value)) != strlen($value)) {
  7484. return 'illegal whitespace';
  7485. }
  7486. break;
  7487. }
  7488. // try to parse
  7489. switch ($column->getType()) {
  7490. case 'integer':
  7491. case 'bigint':
  7492. if (
  7493. filter_var($value, FILTER_SANITIZE_NUMBER_INT) !== $value ||
  7494. filter_var($value, FILTER_VALIDATE_INT) === false
  7495. ) {
  7496. return 'invalid integer';
  7497. }
  7498. break;
  7499. case 'decimal':
  7500. if (strpos($value, '.') !== false) {
  7501. list($whole, $decimals) = explode('.', $value, 2);
  7502. } else {
  7503. list($whole, $decimals) = array($value, '');
  7504. }
  7505. if (strlen($whole) > 0 && !ctype_digit($whole)) {
  7506. return 'invalid decimal';
  7507. }
  7508. if (strlen($decimals) > 0 && !ctype_digit($decimals)) {
  7509. return 'invalid decimal';
  7510. }
  7511. if (strlen($whole) > $column->getPrecision() - $column->getScale()) {
  7512. return 'decimal too large';
  7513. }
  7514. if (strlen($decimals) > $column->getScale()) {
  7515. return 'decimal too precise';
  7516. }
  7517. break;
  7518. case 'float':
  7519. case 'double':
  7520. if (
  7521. filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT) !== $value ||
  7522. filter_var($value, FILTER_VALIDATE_FLOAT) === false
  7523. ) {
  7524. return 'invalid float';
  7525. }
  7526. break;
  7527. case 'boolean':
  7528. if (!in_array(strtolower($value), array('true', 'false'))) {
  7529. return 'invalid boolean';
  7530. }
  7531. break;
  7532. case 'date':
  7533. if (date_create_from_format('Y-m-d', $value) === false) {
  7534. return 'invalid date';
  7535. }
  7536. break;
  7537. case 'time':
  7538. if (date_create_from_format('H:i:s', $value) === false) {
  7539. return 'invalid time';
  7540. }
  7541. break;
  7542. case 'timestamp':
  7543. if (date_create_from_format('Y-m-d H:i:s', $value) === false) {
  7544. return 'invalid timestamp';
  7545. }
  7546. break;
  7547. case 'clob':
  7548. case 'varchar':
  7549. if ($column->hasLength() && mb_strlen($value, 'UTF-8') > $column->getLength()) {
  7550. return 'string too long';
  7551. }
  7552. break;
  7553. case 'blob':
  7554. case 'varbinary':
  7555. if (base64_decode($value, true) === false) {
  7556. return 'invalid base64';
  7557. }
  7558. if ($column->hasLength() && strlen(base64_decode($value)) > $column->getLength()) {
  7559. return 'string too long';
  7560. }
  7561. break;
  7562. case 'geometry':
  7563. // no checks yet
  7564. break;
  7565. }
  7566. } else { // check non-string types
  7567. switch ($column->getType()) {
  7568. case 'integer':
  7569. case 'bigint':
  7570. if (!is_int($value)) {
  7571. return 'invalid integer';
  7572. }
  7573. break;
  7574. case 'float':
  7575. case 'double':
  7576. if (!is_float($value) && !is_int($value)) {
  7577. return 'invalid float';
  7578. }
  7579. break;
  7580. case 'boolean':
  7581. if (!is_bool($value) && ($value !== 0) && ($value !== 1)) {
  7582. return 'invalid boolean';
  7583. }
  7584. break;
  7585. default:
  7586. return 'invalid ' . $column->getType();
  7587. }
  7588. }
  7589. // extra checks
  7590. switch ($column->getType()) {
  7591. case 'integer': // 4 byte signed
  7592. $value = filter_var($value, FILTER_VALIDATE_INT);
  7593. if ($value > 2147483647 || $value < -2147483648) {
  7594. return 'invalid integer';
  7595. }
  7596. break;
  7597. }
  7598. }
  7599. return (true);
  7600. }
  7601. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7602. {
  7603. $operation = RequestUtils::getOperation($request);
  7604. if (in_array($operation, ['create', 'update', 'increment'])) {
  7605. $tableName = RequestUtils::getPathSegment($request, 2);
  7606. if ($this->reflection->hasTable($tableName)) {
  7607. $record = $request->getParsedBody();
  7608. if ($record !== null) {
  7609. $handler = $this->getProperty('handler', '');
  7610. if ($handler !== '') {
  7611. $table = $this->reflection->getTable($tableName);
  7612. if (is_array($record)) {
  7613. foreach ($record as $r) {
  7614. $response = $this->callHandler($handler, $r, $operation, $table);
  7615. if ($response !== null) {
  7616. return $response;
  7617. }
  7618. }
  7619. } else {
  7620. $response = $this->callHandler($handler, $record, $operation, $table);
  7621. if ($response !== null) {
  7622. return $response;
  7623. }
  7624. }
  7625. }
  7626. }
  7627. }
  7628. }
  7629. return $next->handle($request);
  7630. }
  7631. }
  7632. }
  7633. // file: src/Tqdev/PhpCrudApi/Middleware/XmlMiddleware.php
  7634. namespace Tqdev\PhpCrudApi\Middleware {
  7635. use Psr\Http\Message\ResponseInterface;
  7636. use Psr\Http\Message\ServerRequestInterface;
  7637. use Psr\Http\Server\RequestHandlerInterface;
  7638. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7639. use Tqdev\PhpCrudApi\Controller\Responder;
  7640. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7641. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  7642. use Tqdev\PhpCrudApi\RequestUtils;
  7643. use Tqdev\PhpCrudApi\ResponseFactory;
  7644. class XmlMiddleware extends Middleware
  7645. {
  7646. private $reflection;
  7647. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  7648. {
  7649. parent::__construct($router, $responder, $properties);
  7650. $this->reflection = $reflection;
  7651. }
  7652. private function json2xml($json, $types = 'null,boolean,number,string,object,array')
  7653. {
  7654. $a = json_decode($json);
  7655. $d = new \DOMDocument();
  7656. $c = $d->createElement("root");
  7657. $d->appendChild($c);
  7658. $t = function ($v) {
  7659. $type = gettype($v);
  7660. switch ($type) {
  7661. case 'integer':
  7662. return 'number';
  7663. case 'double':
  7664. return 'number';
  7665. default:
  7666. return strtolower($type);
  7667. }
  7668. };
  7669. $ts = explode(',', $types);
  7670. $f = function ($f, $c, $a, $s = false) use ($t, $d, $ts) {
  7671. if (in_array($t($a), $ts)) {
  7672. $c->setAttribute('type', $t($a));
  7673. }
  7674. if ($t($a) != 'array' && $t($a) != 'object') {
  7675. if ($t($a) == 'boolean') {
  7676. $c->appendChild($d->createTextNode($a ? 'true' : 'false'));
  7677. } else {
  7678. $c->appendChild($d->createTextNode($a));
  7679. }
  7680. } else {
  7681. foreach ($a as $k => $v) {
  7682. if ($k == '__type' && $t($a) == 'object') {
  7683. $c->setAttribute('__type', $v);
  7684. } else {
  7685. if ($t($v) == 'object') {
  7686. $ch = $c->appendChild($d->createElementNS(null, $s ? 'item' : $k));
  7687. $f($f, $ch, $v);
  7688. } else if ($t($v) == 'array') {
  7689. $ch = $c->appendChild($d->createElementNS(null, $s ? 'item' : $k));
  7690. $f($f, $ch, $v, true);
  7691. } else {
  7692. $va = $d->createElementNS(null, $s ? 'item' : $k);
  7693. if ($t($v) == 'boolean') {
  7694. $va->appendChild($d->createTextNode($v ? 'true' : 'false'));
  7695. } else {
  7696. $va->appendChild($d->createTextNode($v));
  7697. }
  7698. $ch = $c->appendChild($va);
  7699. if (in_array($t($v), $ts)) {
  7700. $ch->setAttribute('type', $t($v));
  7701. }
  7702. }
  7703. }
  7704. }
  7705. }
  7706. };
  7707. $f($f, $c, $a, $t($a) == 'array');
  7708. return $d->saveXML($d->documentElement);
  7709. }
  7710. private function xml2json($xml)
  7711. {
  7712. $a = @dom_import_simplexml(simplexml_load_string($xml));
  7713. if (!$a) {
  7714. return null;
  7715. }
  7716. $t = function ($v) {
  7717. $t = $v->getAttribute('type');
  7718. $txt = $v->firstChild->nodeType == XML_TEXT_NODE;
  7719. return $t ?: ($txt ? 'string' : 'object');
  7720. };
  7721. $f = function ($f, $a) use ($t) {
  7722. $c = null;
  7723. if ($t($a) == 'null') {
  7724. $c = null;
  7725. } else if ($t($a) == 'boolean') {
  7726. $b = substr(strtolower($a->textContent), 0, 1);
  7727. $c = in_array($b, array('1', 't'));
  7728. } else if ($t($a) == 'number') {
  7729. $c = $a->textContent + 0;
  7730. } else if ($t($a) == 'string') {
  7731. $c = $a->textContent;
  7732. } else if ($t($a) == 'object') {
  7733. $c = array();
  7734. if ($a->getAttribute('__type')) {
  7735. $c['__type'] = $a->getAttribute('__type');
  7736. }
  7737. for ($i = 0; $i < $a->childNodes->length; $i++) {
  7738. $v = $a->childNodes[$i];
  7739. $c[$v->nodeName] = $f($f, $v);
  7740. }
  7741. $c = (object) $c;
  7742. } else if ($t($a) == 'array') {
  7743. $c = array();
  7744. for ($i = 0; $i < $a->childNodes->length; $i++) {
  7745. $v = $a->childNodes[$i];
  7746. $c[$i] = $f($f, $v);
  7747. }
  7748. }
  7749. return $c;
  7750. };
  7751. $c = $f($f, $a);
  7752. return json_encode($c);
  7753. }
  7754. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7755. {
  7756. parse_str($request->getUri()->getQuery(), $params);
  7757. $isXml = isset($params['format']) && $params['format'] == 'xml';
  7758. if ($isXml) {
  7759. $body = $request->getBody()->getContents();
  7760. if ($body) {
  7761. $json = $this->xml2json($body);
  7762. $request = $request->withParsedBody(json_decode($json));
  7763. }
  7764. }
  7765. $response = $next->handle($request);
  7766. if ($isXml) {
  7767. $body = $response->getBody()->getContents();
  7768. if ($body) {
  7769. $types = implode(',', $this->getArrayProperty('types', 'null,array'));
  7770. if ($types == '' || $types == 'all') {
  7771. $xml = $this->json2xml($body);
  7772. } else {
  7773. $xml = $this->json2xml($body, $types);
  7774. }
  7775. $response = ResponseFactory::fromXml(ResponseFactory::OK, $xml);
  7776. }
  7777. }
  7778. return $response;
  7779. }
  7780. }
  7781. }
  7782. // file: src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php
  7783. namespace Tqdev\PhpCrudApi\Middleware {
  7784. use Psr\Http\Message\ResponseInterface;
  7785. use Psr\Http\Message\ServerRequestInterface;
  7786. use Psr\Http\Server\RequestHandlerInterface;
  7787. use Tqdev\PhpCrudApi\Controller\Responder;
  7788. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  7789. use Tqdev\PhpCrudApi\Record\ErrorCode;
  7790. class XsrfMiddleware extends Middleware
  7791. {
  7792. private function getToken(): string
  7793. {
  7794. $cookieName = $this->getProperty('cookieName', 'XSRF-TOKEN');
  7795. if (isset($_COOKIE[$cookieName])) {
  7796. $token = $_COOKIE[$cookieName];
  7797. } else {
  7798. $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
  7799. $token = bin2hex(random_bytes(8));
  7800. if (!headers_sent()) {
  7801. setcookie($cookieName, $token, 0, '', '', $secure);
  7802. }
  7803. }
  7804. return $token;
  7805. }
  7806. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  7807. {
  7808. $token = $this->getToken();
  7809. $method = $request->getMethod();
  7810. $excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
  7811. if (!in_array($method, $excludeMethods)) {
  7812. $headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
  7813. if ($token != $request->getHeader($headerName)) {
  7814. return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
  7815. }
  7816. }
  7817. return $next->handle($request);
  7818. }
  7819. }
  7820. }
  7821. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  7822. namespace Tqdev\PhpCrudApi\OpenApi {
  7823. use Tqdev\PhpCrudApi\Column\ReflectionService;
  7824. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  7825. class OpenApiBuilder
  7826. {
  7827. private $openapi;
  7828. private $records;
  7829. private $columns;
  7830. private $builders;
  7831. public function __construct(ReflectionService $reflection, array $base, array $controllers, array $builders)
  7832. {
  7833. $this->openapi = new OpenApiDefinition($base);
  7834. $this->records = in_array('records', $controllers) ? new OpenApiRecordsBuilder($this->openapi, $reflection) : null;
  7835. $this->columns = in_array('columns', $controllers) ? new OpenApiColumnsBuilder($this->openapi) : null;
  7836. $this->builders = array();
  7837. foreach ($builders as $className) {
  7838. $this->builders[] = new $className($this->openapi, $reflection);
  7839. }
  7840. }
  7841. private function getServerUrl(): string
  7842. {
  7843. $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
  7844. $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
  7845. $host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
  7846. $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
  7847. $path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
  7848. return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
  7849. }
  7850. public function build(): OpenApiDefinition
  7851. {
  7852. $this->openapi->set("openapi", "3.0.0");
  7853. if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
  7854. $this->openapi->set("servers|0|url", $this->getServerUrl());
  7855. }
  7856. if ($this->records) {
  7857. $this->records->build();
  7858. }
  7859. if ($this->columns) {
  7860. $this->columns->build();
  7861. }
  7862. foreach ($this->builders as $builder) {
  7863. $builder->build();
  7864. }
  7865. return $this->openapi;
  7866. }
  7867. }
  7868. }
  7869. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiColumnsBuilder.php
  7870. namespace Tqdev\PhpCrudApi\OpenApi {
  7871. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  7872. class OpenApiColumnsBuilder
  7873. {
  7874. private $openapi;
  7875. private $operations = [
  7876. 'database' => [
  7877. 'read' => 'get',
  7878. ],
  7879. 'table' => [
  7880. 'create' => 'post',
  7881. 'read' => 'get',
  7882. 'update' => 'put', //rename
  7883. 'delete' => 'delete',
  7884. ],
  7885. 'column' => [
  7886. 'create' => 'post',
  7887. 'read' => 'get',
  7888. 'update' => 'put',
  7889. 'delete' => 'delete',
  7890. ]
  7891. ];
  7892. public function __construct(OpenApiDefinition $openapi)
  7893. {
  7894. $this->openapi = $openapi;
  7895. }
  7896. public function build() /*: void*/
  7897. {
  7898. $this->setPaths();
  7899. $this->openapi->set("components|responses|boolSuccess|description", "boolean indicating success or failure");
  7900. $this->openapi->set("components|responses|boolSuccess|content|application/json|schema|type", "boolean");
  7901. $this->setComponentSchema();
  7902. $this->setComponentResponse();
  7903. $this->setComponentRequestBody();
  7904. $this->setComponentParameters();
  7905. foreach (array_keys($this->operations) as $index => $type) {
  7906. $this->setTag($index, $type);
  7907. }
  7908. }
  7909. private function setPaths() /*: void*/
  7910. {
  7911. foreach (array_keys($this->operations) as $type) {
  7912. foreach ($this->operations[$type] as $operation => $method) {
  7913. $parameters = [];
  7914. switch ($type) {
  7915. case 'database':
  7916. $path = '/columns';
  7917. break;
  7918. case 'table':
  7919. $path = $operation == 'create' ? '/columns' : '/columns/{table}';
  7920. break;
  7921. case 'column':
  7922. $path = $operation == 'create' ? '/columns/{table}' : '/columns/{table}/{column}';
  7923. break;
  7924. }
  7925. if (strpos($path, '{table}')) {
  7926. $parameters[] = 'table';
  7927. }
  7928. if (strpos($path, '{column}')) {
  7929. $parameters[] = 'column';
  7930. }
  7931. foreach ($parameters as $p => $parameter) {
  7932. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  7933. }
  7934. $operationType = $operation . ucfirst($type);
  7935. if (in_array($operation, ['create', 'update'])) {
  7936. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operationType");
  7937. }
  7938. $this->openapi->set("paths|$path|$method|tags|0", "$type");
  7939. $this->openapi->set("paths|$path|$method|operationId", "$operation" . "_" . "$type");
  7940. if ($operationType == 'updateTable') {
  7941. $this->openapi->set("paths|$path|$method|description", "rename table");
  7942. } else {
  7943. $this->openapi->set("paths|$path|$method|description", "$operation $type");
  7944. }
  7945. switch ($operation) {
  7946. case 'read':
  7947. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operationType");
  7948. break;
  7949. case 'create':
  7950. case 'update':
  7951. case 'delete':
  7952. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/boolSuccess");
  7953. break;
  7954. }
  7955. }
  7956. }
  7957. }
  7958. private function setComponentSchema() /*: void*/
  7959. {
  7960. foreach (array_keys($this->operations) as $type) {
  7961. foreach (array_keys($this->operations[$type]) as $operation) {
  7962. if ($operation == 'delete') {
  7963. continue;
  7964. }
  7965. $operationType = $operation . ucfirst($type);
  7966. $prefix = "components|schemas|$operationType";
  7967. $this->openapi->set("$prefix|type", "object");
  7968. switch ($type) {
  7969. case 'database':
  7970. $this->openapi->set("$prefix|properties|tables|type", 'array');
  7971. $this->openapi->set("$prefix|properties|tables|items|\$ref", "#/components/schemas/readTable");
  7972. break;
  7973. case 'table':
  7974. if ($operation == 'update') {
  7975. $this->openapi->set("$prefix|required", ['name']);
  7976. $this->openapi->set("$prefix|properties|name|type", 'string');
  7977. } else {
  7978. $this->openapi->set("$prefix|properties|name|type", 'string');
  7979. if ($operation == 'read') {
  7980. $this->openapi->set("$prefix|properties|type|type", 'string');
  7981. }
  7982. $this->openapi->set("$prefix|properties|columns|type", 'array');
  7983. $this->openapi->set("$prefix|properties|columns|items|\$ref", "#/components/schemas/readColumn");
  7984. }
  7985. break;
  7986. case 'column':
  7987. $this->openapi->set("$prefix|required", ['name', 'type']);
  7988. $this->openapi->set("$prefix|properties|name|type", 'string');
  7989. $this->openapi->set("$prefix|properties|type|type", 'string');
  7990. $this->openapi->set("$prefix|properties|length|type", 'integer');
  7991. $this->openapi->set("$prefix|properties|length|format", "int64");
  7992. $this->openapi->set("$prefix|properties|precision|type", 'integer');
  7993. $this->openapi->set("$prefix|properties|precision|format", "int64");
  7994. $this->openapi->set("$prefix|properties|scale|type", 'integer');
  7995. $this->openapi->set("$prefix|properties|scale|format", "int64");
  7996. $this->openapi->set("$prefix|properties|nullable|type", 'boolean');
  7997. $this->openapi->set("$prefix|properties|pk|type", 'boolean');
  7998. $this->openapi->set("$prefix|properties|fk|type", 'string');
  7999. break;
  8000. }
  8001. }
  8002. }
  8003. }
  8004. private function setComponentResponse() /*: void*/
  8005. {
  8006. foreach (array_keys($this->operations) as $type) {
  8007. foreach (array_keys($this->operations[$type]) as $operation) {
  8008. if ($operation != 'read') {
  8009. continue;
  8010. }
  8011. $operationType = $operation . ucfirst($type);
  8012. $this->openapi->set("components|responses|$operationType|description", "single $type record");
  8013. $this->openapi->set("components|responses|$operationType|content|application/json|schema|\$ref", "#/components/schemas/$operationType");
  8014. }
  8015. }
  8016. }
  8017. private function setComponentRequestBody() /*: void*/
  8018. {
  8019. foreach (array_keys($this->operations) as $type) {
  8020. foreach (array_keys($this->operations[$type]) as $operation) {
  8021. if (!in_array($operation, ['create', 'update'])) {
  8022. continue;
  8023. }
  8024. $operationType = $operation . ucfirst($type);
  8025. $this->openapi->set("components|requestBodies|$operationType|description", "single $type record");
  8026. $this->openapi->set("components|requestBodies|$operationType|content|application/json|schema|\$ref", "#/components/schemas/$operationType");
  8027. }
  8028. }
  8029. }
  8030. private function setComponentParameters() /*: void*/
  8031. {
  8032. $this->openapi->set("components|parameters|table|name", "table");
  8033. $this->openapi->set("components|parameters|table|in", "path");
  8034. $this->openapi->set("components|parameters|table|schema|type", "string");
  8035. $this->openapi->set("components|parameters|table|description", "table name");
  8036. $this->openapi->set("components|parameters|table|required", true);
  8037. $this->openapi->set("components|parameters|column|name", "column");
  8038. $this->openapi->set("components|parameters|column|in", "path");
  8039. $this->openapi->set("components|parameters|column|schema|type", "string");
  8040. $this->openapi->set("components|parameters|column|description", "column name");
  8041. $this->openapi->set("components|parameters|column|required", true);
  8042. }
  8043. private function setTag(int $index, string $type) /*: void*/
  8044. {
  8045. $this->openapi->set("tags|$index|name", "$type");
  8046. $this->openapi->set("tags|$index|description", "$type operations");
  8047. }
  8048. }
  8049. }
  8050. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  8051. namespace Tqdev\PhpCrudApi\OpenApi {
  8052. class OpenApiDefinition implements \JsonSerializable
  8053. {
  8054. private $root;
  8055. public function __construct(array $base)
  8056. {
  8057. $this->root = $base;
  8058. }
  8059. public function set(string $path, $value) /*: void*/
  8060. {
  8061. $parts = explode('|', trim($path, '|'));
  8062. $current = &$this->root;
  8063. while (count($parts) > 0) {
  8064. $part = array_shift($parts);
  8065. if (!isset($current[$part])) {
  8066. $current[$part] = [];
  8067. }
  8068. $current = &$current[$part];
  8069. }
  8070. $current = $value;
  8071. }
  8072. public function has(string $path): bool
  8073. {
  8074. $parts = explode('|', trim($path, '|'));
  8075. $current = &$this->root;
  8076. while (count($parts) > 0) {
  8077. $part = array_shift($parts);
  8078. if (!isset($current[$part])) {
  8079. return false;
  8080. }
  8081. $current = &$current[$part];
  8082. }
  8083. return true;
  8084. }
  8085. public function jsonSerialize()
  8086. {
  8087. return $this->root;
  8088. }
  8089. }
  8090. }
  8091. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiRecordsBuilder.php
  8092. namespace Tqdev\PhpCrudApi\OpenApi {
  8093. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8094. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  8095. use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition;
  8096. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  8097. class OpenApiRecordsBuilder
  8098. {
  8099. private $openapi;
  8100. private $reflection;
  8101. private $operations = [
  8102. 'list' => 'get',
  8103. 'create' => 'post',
  8104. 'read' => 'get',
  8105. 'update' => 'put',
  8106. 'delete' => 'delete',
  8107. 'increment' => 'patch',
  8108. ];
  8109. private $types = [
  8110. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  8111. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  8112. 'varchar' => ['type' => 'string'],
  8113. 'clob' => ['type' => 'string', 'format' => 'large-string'], //custom format
  8114. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  8115. 'blob' => ['type' => 'string', 'format' => 'large-byte'], //custom format
  8116. 'decimal' => ['type' => 'string', 'format' => 'decimal'], //custom format
  8117. 'float' => ['type' => 'number', 'format' => 'float'],
  8118. 'double' => ['type' => 'number', 'format' => 'double'],
  8119. 'date' => ['type' => 'string', 'format' => 'date'],
  8120. 'time' => ['type' => 'string', 'format' => 'time'], //custom format
  8121. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  8122. 'geometry' => ['type' => 'string', 'format' => 'geometry'], //custom format
  8123. 'boolean' => ['type' => 'boolean'],
  8124. ];
  8125. public function __construct(OpenApiDefinition $openapi, ReflectionService $reflection)
  8126. {
  8127. $this->openapi = $openapi;
  8128. $this->reflection = $reflection;
  8129. }
  8130. private function getAllTableReferences(): array
  8131. {
  8132. $tableReferences = array();
  8133. foreach ($this->reflection->getTableNames() as $tableName) {
  8134. $table = $this->reflection->getTable($tableName);
  8135. foreach ($table->getColumnNames() as $columnName) {
  8136. $column = $table->getColumn($columnName);
  8137. $referencedTableName = $column->getFk();
  8138. if ($referencedTableName) {
  8139. if (!isset($tableReferences[$referencedTableName])) {
  8140. $tableReferences[$referencedTableName] = array();
  8141. }
  8142. $tableReferences[$referencedTableName][] = "$tableName.$columnName";
  8143. }
  8144. }
  8145. }
  8146. return $tableReferences;
  8147. }
  8148. public function build() /*: void*/
  8149. {
  8150. $tableNames = $this->reflection->getTableNames();
  8151. foreach ($tableNames as $tableName) {
  8152. $this->setPath($tableName);
  8153. }
  8154. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  8155. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  8156. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  8157. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  8158. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  8159. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  8160. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  8161. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  8162. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  8163. $tableReferences = $this->getAllTableReferences();
  8164. foreach ($tableNames as $tableName) {
  8165. $references = isset($tableReferences[$tableName]) ? $tableReferences[$tableName] : array();
  8166. $this->setComponentSchema($tableName, $references);
  8167. $this->setComponentResponse($tableName);
  8168. $this->setComponentRequestBody($tableName);
  8169. }
  8170. $this->setComponentParameters();
  8171. foreach ($tableNames as $index => $tableName) {
  8172. $this->setTag($index, $tableName);
  8173. }
  8174. }
  8175. private function isOperationOnTableAllowed(string $operation, string $tableName): bool
  8176. {
  8177. $tableHandler = VariableStore::get('authorization.tableHandler');
  8178. if (!$tableHandler) {
  8179. return true;
  8180. }
  8181. return (bool) call_user_func($tableHandler, $operation, $tableName);
  8182. }
  8183. private function isOperationOnColumnAllowed(string $operation, string $tableName, string $columnName): bool
  8184. {
  8185. $columnHandler = VariableStore::get('authorization.columnHandler');
  8186. if (!$columnHandler) {
  8187. return true;
  8188. }
  8189. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  8190. }
  8191. private function setPath(string $tableName) /*: void*/
  8192. {
  8193. $table = $this->reflection->getTable($tableName);
  8194. $type = $table->getType();
  8195. $pk = $table->getPk();
  8196. $pkName = $pk ? $pk->getName() : '';
  8197. foreach ($this->operations as $operation => $method) {
  8198. if (!$pkName && $operation != 'list') {
  8199. continue;
  8200. }
  8201. if ($type != 'table' && $operation != 'list') {
  8202. continue;
  8203. }
  8204. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  8205. continue;
  8206. }
  8207. $parameters = [];
  8208. if (in_array($operation, ['list', 'create'])) {
  8209. $path = sprintf('/records/%s', $tableName);
  8210. if ($operation == 'list') {
  8211. $parameters = ['filter', 'include', 'exclude', 'order', 'size', 'page', 'join'];
  8212. }
  8213. } else {
  8214. $path = sprintf('/records/%s/{id}', $tableName);
  8215. if ($operation == 'read') {
  8216. $parameters = ['pk', 'include', 'exclude', 'join'];
  8217. } else {
  8218. $parameters = ['pk'];
  8219. }
  8220. }
  8221. foreach ($parameters as $p => $parameter) {
  8222. $this->openapi->set("paths|$path|$method|parameters|$p|\$ref", "#/components/parameters/$parameter");
  8223. }
  8224. if (in_array($operation, ['create', 'update', 'increment'])) {
  8225. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . rawurlencode($tableName));
  8226. }
  8227. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  8228. $this->openapi->set("paths|$path|$method|operationId", "$operation" . "_" . "$tableName");
  8229. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  8230. switch ($operation) {
  8231. case 'list':
  8232. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . rawurlencode($tableName));
  8233. break;
  8234. case 'create':
  8235. if ($pk->getType() == 'integer') {
  8236. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  8237. } else {
  8238. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  8239. }
  8240. break;
  8241. case 'read':
  8242. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . rawurlencode($tableName));
  8243. break;
  8244. case 'update':
  8245. case 'delete':
  8246. case 'increment':
  8247. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  8248. break;
  8249. }
  8250. }
  8251. }
  8252. private function getPattern(ReflectedColumn $column): string
  8253. {
  8254. switch ($column->getType()) {
  8255. case 'integer':
  8256. $n = strlen(pow(2, 31));
  8257. return '^-?[0-9]{1,' . $n . '}$';
  8258. case 'bigint':
  8259. $n = strlen(pow(2, 63));
  8260. return '^-?[0-9]{1,' . $n . '}$';
  8261. case 'varchar':
  8262. $l = $column->getLength();
  8263. return '^.{0,' . $l . '}$';
  8264. case 'clob':
  8265. return '^.*$';
  8266. case 'varbinary':
  8267. $l = $column->getLength();
  8268. $b = (int) 4 * ceil($l / 3);
  8269. return '^[A-Za-z0-9+/]{0,' . $b . '}=*$';
  8270. case 'blob':
  8271. return '^[A-Za-z0-9+/]*=*$';
  8272. case 'decimal':
  8273. $p = $column->getPrecision();
  8274. $s = $column->getScale();
  8275. return '^-?[0-9]{1,' . ($p - $s) . '}(\.[0-9]{1,' . $s . '})?$';
  8276. case 'float':
  8277. return '^-?[0-9]+(\.[0-9]+)?([eE]-?[0-9]+)?$';
  8278. case 'double':
  8279. return '^-?[0-9]+(\.[0-9]+)?([eE]-?[0-9]+)?$';
  8280. case 'date':
  8281. return '^[0-9]{4}-[0-9]{2}-[0-9]{2}$';
  8282. case 'time':
  8283. return '^[0-9]{2}:[0-9]{2}:[0-9]{2}$';
  8284. case 'timestamp':
  8285. return '^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$';
  8286. return '';
  8287. case 'geometry':
  8288. return '^(POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON)\s*\(.*$';
  8289. case 'boolean':
  8290. return '^(true|false)$';
  8291. }
  8292. return '';
  8293. }
  8294. private function setComponentSchema(string $tableName, array $references) /*: void*/
  8295. {
  8296. $table = $this->reflection->getTable($tableName);
  8297. $type = $table->getType();
  8298. $pk = $table->getPk();
  8299. $pkName = $pk ? $pk->getName() : '';
  8300. foreach ($this->operations as $operation => $method) {
  8301. if (!$pkName && $operation != 'list') {
  8302. continue;
  8303. }
  8304. if ($type != 'table' && $operation != 'list') {
  8305. continue;
  8306. }
  8307. if ($operation == 'delete') {
  8308. continue;
  8309. }
  8310. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  8311. continue;
  8312. }
  8313. if ($operation == 'list') {
  8314. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  8315. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  8316. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  8317. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  8318. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  8319. } else {
  8320. $prefix = "components|schemas|$operation-$tableName";
  8321. }
  8322. $this->openapi->set("$prefix|type", "object");
  8323. foreach ($table->getColumnNames() as $columnName) {
  8324. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  8325. continue;
  8326. }
  8327. $column = $table->getColumn($columnName);
  8328. $properties = $this->types[$column->getType()];
  8329. $properties['maxLength'] = $column->hasLength() ? $column->getLength() : 0;
  8330. $properties['nullable'] = $column->getNullable();
  8331. $properties['pattern'] = $this->getPattern($column);
  8332. foreach ($properties as $key => $value) {
  8333. if ($value) {
  8334. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  8335. }
  8336. }
  8337. if ($column->getPk()) {
  8338. $this->openapi->set("$prefix|properties|$columnName|x-primary-key", true);
  8339. $this->openapi->set("$prefix|properties|$columnName|x-referenced", $references);
  8340. }
  8341. $fk = $column->getFk();
  8342. if ($fk) {
  8343. $this->openapi->set("$prefix|properties|$columnName|x-references", $fk);
  8344. }
  8345. }
  8346. }
  8347. }
  8348. private function setComponentResponse(string $tableName) /*: void*/
  8349. {
  8350. $table = $this->reflection->getTable($tableName);
  8351. $type = $table->getType();
  8352. $pk = $table->getPk();
  8353. $pkName = $pk ? $pk->getName() : '';
  8354. foreach (['list', 'read'] as $operation) {
  8355. if (!$pkName && $operation != 'list') {
  8356. continue;
  8357. }
  8358. if ($type != 'table' && $operation != 'list') {
  8359. continue;
  8360. }
  8361. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  8362. continue;
  8363. }
  8364. if ($operation == 'list') {
  8365. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  8366. } else {
  8367. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  8368. }
  8369. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . rawurlencode($tableName));
  8370. }
  8371. }
  8372. private function setComponentRequestBody(string $tableName) /*: void*/
  8373. {
  8374. $table = $this->reflection->getTable($tableName);
  8375. $type = $table->getType();
  8376. $pk = $table->getPk();
  8377. $pkName = $pk ? $pk->getName() : '';
  8378. if ($pkName && $type == 'table') {
  8379. foreach (['create', 'update', 'increment'] as $operation) {
  8380. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  8381. continue;
  8382. }
  8383. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  8384. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . rawurlencode($tableName));
  8385. }
  8386. }
  8387. }
  8388. private function setComponentParameters() /*: void*/
  8389. {
  8390. $this->openapi->set("components|parameters|pk|name", "id");
  8391. $this->openapi->set("components|parameters|pk|in", "path");
  8392. $this->openapi->set("components|parameters|pk|schema|type", "string");
  8393. $this->openapi->set("components|parameters|pk|description", "primary key value");
  8394. $this->openapi->set("components|parameters|pk|required", true);
  8395. $this->openapi->set("components|parameters|filter|name", "filter");
  8396. $this->openapi->set("components|parameters|filter|in", "query");
  8397. $this->openapi->set("components|parameters|filter|schema|type", "array");
  8398. $this->openapi->set("components|parameters|filter|schema|items|type", "string");
  8399. $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");
  8400. $this->openapi->set("components|parameters|filter|required", false);
  8401. $this->openapi->set("components|parameters|include|name", "include");
  8402. $this->openapi->set("components|parameters|include|in", "query");
  8403. $this->openapi->set("components|parameters|include|schema|type", "string");
  8404. $this->openapi->set("components|parameters|include|description", "Columns you want to include in the output (comma separated). Example: posts.*,categories.name");
  8405. $this->openapi->set("components|parameters|include|required", false);
  8406. $this->openapi->set("components|parameters|exclude|name", "exclude");
  8407. $this->openapi->set("components|parameters|exclude|in", "query");
  8408. $this->openapi->set("components|parameters|exclude|schema|type", "string");
  8409. $this->openapi->set("components|parameters|exclude|description", "Columns you want to exclude from the output (comma separated). Example: posts.content");
  8410. $this->openapi->set("components|parameters|exclude|required", false);
  8411. $this->openapi->set("components|parameters|order|name", "order");
  8412. $this->openapi->set("components|parameters|order|in", "query");
  8413. $this->openapi->set("components|parameters|order|schema|type", "array");
  8414. $this->openapi->set("components|parameters|order|schema|items|type", "string");
  8415. $this->openapi->set("components|parameters|order|description", "Column you want to sort on and the sort direction (comma separated). Example: id,desc");
  8416. $this->openapi->set("components|parameters|order|required", false);
  8417. $this->openapi->set("components|parameters|size|name", "size");
  8418. $this->openapi->set("components|parameters|size|in", "query");
  8419. $this->openapi->set("components|parameters|size|schema|type", "string");
  8420. $this->openapi->set("components|parameters|size|description", "Maximum number of results (for top lists). Example: 10");
  8421. $this->openapi->set("components|parameters|size|required", false);
  8422. $this->openapi->set("components|parameters|page|name", "page");
  8423. $this->openapi->set("components|parameters|page|in", "query");
  8424. $this->openapi->set("components|parameters|page|schema|type", "string");
  8425. $this->openapi->set("components|parameters|page|description", "Page number and page size (comma separated). Example: 1,10");
  8426. $this->openapi->set("components|parameters|page|required", false);
  8427. $this->openapi->set("components|parameters|join|name", "join");
  8428. $this->openapi->set("components|parameters|join|in", "query");
  8429. $this->openapi->set("components|parameters|join|schema|type", "array");
  8430. $this->openapi->set("components|parameters|join|schema|items|type", "string");
  8431. $this->openapi->set("components|parameters|join|description", "Paths (comma separated) to related entities that you want to include. Example: comments,users");
  8432. $this->openapi->set("components|parameters|join|required", false);
  8433. }
  8434. private function setTag(int $index, string $tableName) /*: void*/
  8435. {
  8436. $this->openapi->set("tags|$index|name", "$tableName");
  8437. $this->openapi->set("tags|$index|description", "$tableName operations");
  8438. }
  8439. }
  8440. }
  8441. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  8442. namespace Tqdev\PhpCrudApi\OpenApi {
  8443. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8444. use Tqdev\PhpCrudApi\OpenApi\OpenApiBuilder;
  8445. class OpenApiService
  8446. {
  8447. private $builder;
  8448. public function __construct(ReflectionService $reflection, array $base, array $controllers, array $customBuilders)
  8449. {
  8450. $this->builder = new OpenApiBuilder($reflection, $base, $controllers, $customBuilders);
  8451. }
  8452. public function get(): OpenApiDefinition
  8453. {
  8454. return $this->builder->build();
  8455. }
  8456. }
  8457. }
  8458. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  8459. namespace Tqdev\PhpCrudApi\Record\Condition {
  8460. class AndCondition extends Condition
  8461. {
  8462. private $conditions;
  8463. public function __construct(Condition $condition1, Condition $condition2)
  8464. {
  8465. $this->conditions = [$condition1, $condition2];
  8466. }
  8467. public function _and(Condition $condition): Condition
  8468. {
  8469. if ($condition instanceof NoCondition) {
  8470. return $this;
  8471. }
  8472. $this->conditions[] = $condition;
  8473. return $this;
  8474. }
  8475. public function getConditions(): array
  8476. {
  8477. return $this->conditions;
  8478. }
  8479. public static function fromArray(array $conditions): Condition
  8480. {
  8481. $condition = new NoCondition();
  8482. foreach ($conditions as $c) {
  8483. $condition = $condition->_and($c);
  8484. }
  8485. return $condition;
  8486. }
  8487. }
  8488. }
  8489. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  8490. namespace Tqdev\PhpCrudApi\Record\Condition {
  8491. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedColumn;
  8492. class ColumnCondition extends Condition
  8493. {
  8494. private $column;
  8495. private $operator;
  8496. private $value;
  8497. public function __construct(ReflectedColumn $column, string $operator, string $value)
  8498. {
  8499. $this->column = $column;
  8500. $this->operator = $operator;
  8501. $this->value = $value;
  8502. }
  8503. public function getColumn(): ReflectedColumn
  8504. {
  8505. return $this->column;
  8506. }
  8507. public function getOperator(): string
  8508. {
  8509. return $this->operator;
  8510. }
  8511. public function getValue(): string
  8512. {
  8513. return $this->value;
  8514. }
  8515. }
  8516. }
  8517. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  8518. namespace Tqdev\PhpCrudApi\Record\Condition {
  8519. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8520. abstract class Condition
  8521. {
  8522. public function _and(Condition $condition): Condition
  8523. {
  8524. if ($condition instanceof NoCondition) {
  8525. return $this;
  8526. }
  8527. return new AndCondition($this, $condition);
  8528. }
  8529. public function _or(Condition $condition): Condition
  8530. {
  8531. if ($condition instanceof NoCondition) {
  8532. return $this;
  8533. }
  8534. return new OrCondition($this, $condition);
  8535. }
  8536. public function _not(): Condition
  8537. {
  8538. return new NotCondition($this);
  8539. }
  8540. public static function fromString(ReflectedTable $table, string $value): Condition
  8541. {
  8542. $condition = new NoCondition();
  8543. $parts = explode(',', $value, 3);
  8544. if (count($parts) < 2) {
  8545. return $condition;
  8546. }
  8547. if (count($parts) < 3) {
  8548. $parts[2] = '';
  8549. }
  8550. $field = $table->getColumn($parts[0]);
  8551. $command = $parts[1];
  8552. $negate = false;
  8553. $spatial = false;
  8554. if (strlen($command) > 2) {
  8555. if (substr($command, 0, 1) == 'n') {
  8556. $negate = true;
  8557. $command = substr($command, 1);
  8558. }
  8559. if (substr($command, 0, 1) == 's') {
  8560. $spatial = true;
  8561. $command = substr($command, 1);
  8562. }
  8563. }
  8564. if ($spatial) {
  8565. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  8566. $condition = new SpatialCondition($field, $command, $parts[2]);
  8567. }
  8568. } else {
  8569. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  8570. $condition = new ColumnCondition($field, $command, $parts[2]);
  8571. }
  8572. }
  8573. if ($negate) {
  8574. $condition = $condition->_not();
  8575. }
  8576. return $condition;
  8577. }
  8578. }
  8579. }
  8580. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  8581. namespace Tqdev\PhpCrudApi\Record\Condition {
  8582. class NoCondition extends Condition
  8583. {
  8584. public function _and(Condition $condition): Condition
  8585. {
  8586. return $condition;
  8587. }
  8588. public function _or(Condition $condition): Condition
  8589. {
  8590. return $condition;
  8591. }
  8592. public function _not(): Condition
  8593. {
  8594. return $this;
  8595. }
  8596. }
  8597. }
  8598. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  8599. namespace Tqdev\PhpCrudApi\Record\Condition {
  8600. class NotCondition extends Condition
  8601. {
  8602. private $condition;
  8603. public function __construct(Condition $condition)
  8604. {
  8605. $this->condition = $condition;
  8606. }
  8607. public function getCondition(): Condition
  8608. {
  8609. return $this->condition;
  8610. }
  8611. }
  8612. }
  8613. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  8614. namespace Tqdev\PhpCrudApi\Record\Condition {
  8615. class OrCondition extends Condition
  8616. {
  8617. private $conditions;
  8618. public function __construct(Condition $condition1, Condition $condition2)
  8619. {
  8620. $this->conditions = [$condition1, $condition2];
  8621. }
  8622. public function _or(Condition $condition): Condition
  8623. {
  8624. if ($condition instanceof NoCondition) {
  8625. return $this;
  8626. }
  8627. $this->conditions[] = $condition;
  8628. return $this;
  8629. }
  8630. public function getConditions(): array
  8631. {
  8632. return $this->conditions;
  8633. }
  8634. public static function fromArray(array $conditions): Condition
  8635. {
  8636. $condition = new NoCondition();
  8637. foreach ($conditions as $c) {
  8638. $condition = $condition->_or($c);
  8639. }
  8640. return $condition;
  8641. }
  8642. }
  8643. }
  8644. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  8645. namespace Tqdev\PhpCrudApi\Record\Condition {
  8646. class SpatialCondition extends ColumnCondition
  8647. {
  8648. }
  8649. }
  8650. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  8651. namespace Tqdev\PhpCrudApi\Record\Document {
  8652. use Tqdev\PhpCrudApi\Record\ErrorCode;
  8653. class ErrorDocument implements \JsonSerializable
  8654. {
  8655. public $code;
  8656. public $message;
  8657. public $details;
  8658. public function __construct(ErrorCode $errorCode, string $argument, $details)
  8659. {
  8660. $this->code = $errorCode->getCode();
  8661. $this->message = $errorCode->getMessage($argument);
  8662. $this->details = $details;
  8663. }
  8664. public function getCode(): int
  8665. {
  8666. return $this->code;
  8667. }
  8668. public function getMessage(): string
  8669. {
  8670. return $this->message;
  8671. }
  8672. public function serialize()
  8673. {
  8674. return [
  8675. 'code' => $this->code,
  8676. 'message' => $this->message,
  8677. 'details' => $this->details,
  8678. ];
  8679. }
  8680. public function jsonSerialize()
  8681. {
  8682. return array_filter($this->serialize());
  8683. }
  8684. }
  8685. }
  8686. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  8687. namespace Tqdev\PhpCrudApi\Record\Document {
  8688. class ListDocument implements \JsonSerializable
  8689. {
  8690. private $records;
  8691. private $results;
  8692. public function __construct(array $records, int $results)
  8693. {
  8694. $this->records = $records;
  8695. $this->results = $results;
  8696. }
  8697. public function getRecords(): array
  8698. {
  8699. return $this->records;
  8700. }
  8701. public function getResults(): int
  8702. {
  8703. return $this->results;
  8704. }
  8705. public function serialize()
  8706. {
  8707. return [
  8708. 'records' => $this->records,
  8709. 'results' => $this->results,
  8710. ];
  8711. }
  8712. public function jsonSerialize()
  8713. {
  8714. return array_filter($this->serialize(), function ($v) {
  8715. return $v !== 0;
  8716. });
  8717. }
  8718. }
  8719. }
  8720. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  8721. namespace Tqdev\PhpCrudApi\Record {
  8722. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8723. class ColumnIncluder
  8724. {
  8725. private function isMandatory(string $tableName, string $columnName, array $params): bool
  8726. {
  8727. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  8728. }
  8729. private function select(
  8730. string $tableName,
  8731. bool $primaryTable,
  8732. array $params,
  8733. string $paramName,
  8734. array $columnNames,
  8735. bool $include
  8736. ): array {
  8737. if (!isset($params[$paramName])) {
  8738. return $columnNames;
  8739. }
  8740. $columns = array();
  8741. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  8742. $columns[$columnName] = true;
  8743. }
  8744. $result = array();
  8745. foreach ($columnNames as $columnName) {
  8746. $match = isset($columns['*.*']);
  8747. if (!$match) {
  8748. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  8749. }
  8750. if ($primaryTable && !$match) {
  8751. $match = isset($columns['*']) || isset($columns[$columnName]);
  8752. }
  8753. if ($match) {
  8754. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  8755. $result[] = $columnName;
  8756. }
  8757. } else {
  8758. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  8759. $result[] = $columnName;
  8760. }
  8761. }
  8762. }
  8763. return $result;
  8764. }
  8765. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  8766. {
  8767. $tableName = $table->getName();
  8768. $results = $table->getColumnNames();
  8769. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  8770. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  8771. return $results;
  8772. }
  8773. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  8774. {
  8775. $results = array();
  8776. $columnNames = $this->getNames($table, $primaryTable, $params);
  8777. foreach ($columnNames as $columnName) {
  8778. if (property_exists($record, $columnName)) {
  8779. $results[$columnName] = $record->$columnName;
  8780. }
  8781. }
  8782. return $results;
  8783. }
  8784. }
  8785. }
  8786. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  8787. namespace Tqdev\PhpCrudApi\Record {
  8788. use Tqdev\PhpCrudApi\ResponseFactory;
  8789. class ErrorCode
  8790. {
  8791. private $code;
  8792. private $message;
  8793. private $status;
  8794. const ERROR_NOT_FOUND = 9999;
  8795. const ROUTE_NOT_FOUND = 1000;
  8796. const TABLE_NOT_FOUND = 1001;
  8797. const ARGUMENT_COUNT_MISMATCH = 1002;
  8798. const RECORD_NOT_FOUND = 1003;
  8799. const ORIGIN_FORBIDDEN = 1004;
  8800. const COLUMN_NOT_FOUND = 1005;
  8801. const TABLE_ALREADY_EXISTS = 1006;
  8802. const COLUMN_ALREADY_EXISTS = 1007;
  8803. const HTTP_MESSAGE_NOT_READABLE = 1008;
  8804. const DUPLICATE_KEY_EXCEPTION = 1009;
  8805. const DATA_INTEGRITY_VIOLATION = 1010;
  8806. const AUTHENTICATION_REQUIRED = 1011;
  8807. const AUTHENTICATION_FAILED = 1012;
  8808. const INPUT_VALIDATION_FAILED = 1013;
  8809. const OPERATION_FORBIDDEN = 1014;
  8810. const OPERATION_NOT_SUPPORTED = 1015;
  8811. const TEMPORARY_OR_PERMANENTLY_BLOCKED = 1016;
  8812. const BAD_OR_MISSING_XSRF_TOKEN = 1017;
  8813. const ONLY_AJAX_REQUESTS_ALLOWED = 1018;
  8814. const PAGINATION_FORBIDDEN = 1019;
  8815. private $values = [
  8816. 9999 => ["%s", ResponseFactory::INTERNAL_SERVER_ERROR],
  8817. 1000 => ["Route '%s' not found", ResponseFactory::NOT_FOUND],
  8818. 1001 => ["Table '%s' not found", ResponseFactory::NOT_FOUND],
  8819. 1002 => ["Argument count mismatch in '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  8820. 1003 => ["Record '%s' not found", ResponseFactory::NOT_FOUND],
  8821. 1004 => ["Origin '%s' is forbidden", ResponseFactory::FORBIDDEN],
  8822. 1005 => ["Column '%s' not found", ResponseFactory::NOT_FOUND],
  8823. 1006 => ["Table '%s' already exists", ResponseFactory::CONFLICT],
  8824. 1007 => ["Column '%s' already exists", ResponseFactory::CONFLICT],
  8825. 1008 => ["Cannot read HTTP message", ResponseFactory::UNPROCESSABLE_ENTITY],
  8826. 1009 => ["Duplicate key exception", ResponseFactory::CONFLICT],
  8827. 1010 => ["Data integrity violation", ResponseFactory::CONFLICT],
  8828. 1011 => ["Authentication required", ResponseFactory::UNAUTHORIZED],
  8829. 1012 => ["Authentication failed for '%s'", ResponseFactory::FORBIDDEN],
  8830. 1013 => ["Input validation failed for '%s'", ResponseFactory::UNPROCESSABLE_ENTITY],
  8831. 1014 => ["Operation forbidden", ResponseFactory::FORBIDDEN],
  8832. 1015 => ["Operation '%s' not supported", ResponseFactory::METHOD_NOT_ALLOWED],
  8833. 1016 => ["Temporary or permanently blocked", ResponseFactory::FORBIDDEN],
  8834. 1017 => ["Bad or missing XSRF token", ResponseFactory::FORBIDDEN],
  8835. 1018 => ["Only AJAX requests allowed for '%s'", ResponseFactory::FORBIDDEN],
  8836. 1019 => ["Pagination forbidden", ResponseFactory::FORBIDDEN],
  8837. ];
  8838. public function __construct(int $code)
  8839. {
  8840. if (!isset($this->values[$code])) {
  8841. $code = 9999;
  8842. }
  8843. $this->code = $code;
  8844. $this->message = $this->values[$code][0];
  8845. $this->status = $this->values[$code][1];
  8846. }
  8847. public function getCode(): int
  8848. {
  8849. return $this->code;
  8850. }
  8851. public function getMessage(string $argument): string
  8852. {
  8853. return sprintf($this->message, $argument);
  8854. }
  8855. public function getStatus(): int
  8856. {
  8857. return $this->status;
  8858. }
  8859. }
  8860. }
  8861. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  8862. namespace Tqdev\PhpCrudApi\Record {
  8863. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8864. use Tqdev\PhpCrudApi\Record\Condition\AndCondition;
  8865. use Tqdev\PhpCrudApi\Record\Condition\Condition;
  8866. use Tqdev\PhpCrudApi\Record\Condition\NoCondition;
  8867. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  8868. class FilterInfo
  8869. {
  8870. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  8871. {
  8872. $key = 'filter' . implode('', $path);
  8873. if (isset($params[$key])) {
  8874. foreach ($params[$key] as $filter) {
  8875. $condition = Condition::fromString($table, $filter);
  8876. if (($condition instanceof NoCondition) == false) {
  8877. $conditions->put($path, $condition);
  8878. }
  8879. }
  8880. }
  8881. }
  8882. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  8883. {
  8884. $conditions = new PathTree();
  8885. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  8886. for ($n = ord('0'); $n <= ord('9'); $n++) {
  8887. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  8888. for ($l = ord('a'); $l <= ord('f'); $l++) {
  8889. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  8890. }
  8891. }
  8892. return $conditions;
  8893. }
  8894. private function combinePathTreeOfConditions(PathTree $tree): Condition
  8895. {
  8896. $andConditions = $tree->getValues();
  8897. $and = AndCondition::fromArray($andConditions);
  8898. $orConditions = [];
  8899. foreach ($tree->getKeys() as $p) {
  8900. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  8901. }
  8902. $or = OrCondition::fromArray($orConditions);
  8903. return $and->_and($or);
  8904. }
  8905. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  8906. {
  8907. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  8908. }
  8909. }
  8910. }
  8911. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  8912. namespace Tqdev\PhpCrudApi\Record {
  8913. class HabtmValues
  8914. {
  8915. public $pkValues;
  8916. public $fkValues;
  8917. public function __construct(array $pkValues, array $fkValues)
  8918. {
  8919. $this->pkValues = $pkValues;
  8920. $this->fkValues = $fkValues;
  8921. }
  8922. }
  8923. }
  8924. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  8925. namespace Tqdev\PhpCrudApi\Record {
  8926. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  8927. class OrderingInfo
  8928. {
  8929. public function getColumnOrdering(ReflectedTable $table, array $params): array
  8930. {
  8931. $fields = array();
  8932. if (isset($params['order'])) {
  8933. foreach ($params['order'] as $order) {
  8934. $parts = explode(',', $order, 3);
  8935. $columnName = $parts[0];
  8936. if (!$table->hasColumn($columnName)) {
  8937. continue;
  8938. }
  8939. $ascending = 'ASC';
  8940. if (count($parts) > 1) {
  8941. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  8942. $ascending = 'DESC';
  8943. }
  8944. }
  8945. $fields[] = [$columnName, $ascending];
  8946. }
  8947. }
  8948. if (count($fields) == 0) {
  8949. return $this->getDefaultColumnOrdering($table);
  8950. }
  8951. return $fields;
  8952. }
  8953. public function getDefaultColumnOrdering(ReflectedTable $table): array
  8954. {
  8955. $fields = array();
  8956. $pk = $table->getPk();
  8957. if ($pk) {
  8958. $fields[] = [$pk->getName(), 'ASC'];
  8959. } else {
  8960. foreach ($table->getColumnNames() as $columnName) {
  8961. $fields[] = [$columnName, 'ASC'];
  8962. }
  8963. }
  8964. return $fields;
  8965. }
  8966. }
  8967. }
  8968. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  8969. namespace Tqdev\PhpCrudApi\Record {
  8970. class PaginationInfo
  8971. {
  8972. public $DEFAULT_PAGE_SIZE = 20;
  8973. public function hasPage(array $params): bool
  8974. {
  8975. return isset($params['page']);
  8976. }
  8977. public function getPageOffset(array $params): int
  8978. {
  8979. $offset = 0;
  8980. $pageSize = $this->getPageSize($params);
  8981. if (isset($params['page'])) {
  8982. foreach ($params['page'] as $page) {
  8983. $parts = explode(',', $page, 2);
  8984. $page = intval($parts[0]) - 1;
  8985. $offset = $page * $pageSize;
  8986. }
  8987. }
  8988. return $offset;
  8989. }
  8990. private function getPageSize(array $params): int
  8991. {
  8992. $pageSize = $this->DEFAULT_PAGE_SIZE;
  8993. if (isset($params['page'])) {
  8994. foreach ($params['page'] as $page) {
  8995. $parts = explode(',', $page, 2);
  8996. if (count($parts) > 1) {
  8997. $pageSize = intval($parts[1]);
  8998. }
  8999. }
  9000. }
  9001. return $pageSize;
  9002. }
  9003. public function getResultSize(array $params): int
  9004. {
  9005. $numberOfRows = -1;
  9006. if (isset($params['size'])) {
  9007. foreach ($params['size'] as $size) {
  9008. $numberOfRows = intval($size);
  9009. }
  9010. }
  9011. return $numberOfRows;
  9012. }
  9013. public function getPageLimit(array $params): int
  9014. {
  9015. $pageLimit = -1;
  9016. if ($this->hasPage($params)) {
  9017. $pageLimit = $this->getPageSize($params);
  9018. }
  9019. $resultSize = $this->getResultSize($params);
  9020. if ($resultSize >= 0) {
  9021. if ($pageLimit >= 0) {
  9022. $pageLimit = min($pageLimit, $resultSize);
  9023. } else {
  9024. $pageLimit = $resultSize;
  9025. }
  9026. }
  9027. return $pageLimit;
  9028. }
  9029. }
  9030. }
  9031. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  9032. namespace Tqdev\PhpCrudApi\Record {
  9033. class PathTree implements \JsonSerializable
  9034. {
  9035. const WILDCARD = '*';
  9036. private $tree;
  9037. public function __construct(/* object */&$tree = null)
  9038. {
  9039. if (!$tree) {
  9040. $tree = $this->newTree();
  9041. }
  9042. $this->tree = &$tree;
  9043. }
  9044. public function newTree()
  9045. {
  9046. return (object) ['values' => [], 'branches' => (object) []];
  9047. }
  9048. public function getKeys(): array
  9049. {
  9050. $branches = (array) $this->tree->branches;
  9051. return array_keys($branches);
  9052. }
  9053. public function getValues(): array
  9054. {
  9055. return $this->tree->values;
  9056. }
  9057. public function get(string $key): PathTree
  9058. {
  9059. if (!isset($this->tree->branches->$key)) {
  9060. return null;
  9061. }
  9062. return new PathTree($this->tree->branches->$key);
  9063. }
  9064. public function put(array $path, $value)
  9065. {
  9066. $tree = &$this->tree;
  9067. foreach ($path as $key) {
  9068. if (!isset($tree->branches->$key)) {
  9069. $tree->branches->$key = $this->newTree();
  9070. }
  9071. $tree = &$tree->branches->$key;
  9072. }
  9073. $tree->values[] = $value;
  9074. }
  9075. public function match(array $path): array
  9076. {
  9077. $star = self::WILDCARD;
  9078. $tree = &$this->tree;
  9079. foreach ($path as $key) {
  9080. if (isset($tree->branches->$key)) {
  9081. $tree = &$tree->branches->$key;
  9082. } elseif (isset($tree->branches->$star)) {
  9083. $tree = &$tree->branches->$star;
  9084. } else {
  9085. return [];
  9086. }
  9087. }
  9088. return $tree->values;
  9089. }
  9090. public static function fromJson(/* object */$tree): PathTree
  9091. {
  9092. return new PathTree($tree);
  9093. }
  9094. public function jsonSerialize()
  9095. {
  9096. return $this->tree;
  9097. }
  9098. }
  9099. }
  9100. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  9101. namespace Tqdev\PhpCrudApi\Record {
  9102. use Tqdev\PhpCrudApi\Column\ReflectionService;
  9103. use Tqdev\PhpCrudApi\Database\GenericDB;
  9104. use Tqdev\PhpCrudApi\Record\Document\ListDocument;
  9105. class RecordService
  9106. {
  9107. private $db;
  9108. private $reflection;
  9109. private $columns;
  9110. private $joiner;
  9111. private $filters;
  9112. private $ordering;
  9113. private $pagination;
  9114. public function __construct(GenericDB $db, ReflectionService $reflection)
  9115. {
  9116. $this->db = $db;
  9117. $this->reflection = $reflection;
  9118. $this->columns = new ColumnIncluder();
  9119. $this->joiner = new RelationJoiner($reflection, $this->columns);
  9120. $this->filters = new FilterInfo();
  9121. $this->ordering = new OrderingInfo();
  9122. $this->pagination = new PaginationInfo();
  9123. }
  9124. private function sanitizeRecord(string $tableName, /* object */ $record, string $id)
  9125. {
  9126. $keyset = array_keys((array) $record);
  9127. foreach ($keyset as $key) {
  9128. if (!$this->reflection->getTable($tableName)->hasColumn($key)) {
  9129. unset($record->$key);
  9130. }
  9131. }
  9132. if ($id != '') {
  9133. $pk = $this->reflection->getTable($tableName)->getPk();
  9134. foreach ($this->reflection->getTable($tableName)->getColumnNames() as $key) {
  9135. $field = $this->reflection->getTable($tableName)->getColumn($key);
  9136. if ($field->getName() == $pk->getName()) {
  9137. unset($record->$key);
  9138. }
  9139. }
  9140. }
  9141. }
  9142. public function hasTable(string $table): bool
  9143. {
  9144. return $this->reflection->hasTable($table);
  9145. }
  9146. public function getType(string $table): string
  9147. {
  9148. return $this->reflection->getType($table);
  9149. }
  9150. public function create(string $tableName, /* object */ $record, array $params) /*: ?int*/
  9151. {
  9152. $this->sanitizeRecord($tableName, $record, '');
  9153. $table = $this->reflection->getTable($tableName);
  9154. $columnValues = $this->columns->getValues($table, true, $record, $params);
  9155. return $this->db->createSingle($table, $columnValues);
  9156. }
  9157. public function read(string $tableName, string $id, array $params) /*: ?object*/
  9158. {
  9159. $table = $this->reflection->getTable($tableName);
  9160. $this->joiner->addMandatoryColumns($table, $params);
  9161. $columnNames = $this->columns->getNames($table, true, $params);
  9162. $record = $this->db->selectSingle($table, $columnNames, $id);
  9163. if ($record == null) {
  9164. return null;
  9165. }
  9166. $records = array($record);
  9167. $this->joiner->addJoins($table, $records, $params, $this->db);
  9168. return $records[0];
  9169. }
  9170. public function update(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  9171. {
  9172. $this->sanitizeRecord($tableName, $record, $id);
  9173. $table = $this->reflection->getTable($tableName);
  9174. $columnValues = $this->columns->getValues($table, true, $record, $params);
  9175. return $this->db->updateSingle($table, $columnValues, $id);
  9176. }
  9177. public function delete(string $tableName, string $id, array $params) /*: ?int*/
  9178. {
  9179. $table = $this->reflection->getTable($tableName);
  9180. return $this->db->deleteSingle($table, $id);
  9181. }
  9182. public function increment(string $tableName, string $id, /* object */ $record, array $params) /*: ?int*/
  9183. {
  9184. $this->sanitizeRecord($tableName, $record, $id);
  9185. $table = $this->reflection->getTable($tableName);
  9186. $columnValues = $this->columns->getValues($table, true, $record, $params);
  9187. return $this->db->incrementSingle($table, $columnValues, $id);
  9188. }
  9189. public function _list(string $tableName, array $params): ListDocument
  9190. {
  9191. $table = $this->reflection->getTable($tableName);
  9192. $this->joiner->addMandatoryColumns($table, $params);
  9193. $columnNames = $this->columns->getNames($table, true, $params);
  9194. $condition = $this->filters->getCombinedConditions($table, $params);
  9195. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  9196. if (!$this->pagination->hasPage($params)) {
  9197. $offset = 0;
  9198. $limit = $this->pagination->getPageLimit($params);
  9199. $count = 0;
  9200. } else {
  9201. $offset = $this->pagination->getPageOffset($params);
  9202. $limit = $this->pagination->getPageLimit($params);
  9203. $count = $this->db->selectCount($table, $condition);
  9204. }
  9205. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  9206. $this->joiner->addJoins($table, $records, $params, $this->db);
  9207. return new ListDocument($records, $count);
  9208. }
  9209. }
  9210. }
  9211. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  9212. namespace Tqdev\PhpCrudApi\Record {
  9213. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  9214. use Tqdev\PhpCrudApi\Column\ReflectionService;
  9215. use Tqdev\PhpCrudApi\Database\GenericDB;
  9216. use Tqdev\PhpCrudApi\Middleware\Communication\VariableStore;
  9217. use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
  9218. use Tqdev\PhpCrudApi\Record\Condition\OrCondition;
  9219. class RelationJoiner
  9220. {
  9221. private $reflection;
  9222. private $ordering;
  9223. private $columns;
  9224. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  9225. {
  9226. $this->reflection = $reflection;
  9227. $this->ordering = new OrderingInfo();
  9228. $this->columns = $columns;
  9229. }
  9230. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  9231. {
  9232. if (!isset($params['join']) || !isset($params['include'])) {
  9233. return;
  9234. }
  9235. $params['mandatory'] = array();
  9236. foreach ($params['join'] as $tableNames) {
  9237. $t1 = $table;
  9238. foreach (explode(',', $tableNames) as $tableName) {
  9239. if (!$this->reflection->hasTable($tableName)) {
  9240. continue;
  9241. }
  9242. $t2 = $this->reflection->getTable($tableName);
  9243. $fks1 = $t1->getFksTo($t2->getName());
  9244. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  9245. if ($t3 != null || count($fks1) > 0) {
  9246. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  9247. }
  9248. foreach ($fks1 as $fk) {
  9249. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  9250. }
  9251. $fks2 = $t2->getFksTo($t1->getName());
  9252. if ($t3 != null || count($fks2) > 0) {
  9253. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  9254. }
  9255. foreach ($fks2 as $fk) {
  9256. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  9257. }
  9258. $t1 = $t2;
  9259. }
  9260. }
  9261. }
  9262. private function getJoinsAsPathTree(array $params): PathTree
  9263. {
  9264. $joins = new PathTree();
  9265. if (isset($params['join'])) {
  9266. foreach ($params['join'] as $tableNames) {
  9267. $path = array();
  9268. foreach (explode(',', $tableNames) as $tableName) {
  9269. if (!$this->reflection->hasTable($tableName)) {
  9270. continue;
  9271. }
  9272. $t = $this->reflection->getTable($tableName);
  9273. if ($t != null) {
  9274. $path[] = $t->getName();
  9275. }
  9276. }
  9277. $joins->put($path, true);
  9278. }
  9279. }
  9280. return $joins;
  9281. }
  9282. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  9283. {
  9284. $joins = $this->getJoinsAsPathTree($params);
  9285. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  9286. }
  9287. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  9288. {
  9289. foreach ($this->reflection->getTableNames() as $tableName) {
  9290. $t3 = $this->reflection->getTable($tableName);
  9291. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  9292. return $t3;
  9293. }
  9294. }
  9295. return null;
  9296. }
  9297. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  9298. {
  9299. foreach ($joins->getKeys() as $t2Name) {
  9300. $t2 = $this->reflection->getTable($t2Name);
  9301. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  9302. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  9303. if (!$belongsTo && !$hasMany) {
  9304. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  9305. } else {
  9306. $t3 = null;
  9307. }
  9308. $hasAndBelongsToMany = ($t3 != null);
  9309. $newRecords = array();
  9310. $fkValues = null;
  9311. $pkValues = null;
  9312. $habtmValues = null;
  9313. if ($belongsTo) {
  9314. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  9315. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  9316. }
  9317. if ($hasMany) {
  9318. $pkValues = $this->getPkEmptyValues($t1, $records);
  9319. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  9320. }
  9321. if ($hasAndBelongsToMany) {
  9322. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  9323. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  9324. }
  9325. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  9326. if ($fkValues != null) {
  9327. $this->fillFkValues($t2, $newRecords, $fkValues);
  9328. $this->setFkValues($t1, $t2, $records, $fkValues);
  9329. }
  9330. if ($pkValues != null) {
  9331. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  9332. $this->setPkValues($t1, $t2, $records, $pkValues);
  9333. }
  9334. if ($habtmValues != null) {
  9335. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  9336. $this->setHabtmValues($t1, $t2, $records, $habtmValues);
  9337. }
  9338. }
  9339. }
  9340. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  9341. {
  9342. $fkValues = array();
  9343. $fks = $t1->getFksTo($t2->getName());
  9344. foreach ($fks as $fk) {
  9345. $fkName = $fk->getName();
  9346. foreach ($records as $record) {
  9347. if (isset($record[$fkName])) {
  9348. $fkValue = $record[$fkName];
  9349. $fkValues[$fkValue] = null;
  9350. }
  9351. }
  9352. }
  9353. return $fkValues;
  9354. }
  9355. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  9356. {
  9357. $columnNames = $this->columns->getNames($t2, false, $params);
  9358. $fkIds = array_keys($fkValues);
  9359. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  9360. $records[] = $record;
  9361. }
  9362. }
  9363. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  9364. {
  9365. $pkName = $t2->getPk()->getName();
  9366. foreach ($fkRecords as $fkRecord) {
  9367. $pkValue = $fkRecord[$pkName];
  9368. $fkValues[$pkValue] = $fkRecord;
  9369. }
  9370. }
  9371. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  9372. {
  9373. $fks = $t1->getFksTo($t2->getName());
  9374. foreach ($fks as $fk) {
  9375. $fkName = $fk->getName();
  9376. foreach ($records as $i => $record) {
  9377. if (isset($record[$fkName])) {
  9378. $key = $record[$fkName];
  9379. $records[$i][$fkName] = $fkValues[$key];
  9380. }
  9381. }
  9382. }
  9383. }
  9384. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  9385. {
  9386. $pkValues = array();
  9387. $pkName = $t1->getPk()->getName();
  9388. foreach ($records as $record) {
  9389. $key = $record[$pkName];
  9390. $pkValues[$key] = array();
  9391. }
  9392. return $pkValues;
  9393. }
  9394. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  9395. {
  9396. $fks = $t2->getFksTo($t1->getName());
  9397. $columnNames = $this->columns->getNames($t2, false, $params);
  9398. $pkValueKeys = implode(',', array_keys($pkValues));
  9399. $conditions = array();
  9400. foreach ($fks as $fk) {
  9401. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  9402. }
  9403. $condition = OrCondition::fromArray($conditions);
  9404. $columnOrdering = array();
  9405. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  9406. if ($limit != -1) {
  9407. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t2);
  9408. }
  9409. foreach ($db->selectAll($t2, $columnNames, $condition, $columnOrdering, 0, $limit) as $record) {
  9410. $records[] = $record;
  9411. }
  9412. }
  9413. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  9414. {
  9415. $fks = $t2->getFksTo($t1->getName());
  9416. foreach ($fks as $fk) {
  9417. $fkName = $fk->getName();
  9418. foreach ($pkRecords as $pkRecord) {
  9419. $key = $pkRecord[$fkName];
  9420. if (isset($pkValues[$key])) {
  9421. $pkValues[$key][] = $pkRecord;
  9422. }
  9423. }
  9424. }
  9425. }
  9426. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  9427. {
  9428. $pkName = $t1->getPk()->getName();
  9429. $t2Name = $t2->getName();
  9430. foreach ($records as $i => $record) {
  9431. $key = $record[$pkName];
  9432. $records[$i][$t2Name] = $pkValues[$key];
  9433. }
  9434. }
  9435. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  9436. {
  9437. $pkValues = $this->getPkEmptyValues($t1, $records);
  9438. $fkValues = array();
  9439. $fk1 = $t3->getFksTo($t1->getName())[0];
  9440. $fk2 = $t3->getFksTo($t2->getName())[0];
  9441. $fk1Name = $fk1->getName();
  9442. $fk2Name = $fk2->getName();
  9443. $columnNames = array($fk1Name, $fk2Name);
  9444. $pkIds = implode(',', array_keys($pkValues));
  9445. $condition = new ColumnCondition($t3->getColumn($fk1Name), 'in', $pkIds);
  9446. $columnOrdering = array();
  9447. $limit = VariableStore::get("joinLimits.maxRecords") ?: -1;
  9448. if ($limit != -1) {
  9449. $columnOrdering = $this->ordering->getDefaultColumnOrdering($t3);
  9450. }
  9451. $records = $db->selectAll($t3, $columnNames, $condition, $columnOrdering, 0, $limit);
  9452. foreach ($records as $record) {
  9453. $val1 = $record[$fk1Name];
  9454. $val2 = $record[$fk2Name];
  9455. $pkValues[$val1][] = $val2;
  9456. $fkValues[$val2] = null;
  9457. }
  9458. return new HabtmValues($pkValues, $fkValues);
  9459. }
  9460. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, HabtmValues $habtmValues) /*: void*/
  9461. {
  9462. $pkName = $t1->getPk()->getName();
  9463. $t2Name = $t2->getName();
  9464. foreach ($records as $i => $record) {
  9465. $key = $record[$pkName];
  9466. $val = array();
  9467. $fks = $habtmValues->pkValues[$key];
  9468. foreach ($fks as $fk) {
  9469. $val[] = $habtmValues->fkValues[$fk];
  9470. }
  9471. $records[$i][$t2Name] = $val;
  9472. }
  9473. }
  9474. }
  9475. }
  9476. // file: src/Tqdev/PhpCrudApi/Api.php
  9477. namespace Tqdev\PhpCrudApi {
  9478. use Psr\Http\Message\ResponseInterface;
  9479. use Psr\Http\Message\ServerRequestInterface;
  9480. use Psr\Http\Server\RequestHandlerInterface;
  9481. use Tqdev\PhpCrudApi\Cache\CacheFactory;
  9482. use Tqdev\PhpCrudApi\Column\DefinitionService;
  9483. use Tqdev\PhpCrudApi\Column\ReflectionService;
  9484. use Tqdev\PhpCrudApi\Controller\CacheController;
  9485. use Tqdev\PhpCrudApi\Controller\ColumnController;
  9486. use Tqdev\PhpCrudApi\Controller\GeoJsonController;
  9487. use Tqdev\PhpCrudApi\Controller\JsonResponder;
  9488. use Tqdev\PhpCrudApi\Controller\OpenApiController;
  9489. use Tqdev\PhpCrudApi\Controller\RecordController;
  9490. use Tqdev\PhpCrudApi\Database\GenericDB;
  9491. use Tqdev\PhpCrudApi\GeoJson\GeoJsonService;
  9492. use Tqdev\PhpCrudApi\Middleware\AuthorizationMiddleware;
  9493. use Tqdev\PhpCrudApi\Middleware\BasicAuthMiddleware;
  9494. use Tqdev\PhpCrudApi\Middleware\CorsMiddleware;
  9495. use Tqdev\PhpCrudApi\Middleware\CustomizationMiddleware;
  9496. use Tqdev\PhpCrudApi\Middleware\DbAuthMiddleware;
  9497. use Tqdev\PhpCrudApi\Middleware\FirewallMiddleware;
  9498. use Tqdev\PhpCrudApi\Middleware\IpAddressMiddleware;
  9499. use Tqdev\PhpCrudApi\Middleware\JoinLimitsMiddleware;
  9500. use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware;
  9501. use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware;
  9502. use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware;
  9503. use Tqdev\PhpCrudApi\Middleware\ReconnectMiddleware;
  9504. use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter;
  9505. use Tqdev\PhpCrudApi\Middleware\SanitationMiddleware;
  9506. use Tqdev\PhpCrudApi\Middleware\SslRedirectMiddleware;
  9507. use Tqdev\PhpCrudApi\Middleware\ValidationMiddleware;
  9508. use Tqdev\PhpCrudApi\Middleware\XmlMiddleware;
  9509. use Tqdev\PhpCrudApi\Middleware\XsrfMiddleware;
  9510. use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
  9511. use Tqdev\PhpCrudApi\Record\ErrorCode;
  9512. use Tqdev\PhpCrudApi\Record\RecordService;
  9513. use Tqdev\PhpCrudApi\ResponseUtils;
  9514. class Api implements RequestHandlerInterface
  9515. {
  9516. private $router;
  9517. private $responder;
  9518. private $debug;
  9519. public function __construct(Config $config)
  9520. {
  9521. $db = new GenericDB(
  9522. $config->getDriver(),
  9523. $config->getAddress(),
  9524. $config->getPort(),
  9525. $config->getDatabase(),
  9526. $config->getTables(),
  9527. $config->getUsername(),
  9528. $config->getPassword()
  9529. );
  9530. $prefix = sprintf('phpcrudapi-%s-', substr(md5(__FILE__), 0, 8));
  9531. $cache = CacheFactory::create($config->getCacheType(), $prefix, $config->getCachePath());
  9532. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  9533. $responder = new JsonResponder();
  9534. $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug());
  9535. foreach ($config->getMiddlewares() as $middleware => $properties) {
  9536. switch ($middleware) {
  9537. case 'sslRedirect':
  9538. new SslRedirectMiddleware($router, $responder, $properties);
  9539. break;
  9540. case 'cors':
  9541. new CorsMiddleware($router, $responder, $properties);
  9542. break;
  9543. case 'firewall':
  9544. new FirewallMiddleware($router, $responder, $properties);
  9545. break;
  9546. case 'basicAuth':
  9547. new BasicAuthMiddleware($router, $responder, $properties);
  9548. break;
  9549. case 'jwtAuth':
  9550. new JwtAuthMiddleware($router, $responder, $properties);
  9551. break;
  9552. case 'dbAuth':
  9553. new DbAuthMiddleware($router, $responder, $properties, $reflection, $db);
  9554. break;
  9555. case 'reconnect':
  9556. new ReconnectMiddleware($router, $responder, $properties, $reflection, $db);
  9557. break;
  9558. case 'validation':
  9559. new ValidationMiddleware($router, $responder, $properties, $reflection);
  9560. break;
  9561. case 'ipAddress':
  9562. new IpAddressMiddleware($router, $responder, $properties, $reflection);
  9563. break;
  9564. case 'sanitation':
  9565. new SanitationMiddleware($router, $responder, $properties, $reflection);
  9566. break;
  9567. case 'multiTenancy':
  9568. new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
  9569. break;
  9570. case 'authorization':
  9571. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  9572. break;
  9573. case 'xsrf':
  9574. new XsrfMiddleware($router, $responder, $properties);
  9575. break;
  9576. case 'pageLimits':
  9577. new PageLimitsMiddleware($router, $responder, $properties, $reflection);
  9578. break;
  9579. case 'joinLimits':
  9580. new JoinLimitsMiddleware($router, $responder, $properties, $reflection);
  9581. break;
  9582. case 'customization':
  9583. new CustomizationMiddleware($router, $responder, $properties, $reflection);
  9584. break;
  9585. case 'xml':
  9586. new XmlMiddleware($router, $responder, $properties, $reflection);
  9587. break;
  9588. }
  9589. }
  9590. foreach ($config->getControllers() as $controller) {
  9591. switch ($controller) {
  9592. case 'records':
  9593. $records = new RecordService($db, $reflection);
  9594. new RecordController($router, $responder, $records);
  9595. break;
  9596. case 'columns':
  9597. $definition = new DefinitionService($db, $reflection);
  9598. new ColumnController($router, $responder, $reflection, $definition);
  9599. break;
  9600. case 'cache':
  9601. new CacheController($router, $responder, $cache);
  9602. break;
  9603. case 'openapi':
  9604. $openApi = new OpenApiService($reflection, $config->getOpenApiBase(), $config->getControllers(), $config->getCustomOpenApiBuilders());
  9605. new OpenApiController($router, $responder, $openApi);
  9606. break;
  9607. case 'geojson':
  9608. $records = new RecordService($db, $reflection);
  9609. $geoJson = new GeoJsonService($reflection, $records);
  9610. new GeoJsonController($router, $responder, $geoJson);
  9611. break;
  9612. }
  9613. }
  9614. foreach ($config->getCustomControllers() as $className) {
  9615. if (class_exists($className)) {
  9616. $records = new RecordService($db, $reflection);
  9617. new $className($router, $responder, $records);
  9618. }
  9619. }
  9620. $this->router = $router;
  9621. $this->responder = $responder;
  9622. $this->debug = $config->getDebug();
  9623. }
  9624. private function parseBody(string $body) /*: ?object*/
  9625. {
  9626. $first = substr($body, 0, 1);
  9627. if ($first == '[' || $first == '{') {
  9628. $object = json_decode($body);
  9629. $causeCode = json_last_error();
  9630. if ($causeCode !== JSON_ERROR_NONE) {
  9631. $object = null;
  9632. }
  9633. } else {
  9634. parse_str($body, $input);
  9635. foreach ($input as $key => $value) {
  9636. if (substr($key, -9) == '__is_null') {
  9637. $input[substr($key, 0, -9)] = null;
  9638. unset($input[$key]);
  9639. }
  9640. }
  9641. $object = (object) $input;
  9642. }
  9643. return $object;
  9644. }
  9645. private function addParsedBody(ServerRequestInterface $request): ServerRequestInterface
  9646. {
  9647. $parsedBody = $request->getParsedBody();
  9648. if ($parsedBody) {
  9649. $request = $this->applyParsedBodyHack($request);
  9650. } else {
  9651. $body = $request->getBody();
  9652. if ($body->isReadable()) {
  9653. if ($body->isSeekable()) {
  9654. $body->rewind();
  9655. }
  9656. $contents = $body->getContents();
  9657. if ($body->isSeekable()) {
  9658. $body->rewind();
  9659. }
  9660. if ($contents) {
  9661. $parsedBody = $this->parseBody($contents);
  9662. $request = $request->withParsedBody($parsedBody);
  9663. }
  9664. }
  9665. }
  9666. return $request;
  9667. }
  9668. private function applyParsedBodyHack(ServerRequestInterface $request): ServerRequestInterface
  9669. {
  9670. $parsedBody = $request->getParsedBody();
  9671. if (is_array($parsedBody)) { // is it really?
  9672. $contents = json_encode($parsedBody);
  9673. $parsedBody = $this->parseBody($contents);
  9674. $request = $request->withParsedBody($parsedBody);
  9675. }
  9676. return $request;
  9677. }
  9678. public function handle(ServerRequestInterface $request): ResponseInterface
  9679. {
  9680. $response = null;
  9681. try {
  9682. $response = $this->router->route($this->addParsedBody($request));
  9683. } catch (\Throwable $e) {
  9684. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  9685. if ($this->debug) {
  9686. $response = ResponseUtils::addExceptionHeaders($response, $e);
  9687. }
  9688. }
  9689. return $response;
  9690. }
  9691. }
  9692. }
  9693. // file: src/Tqdev/PhpCrudApi/Config.php
  9694. namespace Tqdev\PhpCrudApi {
  9695. class Config
  9696. {
  9697. private $values = [
  9698. 'driver' => null,
  9699. 'address' => 'localhost',
  9700. 'port' => null,
  9701. 'username' => null,
  9702. 'password' => null,
  9703. 'database' => null,
  9704. 'tables' => '',
  9705. 'middlewares' => 'cors',
  9706. 'controllers' => 'records,geojson,openapi',
  9707. 'customControllers' => '',
  9708. 'customOpenApiBuilders' => '',
  9709. 'cacheType' => 'TempFile',
  9710. 'cachePath' => '',
  9711. 'cacheTime' => 10,
  9712. 'debug' => false,
  9713. 'basePath' => '',
  9714. 'openApiBase' => '{"info":{"title":"PHP-CRUD-API","version":"1.0.0"}}',
  9715. ];
  9716. private function getDefaultDriver(array $values): string
  9717. {
  9718. if (isset($values['driver'])) {
  9719. return $values['driver'];
  9720. }
  9721. return 'mysql';
  9722. }
  9723. private function getDefaultPort(string $driver): int
  9724. {
  9725. switch ($driver) {
  9726. case 'mysql':
  9727. return 3306;
  9728. case 'pgsql':
  9729. return 5432;
  9730. case 'sqlsrv':
  9731. return 1433;
  9732. case 'sqlite':
  9733. return 0;
  9734. }
  9735. }
  9736. private function getDefaultAddress(string $driver): string
  9737. {
  9738. switch ($driver) {
  9739. case 'mysql':
  9740. return 'localhost';
  9741. case 'pgsql':
  9742. return 'localhost';
  9743. case 'sqlsrv':
  9744. return 'localhost';
  9745. case 'sqlite':
  9746. return 'data.db';
  9747. }
  9748. }
  9749. private function getDriverDefaults(string $driver): array
  9750. {
  9751. return [
  9752. 'driver' => $driver,
  9753. 'address' => $this->getDefaultAddress($driver),
  9754. 'port' => $this->getDefaultPort($driver),
  9755. ];
  9756. }
  9757. public function __construct(array $values)
  9758. {
  9759. $driver = $this->getDefaultDriver($values);
  9760. $defaults = $this->getDriverDefaults($driver);
  9761. $newValues = array_merge($this->values, $defaults, $values);
  9762. $newValues = $this->parseMiddlewares($newValues);
  9763. $diff = array_diff_key($newValues, $this->values);
  9764. if (!empty($diff)) {
  9765. $key = array_keys($diff)[0];
  9766. throw new \Exception("Config has invalid value '$key'");
  9767. }
  9768. $this->values = $newValues;
  9769. }
  9770. private function parseMiddlewares(array $values): array
  9771. {
  9772. $newValues = array();
  9773. $properties = array();
  9774. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  9775. foreach ($middlewares as $middleware) {
  9776. $properties[$middleware] = [];
  9777. }
  9778. foreach ($values as $key => $value) {
  9779. if (strpos($key, '.') === false) {
  9780. $newValues[$key] = $value;
  9781. } else {
  9782. list($middleware, $key2) = explode('.', $key, 2);
  9783. if (isset($properties[$middleware])) {
  9784. $properties[$middleware][$key2] = $value;
  9785. } else {
  9786. throw new \Exception("Config has invalid value '$key'");
  9787. }
  9788. }
  9789. }
  9790. $newValues['middlewares'] = array_reverse($properties, true);
  9791. return $newValues;
  9792. }
  9793. public function getDriver(): string
  9794. {
  9795. return $this->values['driver'];
  9796. }
  9797. public function getAddress(): string
  9798. {
  9799. return $this->values['address'];
  9800. }
  9801. public function getPort(): int
  9802. {
  9803. return $this->values['port'];
  9804. }
  9805. public function getUsername(): string
  9806. {
  9807. return $this->values['username'];
  9808. }
  9809. public function getPassword(): string
  9810. {
  9811. return $this->values['password'];
  9812. }
  9813. public function getDatabase(): string
  9814. {
  9815. return $this->values['database'];
  9816. }
  9817. public function getTables(): array
  9818. {
  9819. return array_filter(array_map('trim', explode(',', $this->values['tables'])));
  9820. }
  9821. public function getMiddlewares(): array
  9822. {
  9823. return $this->values['middlewares'];
  9824. }
  9825. public function getControllers(): array
  9826. {
  9827. return array_filter(array_map('trim', explode(',', $this->values['controllers'])));
  9828. }
  9829. public function getCustomControllers(): array
  9830. {
  9831. return array_filter(array_map('trim', explode(',', $this->values['customControllers'])));
  9832. }
  9833. public function getCustomOpenApiBuilders(): array
  9834. {
  9835. return array_filter(array_map('trim', explode(',', $this->values['customOpenApiBuilders'])));
  9836. }
  9837. public function getCacheType(): string
  9838. {
  9839. return $this->values['cacheType'];
  9840. }
  9841. public function getCachePath(): string
  9842. {
  9843. return $this->values['cachePath'];
  9844. }
  9845. public function getCacheTime(): int
  9846. {
  9847. return $this->values['cacheTime'];
  9848. }
  9849. public function getDebug(): bool
  9850. {
  9851. return $this->values['debug'];
  9852. }
  9853. public function getBasePath(): string
  9854. {
  9855. return $this->values['basePath'];
  9856. }
  9857. public function getOpenApiBase(): array
  9858. {
  9859. return json_decode($this->values['openApiBase'], true);
  9860. }
  9861. }
  9862. }
  9863. // file: src/Tqdev/PhpCrudApi/RequestFactory.php
  9864. namespace Tqdev\PhpCrudApi {
  9865. use Nyholm\Psr7\Factory\Psr17Factory;
  9866. use Nyholm\Psr7Server\ServerRequestCreator;
  9867. use Psr\Http\Message\ServerRequestInterface;
  9868. class RequestFactory
  9869. {
  9870. public static function fromGlobals(): ServerRequestInterface
  9871. {
  9872. $psr17Factory = new Psr17Factory();
  9873. $creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
  9874. $serverRequest = $creator->fromGlobals();
  9875. $stream = $psr17Factory->createStreamFromFile('php://input');
  9876. $serverRequest = $serverRequest->withBody($stream);
  9877. return $serverRequest;
  9878. }
  9879. public static function fromString(string $request): ServerRequestInterface
  9880. {
  9881. $parts = explode("\n\n", trim($request), 2);
  9882. $lines = explode("\n", $parts[0]);
  9883. $first = explode(' ', trim(array_shift($lines)), 2);
  9884. $method = $first[0];
  9885. $body = isset($parts[1]) ? $parts[1] : '';
  9886. $url = isset($first[1]) ? $first[1] : '';
  9887. $psr17Factory = new Psr17Factory();
  9888. $serverRequest = $psr17Factory->createServerRequest($method, $url);
  9889. foreach ($lines as $line) {
  9890. list($key, $value) = explode(':', $line, 2);
  9891. $serverRequest = $serverRequest->withAddedHeader($key, $value);
  9892. }
  9893. if ($body) {
  9894. $stream = $psr17Factory->createStream($body);
  9895. $stream->rewind();
  9896. $serverRequest = $serverRequest->withBody($stream);
  9897. }
  9898. return $serverRequest;
  9899. }
  9900. }
  9901. }
  9902. // file: src/Tqdev/PhpCrudApi/RequestUtils.php
  9903. namespace Tqdev\PhpCrudApi {
  9904. use Psr\Http\Message\ServerRequestInterface;
  9905. use Tqdev\PhpCrudApi\Column\ReflectionService;
  9906. class RequestUtils
  9907. {
  9908. public static function setParams(ServerRequestInterface $request, array $params): ServerRequestInterface
  9909. {
  9910. $query = preg_replace('|%5B[0-9]+%5D=|', '=', http_build_query($params));
  9911. return $request->withUri($request->getUri()->withQuery($query));
  9912. }
  9913. public static function getHeader(ServerRequestInterface $request, string $header): string
  9914. {
  9915. $headers = $request->getHeader($header);
  9916. return isset($headers[0]) ? $headers[0] : '';
  9917. }
  9918. public static function getParams(ServerRequestInterface $request): array
  9919. {
  9920. $params = array();
  9921. $query = $request->getUri()->getQuery();
  9922. //$query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  9923. $query = str_replace('%5D%5B%5D=', '%5D=', str_replace('=', '%5B%5D=', $query));
  9924. parse_str($query, $params);
  9925. return $params;
  9926. }
  9927. public static function getPathSegment(ServerRequestInterface $request, int $part): string
  9928. {
  9929. $path = $request->getUri()->getPath();
  9930. $pathSegments = explode('/', rtrim($path, '/'));
  9931. if ($part < 0 || $part >= count($pathSegments)) {
  9932. return '';
  9933. }
  9934. return urldecode($pathSegments[$part]);
  9935. }
  9936. public static function getOperation(ServerRequestInterface $request): string
  9937. {
  9938. $method = $request->getMethod();
  9939. $path = RequestUtils::getPathSegment($request, 1);
  9940. $hasPk = RequestUtils::getPathSegment($request, 3) != '';
  9941. switch ($path) {
  9942. case 'openapi':
  9943. return 'document';
  9944. case 'columns':
  9945. return $method == 'get' ? 'reflect' : 'remodel';
  9946. case 'geojson':
  9947. case 'records':
  9948. switch ($method) {
  9949. case 'POST':
  9950. return 'create';
  9951. case 'GET':
  9952. return $hasPk ? 'read' : 'list';
  9953. case 'PUT':
  9954. return 'update';
  9955. case 'DELETE':
  9956. return 'delete';
  9957. case 'PATCH':
  9958. return 'increment';
  9959. }
  9960. }
  9961. return 'unknown';
  9962. }
  9963. private static function getJoinTables(string $tableName, array $parameters): array
  9964. {
  9965. $uniqueTableNames = array();
  9966. $uniqueTableNames[$tableName] = true;
  9967. if (isset($parameters['join'])) {
  9968. foreach ($parameters['join'] as $parameter) {
  9969. $tableNames = explode(',', trim($parameter));
  9970. foreach ($tableNames as $tableName) {
  9971. $uniqueTableNames[$tableName] = true;
  9972. }
  9973. }
  9974. }
  9975. return array_keys($uniqueTableNames);
  9976. }
  9977. public static function getTableNames(ServerRequestInterface $request, ReflectionService $reflection): array
  9978. {
  9979. $path = RequestUtils::getPathSegment($request, 1);
  9980. $tableName = RequestUtils::getPathSegment($request, 2);
  9981. $allTableNames = $reflection->getTableNames();
  9982. switch ($path) {
  9983. case 'openapi':
  9984. return $allTableNames;
  9985. case 'columns':
  9986. return $tableName ? [$tableName] : $allTableNames;
  9987. case 'records':
  9988. return self::getJoinTables($tableName, RequestUtils::getParams($request));
  9989. }
  9990. return $allTableNames;
  9991. }
  9992. }
  9993. }
  9994. // file: src/Tqdev/PhpCrudApi/ResponseFactory.php
  9995. namespace Tqdev\PhpCrudApi {
  9996. use Nyholm\Psr7\Factory\Psr17Factory;
  9997. use Psr\Http\Message\ResponseInterface;
  9998. class ResponseFactory
  9999. {
  10000. const OK = 200;
  10001. const UNAUTHORIZED = 401;
  10002. const FORBIDDEN = 403;
  10003. const NOT_FOUND = 404;
  10004. const METHOD_NOT_ALLOWED = 405;
  10005. const CONFLICT = 409;
  10006. const UNPROCESSABLE_ENTITY = 422;
  10007. const INTERNAL_SERVER_ERROR = 500;
  10008. public static function fromXml(int $status, string $xml): ResponseInterface
  10009. {
  10010. return self::from($status, 'text/xml', $xml);
  10011. }
  10012. public static function fromCsv(int $status, string $csv): ResponseInterface
  10013. {
  10014. $response = self::from($status, 'text/csv', $csv);
  10015. return $response->withHeader('Content-Type', 'text/csv');
  10016. }
  10017. public static function fromHtml(int $status, string $html): ResponseInterface
  10018. {
  10019. return self::from($status, 'text/html', $html);
  10020. }
  10021. public static function fromObject(int $status, $body): ResponseInterface
  10022. {
  10023. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  10024. return self::from($status, 'application/json', $content);
  10025. }
  10026. private static function from(int $status, string $contentType, string $content): ResponseInterface
  10027. {
  10028. $psr17Factory = new Psr17Factory();
  10029. $response = $psr17Factory->createResponse($status);
  10030. $stream = $psr17Factory->createStream($content);
  10031. $stream->rewind();
  10032. $response = $response->withBody($stream);
  10033. $response = $response->withHeader('Content-Type', $contentType . '; charset=utf-8');
  10034. $response = $response->withHeader('Content-Length', strlen($content));
  10035. return $response;
  10036. }
  10037. public static function fromStatus(int $status): ResponseInterface
  10038. {
  10039. $psr17Factory = new Psr17Factory();
  10040. return $psr17Factory->createResponse($status);
  10041. }
  10042. }
  10043. }
  10044. // file: src/Tqdev/PhpCrudApi/ResponseUtils.php
  10045. namespace Tqdev\PhpCrudApi {
  10046. use Psr\Http\Message\ResponseInterface;
  10047. class ResponseUtils
  10048. {
  10049. public static function output(ResponseInterface $response)
  10050. {
  10051. $status = $response->getStatusCode();
  10052. $headers = $response->getHeaders();
  10053. $body = $response->getBody()->getContents();
  10054. http_response_code($status);
  10055. foreach ($headers as $key => $values) {
  10056. foreach ($values as $value) {
  10057. header("$key: $value");
  10058. }
  10059. }
  10060. echo $body;
  10061. }
  10062. public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
  10063. {
  10064. $response = $response->withHeader('X-Exception-Name', get_class($e));
  10065. $response = $response->withHeader('X-Exception-Message', preg_replace('|\n|', ' ', trim($e->getMessage())));
  10066. $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
  10067. return $response;
  10068. }
  10069. public static function toString(ResponseInterface $response): string
  10070. {
  10071. $status = $response->getStatusCode();
  10072. $headers = $response->getHeaders();
  10073. $body = $response->getBody()->getContents();
  10074. $str = "$status\n";
  10075. foreach ($headers as $key => $values) {
  10076. foreach ($values as $value) {
  10077. $str .= "$key: $value\n";
  10078. }
  10079. }
  10080. if ($body !== '') {
  10081. $str .= "\n";
  10082. $str .= "$body\n";
  10083. }
  10084. return $str;
  10085. }
  10086. }
  10087. }
  10088. // file: src/index.php
  10089. namespace Tqdev\PhpCrudApi {
  10090. use Tqdev\PhpCrudApi\Api;
  10091. use Tqdev\PhpCrudApi\Config;
  10092. use Tqdev\PhpCrudApi\RequestFactory;
  10093. use Tqdev\PhpCrudApi\ResponseUtils;
  10094. $config = new Config([
  10095. // 'driver' => 'mysql',
  10096. // 'address' => 'localhost',
  10097. 'username' => 'php-crud-api',
  10098. 'password' => 'php-crud-api',
  10099. 'database' => 'php-crud-api',
  10100. // 'debug' => false
  10101. ]);
  10102. $request = RequestFactory::fromGlobals();
  10103. $api = new Api($config);
  10104. $response = $api->handle($request);
  10105. ResponseUtils::output($response);
  10106. }