GenerateTreeCommand.php 34 KB

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