GenerateTreeCommand.php 63 KB

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