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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195
  1. <?php
  2. /**
  3. * PHP-CRUD-API v2 License: MIT
  4. * Maurits van der Schee: maurits@vdschee.nl
  5. * https://github.com/mevdschee/php-crud-api
  6. **/
  7. namespace Tqdev\PhpCrudApi;
  8. // file: src/Tqdev/PhpCrudApi/Cache/Cache.php
  9. interface Cache
  10. {
  11. public function set(String $key, String $value, int $ttl = 0): bool;
  12. public function get(String $key): String;
  13. public function clear(): bool;
  14. }
  15. // file: src/Tqdev/PhpCrudApi/Cache/CacheFactory.php
  16. class CacheFactory
  17. {
  18. const PREFIX = 'phpcrudapi-%s-';
  19. private static function getPrefix(): String
  20. {
  21. return sprintf(self::PREFIX, substr(md5(__FILE__), 0, 8));
  22. }
  23. public static function create(Config $config): Cache
  24. {
  25. switch ($config->getCacheType()) {
  26. case 'TempFile':
  27. $cache = new TempFileCache(self::getPrefix(), $config->getCachePath());
  28. break;
  29. case 'Redis':
  30. $cache = new RedisCache(self::getPrefix(), $config->getCachePath());
  31. break;
  32. case 'Memcache':
  33. $cache = new MemcacheCache(self::getPrefix(), $config->getCachePath());
  34. break;
  35. case 'Memcached':
  36. $cache = new MemcachedCache(self::getPrefix(), $config->getCachePath());
  37. break;
  38. default:
  39. $cache = new NoCache();
  40. }
  41. return $cache;
  42. }
  43. }
  44. // file: src/Tqdev/PhpCrudApi/Cache/MemcacheCache.php
  45. class MemcacheCache implements Cache
  46. {
  47. protected $prefix;
  48. protected $memcache;
  49. public function __construct(String $prefix, String $config)
  50. {
  51. $this->prefix = $prefix;
  52. if ($config == '') {
  53. $address = 'localhost';
  54. $port = 11211;
  55. } elseif (strpos($config, ':') === false) {
  56. $address = $config;
  57. $port = 11211;
  58. } else {
  59. list($address, $port) = explode(':', $config);
  60. }
  61. $this->memcache = $this->create();
  62. $this->memcache->addServer($address, $port);
  63. }
  64. protected function create(): stdClass
  65. {
  66. return new \Memcache();
  67. }
  68. public function set(String $key, String $value, int $ttl = 0): bool
  69. {
  70. return $this->memcache->set($this->prefix . $key, $value, 0, $ttl);
  71. }
  72. public function get(String $key): String
  73. {
  74. return $this->memcache->get($this->prefix . $key) ?: '';
  75. }
  76. public function clear(): bool
  77. {
  78. return $this->memcache->flush();
  79. }
  80. }
  81. // file: src/Tqdev/PhpCrudApi/Cache/MemcachedCache.php
  82. class MemcachedCache extends MemcacheCache
  83. {
  84. protected function create(): stdClass
  85. {
  86. return new \Memcached();
  87. }
  88. public function set(String $key, String $value, int $ttl = 0): bool
  89. {
  90. return $this->memcache->set($this->prefix . $key, $value, $ttl);
  91. }
  92. }
  93. // file: src/Tqdev/PhpCrudApi/Cache/NoCache.php
  94. class NoCache implements Cache
  95. {
  96. public function __construct()
  97. {
  98. }
  99. public function set(String $key, String $value, int $ttl = 0): bool
  100. {
  101. return true;
  102. }
  103. public function get(String $key): String
  104. {
  105. return '';
  106. }
  107. public function clear(): bool
  108. {
  109. return true;
  110. }
  111. }
  112. // file: src/Tqdev/PhpCrudApi/Cache/RedisCache.php
  113. class RedisCache implements Cache
  114. {
  115. protected $prefix;
  116. protected $redis;
  117. public function __construct(String $prefix, String $config)
  118. {
  119. $this->prefix = $prefix;
  120. if ($config == '') {
  121. $config = '127.0.0.1';
  122. }
  123. $params = explode(':', $config, 6);
  124. if (isset($params[3])) {
  125. $params[3] = null;
  126. }
  127. $this->redis = new \Redis();
  128. call_user_func_array(array($this->redis, 'pconnect'), $params);
  129. }
  130. public function set(String $key, String $value, int $ttl = 0): bool
  131. {
  132. return $this->redis->set($this->prefix . $key, $value, $ttl);
  133. }
  134. public function get(String $key): String
  135. {
  136. return $this->redis->get($this->prefix . $key) ?: '';
  137. }
  138. public function clear(): bool
  139. {
  140. return $this->redis->flushDb();
  141. }
  142. }
  143. // file: src/Tqdev/PhpCrudApi/Cache/TempFileCache.php
  144. class TempFileCache implements Cache
  145. {
  146. const SUFFIX = 'cache';
  147. private $path;
  148. private $segments;
  149. public function __construct(String $prefix, String $config)
  150. {
  151. $this->segments = [];
  152. $s = DIRECTORY_SEPARATOR;
  153. $ps = PATH_SEPARATOR;
  154. if ($config == '') {
  155. $this->path = sys_get_temp_dir() . $s . $prefix . self::SUFFIX;
  156. } elseif (strpos($config, $ps) === false) {
  157. $this->path = $config;
  158. } else {
  159. list($path, $segments) = explode($ps, $config);
  160. $this->path = $path;
  161. $this->segments = explode(',', $segments);
  162. }
  163. if (file_exists($this->path) && is_dir($this->path)) {
  164. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), false);
  165. }
  166. }
  167. private function getFileName(String $key): String
  168. {
  169. $s = DIRECTORY_SEPARATOR;
  170. $md5 = md5($key);
  171. $filename = rtrim($this->path, $s) . $s;
  172. $i = 0;
  173. foreach ($this->segments as $segment) {
  174. $filename .= substr($md5, $i, $segment) . $s;
  175. $i += $segment;
  176. }
  177. $filename .= substr($md5, $i);
  178. return $filename;
  179. }
  180. public function set(String $key, String $value, int $ttl = 0): bool
  181. {
  182. $filename = $this->getFileName($key);
  183. $dirname = dirname($filename);
  184. if (!file_exists($dirname)) {
  185. if (!mkdir($dirname, 0755, true)) {
  186. return false;
  187. }
  188. }
  189. $string = $ttl . '|' . $value;
  190. return $this->filePutContents($filename, $string) !== false;
  191. }
  192. private function filePutContents($filename, $string)
  193. {
  194. return file_put_contents($filename, $string, LOCK_EX);
  195. }
  196. private function fileGetContents($filename)
  197. {
  198. $file = fopen($filename, 'rb');
  199. if ($file === false) {
  200. return false;
  201. }
  202. $lock = flock($file, LOCK_SH);
  203. if (!$lock) {
  204. fclose($file);
  205. return false;
  206. }
  207. $string = '';
  208. while (!feof($file)) {
  209. $string .= fread($file, 8192);
  210. }
  211. flock($file, LOCK_UN);
  212. fclose($file);
  213. return $string;
  214. }
  215. private function getString($filename): String
  216. {
  217. $data = $this->fileGetContents($filename);
  218. if ($data === false) {
  219. return '';
  220. }
  221. list($ttl, $string) = explode('|', $data, 2);
  222. if ($ttl > 0 && time() - filemtime($filename) > $ttl) {
  223. return '';
  224. }
  225. return $string;
  226. }
  227. public function get(String $key): String
  228. {
  229. $filename = $this->getFileName($key);
  230. if (!file_exists($filename)) {
  231. return '';
  232. }
  233. $string = $this->getString($filename);
  234. if ($string == null) {
  235. return '';
  236. }
  237. return $string;
  238. }
  239. private function clean(String $path, array $segments, int $len, bool $all) /*: void*/
  240. {
  241. $entries = scandir($path);
  242. foreach ($entries as $entry) {
  243. if ($entry === '.' || $entry === '..') {
  244. continue;
  245. }
  246. $filename = $path . DIRECTORY_SEPARATOR . $entry;
  247. if (count($segments) == 0) {
  248. if (strlen($entry) != $len) {
  249. continue;
  250. }
  251. if (is_file($filename)) {
  252. if ($all || $this->getString($filename) == null) {
  253. unlink($filename);
  254. }
  255. }
  256. } else {
  257. if (strlen($entry) != $segments[0]) {
  258. continue;
  259. }
  260. if (is_dir($filename)) {
  261. $this->clean($filename, array_slice($segments, 1), $len - $segments[0], $all);
  262. rmdir($filename);
  263. }
  264. }
  265. }
  266. }
  267. public function clear(): bool
  268. {
  269. if (!file_exists($this->path) || !is_dir($this->path)) {
  270. return false;
  271. }
  272. $this->clean($this->path, array_filter($this->segments), strlen(md5('')), true);
  273. return true;
  274. }
  275. }
  276. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedColumn.php
  277. class ReflectedColumn implements \JsonSerializable
  278. {
  279. const DEFAULT_LENGTH = 255;
  280. const DEFAULT_PRECISION = 19;
  281. const DEFAULT_SCALE = 4;
  282. private $name;
  283. private $type;
  284. private $length;
  285. private $precision;
  286. private $scale;
  287. private $nullable;
  288. private $pk;
  289. private $fk;
  290. public function __construct(String $name, String $type, int $length, int $precision, int $scale, bool $nullable, bool $pk, String $fk)
  291. {
  292. $this->name = $name;
  293. $this->type = $type;
  294. $this->length = $length;
  295. $this->precision = $precision;
  296. $this->scale = $scale;
  297. $this->nullable = $nullable;
  298. $this->pk = $pk;
  299. $this->fk = $fk;
  300. $this->sanitize();
  301. }
  302. public static function fromReflection(GenericReflection $reflection, array $columnResult): ReflectedColumn
  303. {
  304. $name = $columnResult['COLUMN_NAME'];
  305. $length = (int) $columnResult['CHARACTER_MAXIMUM_LENGTH'];
  306. $type = $reflection->toJdbcType($columnResult['DATA_TYPE'], $length);
  307. $precision = (int) $columnResult['NUMERIC_PRECISION'];
  308. $scale = (int) $columnResult['NUMERIC_SCALE'];
  309. $nullable = in_array(strtoupper($columnResult['IS_NULLABLE']), ['TRUE', 'YES', 'T', 'Y', '1']);
  310. $pk = false;
  311. $fk = '';
  312. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  313. }
  314. public static function fromJson( /* object */$json): ReflectedColumn
  315. {
  316. $name = $json->name;
  317. $type = $json->type;
  318. $length = isset($json->length) ? $json->length : 0;
  319. $precision = isset($json->precision) ? $json->precision : 0;
  320. $scale = isset($json->scale) ? $json->scale : 0;
  321. $nullable = isset($json->nullable) ? $json->nullable : false;
  322. $pk = isset($json->pk) ? $json->pk : false;
  323. $fk = isset($json->fk) ? $json->fk : '';
  324. return new ReflectedColumn($name, $type, $length, $precision, $scale, $nullable, $pk, $fk);
  325. }
  326. private function sanitize()
  327. {
  328. $this->length = $this->hasLength() ? $this->getLength() : 0;
  329. $this->precision = $this->hasPrecision() ? $this->getPrecision() : 0;
  330. $this->scale = $this->hasScale() ? $this->getScale() : 0;
  331. }
  332. public function getName(): String
  333. {
  334. return $this->name;
  335. }
  336. public function getNullable(): bool
  337. {
  338. return $this->nullable;
  339. }
  340. public function getType(): String
  341. {
  342. return $this->type;
  343. }
  344. public function getLength(): int
  345. {
  346. return $this->length ?: self::DEFAULT_LENGTH;
  347. }
  348. public function getPrecision(): int
  349. {
  350. return $this->precision ?: self::DEFAULT_PRECISION;
  351. }
  352. public function getScale(): int
  353. {
  354. return $this->scale ?: self::DEFAULT_SCALE;
  355. }
  356. public function hasLength(): bool
  357. {
  358. return in_array($this->type, ['varchar', 'varbinary']);
  359. }
  360. public function hasPrecision(): bool
  361. {
  362. return $this->type == 'decimal';
  363. }
  364. public function hasScale(): bool
  365. {
  366. return $this->type == 'decimal';
  367. }
  368. public function isBinary(): bool
  369. {
  370. return in_array($this->type, ['blob', 'varbinary']);
  371. }
  372. public function isBoolean(): bool
  373. {
  374. return $this->type == 'boolean';
  375. }
  376. public function isGeometry(): bool
  377. {
  378. return $this->type == 'geometry';
  379. }
  380. public function setPk($value) /*: void*/
  381. {
  382. $this->pk = $value;
  383. }
  384. public function getPk(): bool
  385. {
  386. return $this->pk;
  387. }
  388. public function setFk($value) /*: void*/
  389. {
  390. $this->fk = $value;
  391. }
  392. public function getFk(): String
  393. {
  394. return $this->fk;
  395. }
  396. public function serialize()
  397. {
  398. return [
  399. 'name' => $this->name,
  400. 'type' => $this->type,
  401. 'length' => $this->length,
  402. 'precision' => $this->precision,
  403. 'scale' => $this->scale,
  404. 'nullable' => $this->nullable,
  405. 'pk' => $this->pk,
  406. 'fk' => $this->fk,
  407. ];
  408. }
  409. public function jsonSerialize()
  410. {
  411. return array_filter($this->serialize());
  412. }
  413. }
  414. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedDatabase.php
  415. class ReflectedDatabase implements \JsonSerializable
  416. {
  417. private $name;
  418. private $tableNames;
  419. public function __construct(String $name, array $tableNames)
  420. {
  421. $this->name = $name;
  422. $this->tableNames = [];
  423. foreach ($tableNames as $tableName) {
  424. $this->tableNames[$tableName] = true;
  425. }
  426. }
  427. public static function fromReflection(GenericReflection $reflection): ReflectedDatabase
  428. {
  429. $name = $reflection->getDatabaseName();
  430. $tableNames = [];
  431. foreach ($reflection->getTables() as $table) {
  432. $tableName = $table['TABLE_NAME'];
  433. if (in_array($tableName, $reflection->getIgnoredTables())) {
  434. continue;
  435. }
  436. $tableNames[$tableName] = true;
  437. }
  438. return new ReflectedDatabase($name, array_keys($tableNames));
  439. }
  440. public static function fromJson( /* object */$json): ReflectedDatabase
  441. {
  442. $name = $json->name;
  443. $tableNames = $json->tables;
  444. return new ReflectedDatabase($name, $tableNames);
  445. }
  446. public function getName(): String
  447. {
  448. return $this->name;
  449. }
  450. public function exists(String $tableName): bool
  451. {
  452. return isset($this->tableNames[$tableName]);
  453. }
  454. public function getTableNames(): array
  455. {
  456. return array_keys($this->tableNames);
  457. }
  458. public function removeTable(String $tableName): bool
  459. {
  460. if (!isset($this->tableNames[$tableName])) {
  461. return false;
  462. }
  463. unset($this->tableNames[$tableName]);
  464. return true;
  465. }
  466. public function serialize()
  467. {
  468. return [
  469. 'name' => $this->name,
  470. 'tables' => array_keys($this->tableNames),
  471. ];
  472. }
  473. public function jsonSerialize()
  474. {
  475. return $this->serialize();
  476. }
  477. }
  478. // file: src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php
  479. class ReflectedTable implements \JsonSerializable
  480. {
  481. private $name;
  482. private $columns;
  483. private $pk;
  484. private $fks;
  485. public function __construct(String $name, array $columns)
  486. {
  487. $this->name = $name;
  488. $this->columns = [];
  489. foreach ($columns as $column) {
  490. $columnName = $column->getName();
  491. $this->columns[$columnName] = $column;
  492. }
  493. $this->pk = null;
  494. foreach ($columns as $column) {
  495. if ($column->getPk() == true) {
  496. $this->pk = $column;
  497. }
  498. }
  499. $this->fks = [];
  500. foreach ($columns as $column) {
  501. $columnName = $column->getName();
  502. $referencedTableName = $column->getFk();
  503. if ($referencedTableName != '') {
  504. $this->fks[$columnName] = $referencedTableName;
  505. }
  506. }
  507. }
  508. public static function fromReflection(GenericReflection $reflection, String $name): ReflectedTable
  509. {
  510. $columns = [];
  511. foreach ($reflection->getTableColumns($name) as $tableColumn) {
  512. $column = ReflectedColumn::fromReflection($reflection, $tableColumn);
  513. $columns[$column->getName()] = $column;
  514. }
  515. $columnNames = $reflection->getTablePrimaryKeys($name);
  516. if (count($columnNames) == 1) {
  517. $columnName = $columnNames[0];
  518. if (isset($columns[$columnName])) {
  519. $pk = $columns[$columnName];
  520. $pk->setPk(true);
  521. }
  522. }
  523. $fks = $reflection->getTableForeignKeys($name);
  524. foreach ($fks as $columnName => $table) {
  525. $columns[$columnName]->setFk($table);
  526. }
  527. return new ReflectedTable($name, array_values($columns));
  528. }
  529. public static function fromJson( /* object */$json): ReflectedTable
  530. {
  531. $name = $json->name;
  532. $columns = [];
  533. if (isset($json->columns) && is_array($json->columns)) {
  534. foreach ($json->columns as $column) {
  535. $columns[] = ReflectedColumn::fromJson($column);
  536. }
  537. }
  538. return new ReflectedTable($name, $columns);
  539. }
  540. public function exists(String $columnName): bool
  541. {
  542. return isset($this->columns[$columnName]);
  543. }
  544. public function hasPk(): bool
  545. {
  546. return $this->pk != null;
  547. }
  548. public function getPk() /*: ?ReflectedColumn */
  549. {
  550. return $this->pk;
  551. }
  552. public function getName(): String
  553. {
  554. return $this->name;
  555. }
  556. public function columnNames(): array
  557. {
  558. return array_keys($this->columns);
  559. }
  560. public function get($columnName): ReflectedColumn
  561. {
  562. return $this->columns[$columnName];
  563. }
  564. public function getFksTo(String $tableName): array
  565. {
  566. $columns = array();
  567. foreach ($this->fks as $columnName => $referencedTableName) {
  568. if ($tableName == $referencedTableName) {
  569. $columns[] = $this->columns[$columnName];
  570. }
  571. }
  572. return $columns;
  573. }
  574. public function removeColumn(String $columnName): bool
  575. {
  576. if (!isset($this->columns[$columnName])) {
  577. return false;
  578. }
  579. unset($this->columns[$columnName]);
  580. return true;
  581. }
  582. public function serialize()
  583. {
  584. return [
  585. 'name' => $this->name,
  586. 'columns' => array_values($this->columns),
  587. ];
  588. }
  589. public function jsonSerialize()
  590. {
  591. return $this->serialize();
  592. }
  593. }
  594. // file: src/Tqdev/PhpCrudApi/Column/DefinitionService.php
  595. class DefinitionService
  596. {
  597. private $db;
  598. private $reflection;
  599. public function __construct(GenericDB $db, ReflectionService $reflection)
  600. {
  601. $this->db = $db;
  602. $this->reflection = $reflection;
  603. }
  604. public function updateTable(String $tableName, /* object */ $changes): bool
  605. {
  606. $table = $this->reflection->getTable($tableName);
  607. $newTable = ReflectedTable::fromJson((object) array_merge((array) $table->jsonSerialize(), (array) $changes));
  608. if ($table->getName() != $newTable->getName()) {
  609. if (!$this->db->definition()->renameTable($table->getName(), $newTable->getName())) {
  610. return false;
  611. }
  612. }
  613. return true;
  614. }
  615. public function updateColumn(String $tableName, String $columnName, /* object */ $changes): bool
  616. {
  617. $table = $this->reflection->getTable($tableName);
  618. $column = $table->get($columnName);
  619. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  620. if ($newColumn->getPk() != $column->getPk() && $table->hasPk()) {
  621. $oldColumn = $table->getPk();
  622. if ($oldColumn->getName() != $columnName) {
  623. $oldColumn->setPk(false);
  624. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $oldColumn->getName(), $oldColumn)) {
  625. return false;
  626. }
  627. }
  628. }
  629. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), ['pk' => false, 'fk' => false]));
  630. if ($newColumn->getPk() != $column->getPk() && !$newColumn->getPk()) {
  631. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $column->getName(), $newColumn)) {
  632. return false;
  633. }
  634. }
  635. if ($newColumn->getFk() != $column->getFk() && !$newColumn->getFk()) {
  636. if (!$this->db->definition()->removeColumnForeignKey($table->getName(), $column->getName(), $newColumn)) {
  637. return false;
  638. }
  639. }
  640. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  641. $newColumn->setPk(false);
  642. $newColumn->setFk('');
  643. if ($newColumn->getName() != $column->getName()) {
  644. if (!$this->db->definition()->renameColumn($table->getName(), $column->getName(), $newColumn)) {
  645. return false;
  646. }
  647. }
  648. if ($newColumn->getType() != $column->getType() ||
  649. $newColumn->getLength() != $column->getLength() ||
  650. $newColumn->getPrecision() != $column->getPrecision() ||
  651. $newColumn->getScale() != $column->getScale()
  652. ) {
  653. if (!$this->db->definition()->retypeColumn($table->getName(), $newColumn->getName(), $newColumn)) {
  654. return false;
  655. }
  656. }
  657. if ($newColumn->getNullable() != $column->getNullable()) {
  658. if (!$this->db->definition()->setColumnNullable($table->getName(), $newColumn->getName(), $newColumn)) {
  659. return false;
  660. }
  661. }
  662. $newColumn = ReflectedColumn::fromJson((object) array_merge((array) $column->jsonSerialize(), (array) $changes));
  663. if ($newColumn->getFk()) {
  664. if (!$this->db->definition()->addColumnForeignKey($table->getName(), $newColumn->getName(), $newColumn)) {
  665. return false;
  666. }
  667. }
  668. if ($newColumn->getPk()) {
  669. if (!$this->db->definition()->addColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  670. return false;
  671. }
  672. }
  673. return true;
  674. }
  675. public function addTable( /* object */$definition)
  676. {
  677. $newTable = ReflectedTable::fromJson($definition);
  678. if (!$this->db->definition()->addTable($newTable)) {
  679. return false;
  680. }
  681. return true;
  682. }
  683. public function addColumn(String $tableName, /* object */ $definition)
  684. {
  685. $newColumn = ReflectedColumn::fromJson($definition);
  686. if (!$this->db->definition()->addColumn($tableName, $newColumn)) {
  687. return false;
  688. }
  689. if ($newColumn->getFk()) {
  690. if (!$this->db->definition()->addColumnForeignKey($tableName, $newColumn->getName(), $newColumn)) {
  691. return false;
  692. }
  693. }
  694. if ($newColumn->getPk()) {
  695. if (!$this->db->definition()->addColumnPrimaryKey($tableName, $newColumn->getName(), $newColumn)) {
  696. return false;
  697. }
  698. }
  699. return true;
  700. }
  701. public function removeTable(String $tableName)
  702. {
  703. if (!$this->db->definition()->removeTable($tableName)) {
  704. return false;
  705. }
  706. return true;
  707. }
  708. public function removeColumn(String $tableName, String $columnName)
  709. {
  710. $table = $this->reflection->getTable($tableName);
  711. $newColumn = $table->get($columnName);
  712. if ($newColumn->getPk()) {
  713. $newColumn->setPk(false);
  714. if (!$this->db->definition()->removeColumnPrimaryKey($table->getName(), $newColumn->getName(), $newColumn)) {
  715. return false;
  716. }
  717. }
  718. if ($newColumn->getFk()) {
  719. $newColumn->setFk("");
  720. if (!$this->db->definition()->removeColumnForeignKey($tableName, $columnName, $newColumn)) {
  721. return false;
  722. }
  723. }
  724. if (!$this->db->definition()->removeColumn($tableName, $columnName)) {
  725. return false;
  726. }
  727. return true;
  728. }
  729. }
  730. // file: src/Tqdev/PhpCrudApi/Column/ReflectionService.php
  731. class ReflectionService
  732. {
  733. private $db;
  734. private $cache;
  735. private $ttl;
  736. private $database;
  737. private $tables;
  738. public function __construct(GenericDB $db, Cache $cache, int $ttl)
  739. {
  740. $this->db = $db;
  741. $this->cache = $cache;
  742. $this->ttl = $ttl;
  743. $this->database = $this->loadDatabase(true);
  744. $this->tables = [];
  745. }
  746. private function loadDatabase(bool $useCache): ReflectedDatabase
  747. {
  748. $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
  749. if ($data != '') {
  750. $database = ReflectedDatabase::fromJson(json_decode(gzuncompress($data)));
  751. } else {
  752. $database = ReflectedDatabase::fromReflection($this->db->reflection());
  753. $data = gzcompress(json_encode($database, JSON_UNESCAPED_UNICODE));
  754. $this->cache->set('ReflectedDatabase', $data, $this->ttl);
  755. }
  756. return $database;
  757. }
  758. private function loadTable(String $tableName, bool $useCache): ReflectedTable
  759. {
  760. $data = $useCache ? $this->cache->get("ReflectedTable($tableName)") : '';
  761. if ($data != '') {
  762. $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
  763. } else {
  764. $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName);
  765. $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
  766. $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
  767. }
  768. return $table;
  769. }
  770. public function refreshTables()
  771. {
  772. $this->database = $this->loadDatabase(false);
  773. }
  774. public function refreshTable(String $tableName)
  775. {
  776. $this->tables[$tableName] = $this->loadTable($tableName, false);
  777. }
  778. public function hasTable(String $tableName): bool
  779. {
  780. return $this->database->exists($tableName);
  781. }
  782. public function getTable(String $tableName): ReflectedTable
  783. {
  784. if (!isset($this->tables[$tableName])) {
  785. $this->tables[$tableName] = $this->loadTable($tableName, true);
  786. }
  787. return $this->tables[$tableName];
  788. }
  789. public function getTableNames(): array
  790. {
  791. return $this->database->getTableNames();
  792. }
  793. public function getDatabaseName(): String
  794. {
  795. return $this->database->getName();
  796. }
  797. public function removeTable(String $tableName): bool
  798. {
  799. unset($this->tables[$tableName]);
  800. return $this->database->removeTable($tableName);
  801. }
  802. public function removeColumn(String $tableName, String $columnName): bool
  803. {
  804. return $this->getTable($tableName)->removeColumn($columnName);
  805. }
  806. }
  807. // file: src/Tqdev/PhpCrudApi/Controller/CacheController.php
  808. class CacheController
  809. {
  810. private $cache;
  811. private $responder;
  812. public function __construct(Router $router, Responder $responder, Cache $cache)
  813. {
  814. $router->register('GET', '/cache/clear', array($this, 'clear'));
  815. $this->cache = $cache;
  816. $this->responder = $responder;
  817. }
  818. public function clear(Request $request): Response
  819. {
  820. return $this->responder->success($this->cache->clear());
  821. }
  822. }
  823. // file: src/Tqdev/PhpCrudApi/Controller/ColumnController.php
  824. class ColumnController
  825. {
  826. private $responder;
  827. private $reflection;
  828. private $definition;
  829. public function __construct(Router $router, Responder $responder, ReflectionService $reflection, DefinitionService $definition)
  830. {
  831. $router->register('GET', '/columns', array($this, 'getDatabase'));
  832. $router->register('GET', '/columns/*', array($this, 'getTable'));
  833. $router->register('GET', '/columns/*/*', array($this, 'getColumn'));
  834. $router->register('PUT', '/columns/*', array($this, 'updateTable'));
  835. $router->register('PUT', '/columns/*/*', array($this, 'updateColumn'));
  836. $router->register('POST', '/columns', array($this, 'addTable'));
  837. $router->register('POST', '/columns/*', array($this, 'addColumn'));
  838. $router->register('DELETE', '/columns/*', array($this, 'removeTable'));
  839. $router->register('DELETE', '/columns/*/*', array($this, 'removeColumn'));
  840. $this->responder = $responder;
  841. $this->reflection = $reflection;
  842. $this->definition = $definition;
  843. }
  844. public function getDatabase(Request $request): Response
  845. {
  846. $name = $this->reflection->getDatabaseName();
  847. $tables = [];
  848. foreach ($this->reflection->getTableNames() as $table) {
  849. $tables[] = $this->reflection->getTable($table);
  850. }
  851. $database = ['name' => $name, 'tables' => $tables];
  852. return $this->responder->success($database);
  853. }
  854. public function getTable(Request $request): Response
  855. {
  856. $tableName = $request->getPathSegment(2);
  857. if (!$this->reflection->hasTable($tableName)) {
  858. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  859. }
  860. $table = $this->reflection->getTable($tableName);
  861. return $this->responder->success($table);
  862. }
  863. public function getColumn(Request $request): Response
  864. {
  865. $tableName = $request->getPathSegment(2);
  866. $columnName = $request->getPathSegment(3);
  867. if (!$this->reflection->hasTable($tableName)) {
  868. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  869. }
  870. $table = $this->reflection->getTable($tableName);
  871. if (!$table->exists($columnName)) {
  872. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  873. }
  874. $column = $table->get($columnName);
  875. return $this->responder->success($column);
  876. }
  877. public function updateTable(Request $request): Response
  878. {
  879. $tableName = $request->getPathSegment(2);
  880. if (!$this->reflection->hasTable($tableName)) {
  881. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  882. }
  883. $success = $this->definition->updateTable($tableName, $request->getBody());
  884. if ($success) {
  885. $this->reflection->refreshTables();
  886. }
  887. return $this->responder->success($success);
  888. }
  889. public function updateColumn(Request $request): Response
  890. {
  891. $tableName = $request->getPathSegment(2);
  892. $columnName = $request->getPathSegment(3);
  893. if (!$this->reflection->hasTable($tableName)) {
  894. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  895. }
  896. $table = $this->reflection->getTable($tableName);
  897. if (!$table->exists($columnName)) {
  898. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  899. }
  900. $success = $this->definition->updateColumn($tableName, $columnName, $request->getBody());
  901. if ($success) {
  902. $this->reflection->refreshTable($tableName);
  903. }
  904. return $this->responder->success($success);
  905. }
  906. public function addTable(Request $request): Response
  907. {
  908. $tableName = $request->getBody()->name;
  909. if ($this->reflection->hasTable($tableName)) {
  910. return $this->responder->error(ErrorCode::TABLE_ALREADY_EXISTS, $tableName);
  911. }
  912. $success = $this->definition->addTable($request->getBody());
  913. if ($success) {
  914. $this->reflection->refreshTables();
  915. }
  916. return $this->responder->success($success);
  917. }
  918. public function addColumn(Request $request): Response
  919. {
  920. $tableName = $request->getPathSegment(2);
  921. if (!$this->reflection->hasTable($tableName)) {
  922. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  923. }
  924. $columnName = $request->getBody()->name;
  925. $table = $this->reflection->getTable($tableName);
  926. if ($table->exists($columnName)) {
  927. return $this->responder->error(ErrorCode::COLUMN_ALREADY_EXISTS, $columnName);
  928. }
  929. $success = $this->definition->addColumn($tableName, $request->getBody());
  930. if ($success) {
  931. $this->reflection->refreshTable($tableName);
  932. }
  933. return $this->responder->success($success);
  934. }
  935. public function removeTable(Request $request): Response
  936. {
  937. $tableName = $request->getPathSegment(2);
  938. if (!$this->reflection->hasTable($tableName)) {
  939. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  940. }
  941. $success = $this->definition->removeTable($tableName);
  942. if ($success) {
  943. $this->reflection->refreshTables();
  944. }
  945. return $this->responder->success($success);
  946. }
  947. public function removeColumn(Request $request): Response
  948. {
  949. $tableName = $request->getPathSegment(2);
  950. $columnName = $request->getPathSegment(3);
  951. if (!$this->reflection->hasTable($tableName)) {
  952. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $tableName);
  953. }
  954. $table = $this->reflection->getTable($tableName);
  955. if (!$table->exists($columnName)) {
  956. return $this->responder->error(ErrorCode::COLUMN_NOT_FOUND, $columnName);
  957. }
  958. $success = $this->definition->removeColumn($tableName, $columnName);
  959. if ($success) {
  960. $this->reflection->refreshTable($tableName);
  961. }
  962. return $this->responder->success($success);
  963. }
  964. }
  965. // file: src/Tqdev/PhpCrudApi/Controller/OpenApiController.php
  966. class OpenApiController
  967. {
  968. private $openApi;
  969. private $responder;
  970. public function __construct(Router $router, Responder $responder, OpenApiService $openApi)
  971. {
  972. $router->register('GET', '/openapi', array($this, 'openapi'));
  973. $this->openApi = $openApi;
  974. $this->responder = $responder;
  975. }
  976. public function openapi(Request $request): Response
  977. {
  978. return $this->responder->success($this->openApi->get());
  979. }
  980. }
  981. // file: src/Tqdev/PhpCrudApi/Controller/RecordController.php
  982. class RecordController
  983. {
  984. private $service;
  985. private $responder;
  986. public function __construct(Router $router, Responder $responder, RecordService $service)
  987. {
  988. $router->register('GET', '/records/*', array($this, '_list'));
  989. $router->register('POST', '/records/*', array($this, 'create'));
  990. $router->register('GET', '/records/*/*', array($this, 'read'));
  991. $router->register('PUT', '/records/*/*', array($this, 'update'));
  992. $router->register('DELETE', '/records/*/*', array($this, 'delete'));
  993. $router->register('PATCH', '/records/*/*', array($this, 'increment'));
  994. $this->service = $service;
  995. $this->responder = $responder;
  996. }
  997. public function _list(Request $request): Response
  998. {
  999. $table = $request->getPathSegment(2);
  1000. $params = $request->getParams();
  1001. if (!$this->service->exists($table)) {
  1002. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1003. }
  1004. return $this->responder->success($this->service->_list($table, $params));
  1005. }
  1006. public function read(Request $request): Response
  1007. {
  1008. $table = $request->getPathSegment(2);
  1009. $id = $request->getPathSegment(3);
  1010. $params = $request->getParams();
  1011. if (!$this->service->exists($table)) {
  1012. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1013. }
  1014. if (strpos($id, ',') !== false) {
  1015. $ids = explode(',', $id);
  1016. $result = [];
  1017. for ($i = 0; $i < count($ids); $i++) {
  1018. array_push($result, $this->service->read($table, $ids[$i], $params));
  1019. }
  1020. return $this->responder->success($result);
  1021. } else {
  1022. $response = $this->service->read($table, $id, $params);
  1023. if ($response === null) {
  1024. return $this->responder->error(ErrorCode::RECORD_NOT_FOUND, $id);
  1025. }
  1026. return $this->responder->success($response);
  1027. }
  1028. }
  1029. public function create(Request $request): Response
  1030. {
  1031. $table = $request->getPathSegment(2);
  1032. $record = $request->getBody();
  1033. if ($record === null) {
  1034. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  1035. }
  1036. $params = $request->getParams();
  1037. if (!$this->service->exists($table)) {
  1038. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1039. }
  1040. if (is_array($record)) {
  1041. $result = array();
  1042. foreach ($record as $r) {
  1043. $result[] = $this->service->create($table, $r, $params);
  1044. }
  1045. return $this->responder->success($result);
  1046. } else {
  1047. return $this->responder->success($this->service->create($table, $record, $params));
  1048. }
  1049. }
  1050. public function update(Request $request): Response
  1051. {
  1052. $table = $request->getPathSegment(2);
  1053. $id = $request->getPathSegment(3);
  1054. $record = $request->getBody();
  1055. if ($record === null) {
  1056. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  1057. }
  1058. $params = $request->getParams();
  1059. if (!$this->service->exists($table)) {
  1060. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1061. }
  1062. $ids = explode(',', $id);
  1063. if (is_array($record)) {
  1064. if (count($ids) != count($record)) {
  1065. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1066. }
  1067. $result = array();
  1068. for ($i = 0; $i < count($ids); $i++) {
  1069. $result[] = $this->service->update($table, $ids[$i], $record[$i], $params);
  1070. }
  1071. return $this->responder->success($result);
  1072. } else {
  1073. if (count($ids) != 1) {
  1074. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1075. }
  1076. return $this->responder->success($this->service->update($table, $id, $record, $params));
  1077. }
  1078. }
  1079. public function delete(Request $request): Response
  1080. {
  1081. $table = $request->getPathSegment(2);
  1082. $id = $request->getPathSegment(3);
  1083. $params = $request->getParams();
  1084. if (!$this->service->exists($table)) {
  1085. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1086. }
  1087. $ids = explode(',', $id);
  1088. if (count($ids) > 1) {
  1089. $result = array();
  1090. for ($i = 0; $i < count($ids); $i++) {
  1091. $result[] = $this->service->delete($table, $ids[$i], $params);
  1092. }
  1093. return $this->responder->success($result);
  1094. } else {
  1095. return $this->responder->success($this->service->delete($table, $id, $params));
  1096. }
  1097. }
  1098. public function increment(Request $request): Response
  1099. {
  1100. $table = $request->getPathSegment(2);
  1101. $id = $request->getPathSegment(3);
  1102. $record = $request->getBody();
  1103. if ($record === null) {
  1104. return $this->responder->error(ErrorCode::HTTP_MESSAGE_NOT_READABLE, '');
  1105. }
  1106. $params = $request->getParams();
  1107. if (!$this->service->exists($table)) {
  1108. return $this->responder->error(ErrorCode::TABLE_NOT_FOUND, $table);
  1109. }
  1110. $ids = explode(',', $id);
  1111. if (is_array($record)) {
  1112. if (count($ids) != count($record)) {
  1113. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1114. }
  1115. $result = array();
  1116. for ($i = 0; $i < count($ids); $i++) {
  1117. $result[] = $this->service->increment($table, $ids[$i], $record[$i], $params);
  1118. }
  1119. return $this->responder->success($result);
  1120. } else {
  1121. if (count($ids) != 1) {
  1122. return $this->responder->error(ErrorCode::ARGUMENT_COUNT_MISMATCH, $id);
  1123. }
  1124. return $this->responder->success($this->service->increment($table, $id, $record, $params));
  1125. }
  1126. }
  1127. }
  1128. // file: src/Tqdev/PhpCrudApi/Controller/Responder.php
  1129. class Responder
  1130. {
  1131. public function error(int $error, String $argument, $details = null): Response
  1132. {
  1133. $errorCode = new ErrorCode($error);
  1134. $status = $errorCode->getStatus();
  1135. $document = new ErrorDocument($errorCode, $argument, $details);
  1136. return new Response($status, $document);
  1137. }
  1138. public function success($result): Response
  1139. {
  1140. return new Response(Response::OK, $result);
  1141. }
  1142. }
  1143. // file: src/Tqdev/PhpCrudApi/Database/ColumnConverter.php
  1144. class ColumnConverter
  1145. {
  1146. private $driver;
  1147. public function __construct(String $driver)
  1148. {
  1149. $this->driver = $driver;
  1150. }
  1151. public function convertColumnValue(ReflectedColumn $column): String
  1152. {
  1153. if ($column->isBinary()) {
  1154. switch ($this->driver) {
  1155. case 'mysql':
  1156. return "FROM_BASE64(?)";
  1157. case 'pgsql':
  1158. return "decode(?, 'base64')";
  1159. case 'sqlsrv':
  1160. return "CONVERT(XML, ?).value('.','varbinary(max)')";
  1161. }
  1162. }
  1163. if ($column->isGeometry()) {
  1164. switch ($this->driver) {
  1165. case 'mysql':
  1166. case 'pgsql':
  1167. return "ST_GeomFromText(?)";
  1168. case 'sqlsrv':
  1169. return "geometry::STGeomFromText(?,0)";
  1170. }
  1171. }
  1172. return '?';
  1173. }
  1174. public function convertColumnName(ReflectedColumn $column, $value): String
  1175. {
  1176. if ($column->isBinary()) {
  1177. switch ($this->driver) {
  1178. case 'mysql':
  1179. return "TO_BASE64($value) as $value";
  1180. case 'pgsql':
  1181. return "encode($value::bytea, 'base64') as $value";
  1182. case 'sqlsrv':
  1183. return "CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column($value)))', 'VARCHAR(MAX)') as $value";
  1184. }
  1185. }
  1186. if ($column->isGeometry()) {
  1187. switch ($this->driver) {
  1188. case 'mysql':
  1189. case 'pgsql':
  1190. return "ST_AsText($value) as $value";
  1191. case 'sqlsrv':
  1192. return "REPLACE($value.STAsText(),' (','(') as $value";
  1193. }
  1194. }
  1195. return $value;
  1196. }
  1197. }
  1198. // file: src/Tqdev/PhpCrudApi/Database/ColumnsBuilder.php
  1199. class ColumnsBuilder
  1200. {
  1201. private $driver;
  1202. private $converter;
  1203. public function __construct(String $driver)
  1204. {
  1205. $this->driver = $driver;
  1206. $this->converter = new ColumnConverter($driver);
  1207. }
  1208. public function getOffsetLimit(int $offset, int $limit): String
  1209. {
  1210. if ($limit < 0 || $offset < 0) {
  1211. return '';
  1212. }
  1213. switch ($this->driver) {
  1214. case 'mysql':return "LIMIT $offset, $limit";
  1215. case 'pgsql':return "LIMIT $limit OFFSET $offset";
  1216. case 'sqlsrv':return "OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  1217. }
  1218. }
  1219. private function quoteColumnName(ReflectedColumn $column): String
  1220. {
  1221. return '"' . $column->getName() . '"';
  1222. }
  1223. public function getOrderBy(ReflectedTable $table, array $columnOrdering): String
  1224. {
  1225. $results = array();
  1226. foreach ($columnOrdering as $i => list($columnName, $ordering)) {
  1227. $column = $table->get($columnName);
  1228. $quotedColumnName = $this->quoteColumnName($column);
  1229. $results[] = $quotedColumnName . ' ' . $ordering;
  1230. }
  1231. return implode(',', $results);
  1232. }
  1233. public function getSelect(ReflectedTable $table, array $columnNames): String
  1234. {
  1235. $results = array();
  1236. foreach ($columnNames as $columnName) {
  1237. $column = $table->get($columnName);
  1238. $quotedColumnName = $this->quoteColumnName($column);
  1239. $quotedColumnName = $this->converter->convertColumnName($column, $quotedColumnName);
  1240. $results[] = $quotedColumnName;
  1241. }
  1242. return implode(',', $results);
  1243. }
  1244. public function getInsert(ReflectedTable $table, array $columnValues): String
  1245. {
  1246. $columns = array();
  1247. $values = array();
  1248. foreach ($columnValues as $columnName => $columnValue) {
  1249. $column = $table->get($columnName);
  1250. $quotedColumnName = $this->quoteColumnName($column);
  1251. $columns[] = $quotedColumnName;
  1252. $columnValue = $this->converter->convertColumnValue($column);
  1253. $values[] = $columnValue;
  1254. }
  1255. $columnsSql = '(' . implode(',', $columns) . ')';
  1256. $valuesSql = '(' . implode(',', $values) . ')';
  1257. $outputColumn = $this->quoteColumnName($table->getPk());
  1258. switch ($this->driver) {
  1259. case 'mysql':return "$columnsSql VALUES $valuesSql";
  1260. case 'pgsql':return "$columnsSql VALUES $valuesSql RETURNING $outputColumn";
  1261. case 'sqlsrv':return "$columnsSql OUTPUT INSERTED.$outputColumn VALUES $valuesSql";
  1262. }
  1263. }
  1264. public function getUpdate(ReflectedTable $table, array $columnValues): String
  1265. {
  1266. $results = array();
  1267. foreach ($columnValues as $columnName => $columnValue) {
  1268. $column = $table->get($columnName);
  1269. $quotedColumnName = $this->quoteColumnName($column);
  1270. $columnValue = $this->converter->convertColumnValue($column);
  1271. $results[] = $quotedColumnName . '=' . $columnValue;
  1272. }
  1273. return implode(',', $results);
  1274. }
  1275. public function getIncrement(ReflectedTable $table, array $columnValues): String
  1276. {
  1277. $results = array();
  1278. foreach ($columnValues as $columnName => $columnValue) {
  1279. if (!is_numeric($columnValue)) {
  1280. continue;
  1281. }
  1282. $column = $table->get($columnName);
  1283. $quotedColumnName = $this->quoteColumnName($column);
  1284. $columnValue = $this->converter->convertColumnValue($column);
  1285. $results[] = $quotedColumnName . '=' . $quotedColumnName . '+' . $columnValue;
  1286. }
  1287. return implode(',', $results);
  1288. }
  1289. }
  1290. // file: src/Tqdev/PhpCrudApi/Database/ConditionsBuilder.php
  1291. class ConditionsBuilder
  1292. {
  1293. private $driver;
  1294. public function __construct(String $driver)
  1295. {
  1296. $this->driver = $driver;
  1297. }
  1298. private function getConditionSql(Condition $condition, array &$arguments): String
  1299. {
  1300. if ($condition instanceof AndCondition) {
  1301. return $this->getAndConditionSql($condition, $arguments);
  1302. }
  1303. if ($condition instanceof OrCondition) {
  1304. return $this->getOrConditionSql($condition, $arguments);
  1305. }
  1306. if ($condition instanceof NotCondition) {
  1307. return $this->getNotConditionSql($condition, $arguments);
  1308. }
  1309. if ($condition instanceof ColumnCondition) {
  1310. return $this->getColumnConditionSql($condition, $arguments);
  1311. }
  1312. if ($condition instanceof SpatialCondition) {
  1313. return $this->getSpatialConditionSql($condition, $arguments);
  1314. }
  1315. throw new \Exception('Unknown Condition: ' . get_class($condition));
  1316. }
  1317. private function getAndConditionSql(AndCondition $and, array &$arguments): String
  1318. {
  1319. $parts = [];
  1320. foreach ($and->getConditions() as $condition) {
  1321. $parts[] = $this->getConditionSql($condition, $arguments);
  1322. }
  1323. return '(' . implode(' AND ', $parts) . ')';
  1324. }
  1325. private function getOrConditionSql(OrCondition $or, array &$arguments): String
  1326. {
  1327. $parts = [];
  1328. foreach ($or->getConditions() as $condition) {
  1329. $parts[] = $this->getConditionSql($condition, $arguments);
  1330. }
  1331. return '(' . implode(' OR ', $parts) . ')';
  1332. }
  1333. private function getNotConditionSql(NotCondition $not, array &$arguments): String
  1334. {
  1335. $condition = $not->getCondition();
  1336. return '(NOT ' . $this->getConditionSql($condition, $arguments) . ')';
  1337. }
  1338. private function quoteColumnName(ReflectedColumn $column): String
  1339. {
  1340. return '"' . $column->getName() . '"';
  1341. }
  1342. private function escapeLikeValue(String $value): String
  1343. {
  1344. return addcslashes($value, '%_');
  1345. }
  1346. private function getColumnConditionSql(ColumnCondition $condition, array &$arguments): String
  1347. {
  1348. $column = $this->quoteColumnName($condition->getColumn());
  1349. $operator = $condition->getOperator();
  1350. $value = $condition->getValue();
  1351. switch ($operator) {
  1352. case 'cs':
  1353. $sql = "$column LIKE ?";
  1354. $arguments[] = '%' . $this->escapeLikeValue($value) . '%';
  1355. break;
  1356. case 'sw':
  1357. $sql = "$column LIKE ?";
  1358. $arguments[] = $this->escapeLikeValue($value) . '%';
  1359. break;
  1360. case 'ew':
  1361. $sql = "$column LIKE ?";
  1362. $arguments[] = '%' . $this->escapeLikeValue($value);
  1363. break;
  1364. case 'eq':
  1365. $sql = "$column = ?";
  1366. $arguments[] = $value;
  1367. break;
  1368. case 'lt':
  1369. $sql = "$column < ?";
  1370. $arguments[] = $value;
  1371. break;
  1372. case 'le':
  1373. $sql = "$column <= ?";
  1374. $arguments[] = $value;
  1375. break;
  1376. case 'ge':
  1377. $sql = "$column >= ?";
  1378. $arguments[] = $value;
  1379. break;
  1380. case 'gt':
  1381. $sql = "$column > ?";
  1382. $arguments[] = $value;
  1383. break;
  1384. case 'bt':
  1385. $parts = explode(',', $value, 2);
  1386. $count = count($parts);
  1387. if ($count == 2) {
  1388. $sql = "($column >= ? AND $column <= ?)";
  1389. $arguments[] = $parts[0];
  1390. $arguments[] = $parts[1];
  1391. } else {
  1392. $sql = "FALSE";
  1393. }
  1394. break;
  1395. case 'in':
  1396. $parts = explode(',', $value);
  1397. $count = count($parts);
  1398. if ($count > 0) {
  1399. $qmarks = implode(',', str_split(str_repeat('?', $count)));
  1400. $sql = "$column IN ($qmarks)";
  1401. for ($i = 0; $i < $count; $i++) {
  1402. $arguments[] = $parts[$i];
  1403. }
  1404. } else {
  1405. $sql = "FALSE";
  1406. }
  1407. break;
  1408. case 'is':
  1409. $sql = "$column IS NULL";
  1410. break;
  1411. }
  1412. return $sql;
  1413. }
  1414. private function getSpatialFunctionName(String $operator): String
  1415. {
  1416. switch ($operator) {
  1417. case 'co':return 'ST_Contains';
  1418. case 'cr':return 'ST_Crosses';
  1419. case 'di':return 'ST_Disjoint';
  1420. case 'eq':return 'ST_Equals';
  1421. case 'in':return 'ST_Intersects';
  1422. case 'ov':return 'ST_Overlaps';
  1423. case 'to':return 'ST_Touches';
  1424. case 'wi':return 'ST_Within';
  1425. case 'ic':return 'ST_IsClosed';
  1426. case 'is':return 'ST_IsSimple';
  1427. case 'iv':return 'ST_IsValid';
  1428. }
  1429. }
  1430. private function hasSpatialArgument(String $operator): bool
  1431. {
  1432. return in_array($operator, ['ic', 'is', 'iv']) ? false : true;
  1433. }
  1434. private function getSpatialFunctionCall(String $functionName, String $column, bool $hasArgument): String
  1435. {
  1436. switch ($this->driver) {
  1437. case 'mysql':
  1438. case 'pgsql':
  1439. $argument = $hasArgument ? 'ST_GeomFromText(?)' : '';
  1440. return "$functionName($column, $argument)=TRUE";
  1441. case 'sql_srv':
  1442. $functionName = str_replace('ST_', 'ST', $functionName);
  1443. $argument = $hasArgument ? 'geometry::STGeomFromText(?,0)' : '';
  1444. return "$column.$functionName($argument)=1";
  1445. }
  1446. }
  1447. private function getSpatialConditionSql(ColumnCondition $condition, array &$arguments): String
  1448. {
  1449. $column = $this->quoteColumnName($condition->getColumn());
  1450. $operator = $condition->getOperator();
  1451. $value = $condition->getValue();
  1452. $functionName = $this->getSpatialFunctionName($operator);
  1453. $hasArgument = $this->hasSpatialArgument($operator);
  1454. $sql = $this->getSpatialFunctionCall($functionName, $column, $hasArgument);
  1455. if ($hasArgument) {
  1456. $arguments[] = $value;
  1457. }
  1458. return $sql;
  1459. }
  1460. public function getWhereClause(Condition $condition, array &$arguments): String
  1461. {
  1462. if ($condition instanceof NoCondition) {
  1463. return '';
  1464. }
  1465. return ' WHERE ' . $this->getConditionSql($condition, $arguments);
  1466. }
  1467. }
  1468. // file: src/Tqdev/PhpCrudApi/Database/DataConverter.php
  1469. class DataConverter
  1470. {
  1471. private $driver;
  1472. public function __construct(String $driver)
  1473. {
  1474. $this->driver = $driver;
  1475. }
  1476. private function convertRecordValue($conversion, $value)
  1477. {
  1478. switch ($conversion) {
  1479. case 'boolean':
  1480. return $value ? true : false;
  1481. }
  1482. return $value;
  1483. }
  1484. private function getRecordValueConversion(ReflectedColumn $column): String
  1485. {
  1486. if (in_array($this->driver, ['mysql', 'sqlsrv']) && $column->isBoolean()) {
  1487. return 'boolean';
  1488. }
  1489. return 'none';
  1490. }
  1491. public function convertRecords(ReflectedTable $table, array $columnNames, array &$records) /*: void*/
  1492. {
  1493. foreach ($columnNames as $columnName) {
  1494. $column = $table->get($columnName);
  1495. $conversion = $this->getRecordValueConversion($column);
  1496. if ($conversion != 'none') {
  1497. foreach ($records as $i => $record) {
  1498. $value = $records[$i][$columnName];
  1499. if ($value === null) {
  1500. continue;
  1501. }
  1502. $records[$i][$columnName] = $this->convertRecordValue($conversion, $value);
  1503. }
  1504. }
  1505. }
  1506. }
  1507. private function convertInputValue($conversion, $value)
  1508. {
  1509. switch ($conversion) {
  1510. case 'base64url_to_base64':
  1511. return str_pad(strtr($value, '-_', '+/'), ceil(strlen($value) / 4) * 4, '=', STR_PAD_RIGHT);
  1512. }
  1513. return $value;
  1514. }
  1515. private function getInputValueConversion(ReflectedColumn $column): String
  1516. {
  1517. if ($column->isBinary()) {
  1518. return 'base64url_to_base64';
  1519. }
  1520. return 'none';
  1521. }
  1522. public function convertColumnValues(ReflectedTable $table, array &$columnValues) /*: void*/
  1523. {
  1524. $columnNames = array_keys($columnValues);
  1525. foreach ($columnNames as $columnName) {
  1526. $column = $table->get($columnName);
  1527. $conversion = $this->getInputValueConversion($column);
  1528. if ($conversion != 'none') {
  1529. $value = $columnValues[$columnName];
  1530. if ($value !== null) {
  1531. $columnValues[$columnName] = $this->convertInputValue($conversion, $value);
  1532. }
  1533. }
  1534. }
  1535. }
  1536. }
  1537. // file: src/Tqdev/PhpCrudApi/Database/GenericDB.php
  1538. class GenericDB
  1539. {
  1540. private $driver;
  1541. private $database;
  1542. private $pdo;
  1543. private $reflection;
  1544. private $definition;
  1545. private $conditions;
  1546. private $columns;
  1547. private $converter;
  1548. private function getDsn(String $address, String $port = null, String $database = null): String
  1549. {
  1550. switch ($this->driver) {
  1551. case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
  1552. case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
  1553. case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
  1554. }
  1555. }
  1556. private function getCommands(): array
  1557. {
  1558. switch ($this->driver) {
  1559. case 'mysql':return [
  1560. 'SET SESSION sql_warnings=1;',
  1561. 'SET NAMES utf8mb4;',
  1562. 'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
  1563. ];
  1564. case 'pgsql':return [
  1565. "SET NAMES 'UTF8';",
  1566. ];
  1567. case 'sqlsrv':return [
  1568. ];
  1569. }
  1570. }
  1571. private function getOptions(): array
  1572. {
  1573. $options = array(
  1574. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  1575. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  1576. );
  1577. switch ($this->driver) {
  1578. case 'mysql':return $options + [
  1579. \PDO::ATTR_EMULATE_PREPARES => false,
  1580. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  1581. \PDO::ATTR_PERSISTENT => true,
  1582. ];
  1583. case 'pgsql':return $options + [
  1584. \PDO::ATTR_EMULATE_PREPARES => false,
  1585. \PDO::ATTR_PERSISTENT => true,
  1586. ];
  1587. case 'sqlsrv':return $options + [
  1588. \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
  1589. ];
  1590. }
  1591. }
  1592. public function __construct(String $driver, String $address, String $port = null, String $database = null, String $username = null, String $password = null)
  1593. {
  1594. $this->driver = $driver;
  1595. $this->database = $database;
  1596. $dsn = $this->getDsn($address, $port, $database);
  1597. $options = $this->getOptions();
  1598. $this->pdo = new \PDO($dsn, $username, $password, $options);
  1599. $commands = $this->getCommands();
  1600. foreach ($commands as $command) {
  1601. $this->pdo->query($command);
  1602. }
  1603. $this->reflection = new GenericReflection($this->pdo, $driver, $database);
  1604. $this->definition = new GenericDefinition($this->pdo, $driver, $database);
  1605. $this->conditions = new ConditionsBuilder($driver);
  1606. $this->columns = new ColumnsBuilder($driver);
  1607. $this->converter = new DataConverter($driver);
  1608. }
  1609. public function pdo(): \PDO
  1610. {
  1611. return $this->pdo;
  1612. }
  1613. public function reflection(): GenericReflection
  1614. {
  1615. return $this->reflection;
  1616. }
  1617. public function definition(): GenericDefinition
  1618. {
  1619. return $this->definition;
  1620. }
  1621. private function addAuthorizationCondition(String $tableName, Condition $condition2): Condition
  1622. {
  1623. $condition1 = VariableStore::get("authorization.conditions.$tableName");
  1624. return $condition1 ? AndCondition::fromArray([$condition1, $condition2]) : $condition2;
  1625. }
  1626. public function createSingle(ReflectedTable $table, array $columnValues) /*: ?String*/
  1627. {
  1628. $this->converter->convertColumnValues($table, $columnValues);
  1629. $insertColumns = $this->columns->getInsert($table, $columnValues);
  1630. $tableName = $table->getName();
  1631. $pkName = $table->getPk()->getName();
  1632. $parameters = array_values($columnValues);
  1633. $sql = 'INSERT INTO "' . $tableName . '" ' . $insertColumns;
  1634. $stmt = $this->query($sql, $parameters);
  1635. if (isset($columnValues[$pkName])) {
  1636. return $columnValues[$pkName];
  1637. }
  1638. switch ($this->driver) {
  1639. case 'mysql':
  1640. $stmt = $this->query('SELECT LAST_INSERT_ID()', []);
  1641. break;
  1642. }
  1643. return $stmt->fetchColumn(0);
  1644. }
  1645. public function selectSingle(ReflectedTable $table, array $columnNames, String $id) /*: ?array*/
  1646. {
  1647. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1648. $tableName = $table->getName();
  1649. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1650. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1651. $parameters = array();
  1652. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1653. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  1654. $stmt = $this->query($sql, $parameters);
  1655. $record = $stmt->fetch() ?: null;
  1656. if ($record === null) {
  1657. return null;
  1658. }
  1659. $records = array($record);
  1660. $this->converter->convertRecords($table, $columnNames, $records);
  1661. return $records[0];
  1662. }
  1663. public function selectMultiple(ReflectedTable $table, array $columnNames, array $ids): array
  1664. {
  1665. if (count($ids) == 0) {
  1666. return [];
  1667. }
  1668. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1669. $tableName = $table->getName();
  1670. $condition = new ColumnCondition($table->getPk(), 'in', implode(',', $ids));
  1671. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1672. $parameters = array();
  1673. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1674. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '" ' . $whereClause;
  1675. $stmt = $this->query($sql, $parameters);
  1676. $records = $stmt->fetchAll();
  1677. $this->converter->convertRecords($table, $columnNames, $records);
  1678. return $records;
  1679. }
  1680. public function selectCount(ReflectedTable $table, Condition $condition): int
  1681. {
  1682. $tableName = $table->getName();
  1683. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1684. $parameters = array();
  1685. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1686. $sql = 'SELECT COUNT(*) FROM "' . $tableName . '"' . $whereClause;
  1687. $stmt = $this->query($sql, $parameters);
  1688. return $stmt->fetchColumn(0);
  1689. }
  1690. public function selectAllUnordered(ReflectedTable $table, array $columnNames, Condition $condition): array
  1691. {
  1692. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1693. $tableName = $table->getName();
  1694. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1695. $parameters = array();
  1696. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1697. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause;
  1698. $stmt = $this->query($sql, $parameters);
  1699. $records = $stmt->fetchAll();
  1700. $this->converter->convertRecords($table, $columnNames, $records);
  1701. return $records;
  1702. }
  1703. public function selectAll(ReflectedTable $table, array $columnNames, Condition $condition, array $columnOrdering, int $offset, int $limit): array
  1704. {
  1705. if ($limit == 0) {
  1706. return array();
  1707. }
  1708. $selectColumns = $this->columns->getSelect($table, $columnNames);
  1709. $tableName = $table->getName();
  1710. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1711. $parameters = array();
  1712. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1713. $orderBy = $this->columns->getOrderBy($table, $columnOrdering);
  1714. $offsetLimit = $this->columns->getOffsetLimit($offset, $limit);
  1715. $sql = 'SELECT ' . $selectColumns . ' FROM "' . $tableName . '"' . $whereClause . ' ORDER BY ' . $orderBy . ' ' . $offsetLimit;
  1716. $stmt = $this->query($sql, $parameters);
  1717. $records = $stmt->fetchAll();
  1718. $this->converter->convertRecords($table, $columnNames, $records);
  1719. return $records;
  1720. }
  1721. public function updateSingle(ReflectedTable $table, array $columnValues, String $id)
  1722. {
  1723. if (count($columnValues) == 0) {
  1724. return 0;
  1725. }
  1726. $this->converter->convertColumnValues($table, $columnValues);
  1727. $updateColumns = $this->columns->getUpdate($table, $columnValues);
  1728. $tableName = $table->getName();
  1729. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1730. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1731. $parameters = array_values($columnValues);
  1732. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1733. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  1734. $stmt = $this->query($sql, $parameters);
  1735. return $stmt->rowCount();
  1736. }
  1737. public function deleteSingle(ReflectedTable $table, String $id)
  1738. {
  1739. $tableName = $table->getName();
  1740. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1741. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1742. $parameters = array();
  1743. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1744. $sql = 'DELETE FROM "' . $tableName . '" ' . $whereClause;
  1745. $stmt = $this->query($sql, $parameters);
  1746. return $stmt->rowCount();
  1747. }
  1748. public function incrementSingle(ReflectedTable $table, array $columnValues, String $id)
  1749. {
  1750. if (count($columnValues) == 0) {
  1751. return 0;
  1752. }
  1753. $this->converter->convertColumnValues($table, $columnValues);
  1754. $updateColumns = $this->columns->getIncrement($table, $columnValues);
  1755. $tableName = $table->getName();
  1756. $condition = new ColumnCondition($table->getPk(), 'eq', $id);
  1757. $condition = $this->addAuthorizationCondition($tableName, $condition);
  1758. $parameters = array_values($columnValues);
  1759. $whereClause = $this->conditions->getWhereClause($condition, $parameters);
  1760. $sql = 'UPDATE "' . $tableName . '" SET ' . $updateColumns . $whereClause;
  1761. $stmt = $this->query($sql, $parameters);
  1762. return $stmt->rowCount();
  1763. }
  1764. private function query(String $sql, array $parameters): \PDOStatement
  1765. {
  1766. $stmt = $this->pdo->prepare($sql);
  1767. $stmt->execute($parameters);
  1768. return $stmt;
  1769. }
  1770. }
  1771. // file: src/Tqdev/PhpCrudApi/Database/GenericDefinition.php
  1772. class GenericDefinition
  1773. {
  1774. private $pdo;
  1775. private $driver;
  1776. private $database;
  1777. private $typeConverter;
  1778. private $reflection;
  1779. public function __construct(\PDO $pdo, String $driver, String $database)
  1780. {
  1781. $this->pdo = $pdo;
  1782. $this->driver = $driver;
  1783. $this->database = $database;
  1784. $this->typeConverter = new TypeConverter($driver);
  1785. $this->reflection = new GenericReflection($pdo, $driver, $database);
  1786. }
  1787. private function quote(String $identifier): String
  1788. {
  1789. return '"' . str_replace('"', '', $identifier) . '"';
  1790. }
  1791. public function getColumnType(ReflectedColumn $column, bool $update): String
  1792. {
  1793. if ($this->driver == 'pgsql' && !$update && $column->getPk() && $this->canAutoIncrement($column)) {
  1794. return 'serial';
  1795. }
  1796. $type = $this->typeConverter->fromJdbc($column->getType());
  1797. if ($column->hasPrecision() && $column->hasScale()) {
  1798. $size = '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
  1799. } else if ($column->hasPrecision()) {
  1800. $size = '(' . $column->getPrecision() . ')';
  1801. } else if ($column->hasLength()) {
  1802. $size = '(' . $column->getLength() . ')';
  1803. } else {
  1804. $size = '';
  1805. }
  1806. $null = $this->getColumnNullType($column, $update);
  1807. $auto = $this->getColumnAutoIncrement($column, $update);
  1808. return $type . $size . $null . $auto;
  1809. }
  1810. private function getPrimaryKey(String $tableName): String
  1811. {
  1812. $pks = $this->reflection->getTablePrimaryKeys($tableName);
  1813. if (count($pks) == 1) {
  1814. return $pks[0];
  1815. }
  1816. return "";
  1817. }
  1818. private function canAutoIncrement(ReflectedColumn $column): bool
  1819. {
  1820. return in_array($column->getType(), ['integer', 'bigint']);
  1821. }
  1822. private function getColumnAutoIncrement(ReflectedColumn $column, bool $update): String
  1823. {
  1824. if (!$this->canAutoIncrement($column)) {
  1825. return '';
  1826. }
  1827. switch ($this->driver) {
  1828. case 'mysql':
  1829. return $column->getPk() ? ' AUTO_INCREMENT' : '';
  1830. case 'pgsql':
  1831. return '';
  1832. case 'sqlsrv':
  1833. return ($column->getPk() && !$update) ? ' IDENTITY(1,1)' : '';
  1834. }
  1835. }
  1836. private function getColumnNullType(ReflectedColumn $column, bool $update): String
  1837. {
  1838. if ($this->driver == 'pgsql' && $update) {
  1839. return '';
  1840. }
  1841. return $column->getNullable() ? ' NULL' : ' NOT NULL';
  1842. }
  1843. private function getTableRenameSQL(String $tableName, String $newTableName): String
  1844. {
  1845. $p1 = $this->quote($tableName);
  1846. $p2 = $this->quote($newTableName);
  1847. switch ($this->driver) {
  1848. case 'mysql':
  1849. return "RENAME TABLE $p1 TO $p2";
  1850. case 'pgsql':
  1851. return "ALTER TABLE $p1 RENAME TO $p2";
  1852. case 'sqlsrv':
  1853. return "EXEC sp_rename $p1, $p2";
  1854. }
  1855. }
  1856. private function getColumnRenameSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1857. {
  1858. $p1 = $this->quote($tableName);
  1859. $p2 = $this->quote($columnName);
  1860. $p3 = $this->quote($newColumn->getName());
  1861. switch ($this->driver) {
  1862. case 'mysql':
  1863. $p4 = $this->getColumnType($newColumn, true);
  1864. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1865. case 'pgsql':
  1866. return "ALTER TABLE $p1 RENAME COLUMN $p2 TO $p3";
  1867. case 'sqlsrv':
  1868. $p4 = $this->quote($tableName . '.' . $columnName);
  1869. return "EXEC sp_rename $p4, $p3, 'COLUMN'";
  1870. }
  1871. }
  1872. private function getColumnRetypeSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1873. {
  1874. $p1 = $this->quote($tableName);
  1875. $p2 = $this->quote($columnName);
  1876. $p3 = $this->quote($newColumn->getName());
  1877. $p4 = $this->getColumnType($newColumn, true);
  1878. switch ($this->driver) {
  1879. case 'mysql':
  1880. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1881. case 'pgsql':
  1882. return "ALTER TABLE $p1 ALTER COLUMN $p3 TYPE $p4";
  1883. case 'sqlsrv':
  1884. return "ALTER TABLE $p1 ALTER COLUMN $p3 $p4";
  1885. }
  1886. }
  1887. private function getSetColumnNullableSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1888. {
  1889. $p1 = $this->quote($tableName);
  1890. $p2 = $this->quote($columnName);
  1891. $p3 = $this->quote($newColumn->getName());
  1892. $p4 = $this->getColumnType($newColumn, true);
  1893. switch ($this->driver) {
  1894. case 'mysql':
  1895. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1896. case 'pgsql':
  1897. $p5 = $newColumn->getNullable() ? 'DROP NOT NULL' : 'SET NOT NULL';
  1898. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p5";
  1899. case 'sqlsrv':
  1900. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  1901. }
  1902. }
  1903. private function getSetColumnPkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1904. {
  1905. $p1 = $this->quote($tableName);
  1906. $p2 = $this->quote($columnName);
  1907. $p3 = $this->quote($tableName . '_pkey');
  1908. switch ($this->driver) {
  1909. case 'mysql':
  1910. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : 'DROP PRIMARY KEY';
  1911. return "ALTER TABLE $p1 $p4";
  1912. case 'pgsql':
  1913. case 'sqlsrv':
  1914. $p4 = $newColumn->getPk() ? "ADD PRIMARY KEY ($p2)" : "DROP CONSTRAINT $p3";
  1915. return "ALTER TABLE $p1 $p4";
  1916. }
  1917. }
  1918. private function getSetColumnPkSequenceSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1919. {
  1920. $p1 = $this->quote($tableName);
  1921. $p2 = $this->quote($columnName);
  1922. $p3 = $this->quote($tableName . '_' . $columnName . '_seq');
  1923. switch ($this->driver) {
  1924. case 'mysql':
  1925. return "select 1";
  1926. case 'pgsql':
  1927. return $newColumn->getPk() ? "CREATE SEQUENCE $p3 OWNED BY $p1.$p2" : "DROP SEQUENCE $p3";
  1928. case 'sqlsrv':
  1929. return $newColumn->getPk() ? "CREATE SEQUENCE $p3" : "DROP SEQUENCE $p3";
  1930. }
  1931. }
  1932. private function getSetColumnPkSequenceStartSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1933. {
  1934. $p1 = $this->quote($tableName);
  1935. $p2 = $this->quote($columnName);
  1936. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1937. switch ($this->driver) {
  1938. case 'mysql':
  1939. return "select 1";
  1940. case 'pgsql':
  1941. return "SELECT setval($p3, (SELECT max($p2)+1 FROM $p1));";
  1942. case 'sqlsrv':
  1943. return "ALTER SEQUENCE $p3 RESTART WITH (SELECT max($p2)+1 FROM $p1)";
  1944. }
  1945. }
  1946. private function getSetColumnPkDefaultSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1947. {
  1948. $p1 = $this->quote($tableName);
  1949. $p2 = $this->quote($columnName);
  1950. switch ($this->driver) {
  1951. case 'mysql':
  1952. $p3 = $this->quote($newColumn->getName());
  1953. $p4 = $this->getColumnType($newColumn, true);
  1954. return "ALTER TABLE $p1 CHANGE $p2 $p3 $p4";
  1955. case 'pgsql':
  1956. if ($newColumn->getPk()) {
  1957. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1958. $p4 = "SET DEFAULT nextval($p3)";
  1959. } else {
  1960. $p4 = 'DROP DEFAULT';
  1961. }
  1962. return "ALTER TABLE $p1 ALTER COLUMN $p2 $p4";
  1963. case 'sqlsrv':
  1964. $p3 = $this->pdo->quote($tableName . '_' . $columnName . '_seq');
  1965. $p4 = $this->quote('DF_' . $tableName . '_' . $columnName);
  1966. if ($newColumn->getPk()) {
  1967. return "ALTER TABLE $p1 ADD CONSTRAINT $p4 DEFAULT NEXT VALUE FOR $p3 FOR $p2";
  1968. } else {
  1969. return "ALTER TABLE $p1 DROP CONSTRAINT $p4";
  1970. }
  1971. }
  1972. }
  1973. private function getAddColumnFkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1974. {
  1975. $p1 = $this->quote($tableName);
  1976. $p2 = $this->quote($columnName);
  1977. $p3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  1978. $p4 = $this->quote($newColumn->getFk());
  1979. $p5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  1980. return "ALTER TABLE $p1 ADD CONSTRAINT $p3 FOREIGN KEY ($p2) REFERENCES $p4 ($p5)";
  1981. }
  1982. private function getRemoveColumnFkConstraintSQL(String $tableName, String $columnName, ReflectedColumn $newColumn): String
  1983. {
  1984. $p1 = $this->quote($tableName);
  1985. $p2 = $this->quote($tableName . '_' . $columnName . '_fkey');
  1986. switch ($this->driver) {
  1987. case 'mysql':
  1988. return "ALTER TABLE $p1 DROP FOREIGN KEY $p2";
  1989. case 'pgsql':
  1990. case 'sqlsrv':
  1991. return "ALTER TABLE $p1 DROP CONSTRAINT $p2";
  1992. }
  1993. }
  1994. private function getAddTableSQL(ReflectedTable $newTable): String
  1995. {
  1996. $tableName = $newTable->getName();
  1997. $p1 = $this->quote($tableName);
  1998. $fields = [];
  1999. $constraints = [];
  2000. foreach ($newTable->columnNames() as $columnName) {
  2001. $newColumn = $newTable->get($columnName);
  2002. $f1 = $this->quote($columnName);
  2003. $f2 = $this->getColumnType($newColumn, false);
  2004. $f3 = $this->quote($tableName . '_' . $columnName . '_fkey');
  2005. $f4 = $this->quote($newColumn->getFk());
  2006. $f5 = $this->quote($this->getPrimaryKey($newColumn->getFk()));
  2007. $fields[] = "$f1 $f2";
  2008. if ($newColumn->getPk()) {
  2009. $constraints[] = "PRIMARY KEY ($f1)";
  2010. }
  2011. if ($newColumn->getFk()) {
  2012. $constraints[] = "CONSTRAINT $f3 FOREIGN KEY ($f1) REFERENCES $f4 ($f5)";
  2013. }
  2014. }
  2015. $p2 = implode(',', array_merge($fields, $constraints));
  2016. return "CREATE TABLE $p1 ($p2);";
  2017. }
  2018. private function getAddColumnSQL(String $tableName, ReflectedColumn $newColumn): String
  2019. {
  2020. $p1 = $this->quote($tableName);
  2021. $p2 = $this->quote($newColumn->getName());
  2022. $p3 = $this->getColumnType($newColumn, false);
  2023. return "ALTER TABLE $p1 ADD COLUMN $p2 $p3";
  2024. }
  2025. private function getRemoveTableSQL(String $tableName): String
  2026. {
  2027. $p1 = $this->quote($tableName);
  2028. return "DROP TABLE $p1 CASCADE;";
  2029. }
  2030. private function getRemoveColumnSQL(String $tableName, String $columnName): String
  2031. {
  2032. $p1 = $this->quote($tableName);
  2033. $p2 = $this->quote($columnName);
  2034. return "ALTER TABLE $p1 DROP COLUMN $p2 CASCADE;";
  2035. }
  2036. public function renameTable(String $tableName, String $newTableName)
  2037. {
  2038. $sql = $this->getTableRenameSQL($tableName, $newTableName);
  2039. return $this->query($sql);
  2040. }
  2041. public function renameColumn(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2042. {
  2043. $sql = $this->getColumnRenameSQL($tableName, $columnName, $newColumn);
  2044. return $this->query($sql);
  2045. }
  2046. public function retypeColumn(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2047. {
  2048. $sql = $this->getColumnRetypeSQL($tableName, $columnName, $newColumn);
  2049. return $this->query($sql);
  2050. }
  2051. public function setColumnNullable(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2052. {
  2053. $sql = $this->getSetColumnNullableSQL($tableName, $columnName, $newColumn);
  2054. return $this->query($sql);
  2055. }
  2056. public function addColumnPrimaryKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2057. {
  2058. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  2059. $this->query($sql);
  2060. if ($this->canAutoIncrement($newColumn)) {
  2061. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  2062. $this->query($sql);
  2063. $sql = $this->getSetColumnPkSequenceStartSQL($tableName, $columnName, $newColumn);
  2064. $this->query($sql);
  2065. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  2066. $this->query($sql);
  2067. }
  2068. return true;
  2069. }
  2070. public function removeColumnPrimaryKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2071. {
  2072. if ($this->canAutoIncrement($newColumn)) {
  2073. $sql = $this->getSetColumnPkDefaultSQL($tableName, $columnName, $newColumn);
  2074. $this->query($sql);
  2075. $sql = $this->getSetColumnPkSequenceSQL($tableName, $columnName, $newColumn);
  2076. $this->query($sql);
  2077. }
  2078. $sql = $this->getSetColumnPkConstraintSQL($tableName, $columnName, $newColumn);
  2079. $this->query($sql);
  2080. return true;
  2081. }
  2082. public function addColumnForeignKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2083. {
  2084. $sql = $this->getAddColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  2085. return $this->query($sql);
  2086. }
  2087. public function removeColumnForeignKey(String $tableName, String $columnName, ReflectedColumn $newColumn)
  2088. {
  2089. $sql = $this->getRemoveColumnFkConstraintSQL($tableName, $columnName, $newColumn);
  2090. return $this->query($sql);
  2091. }
  2092. public function addTable(ReflectedTable $newTable)
  2093. {
  2094. $sql = $this->getAddTableSQL($newTable);
  2095. return $this->query($sql);
  2096. }
  2097. public function addColumn(String $tableName, ReflectedColumn $newColumn)
  2098. {
  2099. $sql = $this->getAddColumnSQL($tableName, $newColumn);
  2100. return $this->query($sql);
  2101. }
  2102. public function removeTable(String $tableName)
  2103. {
  2104. $sql = $this->getRemoveTableSQL($tableName);
  2105. return $this->query($sql);
  2106. }
  2107. public function removeColumn(String $tableName, String $columnName)
  2108. {
  2109. $sql = $this->getRemoveColumnSQL($tableName, $columnName);
  2110. return $this->query($sql);
  2111. }
  2112. private function query(String $sql): bool
  2113. {
  2114. $stmt = $this->pdo->prepare($sql);
  2115. return $stmt->execute();
  2116. }
  2117. }
  2118. // file: src/Tqdev/PhpCrudApi/Database/GenericReflection.php
  2119. class GenericReflection
  2120. {
  2121. private $pdo;
  2122. private $driver;
  2123. private $database;
  2124. private $typeConverter;
  2125. public function __construct(\PDO $pdo, String $driver, String $database)
  2126. {
  2127. $this->pdo = $pdo;
  2128. $this->driver = $driver;
  2129. $this->database = $database;
  2130. $this->typeConverter = new TypeConverter($driver);
  2131. }
  2132. public function getIgnoredTables(): array
  2133. {
  2134. switch ($this->driver) {
  2135. case 'mysql':return [];
  2136. case 'pgsql':return ['spatial_ref_sys'];
  2137. case 'sqlsrv':return [];
  2138. }
  2139. }
  2140. private function getTablesSQL(): String
  2141. {
  2142. switch ($this->driver) {
  2143. case 'mysql':return 'SELECT "TABLE_NAME" FROM "INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_TYPE" IN (\'BASE TABLE\') AND "TABLE_SCHEMA" = ? ORDER BY BINARY "TABLE_NAME"';
  2144. case 'pgsql':return 'SELECT c.relname as "TABLE_NAME" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN (\'r\') 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";';
  2145. case 'sqlsrv':return 'SELECT o.name as "TABLE_NAME" FROM sysobjects o WHERE o.xtype = \'U\' ORDER BY "TABLE_NAME"';
  2146. }
  2147. }
  2148. private function getTableColumnsSQL(): String
  2149. {
  2150. switch ($this->driver) {
  2151. 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" = ?';
  2152. 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;';
  2153. 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 \'\' <> ?';
  2154. }
  2155. }
  2156. private function getTablePrimaryKeysSQL(): String
  2157. {
  2158. switch ($this->driver) {
  2159. case 'mysql':return 'SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" WHERE "CONSTRAINT_NAME" = \'PRIMARY\' AND "TABLE_NAME" = ? AND "TABLE_SCHEMA" = ?';
  2160. 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\'';
  2161. 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 \'\' <> ?';
  2162. }
  2163. }
  2164. private function getTableForeignKeysSQL(): String
  2165. {
  2166. switch ($this->driver) {
  2167. 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" = ?';
  2168. 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\'';
  2169. 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 \'\' <> ?';
  2170. }
  2171. }
  2172. public function getDatabaseName(): String
  2173. {
  2174. return $this->database;
  2175. }
  2176. public function getTables(): array
  2177. {
  2178. $sql = $this->getTablesSQL();
  2179. return $this->query($sql, [$this->database]);
  2180. }
  2181. public function getTableColumns(String $tableName): array
  2182. {
  2183. $sql = $this->getTableColumnsSQL();
  2184. return $this->query($sql, [$tableName, $this->database]);
  2185. }
  2186. public function getTablePrimaryKeys(String $tableName): array
  2187. {
  2188. $sql = $this->getTablePrimaryKeysSQL();
  2189. $results = $this->query($sql, [$tableName, $this->database]);
  2190. $primaryKeys = [];
  2191. foreach ($results as $result) {
  2192. $primaryKeys[] = $result['COLUMN_NAME'];
  2193. }
  2194. return $primaryKeys;
  2195. }
  2196. public function getTableForeignKeys(String $tableName): array
  2197. {
  2198. $sql = $this->getTableForeignKeysSQL();
  2199. $results = $this->query($sql, [$tableName, $this->database]);
  2200. $foreignKeys = [];
  2201. foreach ($results as $result) {
  2202. $foreignKeys[$result['COLUMN_NAME']] = $result['REFERENCED_TABLE_NAME'];
  2203. }
  2204. return $foreignKeys;
  2205. }
  2206. public function toJdbcType(String $type, int $size): String
  2207. {
  2208. return $this->typeConverter->toJdbc($type, $size);
  2209. }
  2210. private function query(String $sql, array $parameters): array
  2211. {
  2212. $stmt = $this->pdo->prepare($sql);
  2213. $stmt->execute($parameters);
  2214. return $stmt->fetchAll();
  2215. }
  2216. }
  2217. // file: src/Tqdev/PhpCrudApi/Database/TypeConverter.php
  2218. class TypeConverter
  2219. {
  2220. private $driver;
  2221. public function __construct(String $driver)
  2222. {
  2223. $this->driver = $driver;
  2224. }
  2225. private $fromJdbc = [
  2226. 'mysql' => [
  2227. 'clob' => 'longtext',
  2228. 'boolean' => 'bit',
  2229. 'blob' => 'longblob',
  2230. 'timestamp' => 'datetime',
  2231. ],
  2232. 'pgsql' => [
  2233. 'clob' => 'text',
  2234. 'blob' => 'bytea',
  2235. ],
  2236. 'sqlsrv' => [
  2237. 'boolean' => 'bit',
  2238. ],
  2239. ];
  2240. private $toJdbc = [
  2241. 'simplified' => [
  2242. 'char' => 'varchar',
  2243. 'longvarchar' => 'clob',
  2244. 'nchar' => 'varchar',
  2245. 'nvarchar' => 'varchar',
  2246. 'longnvarchar' => 'clob',
  2247. 'binary' => 'varbinary',
  2248. 'longvarbinary' => 'blob',
  2249. 'tinyint' => 'integer',
  2250. 'smallint' => 'integer',
  2251. 'real' => 'float',
  2252. 'numeric' => 'decimal',
  2253. 'time_with_timezone' => 'time',
  2254. 'timestamp_with_timezone' => 'timestamp',
  2255. ],
  2256. 'mysql' => [
  2257. 'tinyint(1)' => 'boolean',
  2258. 'bit(0)' => 'boolean',
  2259. 'bit(1)' => 'boolean',
  2260. 'tinyblob' => 'blob',
  2261. 'mediumblob' => 'blob',
  2262. 'longblob' => 'blob',
  2263. 'tinytext' => 'clob',
  2264. 'mediumtext' => 'clob',
  2265. 'longtext' => 'clob',
  2266. 'text' => 'clob',
  2267. 'int' => 'integer',
  2268. 'polygon' => 'geometry',
  2269. 'point' => 'geometry',
  2270. 'datetime' => 'timestamp',
  2271. ],
  2272. 'pgsql' => [
  2273. 'bigserial' => 'bigint',
  2274. 'bit varying' => 'bit',
  2275. 'box' => 'geometry',
  2276. 'bytea' => 'blob',
  2277. 'character varying' => 'varchar',
  2278. 'character' => 'char',
  2279. 'cidr' => 'varchar',
  2280. 'circle' => 'geometry',
  2281. 'double precision' => 'double',
  2282. 'inet' => 'integer',
  2283. 'jsonb' => 'clob',
  2284. 'line' => 'geometry',
  2285. 'lseg' => 'geometry',
  2286. 'macaddr' => 'varchar',
  2287. 'money' => 'decimal',
  2288. 'path' => 'geometry',
  2289. 'point' => 'geometry',
  2290. 'polygon' => 'geometry',
  2291. 'real' => 'float',
  2292. 'serial' => 'integer',
  2293. 'text' => 'clob',
  2294. 'time without time zone' => 'time',
  2295. 'time with time zone' => 'time_with_timezone',
  2296. 'timestamp without time zone' => 'timestamp',
  2297. 'timestamp with time zone' => 'timestamp_with_timezone',
  2298. 'uuid' => 'char',
  2299. 'xml' => 'clob',
  2300. ],
  2301. 'sqlsrv' => [
  2302. 'varbinary(0)' => 'blob',
  2303. 'bit' => 'boolean',
  2304. 'datetime' => 'timestamp',
  2305. 'datetime2' => 'timestamp',
  2306. 'float' => 'double',
  2307. 'image' => 'longvarbinary',
  2308. 'int' => 'integer',
  2309. 'money' => 'decimal',
  2310. 'ntext' => 'longnvarchar',
  2311. 'smalldatetime' => 'timestamp',
  2312. 'smallmoney' => 'decimal',
  2313. 'text' => 'longvarchar',
  2314. 'timestamp' => 'binary',
  2315. 'tinyint' => 'tinyint',
  2316. 'udt' => 'varbinary',
  2317. 'uniqueidentifier' => 'char',
  2318. 'xml' => 'longnvarchar',
  2319. ],
  2320. ];
  2321. private $valid = [
  2322. 'bigint' => true,
  2323. 'binary' => true,
  2324. 'bit' => true,
  2325. 'blob' => true,
  2326. 'boolean' => true,
  2327. 'char' => true,
  2328. 'clob' => true,
  2329. 'date' => true,
  2330. 'decimal' => true,
  2331. 'distinct' => true,
  2332. 'double' => true,
  2333. 'float' => true,
  2334. 'integer' => true,
  2335. 'longnvarchar' => true,
  2336. 'longvarbinary' => true,
  2337. 'longvarchar' => true,
  2338. 'nchar' => true,
  2339. 'nclob' => true,
  2340. 'numeric' => true,
  2341. 'nvarchar' => true,
  2342. 'real' => true,
  2343. 'smallint' => true,
  2344. 'time' => true,
  2345. 'time_with_timezone' => true,
  2346. 'timestamp' => true,
  2347. 'timestamp_with_timezone' => true,
  2348. 'tinyint' => true,
  2349. 'varbinary' => true,
  2350. 'varchar' => true,
  2351. 'geometry' => true,
  2352. ];
  2353. public function toJdbc(String $type, int $size): String
  2354. {
  2355. $jdbcType = strtolower($type);
  2356. if (isset($this->toJdbc[$this->driver]["$jdbcType($size)"])) {
  2357. $jdbcType = $this->toJdbc[$this->driver]["$jdbcType($size)"];
  2358. }
  2359. if (isset($this->toJdbc[$this->driver][$jdbcType])) {
  2360. $jdbcType = $this->toJdbc[$this->driver][$jdbcType];
  2361. }
  2362. if (isset($this->toJdbc['simplified'][$jdbcType])) {
  2363. $jdbcType = $this->toJdbc['simplified'][$jdbcType];
  2364. }
  2365. if (!isset($this->valid[$jdbcType])) {
  2366. throw new \Exception("Unsupported type '$jdbcType' for driver '$this->driver'");
  2367. }
  2368. return $jdbcType;
  2369. }
  2370. public function fromJdbc(String $type): String
  2371. {
  2372. $jdbcType = strtolower($type);
  2373. if (isset($this->fromJdbc[$this->driver][$jdbcType])) {
  2374. $jdbcType = $this->fromJdbc[$this->driver][$jdbcType];
  2375. }
  2376. return $jdbcType;
  2377. }
  2378. }
  2379. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Handler.php
  2380. interface Handler
  2381. {
  2382. public function handle(Request $request): Response;
  2383. }
  2384. // file: src/Tqdev/PhpCrudApi/Middleware/Base/Middleware.php
  2385. abstract class Middleware implements Handler
  2386. {
  2387. protected $next;
  2388. protected $responder;
  2389. private $properties;
  2390. public function __construct(Router $router, Responder $responder, array $properties)
  2391. {
  2392. $router->load($this);
  2393. $this->responder = $responder;
  2394. $this->properties = $properties;
  2395. }
  2396. public function setNext(Handler $handler) /*: void*/
  2397. {
  2398. $this->next = $handler;
  2399. }
  2400. protected function getProperty(String $key, $default)
  2401. {
  2402. return isset($this->properties[$key]) ? $this->properties[$key] : $default;
  2403. }
  2404. }
  2405. // file: src/Tqdev/PhpCrudApi/Middleware/Communication/VariableStore.php
  2406. class VariableStore
  2407. {
  2408. static $values = array();
  2409. public static function get(String $key)
  2410. {
  2411. if (isset(self::$values[$key])) {
  2412. return self::$values[$key];
  2413. }
  2414. return null;
  2415. }
  2416. public static function set(String $key, /* object */ $value)
  2417. {
  2418. self::$values[$key] = $value;
  2419. }
  2420. }
  2421. // file: src/Tqdev/PhpCrudApi/Middleware/Router/Router.php
  2422. interface Router extends Handler
  2423. {
  2424. public function register(String $method, String $path, array $handler);
  2425. public function load(Middleware $middleware);
  2426. public function route(Request $request): Response;
  2427. }
  2428. // file: src/Tqdev/PhpCrudApi/Middleware/Router/SimpleRouter.php
  2429. class SimpleRouter implements Router
  2430. {
  2431. private $responder;
  2432. private $cache;
  2433. private $ttl;
  2434. private $registration;
  2435. private $routes;
  2436. private $routeHandlers;
  2437. private $middlewares;
  2438. public function __construct(Responder $responder, Cache $cache, int $ttl)
  2439. {
  2440. $this->responder = $responder;
  2441. $this->cache = $cache;
  2442. $this->ttl = $ttl;
  2443. $this->registration = true;
  2444. $this->routes = $this->loadPathTree();
  2445. $this->routeHandlers = [];
  2446. $this->middlewares = array();
  2447. }
  2448. private function loadPathTree(): PathTree
  2449. {
  2450. $data = $this->cache->get('PathTree');
  2451. if ($data != '') {
  2452. $tree = PathTree::fromJson(json_decode(gzuncompress($data)));
  2453. $this->registration = false;
  2454. } else {
  2455. $tree = new PathTree();
  2456. }
  2457. return $tree;
  2458. }
  2459. public function register(String $method, String $path, array $handler)
  2460. {
  2461. $routeNumber = count($this->routeHandlers);
  2462. $this->routeHandlers[$routeNumber] = $handler;
  2463. if ($this->registration) {
  2464. $parts = explode('/', trim($path, '/'));
  2465. array_unshift($parts, $method);
  2466. $this->routes->put($parts, $routeNumber);
  2467. }
  2468. }
  2469. public function load(Middleware $middleware) /*: void*/
  2470. {
  2471. if (count($this->middlewares) > 0) {
  2472. $next = $this->middlewares[0];
  2473. } else {
  2474. $next = $this;
  2475. }
  2476. $middleware->setNext($next);
  2477. array_unshift($this->middlewares, $middleware);
  2478. }
  2479. public function route(Request $request): Response
  2480. {
  2481. if ($this->registration) {
  2482. $data = gzcompress(json_encode($this->routes, JSON_UNESCAPED_UNICODE));
  2483. $this->cache->set('PathTree', $data, $this->ttl);
  2484. }
  2485. $obj = $this;
  2486. if (count($this->middlewares) > 0) {
  2487. $obj = $this->middlewares[0];
  2488. }
  2489. return $obj->handle($request);
  2490. }
  2491. private function getRouteNumbers(Request $request): array
  2492. {
  2493. $method = strtoupper($request->getMethod());
  2494. $path = explode('/', trim($request->getPath(0), '/'));
  2495. array_unshift($path, $method);
  2496. return $this->routes->match($path);
  2497. }
  2498. public function handle(Request $request): Response
  2499. {
  2500. $routeNumbers = $this->getRouteNumbers($request);
  2501. if (count($routeNumbers) == 0) {
  2502. return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getPath());
  2503. }
  2504. return call_user_func($this->routeHandlers[$routeNumbers[0]], $request);
  2505. }
  2506. }
  2507. // file: src/Tqdev/PhpCrudApi/Middleware/AuthorizationMiddleware.php
  2508. class AuthorizationMiddleware extends Middleware
  2509. {
  2510. private $reflection;
  2511. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2512. {
  2513. parent::__construct($router, $responder, $properties);
  2514. $this->reflection = $reflection;
  2515. $this->utils = new RequestUtils($reflection);
  2516. }
  2517. private function handleColumns(String $operation, String $tableName) /*: void*/
  2518. {
  2519. $columnHandler = $this->getProperty('columnHandler', '');
  2520. if ($columnHandler) {
  2521. $table = $this->reflection->getTable($tableName);
  2522. foreach ($table->columnNames() as $columnName) {
  2523. $allowed = call_user_func($columnHandler, $operation, $tableName, $columnName);
  2524. if (!$allowed) {
  2525. $this->reflection->removeColumn($tableName, $columnName);
  2526. }
  2527. }
  2528. }
  2529. }
  2530. private function handleTable(String $operation, String $tableName) /*: void*/
  2531. {
  2532. if (!$this->reflection->hasTable($tableName)) {
  2533. return;
  2534. }
  2535. $tableHandler = $this->getProperty('tableHandler', '');
  2536. if ($tableHandler) {
  2537. $allowed = call_user_func($tableHandler, $operation, $tableName);
  2538. if (!$allowed) {
  2539. $this->reflection->removeTable($tableName);
  2540. } else {
  2541. $this->handleColumns($operation, $tableName);
  2542. }
  2543. }
  2544. }
  2545. private function handleRecords(String $operation, String $tableName) /*: void*/
  2546. {
  2547. if (!$this->reflection->hasTable($tableName)) {
  2548. return;
  2549. }
  2550. $recordHandler = $this->getProperty('recordHandler', '');
  2551. if ($recordHandler) {
  2552. $query = call_user_func($recordHandler, $operation, $tableName);
  2553. $filters = new FilterInfo();
  2554. $table = $this->reflection->getTable($tableName);
  2555. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  2556. parse_str($query, $params);
  2557. $condition = $filters->getCombinedConditions($table, $params);
  2558. VariableStore::set("authorization.conditions.$tableName", $condition);
  2559. }
  2560. }
  2561. public function handle(Request $request): Response
  2562. {
  2563. $path = $request->getPathSegment(1);
  2564. $operation = $this->utils->getOperation($request);
  2565. $tableNames = $this->utils->getTableNames($request);
  2566. foreach ($tableNames as $tableName) {
  2567. $this->handleTable($operation, $tableName);
  2568. if ($path == 'records') {
  2569. $this->handleRecords($operation, $tableName);
  2570. }
  2571. }
  2572. if ($path == 'openapi') {
  2573. VariableStore::set('authorization.tableHandler', $this->getProperty('tableHandler', ''));
  2574. VariableStore::set('authorization.columnHandler', $this->getProperty('columnHandler', ''));
  2575. }
  2576. return $this->next->handle($request);
  2577. }
  2578. }
  2579. // file: src/Tqdev/PhpCrudApi/Middleware/BasicAuthMiddleware.php
  2580. class BasicAuthMiddleware extends Middleware
  2581. {
  2582. private function hasCorrectPassword(String $username, String $password, array &$passwords): bool
  2583. {
  2584. $hash = isset($passwords[$username]) ? $passwords[$username] : false;
  2585. if ($hash && password_verify($password, $hash)) {
  2586. if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
  2587. $passwords[$username] = password_hash($password, PASSWORD_DEFAULT);
  2588. }
  2589. return true;
  2590. }
  2591. return false;
  2592. }
  2593. private function getValidUsername(String $username, String $password, String $passwordFile): String
  2594. {
  2595. $passwords = $this->readPasswords($passwordFile);
  2596. $valid = $this->hasCorrectPassword($username, $password, $passwords);
  2597. $this->writePasswords($passwordFile, $passwords);
  2598. return $valid ? $username : '';
  2599. }
  2600. private function readPasswords(String $passwordFile): array
  2601. {
  2602. $passwords = [];
  2603. $passwordLines = file($passwordFile);
  2604. foreach ($passwordLines as $passwordLine) {
  2605. if (strpos($passwordLine, ':') !== false) {
  2606. list($username, $hash) = explode(':', trim($passwordLine), 2);
  2607. if (strlen($hash) > 0 && $hash[0] != '$') {
  2608. $hash = password_hash($hash, PASSWORD_DEFAULT);
  2609. }
  2610. $passwords[$username] = $hash;
  2611. }
  2612. }
  2613. return $passwords;
  2614. }
  2615. private function writePasswords(String $passwordFile, array $passwords): bool
  2616. {
  2617. $success = false;
  2618. $passwordFileContents = '';
  2619. foreach ($passwords as $username => $hash) {
  2620. $passwordFileContents .= "$username:$hash\n";
  2621. }
  2622. if (file_get_contents($passwordFile) != $passwordFileContents) {
  2623. $success = file_put_contents($passwordFile, $passwordFileContents) !== false;
  2624. }
  2625. return $success;
  2626. }
  2627. private function getAuthorizationCredentials(Request $request): String
  2628. {
  2629. $parts = explode(' ', trim($request->getHeader('Authorization')), 2);
  2630. if (count($parts) != 2) {
  2631. return '';
  2632. }
  2633. if ($parts[0] != 'Basic') {
  2634. return '';
  2635. }
  2636. return base64_decode(strtr($parts[1], '-_', '+/'));
  2637. }
  2638. public function handle(Request $request): Response
  2639. {
  2640. if (session_status() == PHP_SESSION_NONE) {
  2641. session_start();
  2642. }
  2643. $credentials = $this->getAuthorizationCredentials($request);
  2644. if ($credentials) {
  2645. list($username, $password) = array('', '');
  2646. if (strpos($credentials, ':') !== false) {
  2647. list($username, $password) = explode(':', $credentials, 2);
  2648. }
  2649. $passwordFile = $this->getProperty('passwordFile', '.htpasswd');
  2650. $validUser = $this->getValidUsername($username, $password, $passwordFile);
  2651. $_SESSION['username'] = $validUser;
  2652. if (!$validUser) {
  2653. return $this->responder->error(ErrorCode::ACCESS_DENIED, $username);
  2654. }
  2655. }
  2656. return $this->next->handle($request);
  2657. }
  2658. }
  2659. // file: src/Tqdev/PhpCrudApi/Middleware/CorsMiddleware.php
  2660. class CorsMiddleware extends Middleware
  2661. {
  2662. private function isOriginAllowed(String $origin, String $allowedOrigins): bool
  2663. {
  2664. $found = false;
  2665. foreach (explode(',', $allowedOrigins) as $allowedOrigin) {
  2666. $hostname = preg_quote(strtolower(trim($allowedOrigin)));
  2667. $regex = '/^' . str_replace('\*', '.*', $hostname) . '$/';
  2668. if (preg_match($regex, $origin)) {
  2669. $found = true;
  2670. break;
  2671. }
  2672. }
  2673. return $found;
  2674. }
  2675. public function handle(Request $request): Response
  2676. {
  2677. $method = $request->getMethod();
  2678. $origin = $request->getHeader('Origin');
  2679. $allowedOrigins = $this->getProperty('allowedOrigins', '*');
  2680. if ($origin && !$this->isOriginAllowed($origin, $allowedOrigins)) {
  2681. $response = $this->responder->error(ErrorCode::ORIGIN_FORBIDDEN, $origin);
  2682. } elseif ($method == 'OPTIONS') {
  2683. $response = new Response(Response::OK, '');
  2684. $allowHeaders = $this->getProperty('allowHeaders', 'Content-Type, X-XSRF-TOKEN');
  2685. $response->addHeader('Access-Control-Allow-Headers', $allowHeaders);
  2686. $allowMethods = $this->getProperty('allowMethods', 'OPTIONS, GET, PUT, POST, DELETE, PATCH');
  2687. $response->addHeader('Access-Control-Allow-Methods', $allowMethods);
  2688. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  2689. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  2690. $maxAge = $this->getProperty('maxAge', '1728000');
  2691. $response->addHeader('Access-Control-Max-Age', $maxAge);
  2692. } else {
  2693. $response = $this->next->handle($request);
  2694. }
  2695. if ($origin) {
  2696. $allowCredentials = $this->getProperty('allowCredentials', 'true');
  2697. $response->addHeader('Access-Control-Allow-Credentials', $allowCredentials);
  2698. $response->addHeader('Access-Control-Allow-Origin', $origin);
  2699. }
  2700. return $response;
  2701. }
  2702. }
  2703. // file: src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php
  2704. class FirewallMiddleware extends Middleware
  2705. {
  2706. private function ipMatch(String $ip, String $cidr): bool
  2707. {
  2708. if (strpos($cidr, '/') !== false) {
  2709. list($subnet, $mask) = explode('/', trim($cidr));
  2710. if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  2711. return true;
  2712. }
  2713. } else {
  2714. if (ip2long($ip) == ip2long($cidr)) {
  2715. return true;
  2716. }
  2717. }
  2718. return false;
  2719. }
  2720. private function isIpAllowed(String $ipAddress, String $allowedIpAddresses): bool
  2721. {
  2722. foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
  2723. if ($this->ipMatch($ipAddress, $allowedIp)) {
  2724. return true;
  2725. }
  2726. }
  2727. return false;
  2728. }
  2729. public function handle(Request $request): Response
  2730. {
  2731. $reverseProxy = $this->getProperty('reverseProxy', '');
  2732. if ($reverseProxy) {
  2733. $ipAddress = array_pop(explode(',', $request->getHeader('X-Forwarded-For')));
  2734. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  2735. $ipAddress = $_SERVER['REMOTE_ADDR'];
  2736. } else {
  2737. $ipAddress = '127.0.0.1';
  2738. }
  2739. $allowedIpAddresses = $this->getProperty('allowedIpAddresses', '');
  2740. if (!$this->isIpAllowed($ipAddress, $allowedIpAddresses)) {
  2741. $response = $this->responder->error(ErrorCode::ACCESS_DENIED, $ipAddress);
  2742. } else {
  2743. $response = $this->next->handle($request);
  2744. }
  2745. return $response;
  2746. }
  2747. }
  2748. // file: src/Tqdev/PhpCrudApi/Middleware/JwtAuthMiddleware.php
  2749. class JwtAuthMiddleware extends Middleware
  2750. {
  2751. private function getVerifiedClaims(String $token, int $time, int $leeway, int $ttl, String $secret): array
  2752. {
  2753. $algorithms = array('HS256' => 'sha256', 'HS384' => 'sha384', 'HS512' => 'sha512');
  2754. $token = explode('.', $token);
  2755. if (count($token) < 3) {
  2756. return array();
  2757. }
  2758. $header = json_decode(base64_decode(strtr($token[0], '-_', '+/')), true);
  2759. if (!$secret) {
  2760. return array();
  2761. }
  2762. if ($header['typ'] != 'JWT') {
  2763. return array();
  2764. }
  2765. $algorithm = $header['alg'];
  2766. if (!isset($algorithms[$algorithm])) {
  2767. return array();
  2768. }
  2769. $hmac = $algorithms[$algorithm];
  2770. $signature = bin2hex(base64_decode(strtr($token[2], '-_', '+/')));
  2771. if ($signature != hash_hmac($hmac, "$token[0].$token[1]", $secret)) {
  2772. return array();
  2773. }
  2774. $claims = json_decode(base64_decode(strtr($token[1], '-_', '+/')), true);
  2775. if (!$claims) {
  2776. return array();
  2777. }
  2778. if (isset($claims['nbf']) && $time + $leeway < $claims['nbf']) {
  2779. return array();
  2780. }
  2781. if (isset($claims['iat']) && $time + $leeway < $claims['iat']) {
  2782. return array();
  2783. }
  2784. if (isset($claims['exp']) && $time - $leeway > $claims['exp']) {
  2785. return array();
  2786. }
  2787. if (isset($claims['iat']) && !isset($claims['exp'])) {
  2788. if ($time - $leeway > $claims['iat'] + $ttl) {
  2789. return array();
  2790. }
  2791. }
  2792. return $claims;
  2793. }
  2794. private function getClaims(String $token): array
  2795. {
  2796. $time = (int) $this->getProperty('time', time());
  2797. $leeway = (int) $this->getProperty('leeway', '5');
  2798. $ttl = (int) $this->getProperty('ttl', '30');
  2799. $secret = $this->getProperty('secret', '');
  2800. if (!$secret) {
  2801. return array();
  2802. }
  2803. return $this->getVerifiedClaims($token, $time, $leeway, $ttl, $secret);
  2804. }
  2805. private function getAuthorizationToken(Request $request): String
  2806. {
  2807. $parts = explode(' ', trim($request->getHeader('Authorization')), 2);
  2808. if (count($parts) != 2) {
  2809. return '';
  2810. }
  2811. if ($parts[0] != 'Bearer') {
  2812. return '';
  2813. }
  2814. return $parts[1];
  2815. }
  2816. public function handle(Request $request): Response
  2817. {
  2818. if (session_status() == PHP_SESSION_NONE) {
  2819. session_start();
  2820. }
  2821. $token = $this->getAuthorizationToken($request);
  2822. if ($token) {
  2823. $claims = $this->getClaims($token);
  2824. $_SESSION['claims'] = $claims;
  2825. if (empty($claims)) {
  2826. return $this->responder->error(ErrorCode::ACCESS_DENIED, 'JWT');
  2827. }
  2828. }
  2829. return $this->next->handle($request);
  2830. }
  2831. }
  2832. // file: src/Tqdev/PhpCrudApi/Middleware/SanitationMiddleware.php
  2833. class SanitationMiddleware extends Middleware
  2834. {
  2835. private $reflection;
  2836. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2837. {
  2838. parent::__construct($router, $responder, $properties);
  2839. $this->reflection = $reflection;
  2840. $this->utils = new RequestUtils($reflection);
  2841. }
  2842. private function callHandler($handler, $record, String $operation, ReflectedTable $table) /*: object */
  2843. {
  2844. $context = (array) $record;
  2845. $tableName = $table->getName();
  2846. foreach ($context as $columnName => &$value) {
  2847. if ($table->exists($columnName)) {
  2848. $column = $table->get($columnName);
  2849. $value = call_user_func($handler, $operation, $tableName, $column->serialize(), $value);
  2850. }
  2851. }
  2852. return (object) $context;
  2853. }
  2854. public function handle(Request $request): Response
  2855. {
  2856. $operation = $this->utils->getOperation($request);
  2857. if (in_array($operation, ['create', 'update', 'increment'])) {
  2858. $tableName = $request->getPathSegment(2);
  2859. if ($this->reflection->hasTable($tableName)) {
  2860. $record = $request->getBody();
  2861. if ($record !== null) {
  2862. $handler = $this->getProperty('handler', '');
  2863. if ($handler !== '') {
  2864. $table = $this->reflection->getTable($tableName);
  2865. if (is_array($record)) {
  2866. foreach ($record as &$r) {
  2867. $r = $this->callHandler($handler, $r, $operation, $table);
  2868. }
  2869. } else {
  2870. $record = $this->callHandler($handler, $record, $operation, $table);
  2871. }
  2872. $request->setBody($record);
  2873. }
  2874. }
  2875. }
  2876. }
  2877. return $this->next->handle($request);
  2878. }
  2879. }
  2880. // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php
  2881. class ValidationMiddleware extends Middleware
  2882. {
  2883. private $reflection;
  2884. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  2885. {
  2886. parent::__construct($router, $responder, $properties);
  2887. $this->reflection = $reflection;
  2888. $this->utils = new RequestUtils($reflection);
  2889. }
  2890. private function callHandler($handler, $record, String $operation, ReflectedTable $table) /*: Response?*/
  2891. {
  2892. $context = (array) $record;
  2893. $details = array();
  2894. $tableName = $table->getName();
  2895. foreach ($context as $columnName => $value) {
  2896. if ($table->exists($columnName)) {
  2897. $column = $table->get($columnName);
  2898. $valid = call_user_func($handler, $operation, $tableName, $column->serialize(), $value, $context);
  2899. if ($valid !== true && $valid !== '') {
  2900. $details[$columnName] = $valid;
  2901. }
  2902. }
  2903. }
  2904. if (count($details) > 0) {
  2905. return $this->responder->error(ErrorCode::INPUT_VALIDATION_FAILED, $tableName, $details);
  2906. }
  2907. return null;
  2908. }
  2909. public function handle(Request $request): Response
  2910. {
  2911. $operation = $this->utils->getOperation($request);
  2912. if (in_array($operation, ['create', 'update', 'increment'])) {
  2913. $tableName = $request->getPathSegment(2);
  2914. if ($this->reflection->hasTable($tableName)) {
  2915. $record = $request->getBody();
  2916. if ($record !== null) {
  2917. $handler = $this->getProperty('handler', '');
  2918. if ($handler !== '') {
  2919. $table = $this->reflection->getTable($tableName);
  2920. if (is_array($record)) {
  2921. foreach ($record as $r) {
  2922. $response = $this->callHandler($handler, $r, $operation, $table);
  2923. if ($response !== null) {
  2924. return $response;
  2925. }
  2926. }
  2927. } else {
  2928. $response = $this->callHandler($handler, $record, $operation, $table);
  2929. if ($response !== null) {
  2930. return $response;
  2931. }
  2932. }
  2933. }
  2934. }
  2935. }
  2936. }
  2937. return $this->next->handle($request);
  2938. }
  2939. }
  2940. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php
  2941. class OpenApiBuilder
  2942. {
  2943. private $openapi;
  2944. private $reflection;
  2945. private $operations = [
  2946. 'list' => 'get',
  2947. 'create' => 'post',
  2948. 'read' => 'get',
  2949. 'update' => 'put',
  2950. 'delete' => 'delete',
  2951. 'increment' => 'patch',
  2952. ];
  2953. private $types = [
  2954. 'integer' => ['type' => 'integer', 'format' => 'int32'],
  2955. 'bigint' => ['type' => 'integer', 'format' => 'int64'],
  2956. 'varchar' => ['type' => 'string'],
  2957. 'clob' => ['type' => 'string'],
  2958. 'varbinary' => ['type' => 'string', 'format' => 'byte'],
  2959. 'blob' => ['type' => 'string', 'format' => 'byte'],
  2960. 'decimal' => ['type' => 'string'],
  2961. 'float' => ['type' => 'number', 'format' => 'float'],
  2962. 'double' => ['type' => 'number', 'format' => 'double'],
  2963. 'time' => ['type' => 'string', 'format' => 'date-time'],
  2964. 'timestamp' => ['type' => 'string', 'format' => 'date-time'],
  2965. 'geometry' => ['type' => 'string'],
  2966. 'boolean' => ['type' => 'boolean'],
  2967. ];
  2968. public function __construct(ReflectionService $reflection, $base)
  2969. {
  2970. $this->reflection = $reflection;
  2971. $this->openapi = new OpenApiDefinition($base);
  2972. }
  2973. public function build(): OpenApiDefinition
  2974. {
  2975. $this->openapi->set("openapi", "3.0.0");
  2976. $tableNames = $this->reflection->getTableNames();
  2977. foreach ($tableNames as $tableName) {
  2978. $this->setPath($tableName);
  2979. }
  2980. $this->openapi->set("components|responses|pk_integer|description", "inserted primary key value (integer)");
  2981. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|type", "integer");
  2982. $this->openapi->set("components|responses|pk_integer|content|application/json|schema|format", "int64");
  2983. $this->openapi->set("components|responses|pk_string|description", "inserted primary key value (string)");
  2984. $this->openapi->set("components|responses|pk_string|content|application/json|schema|type", "string");
  2985. $this->openapi->set("components|responses|pk_string|content|application/json|schema|format", "uuid");
  2986. $this->openapi->set("components|responses|rows_affected|description", "number of rows affected (integer)");
  2987. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|type", "integer");
  2988. $this->openapi->set("components|responses|rows_affected|content|application/json|schema|format", "int64");
  2989. foreach ($tableNames as $tableName) {
  2990. $this->setComponentSchema($tableName);
  2991. $this->setComponentResponse($tableName);
  2992. $this->setComponentRequestBody($tableName);
  2993. }
  2994. $this->setComponentParameters();
  2995. foreach ($tableNames as $index => $tableName) {
  2996. $this->setTag($index, $tableName);
  2997. }
  2998. return $this->openapi;
  2999. }
  3000. private function isOperationOnTableAllowed(String $operation, String $tableName): bool
  3001. {
  3002. $tableHandler = VariableStore::get('authorization.tableHandler');
  3003. if (!$tableHandler) {
  3004. return true;
  3005. }
  3006. return (bool) call_user_func($tableHandler, $operation, $tableName);
  3007. }
  3008. private function isOperationOnColumnAllowed(String $operation, String $tableName, String $columnName): bool
  3009. {
  3010. $columnHandler = VariableStore::get('authorization.columnHandler');
  3011. if (!$columnHandler) {
  3012. return true;
  3013. }
  3014. return (bool) call_user_func($columnHandler, $operation, $tableName, $columnName);
  3015. }
  3016. private function setPath(String $tableName) /*: void*/
  3017. {
  3018. $table = $this->reflection->getTable($tableName);
  3019. $pk = $table->getPk();
  3020. $pkName = $pk ? $pk->getName() : '';
  3021. foreach ($this->operations as $operation => $method) {
  3022. if (!$pkName && $operation != 'list') {
  3023. continue;
  3024. }
  3025. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3026. continue;
  3027. }
  3028. if (in_array($operation, ['list', 'create'])) {
  3029. $path = sprintf('/records/%s', $tableName);
  3030. } else {
  3031. $path = sprintf('/records/%s/{%s}', $tableName, $pkName);
  3032. $this->openapi->set("paths|$path|$method|parameters|0|\$ref", "#/components/parameters/pk");
  3033. }
  3034. if (in_array($operation, ['create', 'update', 'increment'])) {
  3035. $this->openapi->set("paths|$path|$method|requestBody|\$ref", "#/components/requestBodies/$operation-" . urlencode($tableName));
  3036. }
  3037. $this->openapi->set("paths|$path|$method|tags|0", "$tableName");
  3038. $this->openapi->set("paths|$path|$method|description", "$operation $tableName");
  3039. switch ($operation) {
  3040. case 'list':
  3041. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  3042. break;
  3043. case 'create':
  3044. if ($pk->getType() == 'integer') {
  3045. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_integer");
  3046. } else {
  3047. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/pk_string");
  3048. }
  3049. break;
  3050. case 'read':
  3051. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/$operation-" . urlencode($tableName));
  3052. break;
  3053. case 'update':
  3054. case 'delete':
  3055. case 'increment':
  3056. $this->openapi->set("paths|$path|$method|responses|200|\$ref", "#/components/responses/rows_affected");
  3057. break;
  3058. }
  3059. }
  3060. }
  3061. private function setComponentSchema(String $tableName) /*: void*/
  3062. {
  3063. $table = $this->reflection->getTable($tableName);
  3064. foreach ($this->operations as $operation => $method) {
  3065. if ($operation == 'delete') {
  3066. continue;
  3067. }
  3068. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3069. continue;
  3070. }
  3071. if ($operation == 'list') {
  3072. $this->openapi->set("components|schemas|$operation-$tableName|type", "object");
  3073. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|type", "integer");
  3074. $this->openapi->set("components|schemas|$operation-$tableName|properties|results|format", "int64");
  3075. $this->openapi->set("components|schemas|$operation-$tableName|properties|records|type", "array");
  3076. $prefix = "components|schemas|$operation-$tableName|properties|records|items";
  3077. } else {
  3078. $prefix = "components|schemas|$operation-$tableName";
  3079. }
  3080. $this->openapi->set("$prefix|type", "object");
  3081. foreach ($table->columnNames() as $columnName) {
  3082. if (!$this->isOperationOnColumnAllowed($operation, $tableName, $columnName)) {
  3083. continue;
  3084. }
  3085. $column = $table->get($columnName);
  3086. $properties = $this->types[$column->getType()];
  3087. foreach ($properties as $key => $value) {
  3088. $this->openapi->set("$prefix|properties|$columnName|$key", $value);
  3089. }
  3090. }
  3091. }
  3092. }
  3093. private function setComponentResponse(String $tableName) /*: void*/
  3094. {
  3095. foreach (['list', 'read'] as $operation) {
  3096. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3097. continue;
  3098. }
  3099. if ($operation == 'list') {
  3100. $this->openapi->set("components|responses|$operation-$tableName|description", "list of $tableName records");
  3101. } else {
  3102. $this->openapi->set("components|responses|$operation-$tableName|description", "single $tableName record");
  3103. }
  3104. $this->openapi->set("components|responses|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  3105. }
  3106. }
  3107. private function setComponentRequestBody(String $tableName) /*: void*/
  3108. {
  3109. foreach (['create', 'update', 'increment'] as $operation) {
  3110. if (!$this->isOperationOnTableAllowed($operation, $tableName)) {
  3111. continue;
  3112. }
  3113. $this->openapi->set("components|requestBodies|$operation-$tableName|description", "single $tableName record");
  3114. $this->openapi->set("components|requestBodies|$operation-$tableName|content|application/json|schema|\$ref", "#/components/schemas/$operation-" . urlencode($tableName));
  3115. }
  3116. }
  3117. private function setComponentParameters() /*: void*/
  3118. {
  3119. $this->openapi->set("components|parameters|pk|name", "id");
  3120. $this->openapi->set("components|parameters|pk|in", "path");
  3121. $this->openapi->set("components|parameters|pk|schema|type", "string");
  3122. $this->openapi->set("components|parameters|pk|description", "primary key value");
  3123. $this->openapi->set("components|parameters|pk|required", true);
  3124. }
  3125. private function setTag(int $index, String $tableName) /*: void*/
  3126. {
  3127. $this->openapi->set("tags|$index|name", "$tableName");
  3128. $this->openapi->set("tags|$index|description", "$tableName operations");
  3129. }
  3130. }
  3131. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php
  3132. class OpenApiDefinition implements \JsonSerializable
  3133. {
  3134. private $root;
  3135. public function __construct($base)
  3136. {
  3137. $this->root = $base;
  3138. }
  3139. public function set(String $path, $value) /*: void*/
  3140. {
  3141. $parts = explode('|', trim($path, '|'));
  3142. $current = &$this->root;
  3143. while (count($parts) > 0) {
  3144. $part = array_shift($parts);
  3145. if (!isset($current[$part])) {
  3146. $current[$part] = [];
  3147. }
  3148. $current = &$current[$part];
  3149. }
  3150. $current = $value;
  3151. }
  3152. public function jsonSerialize()
  3153. {
  3154. return $this->root;
  3155. }
  3156. }
  3157. // file: src/Tqdev/PhpCrudApi/OpenApi/OpenApiService.php
  3158. class OpenApiService
  3159. {
  3160. private $builder;
  3161. public function __construct(ReflectionService $reflection, array $base)
  3162. {
  3163. $this->builder = new OpenApiBuilder($reflection, $base);
  3164. }
  3165. public function get(): OpenApiDefinition
  3166. {
  3167. return $this->builder->build();
  3168. }
  3169. }
  3170. // file: src/Tqdev/PhpCrudApi/Record/Condition/AndCondition.php
  3171. class AndCondition extends Condition
  3172. {
  3173. private $conditions;
  3174. public function __construct(Condition $condition1, Condition $condition2)
  3175. {
  3176. $this->conditions = [$condition1, $condition2];
  3177. }
  3178. public function _and(Condition $condition): Condition
  3179. {
  3180. if ($condition instanceof NoCondition) {
  3181. return $this;
  3182. }
  3183. $this->conditions[] = $condition;
  3184. return $this;
  3185. }
  3186. public function getConditions(): array
  3187. {
  3188. return $this->conditions;
  3189. }
  3190. public static function fromArray(array $conditions): Condition
  3191. {
  3192. $condition = new NoCondition();
  3193. foreach ($conditions as $c) {
  3194. $condition = $condition->_and($c);
  3195. }
  3196. return $condition;
  3197. }
  3198. }
  3199. // file: src/Tqdev/PhpCrudApi/Record/Condition/ColumnCondition.php
  3200. class ColumnCondition extends Condition
  3201. {
  3202. private $column;
  3203. private $operator;
  3204. private $value;
  3205. public function __construct(ReflectedColumn $column, String $operator, String $value)
  3206. {
  3207. $this->column = $column;
  3208. $this->operator = $operator;
  3209. $this->value = $value;
  3210. }
  3211. public function getColumn(): ReflectedColumn
  3212. {
  3213. return $this->column;
  3214. }
  3215. public function getOperator(): String
  3216. {
  3217. return $this->operator;
  3218. }
  3219. public function getValue(): String
  3220. {
  3221. return $this->value;
  3222. }
  3223. }
  3224. // file: src/Tqdev/PhpCrudApi/Record/Condition/Condition.php
  3225. abstract class Condition
  3226. {
  3227. public function _and(Condition $condition): Condition
  3228. {
  3229. if ($condition instanceof NoCondition) {
  3230. return $this;
  3231. }
  3232. return new AndCondition($this, $condition);
  3233. }
  3234. public function _or(Condition $condition): Condition
  3235. {
  3236. if ($condition instanceof NoCondition) {
  3237. return $this;
  3238. }
  3239. return new OrCondition($this, $condition);
  3240. }
  3241. public function _not(): Condition
  3242. {
  3243. return new NotCondition($this);
  3244. }
  3245. public static function fromString(ReflectedTable $table, String $value): Condition
  3246. {
  3247. $condition = new NoCondition();
  3248. $parts = explode(',', $value, 3);
  3249. if (count($parts) < 2) {
  3250. return null;
  3251. }
  3252. $field = $table->get($parts[0]);
  3253. $command = $parts[1];
  3254. $negate = false;
  3255. $spatial = false;
  3256. if (strlen($command) > 2) {
  3257. if (substr($command, 0, 1) == 'n') {
  3258. $negate = true;
  3259. $command = substr($command, 1);
  3260. }
  3261. if (substr($command, 0, 1) == 's') {
  3262. $spatial = true;
  3263. $command = substr($command, 1);
  3264. }
  3265. }
  3266. if (count($parts) == 3 || (count($parts) == 2 && in_array($command, ['ic', 'is', 'iv']))) {
  3267. if ($spatial) {
  3268. if (in_array($command, ['co', 'cr', 'di', 'eq', 'in', 'ov', 'to', 'wi', 'ic', 'is', 'iv'])) {
  3269. $condition = new SpatialCondition($field, $command, $parts[2]);
  3270. }
  3271. } else {
  3272. if (in_array($command, ['cs', 'sw', 'ew', 'eq', 'lt', 'le', 'ge', 'gt', 'bt', 'in', 'is'])) {
  3273. $condition = new ColumnCondition($field, $command, $parts[2]);
  3274. }
  3275. }
  3276. }
  3277. if ($negate) {
  3278. $condition = $condition->_not();
  3279. }
  3280. return $condition;
  3281. }
  3282. }
  3283. // file: src/Tqdev/PhpCrudApi/Record/Condition/NoCondition.php
  3284. class NoCondition extends Condition
  3285. {
  3286. public function _and(Condition $condition): Condition
  3287. {
  3288. return $condition;
  3289. }
  3290. public function _or(Condition $condition): Condition
  3291. {
  3292. return $condition;
  3293. }
  3294. public function _not(): Condition
  3295. {
  3296. return $this;
  3297. }
  3298. }
  3299. // file: src/Tqdev/PhpCrudApi/Record/Condition/NotCondition.php
  3300. class NotCondition extends Condition
  3301. {
  3302. private $condition;
  3303. public function __construct(Condition $condition)
  3304. {
  3305. $this->condition = $condition;
  3306. }
  3307. public function getCondition(): Condition
  3308. {
  3309. return $this->condition;
  3310. }
  3311. }
  3312. // file: src/Tqdev/PhpCrudApi/Record/Condition/OrCondition.php
  3313. class OrCondition extends Condition
  3314. {
  3315. private $conditions;
  3316. public function __construct(Condition $condition1, Condition $condition2)
  3317. {
  3318. $this->conditions = [$condition1, $condition2];
  3319. }
  3320. public function _or(Condition $condition): Condition
  3321. {
  3322. if ($condition instanceof NoCondition) {
  3323. return $this;
  3324. }
  3325. $this->conditions[] = $condition;
  3326. return $this;
  3327. }
  3328. public function getConditions(): array
  3329. {
  3330. return $this->conditions;
  3331. }
  3332. public static function fromArray(array $conditions): Condition
  3333. {
  3334. $condition = new NoCondition();
  3335. foreach ($conditions as $c) {
  3336. $condition = $condition->_or($c);
  3337. }
  3338. return $condition;
  3339. }
  3340. }
  3341. // file: src/Tqdev/PhpCrudApi/Record/Condition/SpatialCondition.php
  3342. class SpatialCondition extends ColumnCondition
  3343. {
  3344. }
  3345. // file: src/Tqdev/PhpCrudApi/Record/Document/ErrorDocument.php
  3346. class ErrorDocument implements \JsonSerializable
  3347. {
  3348. public $code;
  3349. public $message;
  3350. public $details;
  3351. public function __construct(ErrorCode $errorCode, String $argument, $details)
  3352. {
  3353. $this->code = $errorCode->getCode();
  3354. $this->message = $errorCode->getMessage($argument);
  3355. $this->details = $details;
  3356. }
  3357. public function getCode(): int
  3358. {
  3359. return $this->code;
  3360. }
  3361. public function getMessage(): String
  3362. {
  3363. return $this->message;
  3364. }
  3365. public function serialize()
  3366. {
  3367. return [
  3368. 'code' => $this->code,
  3369. 'message' => $this->message,
  3370. 'details' => $this->details,
  3371. ];
  3372. }
  3373. public function jsonSerialize()
  3374. {
  3375. return array_filter($this->serialize());
  3376. }
  3377. }
  3378. // file: src/Tqdev/PhpCrudApi/Record/Document/ListDocument.php
  3379. class ListDocument implements \JsonSerializable
  3380. {
  3381. private $records;
  3382. private $results;
  3383. public function __construct(array $records, int $results)
  3384. {
  3385. $this->records = $records;
  3386. $this->results = $results;
  3387. }
  3388. public function getRecords(): array
  3389. {
  3390. return $this->records;
  3391. }
  3392. public function getResults(): int
  3393. {
  3394. return $this->results;
  3395. }
  3396. public function serialize()
  3397. {
  3398. return [
  3399. 'records' => $this->records,
  3400. 'results' => $this->results,
  3401. ];
  3402. }
  3403. public function jsonSerialize()
  3404. {
  3405. return array_filter($this->serialize(), function ($v) {
  3406. return $v !== 0;
  3407. });
  3408. }
  3409. }
  3410. // file: src/Tqdev/PhpCrudApi/Record/ColumnIncluder.php
  3411. class ColumnIncluder
  3412. {
  3413. private function isMandatory(String $tableName, String $columnName, array $params): bool
  3414. {
  3415. return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']);
  3416. }
  3417. private function select(String $tableName, bool $primaryTable, array $params, String $paramName,
  3418. array $columnNames, bool $include): array{
  3419. if (!isset($params[$paramName])) {
  3420. return $columnNames;
  3421. }
  3422. $columns = array();
  3423. foreach (explode(',', $params[$paramName][0]) as $columnName) {
  3424. $columns[$columnName] = true;
  3425. }
  3426. $result = array();
  3427. foreach ($columnNames as $columnName) {
  3428. $match = isset($columns['*.*']);
  3429. if (!$match) {
  3430. $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]);
  3431. }
  3432. if ($primaryTable && !$match) {
  3433. $match = isset($columns['*']) || isset($columns[$columnName]);
  3434. }
  3435. if ($match) {
  3436. if ($include || $this->isMandatory($tableName, $columnName, $params)) {
  3437. $result[] = $columnName;
  3438. }
  3439. } else {
  3440. if (!$include || $this->isMandatory($tableName, $columnName, $params)) {
  3441. $result[] = $columnName;
  3442. }
  3443. }
  3444. }
  3445. return $result;
  3446. }
  3447. public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array
  3448. {
  3449. $tableName = $table->getName();
  3450. $results = $table->columnNames();
  3451. $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true);
  3452. $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false);
  3453. return $results;
  3454. }
  3455. public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array
  3456. {
  3457. $results = array();
  3458. $columnNames = $this->getNames($table, $primaryTable, $params);
  3459. foreach ($columnNames as $columnName) {
  3460. if (property_exists($record, $columnName)) {
  3461. $results[$columnName] = $record->$columnName;
  3462. }
  3463. }
  3464. return $results;
  3465. }
  3466. }
  3467. // file: src/Tqdev/PhpCrudApi/Record/ErrorCode.php
  3468. class ErrorCode
  3469. {
  3470. private $code;
  3471. private $message;
  3472. private $status;
  3473. const ERROR_NOT_FOUND = 9999;
  3474. const ROUTE_NOT_FOUND = 1000;
  3475. const TABLE_NOT_FOUND = 1001;
  3476. const ARGUMENT_COUNT_MISMATCH = 1002;
  3477. const RECORD_NOT_FOUND = 1003;
  3478. const ORIGIN_FORBIDDEN = 1004;
  3479. const COLUMN_NOT_FOUND = 1005;
  3480. const TABLE_ALREADY_EXISTS = 1006;
  3481. const COLUMN_ALREADY_EXISTS = 1007;
  3482. const HTTP_MESSAGE_NOT_READABLE = 1008;
  3483. const DUPLICATE_KEY_EXCEPTION = 1009;
  3484. const DATA_INTEGRITY_VIOLATION = 1010;
  3485. const AUTHORIZATION_REQUIRED = 1011;
  3486. const ACCESS_DENIED = 1012;
  3487. const INPUT_VALIDATION_FAILED = 1013;
  3488. const OPERATION_FORBIDDEN = 1014;
  3489. private $values = [
  3490. 9999 => ["%s", Response::INTERNAL_SERVER_ERROR],
  3491. 1000 => ["Route '%s' not found", Response::NOT_FOUND],
  3492. 1001 => ["Table '%s' not found", Response::NOT_FOUND],
  3493. 1002 => ["Argument count mismatch in '%s'", Response::UNPROCESSABLE_ENTITY],
  3494. 1003 => ["Record '%s' not found", Response::NOT_FOUND],
  3495. 1004 => ["Origin '%s' is forbidden", Response::FORBIDDEN],
  3496. 1005 => ["Column '%s' not found", Response::NOT_FOUND],
  3497. 1006 => ["Table '%s' already exists", Response::CONFLICT],
  3498. 1007 => ["Column '%s' already exists", Response::CONFLICT],
  3499. 1008 => ["Cannot read HTTP message", Response::UNPROCESSABLE_ENTITY],
  3500. 1009 => ["Duplicate key exception", Response::CONFLICT],
  3501. 1010 => ["Data integrity violation", Response::CONFLICT],
  3502. 1011 => ["Authorization required", Response::UNAUTHORIZED],
  3503. 1012 => ["Access denied for '%s'", Response::FORBIDDEN],
  3504. 1013 => ["Input validation failed for '%s'", Response::UNPROCESSABLE_ENTITY],
  3505. 1014 => ["Operation forbidden", Response::FORBIDDEN],
  3506. ];
  3507. public function __construct(int $code)
  3508. {
  3509. if (!isset($this->values[$code])) {
  3510. $code = 9999;
  3511. }
  3512. $this->code = $code;
  3513. $this->message = $this->values[$code][0];
  3514. $this->status = $this->values[$code][1];
  3515. }
  3516. public function getCode(): int
  3517. {
  3518. return $this->code;
  3519. }
  3520. public function getMessage(String $argument): String
  3521. {
  3522. return sprintf($this->message, $argument);
  3523. }
  3524. public function getStatus(): int
  3525. {
  3526. return $this->status;
  3527. }
  3528. }
  3529. // file: src/Tqdev/PhpCrudApi/Record/FilterInfo.php
  3530. class FilterInfo
  3531. {
  3532. private function addConditionFromFilterPath(PathTree $conditions, array $path, ReflectedTable $table, array $params)
  3533. {
  3534. $key = 'filter' . implode('', $path);
  3535. if (isset($params[$key])) {
  3536. foreach ($params[$key] as $filter) {
  3537. $condition = Condition::fromString($table, $filter);
  3538. if ($condition != null) {
  3539. $conditions->put($path, $condition);
  3540. }
  3541. }
  3542. }
  3543. }
  3544. private function getConditionsAsPathTree(ReflectedTable $table, array $params): PathTree
  3545. {
  3546. $conditions = new PathTree();
  3547. $this->addConditionFromFilterPath($conditions, [], $table, $params);
  3548. for ($n = ord('0'); $n <= ord('9'); $n++) {
  3549. $this->addConditionFromFilterPath($conditions, [chr($n)], $table, $params);
  3550. for ($l = ord('a'); $l <= ord('f'); $l++) {
  3551. $this->addConditionFromFilterPath($conditions, [chr($n), chr($l)], $table, $params);
  3552. }
  3553. }
  3554. return $conditions;
  3555. }
  3556. private function combinePathTreeOfConditions(PathTree $tree): Condition
  3557. {
  3558. $andConditions = $tree->getValues();
  3559. $and = AndCondition::fromArray($andConditions);
  3560. $orConditions = [];
  3561. foreach ($tree->getKeys() as $p) {
  3562. $orConditions[] = $this->combinePathTreeOfConditions($tree->get($p));
  3563. }
  3564. $or = OrCondition::fromArray($orConditions);
  3565. return $and->_and($or);
  3566. }
  3567. public function getCombinedConditions(ReflectedTable $table, array $params): Condition
  3568. {
  3569. return $this->combinePathTreeOfConditions($this->getConditionsAsPathTree($table, $params));
  3570. }
  3571. }
  3572. // file: src/Tqdev/PhpCrudApi/Record/HabtmValues.php
  3573. class HabtmValues
  3574. {
  3575. public $pkValues;
  3576. public $fkValues;
  3577. public function __construct(array $pkValues, array $fkValues)
  3578. {
  3579. $this->pkValues = $pkValues;
  3580. $this->fkValues = $fkValues;
  3581. }
  3582. }
  3583. // file: src/Tqdev/PhpCrudApi/Record/OrderingInfo.php
  3584. class OrderingInfo
  3585. {
  3586. public function getColumnOrdering(ReflectedTable $table, array $params): array
  3587. {
  3588. $fields = array();
  3589. if (isset($params['order'])) {
  3590. foreach ($params['order'] as $order) {
  3591. $parts = explode(',', $order, 3);
  3592. $columnName = $parts[0];
  3593. if (!$table->exists($columnName)) {
  3594. continue;
  3595. }
  3596. $ascending = 'ASC';
  3597. if (count($parts) > 1) {
  3598. if (substr(strtoupper($parts[1]), 0, 4) == "DESC") {
  3599. $ascending = 'DESC';
  3600. }
  3601. }
  3602. $fields[] = [$columnName, $ascending];
  3603. }
  3604. }
  3605. if (count($fields) == 0) {
  3606. $pk = $table->getPk();
  3607. if ($pk) {
  3608. $fields[] = [$pk->getName(), 'ASC'];
  3609. } else {
  3610. foreach ($table->columnNames() as $columnName) {
  3611. $fields[] = [$columnName, 'ASC'];
  3612. }
  3613. }
  3614. }
  3615. return $fields;
  3616. }
  3617. }
  3618. // file: src/Tqdev/PhpCrudApi/Record/PaginationInfo.php
  3619. class PaginationInfo
  3620. {
  3621. public $DEFAULT_PAGE_SIZE = 20;
  3622. public function hasPage(array $params): bool
  3623. {
  3624. return isset($params['page']);
  3625. }
  3626. public function getPageOffset(array $params): int
  3627. {
  3628. $offset = 0;
  3629. $pageSize = $this->getPageSize($params);
  3630. if (isset($params['page'])) {
  3631. foreach ($params['page'] as $page) {
  3632. $parts = explode(',', $page, 2);
  3633. $page = intval($parts[0]) - 1;
  3634. $offset = $page * $pageSize;
  3635. }
  3636. }
  3637. return $offset;
  3638. }
  3639. public function getPageSize(array $params): int
  3640. {
  3641. $pageSize = $this->DEFAULT_PAGE_SIZE;
  3642. if (isset($params['page'])) {
  3643. foreach ($params['page'] as $page) {
  3644. $parts = explode(',', $page, 2);
  3645. if (count($parts) > 1) {
  3646. $pageSize = intval($parts[1]);
  3647. }
  3648. }
  3649. }
  3650. return $pageSize;
  3651. }
  3652. public function getResultSize(array $params): int
  3653. {
  3654. $numberOfRows = -1;
  3655. if (isset($params['size'])) {
  3656. foreach ($params['size'] as $size) {
  3657. $numberOfRows = intval($size);
  3658. }
  3659. }
  3660. return $numberOfRows;
  3661. }
  3662. }
  3663. // file: src/Tqdev/PhpCrudApi/Record/PathTree.php
  3664. class PathTree implements \JsonSerializable
  3665. {
  3666. const WILDCARD = '*';
  3667. private $tree;
  3668. public function __construct( /* object */&$tree = null)
  3669. {
  3670. if (!$tree) {
  3671. $tree = $this->newTree();
  3672. }
  3673. $this->tree = &$tree;
  3674. }
  3675. public function newTree()
  3676. {
  3677. return (object) ['values' => [], 'branches' => (object) []];
  3678. }
  3679. public function getKeys(): array
  3680. {
  3681. $branches = (array) $this->tree->branches;
  3682. return array_keys($branches);
  3683. }
  3684. public function getValues(): array
  3685. {
  3686. return $this->tree->values;
  3687. }
  3688. public function get(String $key): PathTree
  3689. {
  3690. if (!isset($this->tree->branches->$key)) {
  3691. return null;
  3692. }
  3693. return new PathTree($this->tree->branches->$key);
  3694. }
  3695. public function put(array $path, $value)
  3696. {
  3697. $tree = &$this->tree;
  3698. foreach ($path as $key) {
  3699. if (!isset($tree->branches->$key)) {
  3700. $tree->branches->$key = $this->newTree();
  3701. }
  3702. $tree = &$tree->branches->$key;
  3703. }
  3704. $tree->values[] = $value;
  3705. }
  3706. public function match(array $path): array
  3707. {
  3708. $star = self::WILDCARD;
  3709. $tree = &$this->tree;
  3710. foreach ($path as $key) {
  3711. if (isset($tree->branches->$key)) {
  3712. $tree = &$tree->branches->$key;
  3713. } else if (isset($tree->branches->$star)) {
  3714. $tree = &$tree->branches->$star;
  3715. } else {
  3716. return [];
  3717. }
  3718. }
  3719. return $tree->values;
  3720. }
  3721. public static function fromJson( /* object */$tree): PathTree
  3722. {
  3723. return new PathTree($tree);
  3724. }
  3725. public function jsonSerialize()
  3726. {
  3727. return $this->tree;
  3728. }
  3729. }
  3730. // file: src/Tqdev/PhpCrudApi/Record/RecordService.php
  3731. class RecordService
  3732. {
  3733. private $db;
  3734. private $reflection;
  3735. private $columns;
  3736. private $joiner;
  3737. private $filters;
  3738. private $ordering;
  3739. private $pagination;
  3740. public function __construct(GenericDB $db, ReflectionService $reflection)
  3741. {
  3742. $this->db = $db;
  3743. $this->reflection = $reflection;
  3744. $this->columns = new ColumnIncluder();
  3745. $this->joiner = new RelationJoiner($reflection, $this->columns);
  3746. $this->filters = new FilterInfo();
  3747. $this->ordering = new OrderingInfo();
  3748. $this->pagination = new PaginationInfo();
  3749. }
  3750. private function sanitizeRecord(String $tableName, /* object */ $record, String $id)
  3751. {
  3752. $keyset = array_keys((array) $record);
  3753. foreach ($keyset as $key) {
  3754. if (!$this->reflection->getTable($tableName)->exists($key)) {
  3755. unset($record->$key);
  3756. }
  3757. }
  3758. if ($id != '') {
  3759. $pk = $this->reflection->getTable($tableName)->getPk();
  3760. foreach ($this->reflection->getTable($tableName)->columnNames() as $key) {
  3761. $field = $this->reflection->getTable($tableName)->get($key);
  3762. if ($field->getName() == $pk->getName()) {
  3763. unset($record->$key);
  3764. }
  3765. }
  3766. }
  3767. }
  3768. public function exists(String $table): bool
  3769. {
  3770. return $this->reflection->hasTable($table);
  3771. }
  3772. public function create(String $tableName, /* object */ $record, array $params)
  3773. {
  3774. $this->sanitizeRecord($tableName, $record, '');
  3775. $table = $this->reflection->getTable($tableName);
  3776. $columnValues = $this->columns->getValues($table, true, $record, $params);
  3777. return $this->db->createSingle($table, $columnValues);
  3778. }
  3779. public function read(String $tableName, String $id, array $params) /*: ?object*/
  3780. {
  3781. $table = $this->reflection->getTable($tableName);
  3782. $this->joiner->addMandatoryColumns($table, $params);
  3783. $columnNames = $this->columns->getNames($table, true, $params);
  3784. $record = $this->db->selectSingle($table, $columnNames, $id);
  3785. if ($record == null) {
  3786. return null;
  3787. }
  3788. $records = array($record);
  3789. $this->joiner->addJoins($table, $records, $params, $this->db);
  3790. return $records[0];
  3791. }
  3792. public function update(String $tableName, String $id, /* object */ $record, array $params)
  3793. {
  3794. $this->sanitizeRecord($tableName, $record, $id);
  3795. $table = $this->reflection->getTable($tableName);
  3796. $columnValues = $this->columns->getValues($table, true, $record, $params);
  3797. return $this->db->updateSingle($table, $columnValues, $id);
  3798. }
  3799. public function delete(String $tableName, String $id, array $params)
  3800. {
  3801. $table = $this->reflection->getTable($tableName);
  3802. return $this->db->deleteSingle($table, $id);
  3803. }
  3804. public function increment(String $tableName, String $id, /* object */ $record, array $params)
  3805. {
  3806. $this->sanitizeRecord($tableName, $record, $id);
  3807. $table = $this->reflection->getTable($tableName);
  3808. $columnValues = $this->columns->getValues($table, true, $record, $params);
  3809. return $this->db->incrementSingle($table, $columnValues, $id);
  3810. }
  3811. public function _list(String $tableName, array $params): ListDocument
  3812. {
  3813. $table = $this->reflection->getTable($tableName);
  3814. $this->joiner->addMandatoryColumns($table, $params);
  3815. $columnNames = $this->columns->getNames($table, true, $params);
  3816. $condition = $this->filters->getCombinedConditions($table, $params);
  3817. $columnOrdering = $this->ordering->getColumnOrdering($table, $params);
  3818. if (!$this->pagination->hasPage($params)) {
  3819. $offset = 0;
  3820. $limit = $this->pagination->getResultSize($params);
  3821. $count = 0;
  3822. } else {
  3823. $offset = $this->pagination->getPageOffset($params);
  3824. $limit = $this->pagination->getPageSize($params);
  3825. $count = $this->db->selectCount($table, $condition);
  3826. }
  3827. $records = $this->db->selectAll($table, $columnNames, $condition, $columnOrdering, $offset, $limit);
  3828. $this->joiner->addJoins($table, $records, $params, $this->db);
  3829. return new ListDocument($records, $count);
  3830. }
  3831. }
  3832. // file: src/Tqdev/PhpCrudApi/Record/RelationJoiner.php
  3833. class RelationJoiner
  3834. {
  3835. private $reflection;
  3836. private $columns;
  3837. public function __construct(ReflectionService $reflection, ColumnIncluder $columns)
  3838. {
  3839. $this->reflection = $reflection;
  3840. $this->columns = $columns;
  3841. }
  3842. public function addMandatoryColumns(ReflectedTable $table, array &$params) /*: void*/
  3843. {
  3844. if (!isset($params['join']) || !isset($params['include'])) {
  3845. return;
  3846. }
  3847. $params['mandatory'] = array();
  3848. foreach ($params['join'] as $tableNames) {
  3849. $t1 = $table;
  3850. foreach (explode(',', $tableNames) as $tableName) {
  3851. if (!$this->reflection->hasTable($tableName)) {
  3852. continue;
  3853. }
  3854. $t2 = $this->reflection->getTable($tableName);
  3855. $fks1 = $t1->getFksTo($t2->getName());
  3856. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  3857. if ($t3 != null || count($fks1) > 0) {
  3858. $params['mandatory'][] = $t2->getName() . '.' . $t2->getPk()->getName();
  3859. }
  3860. foreach ($fks1 as $fk) {
  3861. $params['mandatory'][] = $t1->getName() . '.' . $fk->getName();
  3862. }
  3863. $fks2 = $t2->getFksTo($t1->getName());
  3864. if ($t3 != null || count($fks2) > 0) {
  3865. $params['mandatory'][] = $t1->getName() . '.' . $t1->getPk()->getName();
  3866. }
  3867. foreach ($fks2 as $fk) {
  3868. $params['mandatory'][] = $t2->getName() . '.' . $fk->getName();
  3869. }
  3870. $t1 = $t2;
  3871. }
  3872. }
  3873. }
  3874. private function getJoinsAsPathTree(array $params): PathTree
  3875. {
  3876. $joins = new PathTree();
  3877. if (isset($params['join'])) {
  3878. foreach ($params['join'] as $tableNames) {
  3879. $path = array();
  3880. foreach (explode(',', $tableNames) as $tableName) {
  3881. $t = $this->reflection->getTable($tableName);
  3882. if ($t != null) {
  3883. $path[] = $t->getName();
  3884. }
  3885. }
  3886. $joins->put($path, true);
  3887. }
  3888. }
  3889. return $joins;
  3890. }
  3891. public function addJoins(ReflectedTable $table, array &$records, array $params, GenericDB $db) /*: void*/
  3892. {
  3893. $joins = $this->getJoinsAsPathTree($params);
  3894. $this->addJoinsForTables($table, $joins, $records, $params, $db);
  3895. }
  3896. private function hasAndBelongsToMany(ReflectedTable $t1, ReflectedTable $t2) /*: ?ReflectedTable*/
  3897. {
  3898. foreach ($this->reflection->getTableNames() as $tableName) {
  3899. $t3 = $this->reflection->getTable($tableName);
  3900. if (count($t3->getFksTo($t1->getName())) > 0 && count($t3->getFksTo($t2->getName())) > 0) {
  3901. return $t3;
  3902. }
  3903. }
  3904. return null;
  3905. }
  3906. private function addJoinsForTables(ReflectedTable $t1, PathTree $joins, array &$records, array $params, GenericDB $db)
  3907. {
  3908. foreach ($joins->getKeys() as $t2Name) {
  3909. $t2 = $this->reflection->getTable($t2Name);
  3910. $belongsTo = count($t1->getFksTo($t2->getName())) > 0;
  3911. $hasMany = count($t2->getFksTo($t1->getName())) > 0;
  3912. $t3 = $this->hasAndBelongsToMany($t1, $t2);
  3913. $hasAndBelongsToMany = ($t3 != null);
  3914. $newRecords = array();
  3915. $fkValues = null;
  3916. $pkValues = null;
  3917. $habtmValues = null;
  3918. if ($belongsTo) {
  3919. $fkValues = $this->getFkEmptyValues($t1, $t2, $records);
  3920. $this->addFkRecords($t2, $fkValues, $params, $db, $newRecords);
  3921. }
  3922. if ($hasMany) {
  3923. $pkValues = $this->getPkEmptyValues($t1, $records);
  3924. $this->addPkRecords($t1, $t2, $pkValues, $params, $db, $newRecords);
  3925. }
  3926. if ($hasAndBelongsToMany) {
  3927. $habtmValues = $this->getHabtmEmptyValues($t1, $t2, $t3, $db, $records);
  3928. $this->addFkRecords($t2, $habtmValues->fkValues, $params, $db, $newRecords);
  3929. }
  3930. $this->addJoinsForTables($t2, $joins->get($t2Name), $newRecords, $params, $db);
  3931. if ($fkValues != null) {
  3932. $this->fillFkValues($t2, $newRecords, $fkValues);
  3933. $this->setFkValues($t1, $t2, $records, $fkValues);
  3934. }
  3935. if ($pkValues != null) {
  3936. $this->fillPkValues($t1, $t2, $newRecords, $pkValues);
  3937. $this->setPkValues($t1, $t2, $records, $pkValues);
  3938. }
  3939. if ($habtmValues != null) {
  3940. $this->fillFkValues($t2, $newRecords, $habtmValues->fkValues);
  3941. $this->setHabtmValues($t1, $t3, $records, $habtmValues);
  3942. }
  3943. }
  3944. }
  3945. private function getFkEmptyValues(ReflectedTable $t1, ReflectedTable $t2, array $records): array
  3946. {
  3947. $fkValues = array();
  3948. $fks = $t1->getFksTo($t2->getName());
  3949. foreach ($fks as $fk) {
  3950. $fkName = $fk->getName();
  3951. foreach ($records as $record) {
  3952. if (isset($record[$fkName])) {
  3953. $fkValue = $record[$fkName];
  3954. $fkValues[$fkValue] = null;
  3955. }
  3956. }
  3957. }
  3958. return $fkValues;
  3959. }
  3960. private function addFkRecords(ReflectedTable $t2, array $fkValues, array $params, GenericDB $db, array &$records) /*: void*/
  3961. {
  3962. $columnNames = $this->columns->getNames($t2, false, $params);
  3963. $fkIds = array_keys($fkValues);
  3964. foreach ($db->selectMultiple($t2, $columnNames, $fkIds) as $record) {
  3965. $records[] = $record;
  3966. }
  3967. }
  3968. private function fillFkValues(ReflectedTable $t2, array $fkRecords, array &$fkValues) /*: void*/
  3969. {
  3970. $pkName = $t2->getPk()->getName();
  3971. foreach ($fkRecords as $fkRecord) {
  3972. $pkValue = $fkRecord[$pkName];
  3973. $fkValues[$pkValue] = $fkRecord;
  3974. }
  3975. }
  3976. private function setFkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $fkValues) /*: void*/
  3977. {
  3978. $fks = $t1->getFksTo($t2->getName());
  3979. foreach ($fks as $fk) {
  3980. $fkName = $fk->getName();
  3981. foreach ($records as $i => $record) {
  3982. if (isset($record[$fkName])) {
  3983. $key = $record[$fkName];
  3984. $records[$i][$fkName] = $fkValues[$key];
  3985. }
  3986. }
  3987. }
  3988. }
  3989. private function getPkEmptyValues(ReflectedTable $t1, array $records): array
  3990. {
  3991. $pkValues = array();
  3992. $pkName = $t1->getPk()->getName();
  3993. foreach ($records as $record) {
  3994. $key = $record[$pkName];
  3995. $pkValues[$key] = array();
  3996. }
  3997. return $pkValues;
  3998. }
  3999. private function addPkRecords(ReflectedTable $t1, ReflectedTable $t2, array $pkValues, array $params, GenericDB $db, array &$records) /*: void*/
  4000. {
  4001. $fks = $t2->getFksTo($t1->getName());
  4002. $columnNames = $this->columns->getNames($t2, false, $params);
  4003. $pkValueKeys = implode(',', array_keys($pkValues));
  4004. $conditions = array();
  4005. foreach ($fks as $fk) {
  4006. $conditions[] = new ColumnCondition($fk, 'in', $pkValueKeys);
  4007. }
  4008. $condition = OrCondition::fromArray($conditions);
  4009. foreach ($db->selectAllUnordered($t2, $columnNames, $condition) as $record) {
  4010. $records[] = $record;
  4011. }
  4012. }
  4013. private function fillPkValues(ReflectedTable $t1, ReflectedTable $t2, array $pkRecords, array &$pkValues) /*: void*/
  4014. {
  4015. $fks = $t2->getFksTo($t1->getName());
  4016. foreach ($fks as $fk) {
  4017. $fkName = $fk->getName();
  4018. foreach ($pkRecords as $pkRecord) {
  4019. $key = $pkRecord[$fkName];
  4020. if (isset($pkValues[$key])) {
  4021. $pkValues[$key][] = $pkRecord;
  4022. }
  4023. }
  4024. }
  4025. }
  4026. private function setPkValues(ReflectedTable $t1, ReflectedTable $t2, array &$records, array $pkValues) /*: void*/
  4027. {
  4028. $pkName = $t1->getPk()->getName();
  4029. $t2Name = $t2->getName();
  4030. foreach ($records as $i => $record) {
  4031. $key = $record[$pkName];
  4032. $records[$i][$t2Name] = $pkValues[$key];
  4033. }
  4034. }
  4035. private function getHabtmEmptyValues(ReflectedTable $t1, ReflectedTable $t2, ReflectedTable $t3, GenericDB $db, array $records): HabtmValues
  4036. {
  4037. $pkValues = $this->getPkEmptyValues($t1, $records);
  4038. $fkValues = array();
  4039. $fk1 = $t3->getFksTo($t1->getName())[0];
  4040. $fk2 = $t3->getFksTo($t2->getName())[0];
  4041. $fk1Name = $fk1->getName();
  4042. $fk2Name = $fk2->getName();
  4043. $columnNames = array($fk1Name, $fk2Name);
  4044. $pkIds = implode(',', array_keys($pkValues));
  4045. $condition = new ColumnCondition($t3->get($fk1Name), 'in', $pkIds);
  4046. $records = $db->selectAllUnordered($t3, $columnNames, $condition);
  4047. foreach ($records as $record) {
  4048. $val1 = $record[$fk1Name];
  4049. $val2 = $record[$fk2Name];
  4050. $pkValues[$val1][] = $val2;
  4051. $fkValues[$val2] = null;
  4052. }
  4053. return new HabtmValues($pkValues, $fkValues);
  4054. }
  4055. private function setHabtmValues(ReflectedTable $t1, ReflectedTable $t3, array &$records, HabtmValues $habtmValues) /*: void*/
  4056. {
  4057. $pkName = $t1->getPk()->getName();
  4058. $t3Name = $t3->getName();
  4059. foreach ($records as $i => $record) {
  4060. $key = $record[$pkName];
  4061. $val = array();
  4062. $fks = $habtmValues->pkValues[$key];
  4063. foreach ($fks as $fk) {
  4064. $val[] = $habtmValues->fkValues[$fk];
  4065. }
  4066. $records[$i][$t3Name] = $val;
  4067. }
  4068. }
  4069. }
  4070. // file: src/Tqdev/PhpCrudApi/Record/RequestUtils.php
  4071. class RequestUtils
  4072. {
  4073. private $reflection;
  4074. public function __construct(ReflectionService $reflection)
  4075. {
  4076. $this->reflection = $reflection;
  4077. }
  4078. public function getOperation(Request $request): String
  4079. {
  4080. $method = $request->getMethod();
  4081. $path = $request->getPathSegment(1);
  4082. $hasPk = $request->getPathSegment(3) != '';
  4083. switch ($path) {
  4084. case 'openapi':
  4085. return 'document';
  4086. case 'columns':
  4087. return $method == 'get' ? 'reflect' : 'remodel';
  4088. case 'records':
  4089. switch ($method) {
  4090. case 'POST':
  4091. return 'create';
  4092. case 'GET':
  4093. return $hasPk ? 'read' : 'list';
  4094. case 'PUT':
  4095. return 'update';
  4096. case 'DELETE':
  4097. return 'delete';
  4098. case 'PATCH':
  4099. return 'increment';
  4100. }
  4101. }
  4102. return 'unknown';
  4103. }
  4104. private function getJoinTables(String $tableName, array $parameters): array
  4105. {
  4106. $uniqueTableNames = array();
  4107. $uniqueTableNames[$tableName] = true;
  4108. if (isset($parameters['join'])) {
  4109. foreach ($parameters['join'] as $parameter) {
  4110. $tableNames = explode(',', trim($parameter));
  4111. foreach ($tableNames as $tableName) {
  4112. $uniqueTableNames[$tableName] = true;
  4113. }
  4114. }
  4115. }
  4116. return array_keys($uniqueTableNames);
  4117. }
  4118. public function getTableNames(Request $request): array
  4119. {
  4120. $path = $request->getPathSegment(1);
  4121. $tableName = $request->getPathSegment(2);
  4122. $allTableNames = $this->reflection->getTableNames();
  4123. switch ($path) {
  4124. case 'openapi':
  4125. return $allTableNames;
  4126. case 'columns':
  4127. return $tableName ? [$tableName] : $allTableNames;
  4128. case 'records':
  4129. return $this->getJoinTables($tableName, $request->getParams());
  4130. }
  4131. return $allTableNames;
  4132. }
  4133. }
  4134. // file: src/Tqdev/PhpCrudApi/Api.php
  4135. class Api
  4136. {
  4137. private $router;
  4138. private $responder;
  4139. private $debug;
  4140. public function __construct(Config $config)
  4141. {
  4142. $db = new GenericDB(
  4143. $config->getDriver(),
  4144. $config->getAddress(),
  4145. $config->getPort(),
  4146. $config->getDatabase(),
  4147. $config->getUsername(),
  4148. $config->getPassword()
  4149. );
  4150. $cache = CacheFactory::create($config);
  4151. $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
  4152. $responder = new Responder();
  4153. $router = new SimpleRouter($responder, $cache, $config->getCacheTime());
  4154. foreach ($config->getMiddlewares() as $middleware => $properties) {
  4155. switch ($middleware) {
  4156. case 'cors':
  4157. new CorsMiddleware($router, $responder, $properties);
  4158. break;
  4159. case 'firewall':
  4160. new FirewallMiddleware($router, $responder, $properties);
  4161. break;
  4162. case 'basicAuth':
  4163. new BasicAuthMiddleware($router, $responder, $properties);
  4164. break;
  4165. case 'jwtAuth':
  4166. new JwtAuthMiddleware($router, $responder, $properties);
  4167. break;
  4168. case 'validation':
  4169. new ValidationMiddleware($router, $responder, $properties, $reflection);
  4170. break;
  4171. case 'sanitation':
  4172. new SanitationMiddleware($router, $responder, $properties, $reflection);
  4173. break;
  4174. case 'authorization':
  4175. new AuthorizationMiddleware($router, $responder, $properties, $reflection);
  4176. break;
  4177. }
  4178. }
  4179. foreach ($config->getControllers() as $controller) {
  4180. switch ($controller) {
  4181. case 'records':
  4182. $records = new RecordService($db, $reflection);
  4183. new RecordController($router, $responder, $records);
  4184. break;
  4185. case 'columns':
  4186. $definition = new DefinitionService($db, $reflection);
  4187. new ColumnController($router, $responder, $reflection, $definition);
  4188. break;
  4189. case 'cache':
  4190. new CacheController($router, $responder, $cache);
  4191. break;
  4192. case 'openapi':
  4193. $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
  4194. new OpenApiController($router, $responder, $openApi);
  4195. break;
  4196. }
  4197. }
  4198. $this->router = $router;
  4199. $this->responder = $responder;
  4200. $this->debug = $config->getDebug();
  4201. }
  4202. public function handle(Request $request): Response
  4203. {
  4204. $response = null;
  4205. try {
  4206. $response = $this->router->route($request);
  4207. } catch (\Throwable $e) {
  4208. if ($e instanceof \PDOException) {
  4209. if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
  4210. return $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
  4211. }
  4212. if (strpos(strtolower($e->getMessage()), 'default value') !== false) {
  4213. return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4214. }
  4215. if (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
  4216. return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4217. }
  4218. if (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
  4219. return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
  4220. }
  4221. }
  4222. $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
  4223. if ($this->debug) {
  4224. $response->addHeader('X-Debug-Info', 'Exception in ' . $e->getFile() . ' on line ' . $e->getLine());
  4225. }
  4226. }
  4227. return $response;
  4228. }
  4229. }
  4230. // file: src/Tqdev/PhpCrudApi/Config.php
  4231. class Config
  4232. {
  4233. private $values = [
  4234. 'driver' => null,
  4235. 'address' => 'localhost',
  4236. 'port' => null,
  4237. 'username' => null,
  4238. 'password' => null,
  4239. 'database' => null,
  4240. 'middlewares' => 'cors',
  4241. 'controllers' => 'records,openapi',
  4242. 'cacheType' => 'TempFile',
  4243. 'cachePath' => '',
  4244. 'cacheTime' => 10,
  4245. 'debug' => false,
  4246. 'openApiBase' => '{"info":{"title":"JAVA-CRUD-API","version":"1.0.0"}}',
  4247. ];
  4248. private function getDefaultDriver(array $values): String
  4249. {
  4250. if (isset($values['driver'])) {
  4251. return $values['driver'];
  4252. }
  4253. return 'mysql';
  4254. }
  4255. private function getDefaultPort(String $driver): int
  4256. {
  4257. switch ($driver) {
  4258. case 'mysql':return 3306;
  4259. case 'pgsql':return 5432;
  4260. case 'sqlsrv':return 1433;
  4261. }
  4262. }
  4263. private function getDefaultAddress(String $driver): String
  4264. {
  4265. switch ($driver) {
  4266. case 'mysql':return 'localhost';
  4267. case 'pgsql':return 'localhost';
  4268. case 'sqlsrv':return 'localhost';
  4269. }
  4270. }
  4271. private function getDriverDefaults(String $driver): array
  4272. {
  4273. return [
  4274. 'driver' => $driver,
  4275. 'address' => $this->getDefaultAddress($driver),
  4276. 'port' => $this->getDefaultPort($driver),
  4277. ];
  4278. }
  4279. public function __construct(array $values)
  4280. {
  4281. $driver = $this->getDefaultDriver($values);
  4282. $defaults = $this->getDriverDefaults($driver);
  4283. $newValues = array_merge($this->values, $defaults, $values);
  4284. $newValues = $this->parseMiddlewares($newValues);
  4285. $diff = array_diff_key($newValues, $this->values);
  4286. if (!empty($diff)) {
  4287. $key = array_keys($diff)[0];
  4288. throw new \Exception("Config has invalid value '$key'");
  4289. }
  4290. $this->values = $newValues;
  4291. }
  4292. private function parseMiddlewares(array $values): array
  4293. {
  4294. $newValues = array();
  4295. $properties = array();
  4296. $middlewares = array_map('trim', explode(',', $values['middlewares']));
  4297. foreach ($middlewares as $middleware) {
  4298. $properties[$middleware] = [];
  4299. }
  4300. foreach ($values as $key => $value) {
  4301. if (strpos($key, '.') === false) {
  4302. $newValues[$key] = $value;
  4303. } else {
  4304. list($middleware, $key2) = explode('.', $key, 2);
  4305. if (isset($properties[$middleware])) {
  4306. $properties[$middleware][$key2] = $value;
  4307. } else {
  4308. throw new \Exception("Config has invalid value '$key'");
  4309. }
  4310. }
  4311. }
  4312. $newValues['middlewares'] = array_reverse($properties, true);
  4313. return $newValues;
  4314. }
  4315. public function getDriver(): String
  4316. {
  4317. return $this->values['driver'];
  4318. }
  4319. public function getAddress(): String
  4320. {
  4321. return $this->values['address'];
  4322. }
  4323. public function getPort(): int
  4324. {
  4325. return $this->values['port'];
  4326. }
  4327. public function getUsername(): String
  4328. {
  4329. return $this->values['username'];
  4330. }
  4331. public function getPassword(): String
  4332. {
  4333. return $this->values['password'];
  4334. }
  4335. public function getDatabase(): String
  4336. {
  4337. return $this->values['database'];
  4338. }
  4339. public function getMiddlewares(): array
  4340. {
  4341. return $this->values['middlewares'];
  4342. }
  4343. public function getControllers(): array
  4344. {
  4345. return array_map('trim', explode(',', $this->values['controllers']));
  4346. }
  4347. public function getCacheType(): String
  4348. {
  4349. return $this->values['cacheType'];
  4350. }
  4351. public function getCachePath(): String
  4352. {
  4353. return $this->values['cachePath'];
  4354. }
  4355. public function getCacheTime(): int
  4356. {
  4357. return $this->values['cacheTime'];
  4358. }
  4359. public function getDebug(): String
  4360. {
  4361. return $this->values['debug'];
  4362. }
  4363. public function getOpenApiBase(): array
  4364. {
  4365. return json_decode($this->values['openApiBase'], true);
  4366. }
  4367. }
  4368. // file: src/Tqdev/PhpCrudApi/Request.php
  4369. class Request
  4370. {
  4371. private $method;
  4372. private $path;
  4373. private $pathSegments;
  4374. private $params;
  4375. private $body;
  4376. private $headers;
  4377. private $highPerformance;
  4378. public function __construct(String $method = null, String $path = null, String $query = null, array $headers = null, String $body = null, bool $highPerformance = true)
  4379. {
  4380. $this->parseMethod($method);
  4381. $this->parsePath($path);
  4382. $this->parseParams($query);
  4383. $this->parseHeaders($headers);
  4384. $this->parseBody($body);
  4385. $this->highPerformance = $highPerformance;
  4386. }
  4387. private function parseMethod(String $method = null)
  4388. {
  4389. if (!$method) {
  4390. if (isset($_SERVER['REQUEST_METHOD'])) {
  4391. $method = $_SERVER['REQUEST_METHOD'];
  4392. } else {
  4393. $method = 'GET';
  4394. }
  4395. }
  4396. $this->method = $method;
  4397. }
  4398. private function parsePath(String $path = null)
  4399. {
  4400. if (!$path) {
  4401. if (isset($_SERVER['PATH_INFO'])) {
  4402. $path = $_SERVER['PATH_INFO'];
  4403. } else {
  4404. $path = '/';
  4405. }
  4406. }
  4407. $this->path = $path;
  4408. $this->pathSegments = explode('/', $path);
  4409. }
  4410. private function parseParams(String $query = null)
  4411. {
  4412. if (!$query) {
  4413. if (isset($_SERVER['QUERY_STRING'])) {
  4414. $query = $_SERVER['QUERY_STRING'];
  4415. } else {
  4416. $query = '';
  4417. }
  4418. }
  4419. $query = str_replace('][]=', ']=', str_replace('=', '[]=', $query));
  4420. parse_str($query, $this->params);
  4421. }
  4422. private function parseHeaders(array $headers = null)
  4423. {
  4424. if (!$headers) {
  4425. $headers = array();
  4426. if (!$this->highPerformance) {
  4427. foreach ($_SERVER as $name => $value) {
  4428. if (substr($name, 0, 5) == 'HTTP_') {
  4429. $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
  4430. $headers[$key] = $value;
  4431. }
  4432. }
  4433. }
  4434. }
  4435. $this->headers = $headers;
  4436. }
  4437. private function parseBody(String $body = null)
  4438. {
  4439. if (!$body) {
  4440. $body = file_get_contents('php://input');
  4441. }
  4442. $this->body = $body;
  4443. }
  4444. public function getMethod(): String
  4445. {
  4446. return $this->method;
  4447. }
  4448. public function getPath(): String
  4449. {
  4450. return $this->path;
  4451. }
  4452. public function getPathSegment(int $part): String
  4453. {
  4454. if ($part < 0 || $part >= count($this->pathSegments)) {
  4455. return '';
  4456. }
  4457. return $this->pathSegments[$part];
  4458. }
  4459. public function getParams(): array
  4460. {
  4461. return $this->params;
  4462. }
  4463. public function getBody() /*: ?array*/
  4464. {
  4465. $body = $this->body;
  4466. $first = substr($body, 0, 1);
  4467. if ($first == '[' || $first == '{') {
  4468. $body = json_decode($body);
  4469. $causeCode = json_last_error();
  4470. if ($causeCode !== JSON_ERROR_NONE) {
  4471. return null;
  4472. }
  4473. } else {
  4474. parse_str($body, $input);
  4475. foreach ($input as $key => $value) {
  4476. if (substr($key, -9) == '__is_null') {
  4477. $input[substr($key, 0, -9)] = null;
  4478. unset($input[$key]);
  4479. }
  4480. }
  4481. $body = (object) $input;
  4482. }
  4483. return $body;
  4484. }
  4485. public function setBody($body) /*: void*/
  4486. {
  4487. $this->body = json_encode($body);
  4488. }
  4489. public function addHeader(String $key, String $value)
  4490. {
  4491. $this->headers[$key] = $value;
  4492. }
  4493. public function getHeader(String $key): String
  4494. {
  4495. if (isset($this->headers[$key])) {
  4496. return $this->headers[$key];
  4497. }
  4498. if ($this->highPerformance) {
  4499. $serverKey = 'HTTP_' . strtoupper(str_replace('_', '-', $key));
  4500. if (isset($_SERVER[$serverKey])) {
  4501. return $_SERVER[$serverKey];
  4502. }
  4503. }
  4504. return '';
  4505. }
  4506. public function getHeaders(): array
  4507. {
  4508. return $this->headers;
  4509. }
  4510. public static function fromString(String $request): Request
  4511. {
  4512. $parts = explode("\n\n", trim($request), 2);
  4513. $head = $parts[0];
  4514. $body = isset($parts[1]) ? $parts[1] : null;
  4515. $lines = explode("\n", $head);
  4516. $line = explode(' ', trim(array_shift($lines)), 2);
  4517. $method = $line[0];
  4518. $url = isset($line[1]) ? $line[1] : '';
  4519. $path = parse_url($url, PHP_URL_PATH);
  4520. $query = parse_url($url, PHP_URL_QUERY);
  4521. $headers = array();
  4522. foreach ($lines as $line) {
  4523. list($key, $value) = explode(':', $line, 2);
  4524. $headers[$key] = trim($value);
  4525. }
  4526. return new Request($method, $path, $query, $headers, $body);
  4527. }
  4528. }
  4529. // file: src/Tqdev/PhpCrudApi/Response.php
  4530. class Response
  4531. {
  4532. const OK = 200;
  4533. const UNAUTHORIZED = 401;
  4534. const FORBIDDEN = 403;
  4535. const NOT_FOUND = 404;
  4536. const CONFLICT = 409;
  4537. const UNPROCESSABLE_ENTITY = 422;
  4538. const INTERNAL_SERVER_ERROR = 500;
  4539. private $status;
  4540. private $headers;
  4541. private $body;
  4542. public function __construct(int $status, $body)
  4543. {
  4544. $this->status = $status;
  4545. $this->headers = array();
  4546. $this->parseBody($body);
  4547. }
  4548. private function parseBody($body)
  4549. {
  4550. if ($body === '') {
  4551. $this->body = '';
  4552. } else {
  4553. $data = json_encode($body, JSON_UNESCAPED_UNICODE);
  4554. $this->addHeader('Content-Type', 'application/json');
  4555. $this->addHeader('Content-Length', strlen($data));
  4556. $this->body = $data;
  4557. }
  4558. }
  4559. public function getStatus(): int
  4560. {
  4561. return $this->status;
  4562. }
  4563. public function getBody(): String
  4564. {
  4565. return $this->body;
  4566. }
  4567. public function addHeader(String $key, String $value)
  4568. {
  4569. $this->headers[$key] = $value;
  4570. }
  4571. public function getHeader(String $key): String
  4572. {
  4573. if (isset($this->headers[$key])) {
  4574. return $this->headers[$key];
  4575. }
  4576. return null;
  4577. }
  4578. public function getHeaders(): array
  4579. {
  4580. return $this->headers;
  4581. }
  4582. public function output()
  4583. {
  4584. http_response_code($this->getStatus());
  4585. foreach ($this->headers as $key => $value) {
  4586. header("$key: $value");
  4587. }
  4588. echo $this->getBody();
  4589. }
  4590. public function __toString(): String
  4591. {
  4592. $str = "$this->status\n";
  4593. foreach ($this->headers as $key => $value) {
  4594. $str .= "$key: $value\n";
  4595. }
  4596. if ($this->body !== '') {
  4597. $str .= "\n";
  4598. $str .= "$this->body\n";
  4599. }
  4600. return $str;
  4601. }
  4602. }
  4603. // file: src/index.php
  4604. $config = new Config([
  4605. 'username' => 'php-crud-api',
  4606. 'password' => 'php-crud-api',
  4607. 'database' => 'php-crud-api',
  4608. ]);
  4609. $request = new Request();
  4610. $api = new Api($config);
  4611. $response = $api->handle($request);
  4612. $response->output();