api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.php 252KB

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