GenerateTreeCommand.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. file_put_contents(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. // skip comments
  43. if(trim($line)[0] === '#') continue;
  44. $lineType = null;
  45. // no leading space - root specifier
  46. if($line[0] !== ' ') {
  47. $currentRoot = strtolower(trim($line));
  48. }
  49. else {
  50. $ls = $this->numLS($line);
  51. $line = trim($line);
  52. $exitURL = false;
  53. if(strpos($line, "=>") !== FALSE) {
  54. $parts = explode("=>", $line);
  55. $exitURL = str_replace("UID", "{{ \$subRecord->uid }}", $parts[1]);
  56. $line = $parts[0];
  57. }
  58. $tokens = explode("|", $line);
  59. $line = $tokens[0];
  60. $dbTable = null;
  61. $condition = null;
  62. if(count($tokens) >= 2) {
  63. $dbTable = $tokens[1];
  64. // check if table has loading conditions
  65. if(strpos($dbTable, ":")) {
  66. $parts = explode(":", $dbTable);
  67. $dbTable = $parts[0];
  68. $parts = explode("=", $parts[1]);
  69. $condition = [
  70. "field" => $parts[0],
  71. "value" => str_replace("OWN", "session('proId')" , $parts[1])
  72. ];
  73. }
  74. }
  75. $hasAdd = in_array("add", $tokens);
  76. $hasView = in_array("view", $tokens);
  77. $hasRemove = in_array("remove", $tokens);
  78. switch($ls) {
  79. case 4: // top level controller OR top level controller action
  80. // top level controller-action
  81. if(strpos($line, "/") !== FALSE) {
  82. if(!empty($currentController)) {
  83. $parts = explode(":", $line);
  84. $line = $parts[0];
  85. $method = explode("/", $line)[1];
  86. $newMethod = $currentController->addMethod($method, "/" . $line);
  87. if(count($parts) > 1) {
  88. $newMethod->api = $parts[count($parts) - 1];
  89. }
  90. // create _SINGLE_ controller if view
  91. if($method === "view") {
  92. $currentSubController = new GenController($currentRoot, $currentController->name . "_SINGLE");
  93. $currentSubController->dbTable = $currentController->dbTable;
  94. $currentSubController->parentRoute = "/" . $line;
  95. $currentSubController->parentControllerName = $currentController->name;
  96. $currentSubController->sub = true;
  97. $newMethod->redirect = "/" . $line . "/SUB_dashboard";
  98. }
  99. else if(strpos($method, "add_new") === 0) {
  100. $newMethod->type = 'add';
  101. }
  102. else if(strpos($method, "remove") === 0) {
  103. $newMethod->type = 'remove';
  104. }
  105. $currentMethod = $newMethod;
  106. }
  107. }
  108. // new top level controller
  109. else if(empty($currentController) || $line !== $currentController->name) {
  110. if(!empty($currentController)) {
  111. $currentController->save();
  112. }
  113. $currentController = new GenController($currentRoot, $line);
  114. $currentController->dbTable = $dbTable;
  115. $currentController->condition = $condition;
  116. $currentController->hasAdd = $hasAdd;
  117. $currentController->hasView = $hasView;
  118. $currentController->hasRemove = $hasRemove;
  119. $currentMethod = $currentController->addMethod("index", "/$line");
  120. if(!empty($currentSubController)) {
  121. $currentSubController->save();
  122. }
  123. $currentSubType = '';
  124. $currentSubController = new GenController();
  125. $sideLinks[] = "<li class='nav-item'><a href='/{$currentController->name}' " .
  126. "class='nav-link " .
  127. "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>" .
  128. "<i class='nav-icon fa fa-user'></i>" .
  129. "<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>" .
  130. "</a></li>";
  131. }
  132. break;
  133. case 8: // sub-type declaration | add_new fields | !inc/!exc
  134. if($line === 'ACTIONS' || $line === 'SUB') {
  135. $currentSubType = $line;
  136. }
  137. else if(strpos($line, "!inc:") === 0) { // !inc:
  138. if (!empty($currentMethod)) {
  139. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  140. }
  141. }
  142. else if(strpos($line, "!exc:") === 0) { // !exc:
  143. if (!empty($currentMethod)) {
  144. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  145. }
  146. }
  147. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  148. if (!empty($currentMethod)) {
  149. $currentMethod->viewLinkField = substr($line, 5);
  150. }
  151. }
  152. else if(strpos($line, "!col:") === 0) { // !col:
  153. if (!empty($currentMethod)) {
  154. $currentMethod->setColumnSpec(substr($line, 5), $exitURL, 'record');
  155. }
  156. }
  157. else if (!empty($currentMethod) &&
  158. (strpos($currentMethod->name, 'add_new') === 0 ||
  159. $currentMethod->name === 'remove')) { // this is a field in add_new
  160. $currentMethod->data[] = $line;
  161. }
  162. break;
  163. case 12: // ACTIONS | SUB
  164. // check if this has show conditions
  165. $show = false;
  166. if(strpos($line, ":")) {
  167. $parts = explode(":", $line);
  168. $line = $parts[0];
  169. if($parts[1] === 'if') {
  170. $show = $parts[2];
  171. }
  172. }
  173. if($currentSubType === 'ACTIONS') {
  174. $currentMethod = $currentSubController->addMethod(
  175. "ACTION_" . $line,
  176. "/ACTION_" . $line
  177. );
  178. $currentMethod->type = 'action';
  179. $currentMethod->show = $show;
  180. $currentMethod->data = [];
  181. }
  182. else if($currentSubType === 'SUB') {
  183. $currentMethod = $currentSubController->addMethod(
  184. "SUB_" . $line,
  185. "/SUB_" . $line
  186. );
  187. $currentMethod->type = 'sub';
  188. $currentMethod->show = $show;
  189. $currentMethod->data = [];
  190. }
  191. break;
  192. case 16: // data for actions and subs
  193. if(strpos($line, "!inc:") === 0) { // !inc:
  194. if (!empty($currentMethod)) {
  195. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  196. }
  197. }
  198. else if(strpos($line, "!exc:") === 0) { // !exc:
  199. if (!empty($currentMethod)) {
  200. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  201. }
  202. }
  203. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  204. if (!empty($currentMethod)) {
  205. $currentMethod->viewLinkField = substr($line, 5);
  206. }
  207. }
  208. else if(strpos($line, "!col:") === 0) { // !col:
  209. if (!empty($currentMethod)) {
  210. $currentMethod->setColumnSpec(substr($line, 5), $exitURL,
  211. $currentMethod->name === 'SUB_dashboard' ? 'record' : 'subRecord'
  212. );
  213. }
  214. }
  215. else if(strpos($line, "!grp:") === 0) { // !grp:
  216. if (!empty($currentMethod)) {
  217. $currentMethod->addGroup(substr($line, 5));
  218. }
  219. }
  220. else if(strpos($line, "!act:") === 0) { // !act:
  221. if (!empty($currentMethod)) {
  222. $currentMethod->addColumnAction(substr($line, 5), $exitURL);
  223. }
  224. }
  225. else if(!empty($currentMethod)) {
  226. $currentMethod->data[] = $line;
  227. if($exitURL) {
  228. if(strpos("=", $line) !== FALSE) {
  229. $currentMethod->viewURL = $exitURL;
  230. }
  231. else {
  232. $currentMethod->exitURL = $exitURL;
  233. }
  234. }
  235. }
  236. break;
  237. case 20: // SUB add_new fields
  238. if(!empty($currentMethod)) {
  239. $currentMethod->data[] = $line;
  240. }
  241. break;
  242. default:
  243. dump("ERROR: Cannot have $ls leading spaces!");
  244. dump("Line: $line");
  245. exit(1);
  246. }
  247. }
  248. }
  249. // do any pending saves
  250. if(!empty($currentSubController)) {
  251. $currentSubController->save();
  252. }
  253. if(!empty($currentController)) {
  254. $currentController->save();
  255. }
  256. echo "Saved " . base_path("routes/generated.php") . "\n";
  257. // save side links
  258. file_put_contents(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  259. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  260. }
  261. private function numLS($line) {
  262. $count = 0;
  263. for ($i=0; $i<strlen($line); $i++) {
  264. if($line[$i] !== ' ') break;
  265. $count++;
  266. }
  267. return $count;
  268. }
  269. }
  270. class GenController {
  271. public $root;
  272. public $saved = false;
  273. public $name;
  274. public $methods;
  275. public $parentRoute = "";
  276. public $dbTable = null;
  277. public $condition = null;
  278. public $hasAdd = false;
  279. public $hasView = false;
  280. public $hasRemove = false;
  281. public $sub = false;
  282. public $parentControllerName = '';
  283. public $subLinksSaved = false;
  284. public $actionLinksSaved = false;
  285. public function __construct($root = null, $name = null)
  286. {
  287. $this->root = $root;
  288. $this->name = $name;
  289. $this->methods = [];
  290. }
  291. public function addMethod($method, $route) {
  292. if($this->parentRoute) {
  293. $route = $this->parentRoute . $route;
  294. }
  295. $method = new GenControllerMethod($method, $route);
  296. $this->methods[] = $method;
  297. return $method;
  298. }
  299. public function save() {
  300. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  301. $this->saveController();
  302. $this->saveRoutes();
  303. $this->saved = true;
  304. // $this->log();
  305. }
  306. }
  307. public function saveController() {
  308. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  309. $code = [];
  310. // check if any method has a "sub add_new" in it, if yes, add action for the same
  311. $newMethods = [];
  312. foreach ($this->methods as $method) {
  313. if($method->type === 'sub' && count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  314. $methodName = preg_replace("/^SUB_/", "ACTION_", $method->name) . 'AddNew';
  315. $methodRoute = str_replace("/SUB_", "/ACTION_", $method->route) . 'AddNew';
  316. $newMethod = new GenControllerMethod($methodName, $methodRoute);
  317. $newMethod->hasUID = true;
  318. $newMethod->redirect = false;
  319. $newMethod->type = 'action';
  320. $newMethod->data = [];
  321. for($i = 2; $i<count($method->data); $i++) {
  322. $newMethod->data[] = $method->data[$i];
  323. }
  324. $newMethod->parentSub = $this->name . '-' . $method->name;
  325. $parts = explode(":", $method->data[1]);
  326. $newMethod->table = $parts[1];
  327. if(count($parts) === 3) {
  328. $newMethod->api = $parts[2];
  329. }
  330. $newMethod->exitURL = $method->exitURL;
  331. $newMethod->showLink = false;
  332. $newMethods[] = $newMethod;
  333. $method->childAddRoute = $this->name . '-' . $methodName;
  334. }
  335. }
  336. $this->methods = array_merge($this->methods, $newMethods);
  337. foreach ($this->methods as $method) {
  338. $code[] = "";
  339. $code[] = "\t// GET {$method->route}";
  340. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  341. if($method->redirect) {
  342. $target = str_replace('{uid}', '$uid', $method->redirect);
  343. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  344. }
  345. else {
  346. if($method->hasUID) {
  347. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  348. $input = ["'record'"];
  349. // if sub-index controller, load subRecords
  350. if($method->type === 'sub' && count($method->data)) {
  351. $parts = explode(",", $method->data[0]);
  352. $loadingLine = [];
  353. // first 'where'
  354. $dbParts = explode("=", $parts[0]);
  355. $localField = $dbParts[0];
  356. $dbParts = explode(".", $dbParts[1]);
  357. $foreignTable = $dbParts[0];
  358. $foreignField = $dbParts[1];
  359. $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
  360. $loadingLine[] = "->where('$foreignField', \$record->$localField)";
  361. // other 'where's
  362. if(count($parts) > 1) {
  363. for ($i = 1; $i < count($parts); $i++) {
  364. $dbParts = explode("=", $parts[$i]);
  365. $field = $dbParts[0];
  366. $value = $dbParts[1];
  367. $loadingLine[] = "->where('$field', $value)";
  368. }
  369. }
  370. $loadingLine[] = "->get();";
  371. $code[] = implode("", $loadingLine);
  372. // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  373. $input[] = "'subRecords'";
  374. }
  375. // return response()->view('pro/my_teams/add_new', compact('records'), session('message') ? 500 : 200)->header('Content-Type', 'text/html');
  376. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  377. "compact(" . implode(", ", $input) . "), " .
  378. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  379. }
  380. else {
  381. $loadingLine = [];
  382. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  383. if($this->condition) {
  384. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  385. }
  386. $loadingLine[] = "->get();";
  387. $code[] = implode("", $loadingLine);
  388. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  389. "compact('records'), " .
  390. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  391. }
  392. }
  393. $this->saveView($this, $method);
  394. $code[] = "\t}";
  395. }
  396. $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
  397. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  398. file_put_contents(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  399. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  400. }
  401. public function saveView(GenController $controller, GenControllerMethod $method) {
  402. if($controller->sub) {
  403. $controller->saveSubLinks($controller, $method);
  404. $controller->saveActionLinks($controller, $method);
  405. if($method->type === 'action') {
  406. $this->saveSubActionView($controller, $method);
  407. }
  408. else if($method->type === 'sub' && count($method->data)) {
  409. $this->saveSubIndexView($controller, $method);
  410. }
  411. else {
  412. $this->saveSubDefaultView($controller, $method);
  413. }
  414. }
  415. else {
  416. if($method->name === 'view' && $controller->hasView) {
  417. $this->saveShowView($controller, $method);
  418. }
  419. else if($method->name === 'index') {
  420. $this->saveIndexView($controller, $method);
  421. }
  422. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  423. $this->saveAddNewView($controller, $method);
  424. }
  425. else if($method->name === 'remove' && $controller->hasRemove) {
  426. $this->saveAddNewView($controller, $method);
  427. }
  428. }
  429. }
  430. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  431. {
  432. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  433. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  434. if($controller->hasAdd) {
  435. $addLinks = [];
  436. foreach ($controller->methods as $m) {
  437. if($m->type === 'add') {
  438. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  439. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  440. "href='/{$controller->name}/{$m->name}'>" .
  441. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  442. "{$this->snakeToTitleCase($m->name)}</a>";
  443. }
  444. }
  445. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  446. }
  447. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  448. $ths = [];
  449. $tds = [];
  450. if($controller->hasRemove) {
  451. $ths[] = "<th></th>";
  452. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  453. "<i class='fa fa-trash'></i>" .
  454. "</a></td>";
  455. }
  456. // !inc/!exc
  457. if($method->incType === "include") {
  458. $columns = $method->incFields;
  459. }
  460. else if($method->incType === "exclude") {
  461. $columns = array_filter($columns, function($item) use ($method) {
  462. return in_array($item, $method->incFields) === FALSE;
  463. });
  464. }
  465. foreach ($columns as $column) {
  466. $columnTitle = $this->snakeToTitleCase($column);
  467. $columnValue = "<?= \$record->$column ?>";
  468. $hasLink = $controller->hasView && $column === $method->viewLinkField;
  469. $linkTarget = "/{$controller->name}/view/<?= \$record->uid ?>";
  470. // check if this column has column spec
  471. if(isset($method->columns[$column])) {
  472. $columnTitle = $method->columns[$column]["label"];
  473. if(isset($method->columns[$column]["query"])) {
  474. $columnValue = "<?= \Illuminate\Support\Facades\DB::" .
  475. "select(\"{$method->columns[$column]["query"]}\")[0]->result ?>";
  476. }
  477. if(isset($method->columns[$column]["link"])) {
  478. $hasLink = true;
  479. $linkTarget = $method->columns[$column]["link"];
  480. }
  481. }
  482. $ths[] = "<th>$columnTitle</th>";
  483. $tds[] = "<td>" .
  484. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  485. $columnValue .
  486. ($hasLink ? "</a>" : "") .
  487. "</td>";
  488. }
  489. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  490. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  491. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  492. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  493. }
  494. public function saveShowView(GenController $controller, GenControllerMethod $method)
  495. {
  496. // delete sub links and action links
  497. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  498. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  499. }
  500. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  501. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  502. }
  503. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  504. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  505. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  506. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  507. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  508. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  509. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  510. }
  511. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  512. {
  513. if ($controller->subLinksSaved) return;
  514. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  515. $subLinks = [];
  516. foreach ($controller->methods as $meth) {
  517. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  518. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  519. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  520. "<a " .
  521. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  522. "class='d-block px-3 py-2 border-bottom " .
  523. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  524. (
  525. $meth->name === 'SUB_dashboard' ?
  526. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  527. ""
  528. )
  529. . "'>$display</a>" .
  530. ($meth->show ? " @endif" : "");
  531. }
  532. $this->file_force_contents($subLinksView, implode("\n", $subLinks));
  533. echo "Generated " . $subLinksView . "\n";
  534. $controller->subLinksSaved = true;
  535. }
  536. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  537. {
  538. if ($controller->actionLinksSaved) return;
  539. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  540. $actionLinks = [];
  541. foreach ($controller->methods as $meth) {
  542. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  543. $display = $this->camelToTitleCase(substr($meth->name, 7));
  544. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  545. "<a " .
  546. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  547. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  548. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  549. ($meth->show ? " @endif" : "");
  550. }
  551. $this->file_force_contents($actionLinksView, implode("\n", $actionLinks));
  552. echo "Generated " . $actionLinksView . "\n";
  553. $controller->actionLinksSaved = true;
  554. }
  555. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  556. {
  557. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  558. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  559. $text = $this->generateSubContent($controller, $method, $text);
  560. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  561. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  562. }
  563. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  564. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  565. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  566. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  567. if(!$method->parentSub) {
  568. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  569. }
  570. else {
  571. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  572. }
  573. if(!$method->table) {
  574. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  575. }
  576. else {
  577. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  578. }
  579. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  580. $fields = [];
  581. if(count($method->data)) {
  582. foreach ($method->data as $field) {
  583. $fields[] = $this->generateFormField($field);
  584. }
  585. }
  586. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  587. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  588. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  589. }
  590. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  591. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  592. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  593. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  594. if(count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  595. $addLink = '<a class="btn btn-primary btn-sm" ' .
  596. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  597. 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
  598. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  599. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  600. }
  601. $dbParts = explode("=", $method->data[0]);
  602. $dbParts = explode(".", $dbParts[1]);
  603. $table = $dbParts[0];
  604. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  605. $ths = [];
  606. $tds = [];
  607. // !inc/!exc
  608. if($method->incType === "include") {
  609. $columns = $method->incFields;
  610. }
  611. else if($method->incType === "exclude") {
  612. $columns = array_filter($columns, function($item) use ($method) {
  613. return in_array($item, $method->incFields) === FALSE;
  614. });
  615. }
  616. foreach ($columns as $column) {
  617. $columnTitle = $this->snakeToTitleCase($column);
  618. $columnValue = "<?= \$subRecord->$column ?>";
  619. $hasLink = $method->exitURL && $column === $method->viewLinkField;
  620. $linkTarget = $method->exitURL;
  621. // check if this column has column spec
  622. if(isset($method->columns[$column])) {
  623. $columnTitle = $method->columns[$column]["label"];
  624. if(isset($method->columns[$column]["query"])) {
  625. $columnValue = "<?= \Illuminate\Support\Facades\DB::" .
  626. "select(\"{$method->columns[$column]["query"]}\")[0]->result ?>";
  627. }
  628. if(isset($method->columns[$column]["link"])) {
  629. $hasLink = true;
  630. $linkTarget = $method->columns[$column]["link"];
  631. }
  632. }
  633. $ths[] = "<th>$columnTitle</th>";
  634. $tds[] = "<td>" .
  635. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  636. $columnValue .
  637. ($hasLink ? "</a>" : "") .
  638. "</td>";
  639. }
  640. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  641. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  642. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  643. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  644. }
  645. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  646. if($method->name === 'SUB_dashboard') {
  647. if(!isset($method->groups) || !count($method->groups)) {
  648. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
  649. }
  650. else {
  651. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard-grouped.template.blade.php'));
  652. $groupsHtml = [];
  653. $groupTemplate = file_get_contents(base_path('generatecv/tree-templates/dashboard-group.template.blade.php'));
  654. foreach ($method->groups as $group) {
  655. $groupHtml = $groupTemplate;
  656. $groupHtml = str_replace("<!-- __GROUP_NAME__ -->", $group["name"], $groupHtml);
  657. $fields = [];
  658. foreach ($group["fields"] as $field) {
  659. $columnTitle = $this->snakeToTitleCase($field);
  660. $columnValue = "<?= \$record->$field ?>";
  661. $hasLink = false;
  662. $linkTarget = null;
  663. $actions = [];
  664. // check if this column has column spec
  665. if(isset($method->columns[$field])) {
  666. $columnTitle = $method->columns[$field]["label"];
  667. if(isset($method->columns[$field]["query"])) {
  668. $columnValue = "<?= \Illuminate\Support\Facades\DB::" .
  669. "select(\"{$method->columns[$field]["query"]}\")[0]->result ?>";
  670. }
  671. if(isset($method->columns[$field]["link"])) {
  672. $hasLink = true;
  673. $linkTarget = $method->columns[$field]["link"];
  674. }
  675. }
  676. /*
  677. "is_active" => array:1 [
  678. 0 => array:5 [
  679. "label" => "Deactivate"
  680. "icon" => "edit"
  681. "condition" => "if"
  682. "field" => "is_active"
  683. ]
  684. ]
  685. */
  686. if(isset($method->columnActions[$field])) {
  687. foreach($method->columnActions[$field] as $action) {
  688. $actionLine = [];
  689. if(isset($action["condition"])) {
  690. if($action["condition"] === "if") {
  691. $actionLine[] = "@if(";
  692. }
  693. else {
  694. $actionLine[] = "@if(!";
  695. }
  696. $actionLine[] = "\$record->{$action["field"]})";
  697. }
  698. $actionLine[] = "<a " .
  699. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  700. "href='{$action["link"]}' title='{$action["label"]}' class='ml-2 text-dark font-weight-normal'>" .
  701. "<i class='fa fa-{$action["icon"]} text-sm'></i>" .
  702. "</a>";
  703. if(isset($action["condition"])) {
  704. $actionLine[] = "@endif";
  705. }
  706. $actionLine = implode(" ", $actionLine);
  707. $actions[] = $actionLine;
  708. }
  709. }
  710. $actions = implode("\n", $actions);
  711. $fields[] = "<tr>" .
  712. "<td class=\"w-25 px-2 text-secondary border-right\">$columnTitle</td>" .
  713. "<td class=\"w-75 px-2 font-weight-bold\">" .
  714. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  715. $columnValue .
  716. ($hasLink ? "</a>" : "") .
  717. $actions .
  718. "</td>" .
  719. "</tr>";
  720. }
  721. $groupHtml = str_replace("<!-- __GROUP_FIELDS__ -->", implode("\n", $fields), $groupHtml);
  722. $groupsHtml[] = $groupHtml;
  723. }
  724. $groupsHtml = implode("\n", $groupsHtml);
  725. $html = str_replace("<!-- _GROUPS_ -->", $groupsHtml, $html);
  726. }
  727. $text = str_replace("_SUB_VIEW_", $html, $text);
  728. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  729. }
  730. else {
  731. $text = str_replace("_SUB_VIEW_",
  732. "<h4 class='py-3 border-bottom'>" .
  733. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
  734. "Controller: <b>{$controller->name}</b><br>" .
  735. "Action: <b>{$method->name}()</b><br>" .
  736. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br>",
  737. $text);
  738. }
  739. return $text;
  740. }
  741. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  742. {
  743. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  744. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  745. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  746. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  747. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  748. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  749. $columns = $method->data;
  750. $fields = [];
  751. foreach ($columns as $column) {
  752. $fields[] = $this->generateFormField($column);
  753. }
  754. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  755. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  756. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  757. }
  758. public function saveRoutes() {
  759. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  760. foreach ($this->methods as $method) {
  761. // FORMAT:
  762. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  763. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  764. }
  765. $lines[] = '';
  766. $lines[] = '';
  767. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  768. }
  769. public function log() {
  770. $this->w('');
  771. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  772. $this->w("Table: {$this->dbTable}");
  773. $this->w('---------------------------------------------');
  774. foreach ($this->methods as $method) {
  775. $this->w('Rout: ' . $method->route, 1);
  776. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  777. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  778. $this->w('Exit: ' . $method->exitURL, 1);
  779. $this->w('View: ' . $method->viewURL, 1);
  780. if(!$method->redirect) {
  781. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  782. }
  783. else {
  784. $this->w('Redi: ' . $method->redirect, 1);
  785. }
  786. $this->w('---------------------------------------------');
  787. }
  788. }
  789. public function w($line, $level = -1) {
  790. for($i=0; $i<$level; $i++) echo "\t";
  791. echo "$line\n";
  792. }
  793. public function snakeToTitleCase($text) {
  794. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  795. return ucwords(str_replace("_", " ", $text));
  796. }
  797. public function camelToTitleCase($text) {
  798. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  799. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  800. return ucwords($text);
  801. }
  802. public function snakeToCamelCase($text) {
  803. $text = ucwords(str_replace("_", " ", $text));
  804. $text = str_replace(" ", "", $text);
  805. $text[0] = strtolower($text[0]);
  806. return $text;
  807. }
  808. private function file_force_contents($dir, $contents){
  809. $dir = str_replace("\\", "/", $dir);
  810. $dir = str_replace( '//', '/', $dir);
  811. $parts = explode('/', $dir);
  812. $file = array_pop($parts);
  813. $dir = '';
  814. foreach($parts as $part) {
  815. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  816. if(!is_dir($dir .= "/$part")) mkdir($dir);
  817. }
  818. }
  819. file_put_contents("$dir/$file", $contents);
  820. }
  821. private function generateFormField($line) {
  822. $tokens = explode("=", $line);
  823. $default = false;
  824. if(count($tokens) > 1) {
  825. $default = $tokens[1];
  826. }
  827. $tokens = explode(":", $tokens[0]);
  828. $name = $tokens[0];
  829. $required = false;
  830. if($name[strlen($name) - 1] === '*') { // required field?
  831. $required = true;
  832. $name = substr($name, 0, strlen($name) - 1);
  833. }
  834. $display = $name;
  835. $dotPos = strpos($name, ".");
  836. if($dotPos !== FALSE) {
  837. $display = substr($name, $dotPos + 1);
  838. }
  839. $display = preg_replace('/uid$/i', "", $display);
  840. $type = "text";
  841. $options = [];
  842. if(count($tokens) > 1) {
  843. $type = $tokens[1];
  844. switch ($type) {
  845. case "select":
  846. $options = explode(",", $tokens[2]);
  847. break;
  848. case "record":
  849. $options['table'] = $tokens[2];
  850. $parts = explode(",", $tokens[3]);
  851. $options['valueField'] = $parts[0];
  852. $options['displayField'] = $parts[1];
  853. break;
  854. }
  855. }
  856. if($type !== 'hidden' && $type !== 'bool') {
  857. $code[] = "<div class='form-group mb-3'>";
  858. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  859. ($required ? "*" : "") .
  860. "</label>";
  861. }
  862. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  863. switch ($type) {
  864. case "select":
  865. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  866. ($required ? "required" : "") .
  867. ">";
  868. $code[] = "<option value=''>-- Select --</option>";
  869. foreach ($options as $o) {
  870. $code[] = "<option " .
  871. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  872. "value='$o'>$o</option>";
  873. }
  874. $code[] = "</select>";
  875. break;
  876. case "record":
  877. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  878. ($required ? "required" : "") .
  879. ">";
  880. $code[] = "<option value=''>-- Select --</option>";
  881. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  882. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  883. $code[] = "<option " .
  884. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  885. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  886. $code[] = "<?php endforeach; ?>";
  887. $code[] = "</select>";
  888. break;
  889. case "bool":
  890. $code[] = "<div class='form-group mb-3'>";
  891. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  892. ($required ? "*" : "");
  893. $code[] = "<input class='ml-2' type='checkbox' name='$name' " .
  894. ($required ? "required" : "") .
  895. ">";
  896. $code[] = "</label>";
  897. break;
  898. default:
  899. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
  900. ($required ? "required" : "") .
  901. ">";
  902. }
  903. if($type !== 'hidden') {
  904. $code[] = "</div>";
  905. }
  906. return implode("\n", $code);
  907. }
  908. }
  909. class GenControllerMethod {
  910. public $name;
  911. public $route;
  912. public $hasUID = false;
  913. public $redirect = false;
  914. public $type = '';
  915. public $data = [];
  916. public $parentSub = false;
  917. public $childAddRoute = false;
  918. public $table = false;
  919. public $api = 'create';
  920. public $show = null;
  921. public $viewURL = false;
  922. public $exitURL = false;
  923. public $showLink = true;
  924. public $incType = null;
  925. public $incFields = null;
  926. public $viewLinkField = 'uid';
  927. public $columns = [];
  928. public $columnActions = [];
  929. public $groups = [];
  930. public function __construct($name, $route)
  931. {
  932. $this->name = $name;
  933. $this->route = $route;
  934. if(strpos($this->route, "{uid}") !== FALSE) {
  935. $this->hasUID = true;
  936. }
  937. }
  938. public function setIncFields($type, $fields) {
  939. $this->incType = $type;
  940. $this->incFields = $fields;
  941. for ($i = 0; $i < count($this->incFields); $i++) {
  942. if($this->incFields[$i][0] === '@') {
  943. $this->incFields[$i] = substr($this->incFields[$i], 1);
  944. $this->viewLinkField = $this->incFields[$i];
  945. }
  946. }
  947. }
  948. public function setColumnSpec($line, $link, $recordVariable) {
  949. // ally_pro_id:Ally Pro:select name_display as 'result' from pro where id = $ally_pro_id limit 1
  950. $parts = explode(":", $line);
  951. $spec = [
  952. "label" => $parts[1]
  953. ];
  954. if(count($parts) > 2) {
  955. $query = $parts[2];
  956. $query = preg_replace("/\\$([a-zA-Z0-9_]+)/", "{\$$recordVariable->$1}", $query);
  957. $spec['query'] = $query;
  958. }
  959. if($link) {
  960. $spec['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$$recordVariable->$1 ?>", $link);
  961. }
  962. $this->columns[$parts[0]] = $spec;
  963. }
  964. public function addGroup($line) {
  965. // Basic Details:id,uid,created_at,clients_count
  966. $parts = explode(":", $line);
  967. $this->groups[] = [
  968. "name" => $parts[0],
  969. "fields" => explode(",", $parts[1])
  970. ];
  971. }
  972. public function addColumnAction($line, $link) {
  973. // is_active:Deactivate:deactivate:edit:if:is_active
  974. $parts = explode(":", $line);
  975. $action = [
  976. "label" => $parts[1],
  977. "icon" => isset($parts[2]) ? $parts[2] : 'edit'
  978. ];
  979. if(count($parts) >= 5 ) {
  980. $action["condition"] = $parts[3];
  981. $action["field"] = $parts[4];
  982. }
  983. if($link) {
  984. $action['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$record->$1 ?>", $link);
  985. }
  986. if(!isset($this->columnActions[$parts[0]])) {
  987. $this->columnActions[$parts[0]] = [];
  988. }
  989. $this->columnActions[$parts[0]][] = $action;
  990. }
  991. }