GenerateTreeCommand.php 32 KB

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