GenerateTreeCommand.php 23 KB

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