GenerateTreeCommand.php 30 KB

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