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

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