GenerateTreeCommand.php 33 KB

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