GenerateTreeCommand.php 20 KB

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