GenerateTreeCommand.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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[] = $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. switch($ls) {
  61. case 4: // top level controller OR top level controller action
  62. // top level controller-action
  63. if(strpos($line, "/") !== FALSE) {
  64. if(!empty($currentController)) {
  65. $method = explode("/", $line)[1];
  66. $newMethod = $currentController->addMethod($method, "/" . $line);
  67. // create _SINGLE_ controller if view
  68. if($method === "view") {
  69. $currentSubController = new GenController($currentRoot, $currentController->name . "_SINGLE");
  70. $currentSubController->dbTable = $currentController->dbTable;
  71. $currentSubController->parentRoute = "/" . $line;
  72. $currentSubController->parentControllerName = $currentController->name;
  73. $currentSubController->sub = true;
  74. $newMethod->redirect = "/" . $line . "/SUB_dashboard";
  75. }
  76. $currentMethod = $newMethod;
  77. }
  78. }
  79. // new top level controller
  80. else if(empty($currentController) || $line !== $currentController->name) {
  81. if(!empty($currentController)) {
  82. $currentController->save();
  83. }
  84. $currentController = new GenController($currentRoot, $line);
  85. $currentController->dbTable = $dbTable;
  86. $currentController->hasAdd = $hasAdd;
  87. $currentController->hasView = $hasView;
  88. $currentController->addMethod("index", "/$line");
  89. if(!empty($currentSubController)) {
  90. $currentSubController->save();
  91. }
  92. $currentSubType = '';
  93. $currentSubController = new GenController();
  94. $sideLinks[] = "<li class='nav-item'><a href='/{$currentController->name}' " .
  95. "class='nav-link " .
  96. "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>" .
  97. "<i class='nav-icon fa fa-user'></i>" .
  98. "<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>" .
  99. "</a></li>";
  100. }
  101. break;
  102. case 8: // sub-type declaration
  103. if($line === 'ACTIONS' || $line === 'SUB') {
  104. $currentSubType = $line;
  105. }
  106. else if (!empty($currentMethod) && $currentMethod->name === 'add_new') { // this is a field in add_new
  107. $currentMethod->data[] = $line;
  108. }
  109. break;
  110. case 12: // ACTIONS | SUB | add_new fields
  111. if($currentSubType === 'ACTIONS') {
  112. $currentMethod = $currentSubController->addMethod(
  113. "ACTION_" . $line,
  114. "/ACTION_" . $line
  115. );
  116. $currentMethod->type = 'action';
  117. $currentMethod->data = [];
  118. }
  119. else if($currentSubType === 'SUB') {
  120. $currentMethod = $currentSubController->addMethod(
  121. "SUB_" . $line,
  122. "/SUB_" . $line
  123. );
  124. $currentMethod->type = 'sub';
  125. $currentMethod->data = [];
  126. }
  127. break;
  128. case 16: // data for actions and subs
  129. if(!empty($currentMethod)) {
  130. $currentMethod->data[] = $line;
  131. }
  132. break;
  133. }
  134. }
  135. }
  136. // do any pending saves
  137. if(!empty($currentSubController)) {
  138. $currentSubController->save();
  139. }
  140. if(!empty($currentController)) {
  141. $currentController->save();
  142. }
  143. echo "Saved " . base_path("routes/generated.php") . "\n";
  144. // save side links
  145. file_put_contents(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  146. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  147. }
  148. private function numLS($line) {
  149. $count = 0;
  150. for ($i=0; $i<strlen($line); $i++) {
  151. if($line[$i] !== ' ') break;
  152. $count++;
  153. }
  154. return $count;
  155. }
  156. }
  157. class GenController {
  158. public $root;
  159. public $saved = false;
  160. public $name;
  161. public $methods;
  162. public $parentRoute = "";
  163. public $dbTable = null;
  164. public $hasAdd = false;
  165. public $hasView = false;
  166. public $sub = false;
  167. public $parentControllerName = '';
  168. public $subLinksSaved = false;
  169. public $actionLinksSaved = false;
  170. public function __construct($root = null, $name = null)
  171. {
  172. $this->root = $root;
  173. $this->name = $name;
  174. $this->methods = [];
  175. }
  176. public function addMethod($method, $route) {
  177. if($this->parentRoute) {
  178. $route = $this->parentRoute . $route;
  179. }
  180. $method = new GenControllerMethod($method, $route);
  181. $this->methods[] = $method;
  182. return $method;
  183. }
  184. public function save() {
  185. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  186. $this->saveController();
  187. $this->saveRoutes();
  188. $this->saved = true;
  189. // $this->log();
  190. }
  191. }
  192. public function saveController() {
  193. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  194. $code = [];
  195. foreach ($this->methods as $method) {
  196. $code[] = "";
  197. $code[] = "\t// GET {$method->route}";
  198. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  199. if($method->redirect) {
  200. $target = str_replace('{uid}', '$uid', $method->redirect);
  201. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  202. }
  203. else {
  204. if($method->hasUID) {
  205. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  206. $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', compact('record'));";
  207. }
  208. else {
  209. $code[] = "\t\t\$records = DB::table('{$this->dbTable}')->get();";
  210. $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', compact('records'));";
  211. }
  212. }
  213. $this->saveView($this, $method);
  214. $code[] = "\t}";
  215. }
  216. $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
  217. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  218. file_put_contents(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  219. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  220. }
  221. public function saveView(GenController $controller, GenControllerMethod $method) {
  222. if($controller->sub) {
  223. $controller->saveSubLinks($controller, $method);
  224. $controller->saveActionLinks($controller, $method);
  225. if($method->type === 'action') {
  226. $this->saveSubActionView($controller, $method);
  227. }
  228. else if($method->type === 'sub' && count($method->data)) {
  229. $this->saveSubSubView($controller, $method);
  230. }
  231. else {
  232. $this->saveSubDefaultView($controller, $method);
  233. }
  234. }
  235. else {
  236. if($method->name === 'view' && $controller->hasView) {
  237. $this->saveShowView($controller, $method);
  238. }
  239. else if($method->name === 'index') {
  240. $this->saveIndexView($controller, $method);
  241. }
  242. else if($method->name === 'add_new' && $controller->hasAdd) {
  243. $this->saveAddNewView($controller, $method);
  244. }
  245. }
  246. }
  247. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  248. {
  249. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  250. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  251. if($controller->hasAdd) {
  252. $addLink = "<a class='btn btn-primary btn-sm' href='/{$controller->name}/add_new'>" .
  253. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  254. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  255. }
  256. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  257. $ths = [];
  258. $tds = [];
  259. foreach ($columns as $column) {
  260. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  261. $tds[] = "<td>" .
  262. ($controller->hasView && $column === 'uid' ? '<a href="/' . $controller->name . '/view/<?= $record->uid ?>">' : '') .
  263. "<?= \$record->$column ?>" .
  264. ($controller->hasView && $column === 'uid' ? '</a>' : '') .
  265. "</td>";
  266. }
  267. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  268. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  269. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  270. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  271. }
  272. public function saveShowView(GenController $controller, GenControllerMethod $method)
  273. {
  274. // delete sub links and action links
  275. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  276. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  277. }
  278. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  279. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  280. }
  281. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  282. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  283. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  284. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  285. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  286. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  287. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  288. }
  289. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  290. {
  291. if ($controller->subLinksSaved) return;
  292. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  293. $subLinks = [];
  294. foreach ($controller->methods as $meth) {
  295. if (strpos($meth->name, "SUB_") !== 0) continue;
  296. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  297. $subLinks[] = "<a " .
  298. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  299. "class='d-block p-3 py-2 border-bottom " .
  300. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white' : '' }}" .
  301. ($meth->name === 'SUB_dashboard' ? "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white' : '' }}" : "")
  302. . "'>$display</a>";
  303. }
  304. file_put_contents($subLinksView, implode("\n", $subLinks));
  305. echo "Generated " . $subLinksView . "\n";
  306. $controller->subLinksSaved = true;
  307. }
  308. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  309. {
  310. if ($controller->actionLinksSaved) return;
  311. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  312. $actionLinks = [];
  313. foreach ($controller->methods as $meth) {
  314. if (strpos($meth->name, "ACTION_") !== 0) continue;
  315. $display = $this->camelToTitleCase(substr($meth->name, 7));
  316. $actionLinks[] = "<a " .
  317. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  318. "class='d-block btn btn-sm btn-default mb-3'>$display</a>";
  319. }
  320. file_put_contents($actionLinksView, implode("\n", $actionLinks));
  321. echo "Generated " . $actionLinksView . "\n";
  322. $controller->actionLinksSaved = true;
  323. }
  324. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  325. {
  326. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  327. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  328. $text = $this->generateSubContent($controller, $method, $text);
  329. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  330. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  331. }
  332. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  333. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  334. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  335. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  336. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  337. $text = str_replace("_API_", "/api/{$controller->dbTable}/" . substr($method->name, 7), $text);
  338. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  339. $fields = [];
  340. if(count($method->data)) {
  341. foreach ($method->data as $field) {
  342. $fields[] =
  343. "<div class='form-group mb-3'>" .
  344. "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($field))}</label>" .
  345. "<input class='form-control' type='text' name='$field'>" .
  346. "</div>";
  347. }
  348. }
  349. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  350. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  351. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  352. }
  353. public function saveSubSubView(GenController $controller, GenControllerMethod $method) {
  354. }
  355. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  356. if($method->name === 'SUB_dashboard') {
  357. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
  358. $text = str_replace("_SUB_VIEW_", $html, $text);
  359. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  360. }
  361. else {
  362. $text = str_replace("_SUB_VIEW_",
  363. "<h4 class='py-3 border-bottom'>" .
  364. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
  365. "Controller: <b>{$controller->name}</b><br>" .
  366. "Action: <b>{$method->name}()</b><br>" .
  367. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br>",
  368. $text);
  369. }
  370. return $text;
  371. }
  372. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  373. {
  374. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  375. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  376. $text = str_replace("_API_", "/api/{$controller->dbTable}/create", $text);
  377. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  378. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-add_new", $text);
  379. $columns = $method->data;
  380. $fields = [];
  381. foreach ($columns as $column) {
  382. if(in_array($column,
  383. ['id', 'uid', 'created_at',
  384. 'deactivated_at', 'deactivation_memo',
  385. 'reactivated_at', 'reactivation_memo']) === true) continue;
  386. $fields[] =
  387. "<div class='form-group mb-3'>" .
  388. "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($column))}</label>" .
  389. "<input class='form-control' type='text' name='{$this->snakeToCamelCase($column)}'>" .
  390. "</div>";
  391. }
  392. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  393. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  394. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  395. }
  396. public function saveRoutes() {
  397. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  398. foreach ($this->methods as $method) {
  399. // FORMAT:
  400. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  401. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  402. }
  403. $lines[] = '';
  404. $lines[] = '';
  405. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  406. }
  407. public function log() {
  408. $this->w('');
  409. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  410. $this->w("Table: {$this->dbTable}");
  411. $this->w('---------------------------------------------');
  412. foreach ($this->methods as $method) {
  413. $this->w('Rout: ' . $method->route, 1);
  414. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  415. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  416. if(!$method->redirect) {
  417. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  418. }
  419. else {
  420. $this->w('Redi: ' . $method->redirect, 1);
  421. }
  422. $this->w('---------------------------------------------');
  423. }
  424. }
  425. public function w($line, $level = -1) {
  426. for($i=0; $i<$level; $i++) echo "\t";
  427. echo "$line\n";
  428. }
  429. public function snakeToTitleCase($text) {
  430. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  431. return ucwords(str_replace("_", " ", $text));
  432. }
  433. public function camelToTitleCase($text) {
  434. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  435. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  436. return ucwords($text);
  437. }
  438. public function snakeToCamelCase($text) {
  439. $text = ucwords(str_replace("_", " ", $text));
  440. $text = str_replace(" ", "", $text);
  441. $text[0] = strtolower($text[0]);
  442. return $text;
  443. }
  444. private function file_force_contents($dir, $contents){
  445. $dir = str_replace("\\", "/", $dir);
  446. $dir = str_replace( '//', '/', $dir);
  447. $parts = explode('/', $dir);
  448. $file = array_pop($parts);
  449. $dir = '';
  450. foreach($parts as $part) {
  451. if($part[strlen($part) - 1] !== ':') {
  452. if(!is_dir($dir .= "/$part")) mkdir($dir);
  453. }
  454. }
  455. file_put_contents("$dir/$file", $contents);
  456. }
  457. }
  458. class GenControllerMethod {
  459. public $name;
  460. public $route;
  461. public $hasUID = false;
  462. public $redirect = false;
  463. public $type = '';
  464. public $data = [];
  465. public function __construct($name, $route)
  466. {
  467. $this->name = $name;
  468. $this->route = $route;
  469. if(strpos($this->route, "{uid}") !== FALSE) {
  470. $this->hasUID = true;
  471. }
  472. }
  473. }