GenerateTreeCommand.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. $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. $parts = explode(",", $method->data[0]);
  300. $loadingLine = [];
  301. // first 'where'
  302. $dbParts = explode("=", $parts[0]);
  303. $localField = $dbParts[0];
  304. $dbParts = explode(".", $dbParts[1]);
  305. $foreignTable = $dbParts[0];
  306. $foreignField = $dbParts[1];
  307. $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
  308. $loadingLine[] = "->where('$foreignField', \$record->$localField)";
  309. // other 'where's
  310. if(count($parts) > 1) {
  311. for ($i = 1; $i < count($parts); $i++) {
  312. $dbParts = explode("=", $parts[$i]);
  313. $field = $dbParts[0];
  314. $value = $dbParts[1];
  315. $loadingLine[] = "->where('$field', $value)";
  316. }
  317. }
  318. $loadingLine[] = "->get();";
  319. $code[] = implode("", $loadingLine);
  320. // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  321. $input[] = "'subRecords'";
  322. }
  323. $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', " .
  324. "compact(" . implode(", ", $input) . "));";
  325. }
  326. else {
  327. $loadingLine = [];
  328. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  329. if($this->condition) {
  330. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  331. }
  332. $loadingLine[] = "->get();";
  333. $code[] = implode("", $loadingLine);
  334. $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', " .
  335. "compact('records'));";
  336. }
  337. }
  338. $this->saveView($this, $method);
  339. $code[] = "\t}";
  340. }
  341. $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
  342. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  343. file_put_contents(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  344. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  345. }
  346. public function saveView(GenController $controller, GenControllerMethod $method) {
  347. if($controller->sub) {
  348. $controller->saveSubLinks($controller, $method);
  349. $controller->saveActionLinks($controller, $method);
  350. if($method->type === 'action') {
  351. $this->saveSubActionView($controller, $method);
  352. }
  353. else if($method->type === 'sub' && count($method->data)) {
  354. $this->saveSubIndexView($controller, $method);
  355. }
  356. else {
  357. $this->saveSubDefaultView($controller, $method);
  358. }
  359. }
  360. else {
  361. if($method->name === 'view' && $controller->hasView) {
  362. $this->saveShowView($controller, $method);
  363. }
  364. else if($method->name === 'index') {
  365. $this->saveIndexView($controller, $method);
  366. }
  367. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  368. $this->saveAddNewView($controller, $method);
  369. }
  370. else if($method->name === 'remove' && $controller->hasRemove) {
  371. $this->saveAddNewView($controller, $method);
  372. }
  373. }
  374. }
  375. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  376. {
  377. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  378. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  379. if($controller->hasAdd) {
  380. $addLinks = [];
  381. foreach ($controller->methods as $m) {
  382. if($m->type === 'add') {
  383. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  384. "href='/{$controller->name}/{$m->name}'>" .
  385. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  386. "{$this->snakeToTitleCase($m->name)}</a>";
  387. }
  388. }
  389. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  390. }
  391. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  392. $ths = [];
  393. $tds = [];
  394. if($controller->hasRemove) {
  395. $ths[] = "<th></th>";
  396. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  397. "<i class='fa fa-trash'></i>" .
  398. "</a></td>";
  399. }
  400. foreach ($columns as $column) {
  401. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  402. $tds[] = "<td>" .
  403. ($controller->hasView && $column === 'uid' ? '<a href="/' . $controller->name . '/view/<?= $record->uid ?>">' : '') .
  404. "<?= \$record->$column ?>" .
  405. ($controller->hasView && $column === 'uid' ? '</a>' : '') .
  406. "</td>";
  407. }
  408. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  409. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $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 saveShowView(GenController $controller, GenControllerMethod $method)
  414. {
  415. // delete sub links and action links
  416. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  417. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  418. }
  419. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  420. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  421. }
  422. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  423. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  424. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  425. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  426. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  427. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  428. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  429. }
  430. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  431. {
  432. if ($controller->subLinksSaved) return;
  433. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  434. $subLinks = [];
  435. foreach ($controller->methods as $meth) {
  436. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  437. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  438. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  439. "<a " .
  440. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  441. "class='d-block px-3 py-2 border-bottom " .
  442. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  443. (
  444. $meth->name === 'SUB_dashboard' ?
  445. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  446. ""
  447. )
  448. . "'>$display</a>" .
  449. ($meth->show ? " @endif" : "");
  450. }
  451. $this->file_force_contents($subLinksView, implode("\n", $subLinks));
  452. echo "Generated " . $subLinksView . "\n";
  453. $controller->subLinksSaved = true;
  454. }
  455. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  456. {
  457. if ($controller->actionLinksSaved) return;
  458. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  459. $actionLinks = [];
  460. foreach ($controller->methods as $meth) {
  461. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  462. $display = $this->camelToTitleCase(substr($meth->name, 7));
  463. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  464. "<a " .
  465. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  466. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  467. ($meth->show ? " @endif" : "");
  468. }
  469. $this->file_force_contents($actionLinksView, implode("\n", $actionLinks));
  470. echo "Generated " . $actionLinksView . "\n";
  471. $controller->actionLinksSaved = true;
  472. }
  473. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  474. {
  475. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  476. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  477. $text = $this->generateSubContent($controller, $method, $text);
  478. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  479. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  480. }
  481. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  482. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  483. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  484. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  485. if(!$method->parentSub) {
  486. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  487. }
  488. else {
  489. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  490. }
  491. if(!$method->table) {
  492. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  493. }
  494. else {
  495. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  496. }
  497. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  498. $fields = [];
  499. if(count($method->data)) {
  500. foreach ($method->data as $field) {
  501. $fields[] = $this->generateFormField($field);
  502. }
  503. }
  504. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  505. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  506. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  507. }
  508. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  509. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  510. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  511. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  512. if(count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  513. $addLink = '<a class="btn btn-primary btn-sm" ' .
  514. 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
  515. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  516. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  517. }
  518. $dbParts = explode("=", $method->data[0]);
  519. $dbParts = explode(".", $dbParts[1]);
  520. $table = $dbParts[0];
  521. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  522. $ths = [];
  523. $tds = [];
  524. foreach ($columns as $column) {
  525. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  526. $tds[] = "<td>" .
  527. ($method->exitURL && $column === 'uid' ? '<a href="' . $method->exitURL . '">' : '') .
  528. "<?= \$subRecord->$column ?>" .
  529. ($method->exitURL && $column === 'uid' ? '</a>' : '') .
  530. "</td>";
  531. }
  532. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  533. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  534. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  535. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  536. }
  537. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  538. if($method->name === 'SUB_dashboard') {
  539. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
  540. $text = str_replace("_SUB_VIEW_", $html, $text);
  541. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  542. }
  543. else {
  544. $text = str_replace("_SUB_VIEW_",
  545. "<h4 class='py-3 border-bottom'>" .
  546. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
  547. "Controller: <b>{$controller->name}</b><br>" .
  548. "Action: <b>{$method->name}()</b><br>" .
  549. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br>",
  550. $text);
  551. }
  552. return $text;
  553. }
  554. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  555. {
  556. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  557. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  558. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  559. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  560. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  561. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  562. $columns = $method->data;
  563. $fields = [];
  564. foreach ($columns as $column) {
  565. $fields[] = $this->generateFormField($column);
  566. }
  567. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  568. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  569. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  570. }
  571. public function saveRoutes() {
  572. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  573. foreach ($this->methods as $method) {
  574. // FORMAT:
  575. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  576. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  577. }
  578. $lines[] = '';
  579. $lines[] = '';
  580. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  581. }
  582. public function log() {
  583. $this->w('');
  584. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  585. $this->w("Table: {$this->dbTable}");
  586. $this->w('---------------------------------------------');
  587. foreach ($this->methods as $method) {
  588. $this->w('Rout: ' . $method->route, 1);
  589. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  590. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  591. $this->w('Exit: ' . $method->exitURL, 1);
  592. $this->w('View: ' . $method->viewURL, 1);
  593. if(!$method->redirect) {
  594. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  595. }
  596. else {
  597. $this->w('Redi: ' . $method->redirect, 1);
  598. }
  599. $this->w('---------------------------------------------');
  600. }
  601. }
  602. public function w($line, $level = -1) {
  603. for($i=0; $i<$level; $i++) echo "\t";
  604. echo "$line\n";
  605. }
  606. public function snakeToTitleCase($text) {
  607. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  608. return ucwords(str_replace("_", " ", $text));
  609. }
  610. public function camelToTitleCase($text) {
  611. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  612. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  613. return ucwords($text);
  614. }
  615. public function snakeToCamelCase($text) {
  616. $text = ucwords(str_replace("_", " ", $text));
  617. $text = str_replace(" ", "", $text);
  618. $text[0] = strtolower($text[0]);
  619. return $text;
  620. }
  621. private function file_force_contents($dir, $contents){
  622. $dir = str_replace("\\", "/", $dir);
  623. $dir = str_replace( '//', '/', $dir);
  624. $parts = explode('/', $dir);
  625. $file = array_pop($parts);
  626. $dir = '';
  627. foreach($parts as $part) {
  628. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  629. if(!is_dir($dir .= "/$part")) mkdir($dir);
  630. }
  631. }
  632. file_put_contents("$dir/$file", $contents);
  633. }
  634. private function generateFormField($line) {
  635. $tokens = explode("=", $line);
  636. $default = false;
  637. if(count($tokens) > 1) {
  638. $default = $tokens[1];
  639. }
  640. $tokens = explode(":", $tokens[0]);
  641. $name = $tokens[0];
  642. $display = $name;
  643. $dotPos = strpos($name, ".");
  644. if($dotPos !== FALSE) {
  645. $display = substr($name, $dotPos + 1);
  646. }
  647. $display = preg_replace('/uid$/i', "", $display);
  648. $type = "text";
  649. $options = [];
  650. if(count($tokens) > 1) {
  651. $type = $tokens[1];
  652. switch ($type) {
  653. case "select":
  654. $options = explode(",", $tokens[2]);
  655. break;
  656. case "record":
  657. $options['table'] = $tokens[2];
  658. $parts = explode(",", $tokens[3]);
  659. $options['valueField'] = $parts[0];
  660. $options['displayField'] = $parts[1];
  661. break;
  662. }
  663. }
  664. if($type !== 'hidden' && $type !== 'bool') {
  665. $code[] = "<div class='form-group mb-3'>";
  666. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))}</label>";
  667. }
  668. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  669. switch ($type) {
  670. case "select":
  671. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  672. ">";
  673. $code[] = "<option value=''>-- Select --</option>";
  674. foreach ($options as $o) {
  675. $code[] = "<option " .
  676. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  677. "value='$o'>$o</option>";
  678. }
  679. $code[] = "</select>";
  680. break;
  681. case "record":
  682. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  683. ">";
  684. $code[] = "<option value=''>-- Select --</option>";
  685. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  686. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  687. $code[] = "<option " .
  688. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  689. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  690. $code[] = "<?php endforeach; ?>";
  691. $code[] = "</select>";
  692. break;
  693. case "bool":
  694. $code[] = "<div class='form-group mb-3'>";
  695. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} ";
  696. $code[] = "<input class='form-control' type='checkbox' name='$name'>";
  697. $code[] = "</label>";
  698. break;
  699. default:
  700. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine . ">";
  701. }
  702. if($type !== 'hidden') {
  703. $code[] = "</div>";
  704. }
  705. return implode("\n", $code);
  706. }
  707. }
  708. class GenControllerMethod {
  709. public $name;
  710. public $route;
  711. public $hasUID = false;
  712. public $redirect = false;
  713. public $type = '';
  714. public $data = [];
  715. public $parentSub = false;
  716. public $childAddRoute = false;
  717. public $table = false;
  718. public $api = 'create';
  719. public $show = null;
  720. public $viewURL = false;
  721. public $exitURL = false;
  722. public $showLink = true;
  723. public function __construct($name, $route)
  724. {
  725. $this->name = $name;
  726. $this->route = $route;
  727. if(strpos($this->route, "{uid}") !== FALSE) {
  728. $this->hasUID = true;
  729. }
  730. }
  731. }