GenerateTreeCommand.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. $currentMethod = $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 | !inc/!exc
  134. if($line === 'ACTIONS' || $line === 'SUB') {
  135. $currentSubType = $line;
  136. }
  137. else if(strpos($line, "!inc:") === 0) { // !inc:
  138. if (!empty($currentMethod)) {
  139. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  140. }
  141. }
  142. else if(strpos($line, "!exc:") === 0) { // !exc:
  143. if (!empty($currentMethod)) {
  144. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  145. }
  146. }
  147. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  148. if (!empty($currentMethod)) {
  149. $currentMethod->viewLinkField = substr($line, 5);
  150. }
  151. }
  152. else if (!empty($currentMethod) &&
  153. (strpos($currentMethod->name, 'add_new') === 0 ||
  154. $currentMethod->name === 'remove')) { // this is a field in add_new
  155. $currentMethod->data[] = $line;
  156. }
  157. break;
  158. case 12: // ACTIONS | SUB
  159. // check if this has show conditions
  160. $show = false;
  161. if(strpos($line, ":")) {
  162. $parts = explode(":", $line);
  163. $line = $parts[0];
  164. if($parts[1] === 'if') {
  165. $show = $parts[2];
  166. }
  167. }
  168. if($currentSubType === 'ACTIONS') {
  169. $currentMethod = $currentSubController->addMethod(
  170. "ACTION_" . $line,
  171. "/ACTION_" . $line
  172. );
  173. $currentMethod->type = 'action';
  174. $currentMethod->show = $show;
  175. $currentMethod->data = [];
  176. }
  177. else if($currentSubType === 'SUB') {
  178. $currentMethod = $currentSubController->addMethod(
  179. "SUB_" . $line,
  180. "/SUB_" . $line
  181. );
  182. $currentMethod->type = 'sub';
  183. $currentMethod->show = $show;
  184. $currentMethod->data = [];
  185. }
  186. break;
  187. case 16: // data for actions and subs
  188. if(strpos($line, "!inc:") === 0) { // !inc:
  189. if (!empty($currentMethod)) {
  190. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  191. }
  192. }
  193. else if(strpos($line, "!exc:") === 0) { // !exc:
  194. if (!empty($currentMethod)) {
  195. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  196. }
  197. }
  198. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  199. if (!empty($currentMethod)) {
  200. $currentMethod->viewLinkField = substr($line, 5);
  201. }
  202. }
  203. else if(!empty($currentMethod)) {
  204. $currentMethod->data[] = $line;
  205. if($exitURL) {
  206. if(strpos("=", $line) !== FALSE) {
  207. $currentMethod->viewURL = $exitURL;
  208. }
  209. else {
  210. $currentMethod->exitURL = $exitURL;
  211. }
  212. }
  213. }
  214. break;
  215. case 20: // SUB add_new fields
  216. if(!empty($currentMethod)) {
  217. $currentMethod->data[] = $line;
  218. }
  219. break;
  220. default:
  221. dump("ERROR: Cannot have $ls leading spaces!");
  222. dump("Line: $line");
  223. exit(1);
  224. }
  225. }
  226. }
  227. // do any pending saves
  228. if(!empty($currentSubController)) {
  229. $currentSubController->save();
  230. }
  231. if(!empty($currentController)) {
  232. $currentController->save();
  233. }
  234. echo "Saved " . base_path("routes/generated.php") . "\n";
  235. // save side links
  236. file_put_contents(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  237. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  238. }
  239. private function numLS($line) {
  240. $count = 0;
  241. for ($i=0; $i<strlen($line); $i++) {
  242. if($line[$i] !== ' ') break;
  243. $count++;
  244. }
  245. return $count;
  246. }
  247. }
  248. class GenController {
  249. public $root;
  250. public $saved = false;
  251. public $name;
  252. public $methods;
  253. public $parentRoute = "";
  254. public $dbTable = null;
  255. public $condition = null;
  256. public $hasAdd = false;
  257. public $hasView = false;
  258. public $hasRemove = false;
  259. public $sub = false;
  260. public $parentControllerName = '';
  261. public $subLinksSaved = false;
  262. public $actionLinksSaved = false;
  263. public function __construct($root = null, $name = null)
  264. {
  265. $this->root = $root;
  266. $this->name = $name;
  267. $this->methods = [];
  268. }
  269. public function addMethod($method, $route) {
  270. if($this->parentRoute) {
  271. $route = $this->parentRoute . $route;
  272. }
  273. $method = new GenControllerMethod($method, $route);
  274. $this->methods[] = $method;
  275. return $method;
  276. }
  277. public function save() {
  278. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  279. $this->saveController();
  280. $this->saveRoutes();
  281. $this->saved = true;
  282. // $this->log();
  283. }
  284. }
  285. public function saveController() {
  286. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  287. $code = [];
  288. // check if any method has a "sub add_new" in it, if yes, add action for the same
  289. $newMethods = [];
  290. foreach ($this->methods as $method) {
  291. if($method->type === 'sub' && count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  292. $methodName = preg_replace("/^SUB_/", "ACTION_", $method->name) . 'AddNew';
  293. $methodRoute = str_replace("/SUB_", "/ACTION_", $method->route) . 'AddNew';
  294. $newMethod = new GenControllerMethod($methodName, $methodRoute);
  295. $newMethod->hasUID = true;
  296. $newMethod->redirect = false;
  297. $newMethod->type = 'action';
  298. $newMethod->data = [];
  299. for($i = 2; $i<count($method->data); $i++) {
  300. $newMethod->data[] = $method->data[$i];
  301. }
  302. $newMethod->parentSub = $this->name . '-' . $method->name;
  303. $parts = explode(":", $method->data[1]);
  304. $newMethod->table = $parts[1];
  305. if(count($parts) === 3) {
  306. $newMethod->api = $parts[2];
  307. }
  308. $newMethod->exitURL = $method->exitURL;
  309. $newMethod->showLink = false;
  310. $newMethods[] = $newMethod;
  311. $method->childAddRoute = $this->name . '-' . $methodName;
  312. }
  313. }
  314. $this->methods = array_merge($this->methods, $newMethods);
  315. foreach ($this->methods as $method) {
  316. $code[] = "";
  317. $code[] = "\t// GET {$method->route}";
  318. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  319. if($method->redirect) {
  320. $target = str_replace('{uid}', '$uid', $method->redirect);
  321. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  322. }
  323. else {
  324. if($method->hasUID) {
  325. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  326. $input = ["'record'"];
  327. // if sub-index controller, load subRecords
  328. if($method->type === 'sub' && count($method->data)) {
  329. $parts = explode(",", $method->data[0]);
  330. $loadingLine = [];
  331. // first 'where'
  332. $dbParts = explode("=", $parts[0]);
  333. $localField = $dbParts[0];
  334. $dbParts = explode(".", $dbParts[1]);
  335. $foreignTable = $dbParts[0];
  336. $foreignField = $dbParts[1];
  337. $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
  338. $loadingLine[] = "->where('$foreignField', \$record->$localField)";
  339. // other 'where's
  340. if(count($parts) > 1) {
  341. for ($i = 1; $i < count($parts); $i++) {
  342. $dbParts = explode("=", $parts[$i]);
  343. $field = $dbParts[0];
  344. $value = $dbParts[1];
  345. $loadingLine[] = "->where('$field', $value)";
  346. }
  347. }
  348. $loadingLine[] = "->get();";
  349. $code[] = implode("", $loadingLine);
  350. // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  351. $input[] = "'subRecords'";
  352. }
  353. // return response()->view('pro/my_teams/add_new', compact('records'), session('message') ? 500 : 200)->header('Content-Type', 'text/html');
  354. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  355. "compact(" . implode(", ", $input) . "), " .
  356. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  357. }
  358. else {
  359. $loadingLine = [];
  360. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  361. if($this->condition) {
  362. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  363. }
  364. $loadingLine[] = "->get();";
  365. $code[] = implode("", $loadingLine);
  366. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  367. "compact('records'), " .
  368. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  369. }
  370. }
  371. $this->saveView($this, $method);
  372. $code[] = "\t}";
  373. }
  374. $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
  375. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  376. file_put_contents(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  377. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  378. }
  379. public function saveView(GenController $controller, GenControllerMethod $method) {
  380. if($controller->sub) {
  381. $controller->saveSubLinks($controller, $method);
  382. $controller->saveActionLinks($controller, $method);
  383. if($method->type === 'action') {
  384. $this->saveSubActionView($controller, $method);
  385. }
  386. else if($method->type === 'sub' && count($method->data)) {
  387. $this->saveSubIndexView($controller, $method);
  388. }
  389. else {
  390. $this->saveSubDefaultView($controller, $method);
  391. }
  392. }
  393. else {
  394. if($method->name === 'view' && $controller->hasView) {
  395. $this->saveShowView($controller, $method);
  396. }
  397. else if($method->name === 'index') {
  398. $this->saveIndexView($controller, $method);
  399. }
  400. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  401. $this->saveAddNewView($controller, $method);
  402. }
  403. else if($method->name === 'remove' && $controller->hasRemove) {
  404. $this->saveAddNewView($controller, $method);
  405. }
  406. }
  407. }
  408. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  409. {
  410. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  411. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  412. if($controller->hasAdd) {
  413. $addLinks = [];
  414. foreach ($controller->methods as $m) {
  415. if($m->type === 'add') {
  416. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  417. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  418. "href='/{$controller->name}/{$m->name}'>" .
  419. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  420. "{$this->snakeToTitleCase($m->name)}</a>";
  421. }
  422. }
  423. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  424. }
  425. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  426. $ths = [];
  427. $tds = [];
  428. if($controller->hasRemove) {
  429. $ths[] = "<th></th>";
  430. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  431. "<i class='fa fa-trash'></i>" .
  432. "</a></td>";
  433. }
  434. // !inc/!exc
  435. if($method->incType === "include") {
  436. $columns = $method->incFields;
  437. }
  438. else if($method->incType === "exclude") {
  439. $columns = array_filter($columns, function($item) use ($method) {
  440. return in_array($item, $method->incFields) === FALSE;
  441. });
  442. }
  443. foreach ($columns as $column) {
  444. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  445. $tds[] = "<td>" .
  446. ($controller->hasView && $column === $method->viewLinkField ? '<a href="/' . $controller->name . '/view/<?= $record->uid ?>">' : '') .
  447. "<?= \$record->$column ?>" .
  448. ($controller->hasView && $column === $method->viewLinkField ? '</a>' : '') .
  449. "</td>";
  450. }
  451. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  452. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  453. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  454. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  455. }
  456. public function saveShowView(GenController $controller, GenControllerMethod $method)
  457. {
  458. // delete sub links and action links
  459. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  460. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  461. }
  462. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  463. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  464. }
  465. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  466. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  467. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  468. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  469. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  470. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  471. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  472. }
  473. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  474. {
  475. if ($controller->subLinksSaved) return;
  476. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  477. $subLinks = [];
  478. foreach ($controller->methods as $meth) {
  479. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  480. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  481. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  482. "<a " .
  483. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  484. "class='d-block px-3 py-2 border-bottom " .
  485. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  486. (
  487. $meth->name === 'SUB_dashboard' ?
  488. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  489. ""
  490. )
  491. . "'>$display</a>" .
  492. ($meth->show ? " @endif" : "");
  493. }
  494. $this->file_force_contents($subLinksView, implode("\n", $subLinks));
  495. echo "Generated " . $subLinksView . "\n";
  496. $controller->subLinksSaved = true;
  497. }
  498. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  499. {
  500. if ($controller->actionLinksSaved) return;
  501. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  502. $actionLinks = [];
  503. foreach ($controller->methods as $meth) {
  504. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  505. $display = $this->camelToTitleCase(substr($meth->name, 7));
  506. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  507. "<a " .
  508. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  509. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  510. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  511. ($meth->show ? " @endif" : "");
  512. }
  513. $this->file_force_contents($actionLinksView, implode("\n", $actionLinks));
  514. echo "Generated " . $actionLinksView . "\n";
  515. $controller->actionLinksSaved = true;
  516. }
  517. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  518. {
  519. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  520. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  521. $text = $this->generateSubContent($controller, $method, $text);
  522. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  523. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  524. }
  525. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  526. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  527. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  528. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  529. if(!$method->parentSub) {
  530. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  531. }
  532. else {
  533. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  534. }
  535. if(!$method->table) {
  536. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  537. }
  538. else {
  539. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  540. }
  541. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  542. $fields = [];
  543. if(count($method->data)) {
  544. foreach ($method->data as $field) {
  545. $fields[] = $this->generateFormField($field);
  546. }
  547. }
  548. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  549. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  550. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  551. }
  552. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  553. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  554. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  555. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  556. if(count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  557. $addLink = '<a class="btn btn-primary btn-sm" ' .
  558. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  559. 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
  560. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  561. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  562. }
  563. $dbParts = explode("=", $method->data[0]);
  564. $dbParts = explode(".", $dbParts[1]);
  565. $table = $dbParts[0];
  566. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  567. $ths = [];
  568. $tds = [];
  569. // !inc/!exc
  570. if($method->incType === "include") {
  571. $columns = $method->incFields;
  572. }
  573. else if($method->incType === "exclude") {
  574. $columns = array_filter($columns, function($item) use ($method) {
  575. return in_array($item, $method->incFields) === FALSE;
  576. });
  577. }
  578. foreach ($columns as $column) {
  579. $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
  580. $tds[] = "<td>" .
  581. ($method->exitURL && $column === $method->viewLinkField ? '<a href="' . $method->exitURL . '">' : '') .
  582. "<?= \$subRecord->$column ?>" .
  583. ($method->exitURL && $column === $method->viewLinkField ? '</a>' : '') .
  584. "</td>";
  585. }
  586. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  587. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  588. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  589. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  590. }
  591. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  592. if($method->name === 'SUB_dashboard') {
  593. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
  594. $text = str_replace("_SUB_VIEW_", $html, $text);
  595. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  596. }
  597. else {
  598. $text = str_replace("_SUB_VIEW_",
  599. "<h4 class='py-3 border-bottom'>" .
  600. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
  601. "Controller: <b>{$controller->name}</b><br>" .
  602. "Action: <b>{$method->name}()</b><br>" .
  603. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br>",
  604. $text);
  605. }
  606. return $text;
  607. }
  608. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  609. {
  610. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  611. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  612. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  613. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  614. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  615. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  616. $columns = $method->data;
  617. $fields = [];
  618. foreach ($columns as $column) {
  619. $fields[] = $this->generateFormField($column);
  620. }
  621. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  622. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  623. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  624. }
  625. public function saveRoutes() {
  626. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  627. foreach ($this->methods as $method) {
  628. // FORMAT:
  629. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  630. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  631. }
  632. $lines[] = '';
  633. $lines[] = '';
  634. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  635. }
  636. public function log() {
  637. $this->w('');
  638. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  639. $this->w("Table: {$this->dbTable}");
  640. $this->w('---------------------------------------------');
  641. foreach ($this->methods as $method) {
  642. $this->w('Rout: ' . $method->route, 1);
  643. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  644. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  645. $this->w('Exit: ' . $method->exitURL, 1);
  646. $this->w('View: ' . $method->viewURL, 1);
  647. if(!$method->redirect) {
  648. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  649. }
  650. else {
  651. $this->w('Redi: ' . $method->redirect, 1);
  652. }
  653. $this->w('---------------------------------------------');
  654. }
  655. }
  656. public function w($line, $level = -1) {
  657. for($i=0; $i<$level; $i++) echo "\t";
  658. echo "$line\n";
  659. }
  660. public function snakeToTitleCase($text) {
  661. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  662. return ucwords(str_replace("_", " ", $text));
  663. }
  664. public function camelToTitleCase($text) {
  665. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  666. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  667. return ucwords($text);
  668. }
  669. public function snakeToCamelCase($text) {
  670. $text = ucwords(str_replace("_", " ", $text));
  671. $text = str_replace(" ", "", $text);
  672. $text[0] = strtolower($text[0]);
  673. return $text;
  674. }
  675. private function file_force_contents($dir, $contents){
  676. $dir = str_replace("\\", "/", $dir);
  677. $dir = str_replace( '//', '/', $dir);
  678. $parts = explode('/', $dir);
  679. $file = array_pop($parts);
  680. $dir = '';
  681. foreach($parts as $part) {
  682. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  683. if(!is_dir($dir .= "/$part")) mkdir($dir);
  684. }
  685. }
  686. file_put_contents("$dir/$file", $contents);
  687. }
  688. private function generateFormField($line) {
  689. $tokens = explode("=", $line);
  690. $default = false;
  691. if(count($tokens) > 1) {
  692. $default = $tokens[1];
  693. }
  694. $tokens = explode(":", $tokens[0]);
  695. $name = $tokens[0];
  696. $display = $name;
  697. $dotPos = strpos($name, ".");
  698. if($dotPos !== FALSE) {
  699. $display = substr($name, $dotPos + 1);
  700. }
  701. $display = preg_replace('/uid$/i', "", $display);
  702. $type = "text";
  703. $options = [];
  704. if(count($tokens) > 1) {
  705. $type = $tokens[1];
  706. switch ($type) {
  707. case "select":
  708. $options = explode(",", $tokens[2]);
  709. break;
  710. case "record":
  711. $options['table'] = $tokens[2];
  712. $parts = explode(",", $tokens[3]);
  713. $options['valueField'] = $parts[0];
  714. $options['displayField'] = $parts[1];
  715. break;
  716. }
  717. }
  718. if($type !== 'hidden' && $type !== 'bool') {
  719. $code[] = "<div class='form-group mb-3'>";
  720. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))}</label>";
  721. }
  722. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  723. switch ($type) {
  724. case "select":
  725. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  726. ">";
  727. $code[] = "<option value=''>-- Select --</option>";
  728. foreach ($options as $o) {
  729. $code[] = "<option " .
  730. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  731. "value='$o'>$o</option>";
  732. }
  733. $code[] = "</select>";
  734. break;
  735. case "record":
  736. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  737. ">";
  738. $code[] = "<option value=''>-- Select --</option>";
  739. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  740. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  741. $code[] = "<option " .
  742. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  743. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  744. $code[] = "<?php endforeach; ?>";
  745. $code[] = "</select>";
  746. break;
  747. case "bool":
  748. $code[] = "<div class='form-group mb-3'>";
  749. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} ";
  750. $code[] = "<input class='ml-2' type='checkbox' name='$name'>";
  751. $code[] = "</label>";
  752. break;
  753. default:
  754. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine . ">";
  755. }
  756. if($type !== 'hidden') {
  757. $code[] = "</div>";
  758. }
  759. return implode("\n", $code);
  760. }
  761. }
  762. class GenControllerMethod {
  763. public $name;
  764. public $route;
  765. public $hasUID = false;
  766. public $redirect = false;
  767. public $type = '';
  768. public $data = [];
  769. public $parentSub = false;
  770. public $childAddRoute = false;
  771. public $table = false;
  772. public $api = 'create';
  773. public $show = null;
  774. public $viewURL = false;
  775. public $exitURL = false;
  776. public $showLink = true;
  777. public $incType = null;
  778. public $incFields = null;
  779. public $viewLinkField = 'uid';
  780. public function __construct($name, $route)
  781. {
  782. $this->name = $name;
  783. $this->route = $route;
  784. if(strpos($this->route, "{uid}") !== FALSE) {
  785. $this->hasUID = true;
  786. }
  787. }
  788. public function setIncFields($type, $fields) {
  789. $this->incType = $type;
  790. $this->incFields = $fields;
  791. for ($i = 0; $i < count($this->incFields); $i++) {
  792. if($this->incFields[$i][0] === '@') {
  793. $this->incFields[$i] = substr($this->incFields[$i], 1);
  794. $this->viewLinkField = $this->incFields[$i];
  795. }
  796. }
  797. }
  798. }