GenerateTreeCommand.php 41 KB

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