GenerateTreeCommand.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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", "Auth::user()->id" , $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. $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
  134. if($line === 'ACTIONS' || $line === 'SUB') {
  135. $currentSubType = $line;
  136. }
  137. else if (!empty($currentMethod) &&
  138. (strpos($currentMethod->name, 'add_new') === 0 ||
  139. $currentMethod->name === 'remove')) { // this is a field in add_new
  140. $currentMethod->data[] = $line;
  141. }
  142. break;
  143. case 12: // ACTIONS | SUB
  144. // check if this has show conditions
  145. $show = false;
  146. if(strpos($line, ":")) {
  147. $parts = explode(":", $line);
  148. $line = $parts[0];
  149. if($parts[1] === 'if') {
  150. $show = $parts[2];
  151. }
  152. }
  153. if($currentSubType === 'ACTIONS') {
  154. $currentMethod = $currentSubController->addMethod(
  155. "ACTION_" . $line,
  156. "/ACTION_" . $line
  157. );
  158. $currentMethod->type = 'action';
  159. $currentMethod->show = $show;
  160. $currentMethod->data = [];
  161. }
  162. else if($currentSubType === 'SUB') {
  163. $currentMethod = $currentSubController->addMethod(
  164. "SUB_" . $line,
  165. "/SUB_" . $line
  166. );
  167. $currentMethod->type = 'sub';
  168. $currentMethod->show = $show;
  169. $currentMethod->data = [];
  170. }
  171. break;
  172. case 16: // data for actions and subs
  173. if(!empty($currentMethod)) {
  174. $currentMethod->data[] = $line;
  175. if($exitURL) {
  176. if(strpos("=", $line) !== FALSE) {
  177. $currentMethod->viewURL = $exitURL;
  178. }
  179. else {
  180. $currentMethod->exitURL = $exitURL;
  181. }
  182. }
  183. }
  184. break;
  185. case 20: // SUB add_new fields
  186. if(!empty($currentMethod)) {
  187. $currentMethod->data[] = $line;
  188. }
  189. break;
  190. default:
  191. dump("ERROR: Cannot have $ls leading spaces!");
  192. dump("Line: $line");
  193. exit(1);
  194. }
  195. }
  196. }
  197. // do any pending saves
  198. if(!empty($currentSubController)) {
  199. $currentSubController->save();
  200. }
  201. if(!empty($currentController)) {
  202. $currentController->save();
  203. }
  204. echo "Saved " . base_path("routes/generated.php") . "\n";
  205. // save side links
  206. file_put_contents(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  207. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  208. }
  209. private function numLS($line) {
  210. $count = 0;
  211. for ($i=0; $i<strlen($line); $i++) {
  212. if($line[$i] !== ' ') break;
  213. $count++;
  214. }
  215. return $count;
  216. }
  217. }
  218. class GenController {
  219. public $root;
  220. public $saved = false;
  221. public $name;
  222. public $methods;
  223. public $parentRoute = "";
  224. public $dbTable = null;
  225. public $condition = null;
  226. public $hasAdd = false;
  227. public $hasView = false;
  228. public $hasRemove = false;
  229. public $sub = false;
  230. public $parentControllerName = '';
  231. public $subLinksSaved = false;
  232. public $actionLinksSaved = false;
  233. public function __construct($root = null, $name = null)
  234. {
  235. $this->root = $root;
  236. $this->name = $name;
  237. $this->methods = [];
  238. }
  239. public function addMethod($method, $route) {
  240. if($this->parentRoute) {
  241. $route = $this->parentRoute . $route;
  242. }
  243. $method = new GenControllerMethod($method, $route);
  244. $this->methods[] = $method;
  245. return $method;
  246. }
  247. public function save() {
  248. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  249. $this->saveController();
  250. $this->saveRoutes();
  251. $this->saved = true;
  252. // $this->log();
  253. }
  254. }
  255. public function saveController() {
  256. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  257. $code = [];
  258. // check if any method has a "sub add_new" in it, if yes, add action for the same
  259. $newMethods = [];
  260. foreach ($this->methods as $method) {
  261. if($method->type === 'sub' && count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  262. $methodName = preg_replace("/^SUB_/", "ACTION_", $method->name) . 'AddNew';
  263. $methodRoute = str_replace("/SUB_", "/ACTION_", $method->route) . 'AddNew';
  264. $newMethod = new GenControllerMethod($methodName, $methodRoute);
  265. $newMethod->hasUID = true;
  266. $newMethod->redirect = false;
  267. $newMethod->type = 'action';
  268. $newMethod->data = [];
  269. for($i = 2; $i<count($method->data); $i++) {
  270. $newMethod->data[] = $method->data[$i];
  271. }
  272. $newMethod->parentSub = $this->name . '-' . $method->name;
  273. $parts = explode(":", $method->data[1]);
  274. $newMethod->table = $parts[1];
  275. if(count($parts) === 3) {
  276. $newMethod->api = $parts[2];
  277. }
  278. $newMethod->exitURL = $method->exitURL;
  279. $newMethod->showLink = false;
  280. $newMethods[] = $newMethod;
  281. $method->childAddRoute = $this->name . '-' . $methodName;
  282. }
  283. }
  284. $this->methods = array_merge($this->methods, $newMethods);
  285. foreach ($this->methods as $method) {
  286. $code[] = "";
  287. $code[] = "\t// GET {$method->route}";
  288. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  289. if($method->redirect) {
  290. $target = str_replace('{uid}', '$uid', $method->redirect);
  291. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  292. }
  293. else {
  294. if($method->hasUID) {
  295. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  296. $input = ["'record'"];
  297. // if sub-index controller, load subRecords
  298. if($method->type === 'sub' && count($method->data)) {
  299. $dbParts = explode("=", $method->data[0]);
  300. $localField = $dbParts[0];
  301. $dbParts = explode(".", $dbParts[1]);
  302. $foreignTable = $dbParts[0];
  303. $foreignField = $dbParts[1];
  304. $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  305. $input[] = "'subRecords'";
  306. }
  307. $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', " .
  308. "compact(" . implode(", ", $input) . "));";
  309. }
  310. else {
  311. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  312. if($this->condition) {
  313. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  314. }
  315. $loadingLine[] = "->get();";
  316. $code[] = implode("", $loadingLine);
  317. $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', " .
  318. "compact('records'));";
  319. }
  320. }
  321. $this->saveView($this, $method);
  322. $code[] = "\t}";
  323. }
  324. $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
  325. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  326. file_put_contents(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  327. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  328. }
  329. public function saveView(GenController $controller, GenControllerMethod $method) {
  330. if($controller->sub) {
  331. $controller->saveSubLinks($controller, $method);
  332. $controller->saveActionLinks($controller, $method);
  333. if($method->type === 'action') {
  334. $this->saveSubActionView($controller, $method);
  335. }
  336. else if($method->type === 'sub' && count($method->data)) {
  337. $this->saveSubIndexView($controller, $method);
  338. }
  339. else {
  340. $this->saveSubDefaultView($controller, $method);
  341. }
  342. }
  343. else {
  344. if($method->name === 'view' && $controller->hasView) {
  345. $this->saveShowView($controller, $method);
  346. }
  347. else if($method->name === 'index') {
  348. $this->saveIndexView($controller, $method);
  349. }
  350. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  351. $this->saveAddNewView($controller, $method);
  352. }
  353. else if($method->name === 'remove' && $controller->hasRemove) {
  354. $this->saveAddNewView($controller, $method);
  355. }
  356. }
  357. }
  358. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  359. {
  360. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  361. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  362. if($controller->hasAdd) {
  363. $addLinks = [];
  364. foreach ($controller->methods as $m) {
  365. if($m->type === 'add') {
  366. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  367. "href='/{$controller->name}/{$m->name}'>" .
  368. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  369. "{$this->snakeToTitleCase($m->name)}</a>";
  370. }
  371. }
  372. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  373. }
  374. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  375. $ths = [];
  376. $tds = [];
  377. if($controller->hasRemove) {
  378. $ths[] = "<th></th>";
  379. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  380. "<i class='fa fa-trash'></i>" .
  381. "</a></td>";
  382. }
  383. foreach ($columns as $column) {
  384. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  385. $tds[] = "<td>" .
  386. ($controller->hasView && $column === 'uid' ? '<a href="/' . $controller->name . '/view/<?= $record->uid ?>">' : '') .
  387. "<?= \$record->$column ?>" .
  388. ($controller->hasView && $column === 'uid' ? '</a>' : '') .
  389. "</td>";
  390. }
  391. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  392. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  393. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  394. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  395. }
  396. public function saveShowView(GenController $controller, GenControllerMethod $method)
  397. {
  398. // delete sub links and action links
  399. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  400. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  401. }
  402. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  403. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  404. }
  405. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  406. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  407. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  408. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  409. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  410. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  411. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  412. }
  413. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  414. {
  415. if ($controller->subLinksSaved) return;
  416. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  417. $subLinks = [];
  418. foreach ($controller->methods as $meth) {
  419. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  420. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  421. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  422. "<a " .
  423. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  424. "class='d-block px-3 py-2 border-bottom " .
  425. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  426. (
  427. $meth->name === 'SUB_dashboard' ?
  428. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  429. ""
  430. )
  431. . "'>$display</a>" .
  432. ($meth->show ? " @endif" : "");
  433. }
  434. $this->file_force_contents($subLinksView, implode("\n", $subLinks));
  435. echo "Generated " . $subLinksView . "\n";
  436. $controller->subLinksSaved = true;
  437. }
  438. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  439. {
  440. if ($controller->actionLinksSaved) return;
  441. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  442. $actionLinks = [];
  443. foreach ($controller->methods as $meth) {
  444. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  445. $display = $this->camelToTitleCase(substr($meth->name, 7));
  446. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  447. "<a " .
  448. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  449. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  450. ($meth->show ? " @endif" : "");
  451. }
  452. $this->file_force_contents($actionLinksView, implode("\n", $actionLinks));
  453. echo "Generated " . $actionLinksView . "\n";
  454. $controller->actionLinksSaved = true;
  455. }
  456. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  457. {
  458. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  459. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  460. $text = $this->generateSubContent($controller, $method, $text);
  461. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  462. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  463. }
  464. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  465. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  466. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  467. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  468. if(!$method->parentSub) {
  469. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  470. }
  471. else {
  472. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  473. }
  474. if(!$method->table) {
  475. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  476. }
  477. else {
  478. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  479. }
  480. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  481. $fields = [];
  482. if(count($method->data)) {
  483. foreach ($method->data as $field) {
  484. $fields[] = $this->generateFormField($field);
  485. }
  486. }
  487. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  488. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  489. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  490. }
  491. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  492. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  493. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  494. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  495. if(count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  496. $addLink = '<a class="btn btn-primary btn-sm" ' .
  497. 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
  498. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  499. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  500. }
  501. $dbParts = explode("=", $method->data[0]);
  502. $dbParts = explode(".", $dbParts[1]);
  503. $table = $dbParts[0];
  504. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  505. $ths = [];
  506. $tds = [];
  507. foreach ($columns as $column) {
  508. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  509. $tds[] = "<td>" .
  510. ($method->exitURL && $column === 'uid' ? '<a href="' . $method->exitURL . '">' : '') .
  511. "<?= \$subRecord->$column ?>" .
  512. ($method->exitURL && $column === 'uid' ? '</a>' : '') .
  513. "</td>";
  514. }
  515. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  516. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  517. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  518. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  519. }
  520. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  521. if($method->name === 'SUB_dashboard') {
  522. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
  523. $text = str_replace("_SUB_VIEW_", $html, $text);
  524. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  525. }
  526. else {
  527. $text = str_replace("_SUB_VIEW_",
  528. "<h4 class='py-3 border-bottom'>" .
  529. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
  530. "Controller: <b>{$controller->name}</b><br>" .
  531. "Action: <b>{$method->name}()</b><br>" .
  532. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br>",
  533. $text);
  534. }
  535. return $text;
  536. }
  537. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  538. {
  539. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  540. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  541. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  542. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  543. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  544. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  545. $columns = $method->data;
  546. $fields = [];
  547. foreach ($columns as $column) {
  548. $fields[] = $this->generateFormField($column);
  549. }
  550. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  551. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  552. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  553. }
  554. public function saveRoutes() {
  555. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  556. foreach ($this->methods as $method) {
  557. // FORMAT:
  558. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  559. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  560. }
  561. $lines[] = '';
  562. $lines[] = '';
  563. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  564. }
  565. public function log() {
  566. $this->w('');
  567. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  568. $this->w("Table: {$this->dbTable}");
  569. $this->w('---------------------------------------------');
  570. foreach ($this->methods as $method) {
  571. $this->w('Rout: ' . $method->route, 1);
  572. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  573. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  574. $this->w('Exit: ' . $method->exitURL, 1);
  575. $this->w('View: ' . $method->viewURL, 1);
  576. if(!$method->redirect) {
  577. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  578. }
  579. else {
  580. $this->w('Redi: ' . $method->redirect, 1);
  581. }
  582. $this->w('---------------------------------------------');
  583. }
  584. }
  585. public function w($line, $level = -1) {
  586. for($i=0; $i<$level; $i++) echo "\t";
  587. echo "$line\n";
  588. }
  589. public function snakeToTitleCase($text) {
  590. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  591. return ucwords(str_replace("_", " ", $text));
  592. }
  593. public function camelToTitleCase($text) {
  594. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  595. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  596. return ucwords($text);
  597. }
  598. public function snakeToCamelCase($text) {
  599. $text = ucwords(str_replace("_", " ", $text));
  600. $text = str_replace(" ", "", $text);
  601. $text[0] = strtolower($text[0]);
  602. return $text;
  603. }
  604. private function file_force_contents($dir, $contents){
  605. $dir = str_replace("\\", "/", $dir);
  606. $dir = str_replace( '//', '/', $dir);
  607. $parts = explode('/', $dir);
  608. $file = array_pop($parts);
  609. $dir = '';
  610. foreach($parts as $part) {
  611. if($part[strlen($part) - 1] !== ':') {
  612. if(!is_dir($dir .= "/$part")) mkdir($dir);
  613. }
  614. }
  615. file_put_contents("$dir/$file", $contents);
  616. }
  617. private function generateFormField($line) {
  618. $tokens = explode("=", $line);
  619. $default = false;
  620. if(count($tokens) > 1) {
  621. $default = $tokens[1];
  622. }
  623. $tokens = explode(":", $tokens[0]);
  624. $name = $tokens[0];
  625. $display = $name;
  626. $dotPos = strpos($name, ".");
  627. if($dotPos !== FALSE) {
  628. $display = substr($name, $dotPos + 1);
  629. }
  630. $display = preg_replace('/uid$/i', "", $display);
  631. $type = "text";
  632. $options = [];
  633. if(count($tokens) > 1) {
  634. $type = $tokens[1];
  635. switch ($type) {
  636. case "select":
  637. $options = explode(",", $tokens[2]);
  638. break;
  639. case "record":
  640. $options['table'] = $tokens[2];
  641. $parts = explode(",", $tokens[3]);
  642. $options['valueField'] = $parts[0];
  643. $options['displayField'] = $parts[1];
  644. break;
  645. }
  646. }
  647. if($type !== 'hidden') {
  648. $code[] = "<div class='form-group mb-3'>";
  649. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))}</label>";
  650. }
  651. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  652. switch ($type) {
  653. case "select":
  654. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  655. ">";
  656. $code[] = "<option value=''>-- Select --</option>";
  657. foreach ($options as $o) {
  658. $code[] = "<option " .
  659. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  660. "value='$o'>$o</option>";
  661. }
  662. $code[] = "</select>";
  663. break;
  664. case "record":
  665. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  666. ">";
  667. $code[] = "<option value=''>-- Select --</option>";
  668. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  669. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  670. $code[] = "<option " .
  671. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  672. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  673. $code[] = "<?php endforeach; ?>";
  674. $code[] = "</select>";
  675. break;
  676. default:
  677. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
  678. ">";
  679. }
  680. if($type !== 'hidden') {
  681. $code[] = "</div>";
  682. }
  683. return implode("\n", $code);
  684. }
  685. }
  686. class GenControllerMethod {
  687. public $name;
  688. public $route;
  689. public $hasUID = false;
  690. public $redirect = false;
  691. public $type = '';
  692. public $data = [];
  693. public $parentSub = false;
  694. public $childAddRoute = false;
  695. public $table = false;
  696. public $api = 'create';
  697. public $show = null;
  698. public $viewURL = false;
  699. public $exitURL = false;
  700. public $showLink = true;
  701. public function __construct($name, $route)
  702. {
  703. $this->name = $name;
  704. $this->route = $route;
  705. if(strpos($this->route, "{uid}") !== FALSE) {
  706. $this->hasUID = true;
  707. }
  708. }
  709. }