GenerateTreeCommand.php 31 KB

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