GenerateTreeCommand.php 62 KB

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