GenerateTreeCommand.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\DB;
  5. class GenerateTreeCommand extends Command
  6. {
  7. private $routesFile = null;
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'generatetree
  14. {path: /path/to/tree.txt}';
  15. /**
  16. * Execute the console command.
  17. *
  18. * @return mixed
  19. */
  20. public function handle()
  21. {
  22. $lines = ['<?php', '', 'use Illuminate\Support\Facades\Route;', '', ''];
  23. GenerateTreeCommand::save(base_path("routes/generated.php"), implode("\n", $lines));
  24. $sideLinks = [];
  25. global $argv;
  26. $file = fopen($argv[2], "r");
  27. $lines = [];
  28. while (!feof($file)) {
  29. $line = rtrim(fgets($file));
  30. if(trim($line) !== '') {
  31. $lines[] = str_replace("\t", " ", $line);
  32. }
  33. }
  34. fclose($file);
  35. $currentRoot = "";
  36. $currentController = new GenController();
  37. $currentSubController = new GenController();
  38. $currentSubType = "";
  39. $currentView = "";
  40. $currentMethod = null;
  41. $currentSubAdder = null;
  42. foreach ($lines as $line) {
  43. // stop (debugging)
  44. if(trim($line) === '##stop') {
  45. exit(0);
  46. }
  47. // skip comments
  48. if(trim($line)[0] === '#') continue;
  49. $lineType = null;
  50. // no leading space - root specifier
  51. if($line[0] !== ' ') {
  52. $currentRoot = strtolower(trim($line));
  53. }
  54. else {
  55. $ls = $this->numLS($line);
  56. $line = trim($line);
  57. $exitURL = false;
  58. if(strpos($line, "=>") !== FALSE) {
  59. $parts = explode("=>", $line);
  60. $exitURL = str_replace("UID", "{{ \$subRecord->uid }}", $parts[1]);
  61. $line = $parts[0];
  62. }
  63. $tokens = explode("|", $line);
  64. $line = $tokens[0];
  65. $dbTable = null;
  66. $condition = null;
  67. if(count($tokens) >= 2) {
  68. $dbTable = $tokens[1];
  69. // check if table has loading conditions
  70. if(strpos($dbTable, ":")) {
  71. $parts = explode(":", $dbTable);
  72. $dbTable = $parts[0];
  73. $parts = explode("=", $parts[1]);
  74. $condition = [
  75. "field" => $parts[0],
  76. "value" => str_replace("OWN", "session('proId')" , $parts[1])
  77. ];
  78. }
  79. }
  80. $hasAdd = in_array("add", $tokens);
  81. $hasView = in_array("view", $tokens);
  82. $hasRemove = in_array("remove", $tokens);
  83. $icon = "user";
  84. if(strpos($tokens[count($tokens) - 1], "icon:") === 0) {
  85. $icon = substr($tokens[count($tokens) - 1], 5);
  86. }
  87. switch($ls) {
  88. case 4: // top level controller OR top level controller action
  89. // top level controller-action
  90. if(strpos($line, "/") !== FALSE) {
  91. if(!empty($currentController)) {
  92. $parts = explode(":", $line);
  93. $line = $parts[0];
  94. $method = explode("/", $line)[1];
  95. $newMethod = $currentController->addMethod($method, "/" . $line);
  96. if(count($parts) > 1) {
  97. $newMethod->api = $parts[count($parts) - 1];
  98. }
  99. // create _SINGLE_ controller if view
  100. if($method === "view") {
  101. $currentSubController = new GenController($currentRoot, $currentController->name . "_SINGLE");
  102. $currentSubController->dbTable = $currentController->dbTable;
  103. $currentSubController->parentRoute = "/" . $line;
  104. $currentSubController->parentControllerName = $currentController->name;
  105. $currentSubController->sub = true;
  106. $newMethod->redirect = "/" . $line . "/SUB_dashboard";
  107. }
  108. else if(strpos($method, "add_new") === 0) {
  109. $newMethod->type = 'add';
  110. }
  111. else if(strpos($method, "remove") === 0) {
  112. $newMethod->type = 'remove';
  113. }
  114. $currentMethod = $newMethod;
  115. }
  116. }
  117. // new top level controller
  118. else if(empty($currentController) || $line !== $currentController->name) {
  119. if(!empty($currentController)) {
  120. $currentController->save();
  121. }
  122. $currentController = new GenController($currentRoot, $line, $icon);
  123. $currentController->dbTable = $dbTable;
  124. $currentController->condition = $condition;
  125. $currentController->hasAdd = $hasAdd;
  126. $currentController->hasView = $hasView;
  127. $currentController->hasRemove = $hasRemove;
  128. $currentMethod = $currentController->addMethod("index", "/$line");
  129. if(!empty($currentSubController)) {
  130. $currentSubController->save();
  131. }
  132. $currentSubType = '';
  133. $currentSubController = new GenController();
  134. $sideLinks[] = "<li class='nav-item'>\n" .
  135. "\t<a href='/{$currentController->name}' " .
  136. "class='nav-link " .
  137. "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>\n" .
  138. "\t\t<i class='nav-icon fa fa-$icon'></i>\n" .
  139. "\t\t<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>\n" .
  140. "\t</a>\n</li>\n";
  141. }
  142. break;
  143. case 8: // sub-type declaration | add_new fields | !inc/!exc
  144. if($line === 'ACTIONS' || $line === 'SUB') {
  145. $currentSubType = $line;
  146. }
  147. else if(strpos($line, "!inc:") === 0) { // !inc:
  148. if (!empty($currentMethod)) {
  149. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  150. }
  151. }
  152. else if(strpos($line, "!exc:") === 0) { // !exc:
  153. if (!empty($currentMethod)) {
  154. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  155. }
  156. }
  157. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  158. if (!empty($currentMethod)) {
  159. $currentMethod->viewLinkField = substr($line, 5);
  160. }
  161. }
  162. else if(strpos($line, "!col:") === 0) { // !col:
  163. if (!empty($currentMethod)) {
  164. $currentMethod->setColumnSpec(substr($line, 5), $exitURL, 'record');
  165. }
  166. }
  167. else if(strpos($line, "!qry:") === 0) { // !qry:
  168. if (!empty($currentMethod)) {
  169. $currentMethod->addQuery(substr($line, 5));
  170. }
  171. }
  172. else if (!empty($currentMethod) &&
  173. (strpos($currentMethod->name, 'add_new') === 0 ||
  174. $currentMethod->name === 'remove')) { // this is a field in add_new
  175. $currentMethod->data[] = $line;
  176. }
  177. break;
  178. case 12: // ACTIONS | SUB
  179. // check if this has show conditions
  180. $show = false;
  181. $isDashboard = 'unspecified';
  182. if(strpos($line, ":")) {
  183. $parts = explode(":", $line);
  184. $line = $parts[0];
  185. if($parts[1] === 'if') {
  186. $show = $parts[2];
  187. }
  188. else if($parts[1] === 'dashboard') {
  189. $isDashboard = true;
  190. }
  191. else if($parts[1] === 'custom') {
  192. $isDashboard = false;
  193. }
  194. }
  195. if($currentSubType === 'ACTIONS') {
  196. $currentMethod = $currentSubController->addMethod(
  197. "ACTION_" . $line,
  198. "/ACTION_" . $line
  199. );
  200. $currentMethod->type = 'action';
  201. $currentMethod->show = $show;
  202. $currentMethod->data = [];
  203. }
  204. else if($currentSubType === 'SUB') {
  205. $currentMethod = $currentSubController->addMethod(
  206. "SUB_" . $line,
  207. "/SUB_" . $line
  208. );
  209. $currentMethod->type = 'sub';
  210. $currentMethod->show = $show;
  211. $currentMethod->data = [];
  212. if($isDashboard !== 'unspecified') {
  213. $currentMethod->dashboard = $isDashboard;
  214. if($isDashboard) {
  215. $currentSubController->dashboardName = $line;
  216. if($currentController && $currentSubController && $currentController->name !== $currentSubController->name) {
  217. // change the redirect in /view/{uid} method of $currentController
  218. foreach($currentController->methods as $method) {
  219. if($method->name === 'view' && $method->redirect) {
  220. $method->redirect = $method->route . '/SUB_' . $line;
  221. break;
  222. }
  223. }
  224. }
  225. }
  226. /*dump("/SUB_" . $line . " ==> " . ($isDashboard ? "yes" : "no"));
  227. dump($currentMethod);
  228. dump($currentSubController->dashboardName);
  229. if($isDashboard) exit(1);*/
  230. }
  231. else if($line === 'dashboard') {
  232. $currentMethod->dashboard = true;
  233. }
  234. }
  235. break;
  236. case 16: // data for actions and subs
  237. $currentSubAdder = null;
  238. if(strpos($line, "!inc:") === 0) { // !inc:
  239. if (!empty($currentMethod)) {
  240. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  241. }
  242. }
  243. else if(strpos($line, "!exc:") === 0) { // !exc:
  244. if (!empty($currentMethod)) {
  245. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  246. }
  247. }
  248. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  249. if (!empty($currentMethod)) {
  250. $currentMethod->viewLinkField = substr($line, 5);
  251. }
  252. }
  253. else if(strpos($line, "!col:") === 0) { // !col:
  254. if (!empty($currentMethod)) {
  255. $currentMethod->setColumnSpec(substr($line, 5), $exitURL,
  256. $currentMethod->dashboard ? 'record' : 'subRecord'
  257. );
  258. }
  259. }
  260. else if(strpos($line, "!qry:") === 0) { // !qry:
  261. if (!empty($currentMethod)) {
  262. $currentMethod->addQuery(substr($line, 5));
  263. }
  264. }
  265. else if(strpos($line, "!grp:") === 0) { // !grp:
  266. if (!empty($currentMethod)) {
  267. $currentMethod->addGroup(substr($line, 5), $exitURL);
  268. }
  269. }
  270. else if(strpos($line, "!act:") === 0) { // !act:
  271. if (!empty($currentMethod)) {
  272. $currentMethod->addAction(substr($line, 5), $exitURL);
  273. }
  274. }
  275. else if(strpos($line, "!nal:") === 0) { // !nal:
  276. if (!empty($currentMethod)) {
  277. $currentMethod->noActionLinks = true;
  278. }
  279. }
  280. else if(strpos($line, "add_new") === 0) { // sub add_new..
  281. if(!empty($currentMethod)) {
  282. $currentSubAdder = $currentMethod->addSubAdder(
  283. $line,
  284. $currentSubController->name,
  285. $currentController->snakeToTitleCase(explode(":", $line)[0]),
  286. $exitURL
  287. );
  288. }
  289. }
  290. else if(!empty($currentMethod)) {
  291. $currentMethod->data[] = $line;
  292. if($exitURL) {
  293. if(strpos("=", $line) !== FALSE) {
  294. $currentMethod->viewURL = $exitURL;
  295. }
  296. else {
  297. $currentMethod->exitURL = $exitURL;
  298. }
  299. }
  300. }
  301. break;
  302. case 20: // SUB add_new fields
  303. if(count($currentMethod->subAdders)) {
  304. $currentMethod->subAdders[count($currentMethod->subAdders) - 1]["data"][] = $line;
  305. }
  306. break;
  307. default:
  308. dump("ERROR: Cannot have $ls leading spaces!");
  309. dump("Line: $line");
  310. exit(1);
  311. }
  312. }
  313. }
  314. // do any pending saves
  315. if(!empty($currentSubController)) {
  316. $currentSubController->save();
  317. }
  318. if(!empty($currentController)) {
  319. $currentController->save();
  320. }
  321. echo "Saved " . base_path("routes/generated.php") . "\n";
  322. // save side links
  323. GenerateTreeCommand::save(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  324. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  325. $this->humanizeRoutes();
  326. }
  327. private function numLS($line) {
  328. $count = 0;
  329. for ($i=0; $i<strlen($line); $i++) {
  330. if($line[$i] !== ' ') break;
  331. $count++;
  332. }
  333. return $count;
  334. }
  335. private function humanizeRoutes() {
  336. $path = base_path("routes/generated.php");
  337. $file = fopen($path, "r");
  338. $lines = [];
  339. $groups = [];
  340. $currentGroup = FALSE;
  341. $comment = '';
  342. $prefix = '';
  343. while (!feof($file)) {
  344. $line = rtrim(fgets($file));
  345. if($line === "") {
  346. if($currentGroup !== FALSE) {
  347. $groups[] = $currentGroup;
  348. $currentGroup = FALSE;
  349. }
  350. }
  351. else if(strpos($line, "// --- ") === 0) {
  352. $comment = $line;
  353. }
  354. else if(strpos($line, "Route::get('") === 0) {
  355. $parts = explode("'", $line);
  356. $route = $parts[1];
  357. $action = $parts[3];
  358. $name = $parts[5];
  359. if($currentGroup === FALSE) {
  360. $prefix = $route;
  361. if (($uidPos = strpos($route, "/{uid}/")) !== FALSE) {
  362. $prefix = substr($route, 0, $uidPos + 6);
  363. }
  364. }
  365. $route = substr($route, strlen($prefix));
  366. if(strlen($route) && $route[0] === "/") {
  367. $route = substr($route, 1);
  368. }
  369. if($currentGroup === FALSE) {
  370. $currentGroup = [
  371. "comment" => $comment,
  372. "prefix" => $prefix,
  373. "routes" => [
  374. [
  375. "route" => $route,
  376. "action" => $action,
  377. "name" => $name
  378. ]
  379. ]
  380. ];
  381. }
  382. else {
  383. $currentGroup["routes"][] = [
  384. "route" => $route,
  385. "action" => $action,
  386. "name" => $name
  387. ];
  388. }
  389. }
  390. }
  391. fclose($file);
  392. // write the routes
  393. $lines = ["<?php", "", "use Illuminate\Support\Facades\Route;", ""];
  394. foreach ($groups as $group) {
  395. $lines[] = $group["comment"];
  396. $lines[] = "Route::prefix('{$group["prefix"]}')->group(function () {";
  397. foreach ($group["routes"] as $route) {
  398. $lines[] = "\tRoute::get('{$route["route"]}', '{$route["action"]}')->name('{$route["name"]}');";
  399. }
  400. $lines[] = "});";
  401. $lines[] = "";
  402. }
  403. GenerateTreeCommand::save($path, implode("\n", $lines));
  404. echo "Cleaned " . base_path("routes/generated.php") . "\n";
  405. }
  406. public static function save($dir, $contents, $flags = FALSE){
  407. // if file exists, check if it has "DO NOT GENERATE" as the first line
  408. if(file_exists($dir) && is_file($dir)) {
  409. $file = fopen($dir, "r");
  410. $lines = [];
  411. $line = rtrim(fgets($file));
  412. if($line === '<?php /* DO NOT GENERATE */ ?>') {
  413. dump("Not writing to protected file: $dir");
  414. fclose($file);
  415. return;
  416. }
  417. fclose($file);
  418. $file = null;
  419. }
  420. $dir = str_replace("\\", "/", $dir);
  421. $dir = str_replace( '//', '/', $dir);
  422. $parts = explode('/', $dir);
  423. $file = array_pop($parts);
  424. $dir = '';
  425. foreach($parts as $part) {
  426. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  427. if(!is_dir($dir .= "/$part")) mkdir($dir);
  428. }
  429. }
  430. if($flags !== FALSE) {
  431. file_put_contents("$dir/$file", $contents, $flags);
  432. }
  433. else {
  434. file_put_contents("$dir/$file", $contents);
  435. }
  436. }
  437. }
  438. class GenController {
  439. public $root;
  440. public $saved = false;
  441. public $name;
  442. public $methods;
  443. public $parentRoute = "";
  444. public $dbTable = null;
  445. public $condition = null;
  446. public $hasAdd = false;
  447. public $hasView = false;
  448. public $hasRemove = false;
  449. public $sub = false;
  450. public $parentControllerName = '';
  451. public $parentController = false;
  452. public $subLinksSaved = false;
  453. public $actionLinksSaved = false;
  454. public $icon = "user";
  455. public $dashboardName = 'dashboard';
  456. public function __construct($root = null, $name = null, $icon = "user")
  457. {
  458. $this->root = $root;
  459. $this->name = $name;
  460. $this->icon = $icon;
  461. $this->methods = [];
  462. }
  463. public function addMethod($method, $route) {
  464. if($this->parentRoute) {
  465. $route = $this->parentRoute . $route;
  466. }
  467. $method = new GenControllerMethod($method, $route);
  468. $this->methods[] = $method;
  469. return $method;
  470. }
  471. public function save() {
  472. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  473. $this->saveController();
  474. $this->saveRoutes();
  475. $this->saved = true;
  476. // $this->log();
  477. }
  478. }
  479. public function saveController() {
  480. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  481. $code = [];
  482. // check if any method has a "sub add_new" in it, if yes, add action for the same
  483. $newMethods = [];
  484. foreach ($this->methods as $method) {
  485. if($method->type === 'sub' && count($method->subAdders) >= 1) {
  486. foreach ($method->subAdders as $subAdder) {
  487. $methodName = "ACTION_" . $subAdder["name"];
  488. $methodRoute = preg_replace("/\\/SUB_.+$/", '/' . $methodName, $method->route);
  489. $newMethod = new GenControllerMethod($methodName, $methodRoute);
  490. $newMethod->hasUID = true;
  491. $newMethod->redirect = false;
  492. $newMethod->type = 'action';
  493. $newMethod->data = $subAdder["data"];
  494. $newMethod->parentSub = $this->name . '-' . $method->name;
  495. $newMethod->table = $subAdder["table"];
  496. if(!empty($subAdder["api"])) {
  497. $newMethod->api = $subAdder["api"];
  498. }
  499. $newMethod->exitURL = $subAdder["link"];
  500. $newMethod->showLink = false;
  501. $newMethod->routeName = $this->name . '-' . $methodName;
  502. $newMethods[] = $newMethod;
  503. }
  504. }
  505. }
  506. $this->methods = array_merge($this->methods, $newMethods);
  507. foreach ($this->methods as $method) {
  508. $code[] = "";
  509. $code[] = "\t// GET {$method->route}";
  510. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  511. if($method->redirect) {
  512. $target = str_replace('{uid}', '$uid', $method->redirect);
  513. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  514. }
  515. else {
  516. $input = [];
  517. if($method->hasUID) {
  518. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  519. $input[] = "'record'";
  520. // if sub-index controller, load subRecords
  521. if($method->type === 'sub' && count($method->data)) {
  522. $parts = explode(",", $method->data[0]);
  523. $loadingLine = [];
  524. // first 'where'
  525. $dbParts = explode("=", $parts[0]);
  526. $localField = $dbParts[0];
  527. $dbParts = explode(".", $dbParts[1]);
  528. $foreignTable = $dbParts[0];
  529. $foreignField = $dbParts[1];
  530. $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
  531. $loadingLine[] = "->where('$foreignField', \$record->$localField)";
  532. // other 'where's
  533. if(count($parts) > 1) {
  534. for ($i = 1; $i < count($parts); $i++) {
  535. $dbParts = explode("=", $parts[$i]);
  536. $field = $dbParts[0];
  537. $value = $dbParts[1];
  538. $loadingLine[] = "->where('$field', $value)";
  539. }
  540. }
  541. $loadingLine[] = "->get();";
  542. $code[] = implode("", $loadingLine);
  543. // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  544. $input[] = "'subRecords'";
  545. }
  546. foreach ($method->queries as $key => $query) {
  547. // replace $x with " . ($record->x ? $record->x : "''") . "
  548. $query = preg_replace("/([^$])\\$([a-zA-Z0-9_]+)/", "$1\" . (\$record->$2 ? \$record->$2 : \"''\") . \"", $query);
  549. // replace $$x with " . ($subRecord->x ? $subRecord->x : "''") . "
  550. $query = preg_replace("/\\$\\$([a-zA-Z0-9_]+)/", "\" . (\$subRecord->$1 ? \$subRecord->$1 : \"''\") . \"", $query);
  551. $code[] = "\t\t\$result_$key = DB::select(\"$query\");";
  552. $input[] = "'result_$key'";
  553. }
  554. // return response()->view('pro/my_teams/add_new', compact('records'), session('message') ? 500 : 200)->header('Content-Type', 'text/html');
  555. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  556. "compact(" . implode(", ", $input) . "), " .
  557. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  558. }
  559. else {
  560. $loadingLine = [];
  561. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  562. if($this->condition) {
  563. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  564. }
  565. $loadingLine[] = "->get();";
  566. $input[] = "'records'";
  567. $code[] = implode("", $loadingLine);
  568. foreach ($method->queries as $key => $query) {
  569. // replace $x with " . ($record->x ? $record->x : "''") . "
  570. $query = preg_replace("/([^$])\\$([a-zA-Z0-9_]+)/", "$1\" . (\$record->$2 ? \$record->$2 : \"''\") . \"", $query);
  571. // replace $$x with " . ($subRecord->x ? $subRecord->x : "''") . "
  572. $query = preg_replace("/\\$\\$([a-zA-Z0-9_]+)/", "\" . (\$subRecord->$1 ? \$subRecord->$1 : \"''\") . \"", $query);
  573. $code[] = "\t\t\$result_$key = DB::select(\"$query\");";
  574. $input[] = "'result_$key'";
  575. }
  576. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  577. "compact(" . implode(", ", $input) . "), " .
  578. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  579. }
  580. }
  581. $this->saveView($this, $method);
  582. $code[] = "\t}";
  583. }
  584. $text = str_replace("__DASHBOARD_NAME__", $this->dashboardName, $text);
  585. $text = str_replace("__NAME__", "{$this->name}_Controller", $text);
  586. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  587. GenerateTreeCommand::save(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  588. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  589. }
  590. public function saveView(GenController $controller, GenControllerMethod $method) {
  591. if($controller->sub) {
  592. $controller->saveSubLinks($controller, $method);
  593. $controller->saveActionLinks($controller, $method);
  594. if($method->type === 'action') {
  595. $this->saveSubActionView($controller, $method);
  596. }
  597. else if($method->type === 'sub' && count($method->data)) {
  598. $this->saveSubIndexView($controller, $method);
  599. }
  600. else {
  601. $this->saveSubDefaultView($controller, $method);
  602. }
  603. }
  604. else {
  605. if($method->name === 'view' && $controller->hasView) {
  606. $this->saveShowView($controller, $method);
  607. }
  608. else if($method->name === 'index') {
  609. $this->saveIndexView($controller, $method);
  610. }
  611. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  612. $this->saveAddNewView($controller, $method);
  613. }
  614. else if($method->name === 'remove' && $controller->hasRemove) {
  615. $this->saveAddNewView($controller, $method);
  616. }
  617. }
  618. }
  619. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  620. {
  621. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  622. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  623. if($controller->hasAdd) {
  624. $addLinks = [];
  625. foreach ($controller->methods as $m) {
  626. if($m->type === 'add') {
  627. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  628. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  629. "href='/{$controller->name}/{$m->name}?optimised=1'>" .
  630. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  631. "{$this->snakeToTitleCase($m->name)}</a>";
  632. }
  633. }
  634. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  635. }
  636. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  637. $ths = [];
  638. $tds = [];
  639. if($controller->hasRemove) {
  640. $ths[] = "<th></th>";
  641. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  642. "<i class='fa fa-trash'></i>" .
  643. "</a></td>";
  644. }
  645. // !inc/!exc
  646. if($method->incType === "include") {
  647. $columns = $method->incFields;
  648. }
  649. else if($method->incType === "exclude") {
  650. $columns = array_filter($columns, function($item) use ($method) {
  651. return in_array($item, $method->incFields) === FALSE;
  652. });
  653. }
  654. // ensure uid column is at the start
  655. $columns = array_merge(['uid'], array_filter($columns, function($x) {
  656. return $x !== 'uid';
  657. }));
  658. foreach ($columns as $column) {
  659. if($column === 'id') continue;
  660. $columnTitle = $this->snakeToTitleCase($column);
  661. $columnValue = "<?= \$record->$column ?>";
  662. $hasLink = $controller->hasView && $column === $method->viewLinkField;
  663. $linkTarget = "/{$controller->name}/view/<?= \$record->uid ?>";
  664. if(substr($column, -3) === '_at') {
  665. $columnValue = "<?= friendly_date_time(\$record->$column) ?>";
  666. }
  667. // check if this column has column spec
  668. if(isset($method->columns[$column])) {
  669. $columnTitle = $method->columns[$column]["label"];
  670. if(isset($method->columns[$column]["query"])) {
  671. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  672. "select(\"{$method->columns[$column]["query"]}\");\n" .
  673. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  674. }
  675. else if(isset($method->columns[$column]["getter"])) {
  676. $columnValue = $method->columns[$column]["getter"];
  677. }
  678. if(isset($method->columns[$column]["link"])) {
  679. $hasLink = true;
  680. $linkTarget = $method->columns[$column]["link"];
  681. }
  682. }
  683. else if($column === 'uid') {
  684. $columnTitle = '&nbsp;';
  685. $columnValue = '<i class="fas fa-share-square"></i>';
  686. $hasLink = true;
  687. }
  688. $ths[] = "<th>$columnTitle</th>";
  689. $tds[] = "<td>" .
  690. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  691. $columnValue .
  692. ($hasLink ? "</a>" : "") .
  693. "</td>";
  694. }
  695. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  696. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  697. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  698. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  699. }
  700. public function saveShowView(GenController $controller, GenControllerMethod $method)
  701. {
  702. // delete sub links and action links
  703. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  704. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  705. }
  706. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  707. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  708. }
  709. // write info view
  710. $text = file_get_contents(base_path('generatecv/tree-templates/info.template.blade.php'));
  711. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  712. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  713. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  714. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/info.blade.php"), $text);
  715. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/info.blade.php") . "\n";
  716. // write main view
  717. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  718. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  719. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  720. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  721. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  722. $text = str_replace("_INFO_VIEW_", "{$controller->root}/{$controller->name}/info", $text);
  723. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  724. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  725. }
  726. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  727. {
  728. if ($controller->subLinksSaved) return;
  729. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  730. $subLinks = [];
  731. foreach ($controller->methods as $meth) {
  732. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  733. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  734. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  735. "<a " .
  736. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  737. "class='d-block px-3 py-2 border-bottom stag-sublink " .
  738. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  739. (
  740. $meth->name === 'SUB_dashboard' ?
  741. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  742. ""
  743. )
  744. . "'>$display</a>" .
  745. ($meth->show ? " @endif" : "");
  746. }
  747. GenerateTreeCommand::save($subLinksView, implode("\n", $subLinks));
  748. echo "Generated " . $subLinksView . "\n";
  749. $controller->subLinksSaved = true;
  750. }
  751. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  752. {
  753. if ($controller->actionLinksSaved) return;
  754. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  755. $actionLinks = [];
  756. foreach ($controller->methods as $meth) {
  757. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  758. $display = $this->camelToTitleCase(substr($meth->name, 7));
  759. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  760. "<a " .
  761. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  762. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}?optimised=1' " .
  763. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  764. ($meth->show ? " @endif" : "");
  765. }
  766. GenerateTreeCommand::save($actionLinksView, implode("\n", $actionLinks));
  767. echo "Generated " . $actionLinksView . "\n";
  768. $controller->actionLinksSaved = true;
  769. }
  770. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  771. {
  772. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  773. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  774. $text = $this->generateSubContent($controller, $method, $text);
  775. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  776. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  777. }
  778. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  779. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  780. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  781. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  782. if(!$method->parentSub) {
  783. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  784. }
  785. else {
  786. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  787. }
  788. if(!$method->table) {
  789. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  790. }
  791. else {
  792. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  793. }
  794. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  795. $fields = [];
  796. if(count($method->data)) {
  797. foreach ($method->data as $field) {
  798. $fields[] = $this->generateFormField($field);
  799. }
  800. }
  801. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  802. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  803. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  804. }
  805. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  806. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  807. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  808. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  809. if(count($method->subAdders) >= 1) {
  810. $addLinks = [];
  811. foreach ($method->subAdders as $subAdder) {
  812. $addLink = '<a class="btn btn-primary btn-sm ml-2" ' .
  813. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  814. 'href="{{route(\'' . $subAdder["routeName"] . '\', [\'uid\' => $record->uid])}}?optimised=1">' .
  815. "<i class='fa fa-plus-circle' aria-hidden='true'></i> {$subAdder["buttonLabel"]}</a>";
  816. $addLinks[] = $addLink;
  817. }
  818. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("", $addLinks), $text);
  819. }
  820. $dbParts = explode("=", $method->data[0]);
  821. $dbParts = explode(".", $dbParts[1]);
  822. $table = $dbParts[0];
  823. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  824. $ths = [];
  825. $tds = [];
  826. // !inc/!exc
  827. if($method->incType === "include") {
  828. $columns = $method->incFields;
  829. }
  830. else if($method->incType === "exclude") {
  831. $columns = array_filter($columns, function($item) use ($method) {
  832. return in_array($item, $method->incFields) === FALSE;
  833. });
  834. }
  835. // ensure uid column is at the start
  836. $columns = array_merge(['uid'], array_filter($columns, function($x) {
  837. return $x !== 'uid';
  838. }));
  839. foreach ($columns as $column) {
  840. if($column === 'id') continue;
  841. $columnTitle = $this->snakeToTitleCase($column);
  842. $columnValue = "<?= \$subRecord->$column ?>";
  843. $hasLink = $method->exitURL && $column === $method->viewLinkField;
  844. $linkTarget = $method->exitURL;
  845. if(substr($column, -3) === '_at') {
  846. $columnValue = "<?= friendly_date_time(\$subRecord->$column) ?>";
  847. }
  848. // check if this column has column spec
  849. if(isset($method->columns[$column])) {
  850. $columnTitle = $method->columns[$column]["label"];
  851. if(isset($method->columns[$column]["query"])) {
  852. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  853. "select(\"{$method->columns[$column]["query"]}\");\n" .
  854. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  855. }
  856. else if(isset($method->columns[$column]["getter"])) {
  857. $columnValue = $method->columns[$column]["getter"];
  858. }
  859. if(isset($method->columns[$column]["link"])) {
  860. $hasLink = true;
  861. $linkTarget = $method->columns[$column]["link"];
  862. }
  863. }
  864. else if($column === 'uid') {
  865. $columnTitle = '&nbsp;';
  866. $columnValue = '<i class="fas fa-share-square"></i>';
  867. $hasLink = true;
  868. }
  869. $ths[] = "<th>$columnTitle</th>";
  870. $tds[] = "<td>" .
  871. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  872. $columnValue .
  873. ($hasLink ? "</a>" : "") .
  874. "</td>";
  875. }
  876. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  877. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  878. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  879. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  880. }
  881. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  882. if($method->dashboard) {
  883. if(!isset($method->groups) || !count($method->groups)) {
  884. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
  885. }
  886. else {
  887. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard-grouped' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
  888. $groupsHtml = [];
  889. $groupTemplate = file_get_contents(base_path('generatecv/tree-templates/dashboard-group.template.blade.php'));
  890. foreach ($method->groups as $group) {
  891. $groupHtml = $groupTemplate;
  892. $groupHtml = str_replace("<!-- __GROUP_NAME__ -->", $group["name"], $groupHtml);
  893. if (isset($group["action"])) {
  894. $action = $group["action"];
  895. $actionLine = [];
  896. if (isset($action["condition"])) {
  897. if ($action["condition"] === "if") {
  898. $actionLine[] = "@if(";
  899. } else {
  900. $actionLine[] = "@if(!";
  901. }
  902. $actionLine[] = "\$record->{$action["field"]})";
  903. }
  904. $title = $this->camelToTitleCase($action["label"]);
  905. $actionLine[] = "<a " .
  906. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  907. "href='{$action["link"]}' title='{$action["label"]}?optimised=1'" .
  908. "class='mx-2 font-weight-normal text-primary text-xs'>" .
  909. "<i class='fa fa-{$action["icon"]}'></i>&nbsp;" .
  910. "<span>{$title}</span>" .
  911. "</a>";
  912. if (isset($action["condition"])) {
  913. $actionLine[] = "@endif";
  914. }
  915. $actionLine = implode(" ", $actionLine);
  916. $groupHtml = str_replace("<!-- __GROUP_ACTION__ -->", $actionLine, $groupHtml);
  917. }
  918. $fields = [];
  919. foreach ($group["fields"] as $field) {
  920. if($field === 'id' || $field === 'uid') continue;
  921. $columnTitle = $this->snakeToTitleCase($field);
  922. $columnValue = "<?= \$record->$field ?>";
  923. $hasLink = false;
  924. $linkTarget = null;
  925. $actions = [];
  926. if(substr($field, -3) === '_at') {
  927. $columnValue = "<?= friendly_date_time(\$record->$field) ?>";
  928. }
  929. // check if this column has column spec
  930. if(isset($method->columns[$field])) {
  931. $columnTitle = $method->columns[$field]["label"];
  932. if(isset($method->columns[$field]["query"])) {
  933. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  934. "select(\"{$method->columns[$field]["query"]}\");\n" .
  935. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  936. }
  937. else if(isset($method->columns[$field]["getter"])) {
  938. $columnValue = $method->columns[$field]["getter"];
  939. }
  940. if(isset($method->columns[$field]["link"])) {
  941. $hasLink = true;
  942. $linkTarget = $method->columns[$field]["link"];
  943. }
  944. }
  945. if(isset($method->columnActions[$field])) {
  946. foreach($method->columnActions[$field] as $action) {
  947. $actionLine = [];
  948. if(isset($action["condition"])) {
  949. if($action["condition"] === "if") {
  950. $actionLine[] = "@if(";
  951. }
  952. else {
  953. $actionLine[] = "@if(!";
  954. }
  955. $actionLine[] = "\$record->{$action["field"]})";
  956. }
  957. $title = $this->camelToTitleCase($action["label"]);
  958. $actionLine[] = "<a " .
  959. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  960. "href='{$action["link"]}?optimised=1' title='{$action["label"]}' " .
  961. "class='mx-2 font-weight-normal text-primary text-xs'>" .
  962. "<i class='fa fa-{$action["icon"]}'></i>&nbsp;" .
  963. "<span>{$title}</span>" .
  964. "</a>";
  965. if(isset($action["condition"])) {
  966. $actionLine[] = "@endif";
  967. }
  968. $actionLine = implode(" ", $actionLine);
  969. $actions[] = $actionLine;
  970. }
  971. }
  972. $actions = implode("\n", $actions);
  973. $fields[] = "<tr>" .
  974. "<td class=\"w-25 px-2 text-secondary border-right\">$columnTitle</td>" .
  975. "<td class=\"w-75 px-2 font-weight-bold\">" .
  976. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  977. $columnValue .
  978. ($hasLink ? "</a>" : "") .
  979. $actions .
  980. "</td>" .
  981. "</tr>";
  982. }
  983. $groupHtml = str_replace("<!-- __GROUP_FIELDS__ -->", implode("\n", $fields), $groupHtml);
  984. $groupsHtml[] = $groupHtml;
  985. }
  986. $groupsHtml = implode("\n", $groupsHtml);
  987. $html = str_replace("<!-- _GROUPS_ -->", $groupsHtml, $html);
  988. }
  989. $text = str_replace("_SUB_VIEW_", $html, $text);
  990. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  991. }
  992. else {
  993. $text = str_replace("_SUB_VIEW_",
  994. "<h5 class='py-3 border-bottom'>" .
  995. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h5>" .
  996. "Controller: <b>{$controller->name}</b><br>" .
  997. "Action: <b>{$method->name}()</b><br>" .
  998. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br><br>",
  999. $text);
  1000. }
  1001. return $text;
  1002. }
  1003. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  1004. {
  1005. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  1006. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  1007. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  1008. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  1009. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  1010. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  1011. $columns = $method->data;
  1012. $fields = [];
  1013. foreach ($columns as $column) {
  1014. $fields[] = $this->generateFormField($column);
  1015. }
  1016. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  1017. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  1018. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  1019. }
  1020. public function saveRoutes() {
  1021. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  1022. foreach ($this->methods as $method) {
  1023. // FORMAT:
  1024. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  1025. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  1026. }
  1027. $lines[] = '';
  1028. $lines[] = '';
  1029. GenerateTreeCommand::save(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  1030. }
  1031. public function log() {
  1032. $this->w('');
  1033. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  1034. $this->w("Table: {$this->dbTable}");
  1035. $this->w('---------------------------------------------');
  1036. foreach ($this->methods as $method) {
  1037. $this->w('Rout: ' . $method->route, 1);
  1038. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  1039. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  1040. // $this->w('Exit: ' . $method->exitURL, 1);
  1041. // $this->w('View: ' . $method->viewURL, 1);
  1042. dump($method->columns);
  1043. dump($method->queries);
  1044. if(!$method->redirect) {
  1045. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  1046. }
  1047. else {
  1048. $this->w('Redi: ' . $method->redirect, 1);
  1049. }
  1050. $this->w('---------------------------------------------');
  1051. }
  1052. }
  1053. public function w($line, $level = -1) {
  1054. for($i=0; $i<$level; $i++) echo "\t";
  1055. echo "$line\n";
  1056. }
  1057. public function snakeToTitleCase($text) {
  1058. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  1059. return ucwords(str_replace("_", " ", $text));
  1060. }
  1061. public function camelToTitleCase($text) {
  1062. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  1063. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  1064. return ucwords($text);
  1065. }
  1066. public function snakeToCamelCase($text) {
  1067. $text = ucwords(str_replace("_", " ", $text));
  1068. $text = str_replace(" ", "", $text);
  1069. $text[0] = strtolower($text[0]);
  1070. return $text;
  1071. }
  1072. private function generateFormField($line) {
  1073. $tokens = explode("=", $line);
  1074. $default = false;
  1075. if(count($tokens) > 1) {
  1076. $default = $tokens[1];
  1077. }
  1078. $tokens = explode(":", $tokens[0]);
  1079. $name = $tokens[0];
  1080. $required = false;
  1081. if($name[strlen($name) - 1] === '*') { // required field?
  1082. $required = true;
  1083. $name = substr($name, 0, strlen($name) - 1);
  1084. }
  1085. $display = $name;
  1086. $dotPos = strpos($name, ".");
  1087. if($dotPos !== FALSE) {
  1088. $display = substr($name, $dotPos + 1);
  1089. }
  1090. $display = preg_replace('/uid$/i', "", $display);
  1091. $type = "text";
  1092. $options = [];
  1093. if(count($tokens) > 1) {
  1094. $type = $tokens[1];
  1095. switch ($type) {
  1096. case "select":
  1097. $options = explode(",", $tokens[2]);
  1098. break;
  1099. case "record":
  1100. $options['table'] = $tokens[2];
  1101. $parts = explode(",", $tokens[3]);
  1102. $options['valueField'] = $parts[0];
  1103. $options['displayField'] = $parts[1];
  1104. break;
  1105. }
  1106. }
  1107. if($type !== 'hidden' && $type !== 'bool') {
  1108. $code[] = "<div class='form-group mb-3'>";
  1109. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  1110. ($required ? "*" : "") .
  1111. "</label>";
  1112. }
  1113. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  1114. switch ($type) {
  1115. case "select":
  1116. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  1117. ($required ? "required" : "") .
  1118. ">";
  1119. $code[] = "<option value=''>-- Select --</option>";
  1120. foreach ($options as $o) {
  1121. $code[] = "<option " .
  1122. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  1123. "value='$o'>$o</option>";
  1124. }
  1125. $code[] = "</select>";
  1126. break;
  1127. case "record":
  1128. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  1129. ($required ? "required" : "") .
  1130. ">";
  1131. $code[] = "<option value=''>-- Select --</option>";
  1132. if($options['table'][0] === '~') { // from named query
  1133. $code[] = "<?php foreach(\$result_" . substr($options['table'], 1) . " as \$o): ?>";
  1134. }
  1135. else { // select query
  1136. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  1137. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  1138. }
  1139. $code[] = "<option " .
  1140. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  1141. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  1142. $code[] = "<?php endforeach; ?>";
  1143. $code[] = "</select>";
  1144. break;
  1145. case "bool":
  1146. $code[] = "<div class='form-group mb-3'>";
  1147. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  1148. ($required ? "*" : "");
  1149. $code[] = "<input class='ml-2' type='checkbox' name='$name' " .
  1150. ($required ? "required" : "") .
  1151. ">";
  1152. $code[] = "</label>";
  1153. break;
  1154. default:
  1155. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
  1156. ($required ? "required" : "") .
  1157. ">";
  1158. }
  1159. if($type !== 'hidden') {
  1160. $code[] = "</div>";
  1161. }
  1162. return implode("\n", $code);
  1163. }
  1164. }
  1165. class GenControllerMethod {
  1166. public $name;
  1167. public $route;
  1168. public $hasUID = false;
  1169. public $redirect = false;
  1170. public $type = '';
  1171. public $data = [];
  1172. public $parentSub = false;
  1173. public $childAddRoute = false;
  1174. public $table = false;
  1175. public $api = 'create';
  1176. public $show = null;
  1177. public $viewURL = false;
  1178. public $exitURL = false;
  1179. public $showLink = true;
  1180. public $incType = null;
  1181. public $incFields = null;
  1182. public $viewLinkField = 'uid';
  1183. public $columns = [];
  1184. public $columnActions = [];
  1185. public $groups = [];
  1186. public $dashboard = false;
  1187. public $noActionLinks = false;
  1188. public $queries = [];
  1189. public $subAdders = [];
  1190. public function __construct($name, $route)
  1191. {
  1192. $this->name = $name;
  1193. $this->route = $route;
  1194. if(strpos($this->route, "{uid}") !== FALSE) {
  1195. $this->hasUID = true;
  1196. }
  1197. }
  1198. public function addSubAdder($line, $parentControllerName, $label, $link) {
  1199. $parts = explode(":", $line);
  1200. $newSubAdder = [
  1201. "name" => $parts[0],
  1202. "table" => $parts[1],
  1203. "api" => count($parts) >= 3 ? $parts[2] : null,
  1204. "link" => $link,
  1205. "data" => [],
  1206. "routeName" => "$parentControllerName-ACTION_{$parts[0]}",
  1207. "buttonLabel" => $label
  1208. ];
  1209. $this->subAdders[] = $newSubAdder;
  1210. return $newSubAdder;
  1211. }
  1212. public function setIncFields($type, $fields) {
  1213. $this->incType = $type;
  1214. $this->incFields = $fields;
  1215. for ($i = 0; $i < count($this->incFields); $i++) {
  1216. if($this->incFields[$i][0] === '@') {
  1217. $this->incFields[$i] = substr($this->incFields[$i], 1);
  1218. $this->viewLinkField = $this->incFields[$i];
  1219. }
  1220. }
  1221. }
  1222. public function setColumnSpec($line, $link, $recordVariable) {
  1223. // ally_pro_id:Ally Pro:select name_display as 'result' from pro where id = $ally_pro_id limit 1
  1224. $parts = explode(":", $line);
  1225. $spec = [
  1226. "label" => $parts[1]
  1227. ];
  1228. if(count($parts) > 2) {
  1229. $query = $parts[2];
  1230. // check if named query
  1231. if($query[0] === '~') {
  1232. // hcp_pro_id:HCP Pro:~pros:name_display:id,=,$hcp_pro_id;is_active,=,true:all
  1233. $recordSet = '$result_' . substr($query, 1);
  1234. $field = $parts[3];
  1235. $checkParts = explode(";", $parts[4]);
  1236. $checks = [];
  1237. foreach ($checkParts as $checkPart) {
  1238. $checkPart = explode(",", $checkPart);
  1239. $value = $checkPart[2];
  1240. if(strpos($value, '$$') === 0) {
  1241. $value = '$subRecord->' . substr($value, 2);
  1242. }
  1243. else if(strpos($value, '$') === 0) {
  1244. $value = '$record->' . substr($value, 1);
  1245. }
  1246. $checks[] = [
  1247. "field" => $checkPart[0],
  1248. "op" => $checkPart[1],
  1249. "value" => $value
  1250. ];
  1251. }
  1252. $condition = 'all';
  1253. if(count($parts) >= 6) {
  1254. $condition = $parts[5];
  1255. }
  1256. $checksArray = ["["];
  1257. foreach ($checks as $check) {
  1258. $checksArray[] = "[";
  1259. $checksArray[] = "'{$check['field']}'";
  1260. $checksArray[] = ", ";
  1261. $checksArray[] = "'{$check['op']}'";
  1262. $checksArray[] = ", ";
  1263. $checksArray[] = "{$check['value']}";
  1264. $checksArray[] = "], ";
  1265. }
  1266. $checksArray[] = "]";
  1267. $checks = implode("", $checksArray);
  1268. $spec['getter'] = "<?= value_from_rs($recordSet, '$field', " . $checks . ", '$condition'); ?>";
  1269. }
  1270. else {
  1271. $query = preg_replace("/\\$([a-zA-Z0-9_]+)/", "\" . ($$recordVariable->$1 ? $$recordVariable->$1 : -1) . \"", $query);
  1272. $spec['query'] = $query;
  1273. }
  1274. }
  1275. if($link) {
  1276. $spec['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$$recordVariable->$1 ?>", $link);
  1277. }
  1278. $this->columns[$parts[0]] = $spec;
  1279. }
  1280. public function addGroup($line, $link) {
  1281. // Basic Details:id,uid,created_at,clients_count
  1282. $parts = explode(":", $line);
  1283. $group = [
  1284. "name" => $parts[0],
  1285. "fields" => explode(",", $parts[1])
  1286. ];
  1287. // is there a group action
  1288. if(count($parts) > 2) {
  1289. $actionParts = ["-"];
  1290. for($i = 2; $i < count($parts); $i++) {
  1291. $actionParts[] = $parts[$i];
  1292. }
  1293. $actionParts = implode(":", $actionParts);
  1294. $group["action"] = $this->addAction($actionParts, $link, true);
  1295. }
  1296. $this->groups[] = $group;
  1297. $this->dashboard = true;
  1298. }
  1299. public function addAction($line, $link, $group = false) {
  1300. // is_active:Deactivate:deactivate:edit:if:is_active
  1301. $parts = explode(":", $line);
  1302. $action = [
  1303. "label" => $parts[1],
  1304. "icon" => isset($parts[2]) ? $parts[2] : 'edit'
  1305. ];
  1306. if(count($parts) >= 5 ) {
  1307. $action["condition"] = $parts[3];
  1308. $action["field"] = $parts[4];
  1309. }
  1310. if($link) {
  1311. $action['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$record->$1 ?>", $link);
  1312. }
  1313. if(!$group) {
  1314. if(!isset($this->columnActions[$parts[0]])) {
  1315. $this->columnActions[$parts[0]] = [];
  1316. }
  1317. $this->columnActions[$parts[0]][] = $action;
  1318. }
  1319. return $action;
  1320. }
  1321. public function addQuery($line) {
  1322. $parts = explode(":", $line);
  1323. $this->queries[$parts[0]] = $parts[1];
  1324. }
  1325. }