GenerateTreeCommand.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\DB;
  5. class GenerateTreeCommand extends Command
  6. {
  7. private $routesFile = null;
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'generatetree
  14. {path: /path/to/tree.txt}';
  15. /**
  16. * Execute the console command.
  17. *
  18. * @return mixed
  19. */
  20. public function handle()
  21. {
  22. $lines = ['<?php', '', 'use Illuminate\Support\Facades\Route;', '', ''];
  23. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines));
  24. $sideLinks = [];
  25. global $argv;
  26. $file = fopen($argv[2], "r");
  27. $lines = [];
  28. while (!feof($file)) {
  29. $line = rtrim(fgets($file));
  30. if(trim($line) !== '') {
  31. $lines[] = str_replace("\t", " ", $line);
  32. }
  33. }
  34. fclose($file);
  35. $currentRoot = "";
  36. $currentController = new GenController();
  37. $currentSubController = new GenController();
  38. $currentSubType = "";
  39. $currentView = "";
  40. $currentMethod = null;
  41. foreach ($lines as $line) {
  42. // skip comments
  43. if(trim($line)[0] === '#') continue;
  44. $lineType = null;
  45. // no leading space - root specifier
  46. if($line[0] !== ' ') {
  47. $currentRoot = strtolower(trim($line));
  48. }
  49. else {
  50. $ls = $this->numLS($line);
  51. $line = trim($line);
  52. $exitURL = false;
  53. if(strpos($line, "=>") !== FALSE) {
  54. $parts = explode("=>", $line);
  55. $exitURL = str_replace("UID", "{{ \$subRecord->uid }}", $parts[1]);
  56. $line = $parts[0];
  57. }
  58. $tokens = explode("|", $line);
  59. $line = $tokens[0];
  60. $dbTable = null;
  61. $condition = null;
  62. if(count($tokens) >= 2) {
  63. $dbTable = $tokens[1];
  64. // check if table has loading conditions
  65. if(strpos($dbTable, ":")) {
  66. $parts = explode(":", $dbTable);
  67. $dbTable = $parts[0];
  68. $parts = explode("=", $parts[1]);
  69. $condition = [
  70. "field" => $parts[0],
  71. "value" => str_replace("OWN", "session('proId')" , $parts[1])
  72. ];
  73. }
  74. }
  75. $hasAdd = in_array("add", $tokens);
  76. $hasView = in_array("view", $tokens);
  77. $hasRemove = in_array("remove", $tokens);
  78. switch($ls) {
  79. case 4: // top level controller OR top level controller action
  80. // top level controller-action
  81. if(strpos($line, "/") !== FALSE) {
  82. if(!empty($currentController)) {
  83. $parts = explode(":", $line);
  84. $line = $parts[0];
  85. $method = explode("/", $line)[1];
  86. $newMethod = $currentController->addMethod($method, "/" . $line);
  87. if(count($parts) > 1) {
  88. $newMethod->api = $parts[count($parts) - 1];
  89. }
  90. // create _SINGLE_ controller if view
  91. if($method === "view") {
  92. $currentSubController = new GenController($currentRoot, $currentController->name . "_SINGLE");
  93. $currentSubController->dbTable = $currentController->dbTable;
  94. $currentSubController->parentRoute = "/" . $line;
  95. $currentSubController->parentControllerName = $currentController->name;
  96. $currentSubController->sub = true;
  97. $newMethod->redirect = "/" . $line . "/SUB_dashboard";
  98. }
  99. else if(strpos($method, "add_new") === 0) {
  100. $newMethod->type = 'add';
  101. }
  102. else if(strpos($method, "remove") === 0) {
  103. $newMethod->type = 'remove';
  104. }
  105. $currentMethod = $newMethod;
  106. }
  107. }
  108. // new top level controller
  109. else if(empty($currentController) || $line !== $currentController->name) {
  110. if(!empty($currentController)) {
  111. $currentController->save();
  112. }
  113. $currentController = new GenController($currentRoot, $line);
  114. $currentController->dbTable = $dbTable;
  115. $currentController->condition = $condition;
  116. $currentController->hasAdd = $hasAdd;
  117. $currentController->hasView = $hasView;
  118. $currentController->hasRemove = $hasRemove;
  119. $currentController->addMethod("index", "/$line");
  120. if(!empty($currentSubController)) {
  121. $currentSubController->save();
  122. }
  123. $currentSubType = '';
  124. $currentSubController = new GenController();
  125. $sideLinks[] = "<li class='nav-item'><a href='/{$currentController->name}' " .
  126. "class='nav-link " .
  127. "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>" .
  128. "<i class='nav-icon fa fa-user'></i>" .
  129. "<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>" .
  130. "</a></li>";
  131. }
  132. break;
  133. case 8: // sub-type declaration | add_new fields
  134. if($line === 'ACTIONS' || $line === 'SUB') {
  135. $currentSubType = $line;
  136. }
  137. else if (!empty($currentMethod) &&
  138. (strpos($currentMethod->name, 'add_new') === 0 ||
  139. $currentMethod->name === 'remove')) { // this is a field in add_new
  140. $currentMethod->data[] = $line;
  141. }
  142. break;
  143. case 12: // ACTIONS | SUB
  144. // check if this has show conditions
  145. $show = false;
  146. if(strpos($line, ":")) {
  147. $parts = explode(":", $line);
  148. $line = $parts[0];
  149. if($parts[1] === 'if') {
  150. $show = $parts[2];
  151. }
  152. }
  153. if($currentSubType === 'ACTIONS') {
  154. $currentMethod = $currentSubController->addMethod(
  155. "ACTION_" . $line,
  156. "/ACTION_" . $line
  157. );
  158. $currentMethod->type = 'action';
  159. $currentMethod->show = $show;
  160. $currentMethod->data = [];
  161. }
  162. else if($currentSubType === 'SUB') {
  163. $currentMethod = $currentSubController->addMethod(
  164. "SUB_" . $line,
  165. "/SUB_" . $line
  166. );
  167. $currentMethod->type = 'sub';
  168. $currentMethod->show = $show;
  169. $currentMethod->data = [];
  170. }
  171. break;
  172. case 16: // data for actions and subs
  173. if(!empty($currentMethod)) {
  174. $currentMethod->data[] = $line;
  175. if($exitURL) {
  176. if(strpos("=", $line) !== FALSE) {
  177. $currentMethod->viewURL = $exitURL;
  178. }
  179. else {
  180. $currentMethod->exitURL = $exitURL;
  181. }
  182. }
  183. }
  184. break;
  185. case 20: // SUB add_new fields
  186. if(!empty($currentMethod)) {
  187. $currentMethod->data[] = $line;
  188. }
  189. break;
  190. default:
  191. dump("ERROR: Cannot have $ls leading spaces!");
  192. dump("Line: $line");
  193. exit(1);
  194. }
  195. }
  196. }
  197. // do any pending saves
  198. if(!empty($currentSubController)) {
  199. $currentSubController->save();
  200. }
  201. if(!empty($currentController)) {
  202. $currentController->save();
  203. }
  204. echo "Saved " . base_path("routes/generated.php") . "\n";
  205. // save side links
  206. file_put_contents(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  207. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  208. }
  209. private function numLS($line) {
  210. $count = 0;
  211. for ($i=0; $i<strlen($line); $i++) {
  212. if($line[$i] !== ' ') break;
  213. $count++;
  214. }
  215. return $count;
  216. }
  217. }
  218. class GenController {
  219. public $root;
  220. public $saved = false;
  221. public $name;
  222. public $methods;
  223. public $parentRoute = "";
  224. public $dbTable = null;
  225. public $condition = null;
  226. public $hasAdd = false;
  227. public $hasView = false;
  228. public $hasRemove = false;
  229. public $sub = false;
  230. public $parentControllerName = '';
  231. public $subLinksSaved = false;
  232. public $actionLinksSaved = false;
  233. public function __construct($root = null, $name = null)
  234. {
  235. $this->root = $root;
  236. $this->name = $name;
  237. $this->methods = [];
  238. }
  239. public function addMethod($method, $route) {
  240. if($this->parentRoute) {
  241. $route = $this->parentRoute . $route;
  242. }
  243. $method = new GenControllerMethod($method, $route);
  244. $this->methods[] = $method;
  245. return $method;
  246. }
  247. public function save() {
  248. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  249. $this->saveController();
  250. $this->saveRoutes();
  251. $this->saved = true;
  252. // $this->log();
  253. }
  254. }
  255. public function saveController() {
  256. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  257. $code = [];
  258. // check if any method has a "sub add_new" in it, if yes, add action for the same
  259. $newMethods = [];
  260. foreach ($this->methods as $method) {
  261. if($method->type === 'sub' && count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  262. $methodName = preg_replace("/^SUB_/", "ACTION_", $method->name) . 'AddNew';
  263. $methodRoute = str_replace("/SUB_", "/ACTION_", $method->route) . 'AddNew';
  264. $newMethod = new GenControllerMethod($methodName, $methodRoute);
  265. $newMethod->hasUID = true;
  266. $newMethod->redirect = false;
  267. $newMethod->type = 'action';
  268. $newMethod->data = [];
  269. for($i = 2; $i<count($method->data); $i++) {
  270. $newMethod->data[] = $method->data[$i];
  271. }
  272. $newMethod->parentSub = $this->name . '-' . $method->name;
  273. $parts = explode(":", $method->data[1]);
  274. $newMethod->table = $parts[1];
  275. if(count($parts) === 3) {
  276. $newMethod->api = $parts[2];
  277. }
  278. $newMethod->exitURL = $method->exitURL;
  279. $newMethod->showLink = false;
  280. $newMethods[] = $newMethod;
  281. $method->childAddRoute = $this->name . '-' . $methodName;
  282. }
  283. }
  284. $this->methods = array_merge($this->methods, $newMethods);
  285. foreach ($this->methods as $method) {
  286. $code[] = "";
  287. $code[] = "\t// GET {$method->route}";
  288. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  289. if($method->redirect) {
  290. $target = str_replace('{uid}', '$uid', $method->redirect);
  291. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  292. }
  293. else {
  294. if($method->hasUID) {
  295. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  296. $input = ["'record'"];
  297. // if sub-index controller, load subRecords
  298. if($method->type === 'sub' && count($method->data)) {
  299. $parts = explode(",", $method->data[0]);
  300. $loadingLine = [];
  301. // first 'where'
  302. $dbParts = explode("=", $parts[0]);
  303. $localField = $dbParts[0];
  304. $dbParts = explode(".", $dbParts[1]);
  305. $foreignTable = $dbParts[0];
  306. $foreignField = $dbParts[1];
  307. $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
  308. $loadingLine[] = "->where('$foreignField', \$record->$localField)";
  309. // other 'where's
  310. if(count($parts) > 1) {
  311. for ($i = 1; $i < count($parts); $i++) {
  312. $dbParts = explode("=", $parts[$i]);
  313. $field = $dbParts[0];
  314. $value = $dbParts[1];
  315. $loadingLine[] = "->where('$field', $value)";
  316. }
  317. }
  318. $loadingLine[] = "->get();";
  319. $code[] = implode("", $loadingLine);
  320. // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  321. $input[] = "'subRecords'";
  322. }
  323. // return response()->view('pro/my_teams/add_new', compact('records'), session('message') ? 500 : 200)->header('Content-Type', 'text/html');
  324. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  325. "compact(" . implode(", ", $input) . "), " .
  326. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  327. }
  328. else {
  329. $loadingLine = [];
  330. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  331. if($this->condition) {
  332. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  333. }
  334. $loadingLine[] = "->get();";
  335. $code[] = implode("", $loadingLine);
  336. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  337. "compact('records'), " .
  338. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  339. }
  340. }
  341. $this->saveView($this, $method);
  342. $code[] = "\t}";
  343. }
  344. $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
  345. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  346. file_put_contents(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  347. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  348. }
  349. public function saveView(GenController $controller, GenControllerMethod $method) {
  350. if($controller->sub) {
  351. $controller->saveSubLinks($controller, $method);
  352. $controller->saveActionLinks($controller, $method);
  353. if($method->type === 'action') {
  354. $this->saveSubActionView($controller, $method);
  355. }
  356. else if($method->type === 'sub' && count($method->data)) {
  357. $this->saveSubIndexView($controller, $method);
  358. }
  359. else {
  360. $this->saveSubDefaultView($controller, $method);
  361. }
  362. }
  363. else {
  364. if($method->name === 'view' && $controller->hasView) {
  365. $this->saveShowView($controller, $method);
  366. }
  367. else if($method->name === 'index') {
  368. $this->saveIndexView($controller, $method);
  369. }
  370. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  371. $this->saveAddNewView($controller, $method);
  372. }
  373. else if($method->name === 'remove' && $controller->hasRemove) {
  374. $this->saveAddNewView($controller, $method);
  375. }
  376. }
  377. }
  378. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  379. {
  380. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  381. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  382. if($controller->hasAdd) {
  383. $addLinks = [];
  384. foreach ($controller->methods as $m) {
  385. if($m->type === 'add') {
  386. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  387. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  388. "href='/{$controller->name}/{$m->name}'>" .
  389. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  390. "{$this->snakeToTitleCase($m->name)}</a>";
  391. }
  392. }
  393. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  394. }
  395. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  396. $ths = [];
  397. $tds = [];
  398. if($controller->hasRemove) {
  399. $ths[] = "<th></th>";
  400. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  401. "<i class='fa fa-trash'></i>" .
  402. "</a></td>";
  403. }
  404. foreach ($columns as $column) {
  405. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  406. $tds[] = "<td>" .
  407. ($controller->hasView && $column === 'uid' ? '<a href="/' . $controller->name . '/view/<?= $record->uid ?>">' : '') .
  408. "<?= \$record->$column ?>" .
  409. ($controller->hasView && $column === 'uid' ? '</a>' : '') .
  410. "</td>";
  411. }
  412. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  413. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $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 saveShowView(GenController $controller, GenControllerMethod $method)
  418. {
  419. // delete sub links and action links
  420. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  421. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  422. }
  423. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  424. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  425. }
  426. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  427. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  428. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  429. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  430. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  431. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  432. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  433. }
  434. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  435. {
  436. if ($controller->subLinksSaved) return;
  437. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  438. $subLinks = [];
  439. foreach ($controller->methods as $meth) {
  440. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  441. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  442. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  443. "<a " .
  444. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  445. "class='d-block px-3 py-2 border-bottom " .
  446. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  447. (
  448. $meth->name === 'SUB_dashboard' ?
  449. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  450. ""
  451. )
  452. . "'>$display</a>" .
  453. ($meth->show ? " @endif" : "");
  454. }
  455. $this->file_force_contents($subLinksView, implode("\n", $subLinks));
  456. echo "Generated " . $subLinksView . "\n";
  457. $controller->subLinksSaved = true;
  458. }
  459. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  460. {
  461. if ($controller->actionLinksSaved) return;
  462. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  463. $actionLinks = [];
  464. foreach ($controller->methods as $meth) {
  465. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  466. $display = $this->camelToTitleCase(substr($meth->name, 7));
  467. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  468. "<a " .
  469. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  470. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  471. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  472. ($meth->show ? " @endif" : "");
  473. }
  474. $this->file_force_contents($actionLinksView, implode("\n", $actionLinks));
  475. echo "Generated " . $actionLinksView . "\n";
  476. $controller->actionLinksSaved = true;
  477. }
  478. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  479. {
  480. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  481. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  482. $text = $this->generateSubContent($controller, $method, $text);
  483. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  484. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  485. }
  486. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  487. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  488. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  489. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  490. if(!$method->parentSub) {
  491. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  492. }
  493. else {
  494. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  495. }
  496. if(!$method->table) {
  497. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  498. }
  499. else {
  500. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  501. }
  502. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  503. $fields = [];
  504. if(count($method->data)) {
  505. foreach ($method->data as $field) {
  506. $fields[] = $this->generateFormField($field);
  507. }
  508. }
  509. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  510. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  511. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  512. }
  513. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  514. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  515. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  516. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  517. if(count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  518. $addLink = '<a class="btn btn-primary btn-sm" ' .
  519. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  520. 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
  521. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  522. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  523. }
  524. $dbParts = explode("=", $method->data[0]);
  525. $dbParts = explode(".", $dbParts[1]);
  526. $table = $dbParts[0];
  527. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  528. $ths = [];
  529. $tds = [];
  530. foreach ($columns as $column) {
  531. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  532. $tds[] = "<td>" .
  533. ($method->exitURL && $column === 'uid' ? '<a href="' . $method->exitURL . '">' : '') .
  534. "<?= \$subRecord->$column ?>" .
  535. ($method->exitURL && $column === 'uid' ? '</a>' : '') .
  536. "</td>";
  537. }
  538. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  539. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  540. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  541. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  542. }
  543. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  544. if($method->name === 'SUB_dashboard') {
  545. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
  546. $text = str_replace("_SUB_VIEW_", $html, $text);
  547. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  548. }
  549. else {
  550. $text = str_replace("_SUB_VIEW_",
  551. "<h4 class='py-3 border-bottom'>" .
  552. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
  553. "Controller: <b>{$controller->name}</b><br>" .
  554. "Action: <b>{$method->name}()</b><br>" .
  555. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br>",
  556. $text);
  557. }
  558. return $text;
  559. }
  560. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  561. {
  562. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  563. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  564. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  565. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  566. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  567. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  568. $columns = $method->data;
  569. $fields = [];
  570. foreach ($columns as $column) {
  571. $fields[] = $this->generateFormField($column);
  572. }
  573. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  574. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  575. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  576. }
  577. public function saveRoutes() {
  578. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  579. foreach ($this->methods as $method) {
  580. // FORMAT:
  581. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  582. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  583. }
  584. $lines[] = '';
  585. $lines[] = '';
  586. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  587. }
  588. public function log() {
  589. $this->w('');
  590. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  591. $this->w("Table: {$this->dbTable}");
  592. $this->w('---------------------------------------------');
  593. foreach ($this->methods as $method) {
  594. $this->w('Rout: ' . $method->route, 1);
  595. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  596. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  597. $this->w('Exit: ' . $method->exitURL, 1);
  598. $this->w('View: ' . $method->viewURL, 1);
  599. if(!$method->redirect) {
  600. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  601. }
  602. else {
  603. $this->w('Redi: ' . $method->redirect, 1);
  604. }
  605. $this->w('---------------------------------------------');
  606. }
  607. }
  608. public function w($line, $level = -1) {
  609. for($i=0; $i<$level; $i++) echo "\t";
  610. echo "$line\n";
  611. }
  612. public function snakeToTitleCase($text) {
  613. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  614. return ucwords(str_replace("_", " ", $text));
  615. }
  616. public function camelToTitleCase($text) {
  617. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  618. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  619. return ucwords($text);
  620. }
  621. public function snakeToCamelCase($text) {
  622. $text = ucwords(str_replace("_", " ", $text));
  623. $text = str_replace(" ", "", $text);
  624. $text[0] = strtolower($text[0]);
  625. return $text;
  626. }
  627. private function file_force_contents($dir, $contents){
  628. $dir = str_replace("\\", "/", $dir);
  629. $dir = str_replace( '//', '/', $dir);
  630. $parts = explode('/', $dir);
  631. $file = array_pop($parts);
  632. $dir = '';
  633. foreach($parts as $part) {
  634. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  635. if(!is_dir($dir .= "/$part")) mkdir($dir);
  636. }
  637. }
  638. file_put_contents("$dir/$file", $contents);
  639. }
  640. private function generateFormField($line) {
  641. $tokens = explode("=", $line);
  642. $default = false;
  643. if(count($tokens) > 1) {
  644. $default = $tokens[1];
  645. }
  646. $tokens = explode(":", $tokens[0]);
  647. $name = $tokens[0];
  648. $display = $name;
  649. $dotPos = strpos($name, ".");
  650. if($dotPos !== FALSE) {
  651. $display = substr($name, $dotPos + 1);
  652. }
  653. $display = preg_replace('/uid$/i', "", $display);
  654. $type = "text";
  655. $options = [];
  656. if(count($tokens) > 1) {
  657. $type = $tokens[1];
  658. switch ($type) {
  659. case "select":
  660. $options = explode(",", $tokens[2]);
  661. break;
  662. case "record":
  663. $options['table'] = $tokens[2];
  664. $parts = explode(",", $tokens[3]);
  665. $options['valueField'] = $parts[0];
  666. $options['displayField'] = $parts[1];
  667. break;
  668. }
  669. }
  670. if($type !== 'hidden' && $type !== 'bool') {
  671. $code[] = "<div class='form-group mb-3'>";
  672. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))}</label>";
  673. }
  674. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  675. switch ($type) {
  676. case "select":
  677. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  678. ">";
  679. $code[] = "<option value=''>-- Select --</option>";
  680. foreach ($options as $o) {
  681. $code[] = "<option " .
  682. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  683. "value='$o'>$o</option>";
  684. }
  685. $code[] = "</select>";
  686. break;
  687. case "record":
  688. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  689. ">";
  690. $code[] = "<option value=''>-- Select --</option>";
  691. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  692. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  693. $code[] = "<option " .
  694. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  695. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  696. $code[] = "<?php endforeach; ?>";
  697. $code[] = "</select>";
  698. break;
  699. case "bool":
  700. $code[] = "<div class='form-group mb-3'>";
  701. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} ";
  702. $code[] = "<input class='ml-2' type='checkbox' name='$name'>";
  703. $code[] = "</label>";
  704. break;
  705. default:
  706. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine . ">";
  707. }
  708. if($type !== 'hidden') {
  709. $code[] = "</div>";
  710. }
  711. return implode("\n", $code);
  712. }
  713. }
  714. class GenControllerMethod {
  715. public $name;
  716. public $route;
  717. public $hasUID = false;
  718. public $redirect = false;
  719. public $type = '';
  720. public $data = [];
  721. public $parentSub = false;
  722. public $childAddRoute = false;
  723. public $table = false;
  724. public $api = 'create';
  725. public $show = null;
  726. public $viewURL = false;
  727. public $exitURL = false;
  728. public $showLink = true;
  729. public function __construct($name, $route)
  730. {
  731. $this->name = $name;
  732. $this->route = $route;
  733. if(strpos($this->route, "{uid}") !== FALSE) {
  734. $this->hasUID = true;
  735. }
  736. }
  737. }