GenerateTreeCommand.php 48 KB

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