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

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