GenerateTreeCommand.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  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. GenerateTreeCommand::save(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. $currentSubAdder = null;
  42. foreach ($lines as $line) {
  43. // stop (debugging)
  44. if(trim($line) === '##stop') {
  45. exit(0);
  46. }
  47. // skip comments
  48. if(trim($line)[0] === '#') continue;
  49. $lineType = null;
  50. // no leading space - root specifier
  51. if($line[0] !== ' ') {
  52. $currentRoot = strtolower(trim($line));
  53. }
  54. else {
  55. $ls = $this->numLS($line);
  56. $line = trim($line);
  57. $exitURL = false;
  58. if(strpos($line, "=>") !== FALSE) {
  59. $parts = explode("=>", $line);
  60. $exitURL = str_replace("UID", "{{ \$subRecord->uid }}", $parts[1]);
  61. $line = $parts[0];
  62. }
  63. $tokens = explode("|", $line);
  64. $line = $tokens[0];
  65. $dbTable = null;
  66. $condition = null;
  67. if(count($tokens) >= 2) {
  68. $dbTable = $tokens[1];
  69. // check if table has loading conditions
  70. if(strpos($dbTable, ":")) {
  71. $parts = explode(":", $dbTable);
  72. $dbTable = $parts[0];
  73. $parts = explode("=", $parts[1]);
  74. $condition = [
  75. "field" => $parts[0],
  76. "value" => str_replace("OWN", "session('proId')" , $parts[1])
  77. ];
  78. }
  79. }
  80. $hasAdd = in_array("add", $tokens);
  81. $hasView = in_array("view", $tokens);
  82. $hasRemove = in_array("remove", $tokens);
  83. $icon = "user";
  84. if(strpos($tokens[count($tokens) - 1], "icon:") === 0) {
  85. $icon = substr($tokens[count($tokens) - 1], 5);
  86. }
  87. switch($ls) {
  88. case 4: // top level controller OR top level controller action
  89. // top level controller-action
  90. if(strpos($line, "/") !== FALSE) {
  91. if(!empty($currentController)) {
  92. $parts = explode(":", $line);
  93. $line = $parts[0];
  94. $method = explode("/", $line)[1];
  95. $newMethod = $currentController->addMethod($method, "/" . $line);
  96. if(count($parts) > 1) {
  97. $newMethod->api = $parts[count($parts) - 1];
  98. }
  99. // create _SINGLE_ controller if view
  100. if($method === "view") {
  101. $currentSubController = new GenController($currentRoot, $currentController->name . "_SINGLE");
  102. $currentSubController->dbTable = $currentController->dbTable;
  103. $currentSubController->parentRoute = "/" . $line;
  104. $currentSubController->parentControllerName = $currentController->name;
  105. $currentSubController->sub = true;
  106. $newMethod->redirect = "/" . $line . "/SUB_dashboard";
  107. }
  108. else if(strpos($method, "add_new") === 0) {
  109. $newMethod->type = 'add';
  110. }
  111. else if(strpos($method, "remove") === 0) {
  112. $newMethod->type = 'remove';
  113. }
  114. $currentMethod = $newMethod;
  115. }
  116. }
  117. // new top level controller
  118. else if(empty($currentController) || $line !== $currentController->name) {
  119. if(!empty($currentController)) {
  120. $currentController->save();
  121. }
  122. $currentController = new GenController($currentRoot, $line, $icon);
  123. $currentController->dbTable = $dbTable;
  124. $currentController->condition = $condition;
  125. $currentController->hasAdd = $hasAdd;
  126. $currentController->hasView = $hasView;
  127. $currentController->hasRemove = $hasRemove;
  128. $currentMethod = $currentController->addMethod("index", "/$line");
  129. if(!empty($currentSubController)) {
  130. $currentSubController->save();
  131. }
  132. $currentSubType = '';
  133. $currentSubController = new GenController();
  134. $sideLinks[] = "<li class='nav-item'>\n" .
  135. "\t<a href='/{$currentController->name}' " .
  136. "class='nav-link " .
  137. "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>\n" .
  138. "\t\t<i class='nav-icon fa fa-$icon'></i>\n" .
  139. "\t\t<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>\n" .
  140. "\t</a>\n</li>\n";
  141. }
  142. break;
  143. case 8: // sub-type declaration | add_new fields | !inc/!exc
  144. if($line === 'ACTIONS' || $line === 'SUB') {
  145. $currentSubType = $line;
  146. }
  147. else if(strpos($line, "!inc:") === 0) { // !inc:
  148. if (!empty($currentMethod)) {
  149. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  150. }
  151. }
  152. else if(strpos($line, "!exc:") === 0) { // !exc:
  153. if (!empty($currentMethod)) {
  154. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  155. }
  156. }
  157. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  158. if (!empty($currentMethod)) {
  159. $currentMethod->viewLinkField = substr($line, 5);
  160. }
  161. }
  162. else if(strpos($line, "!col:") === 0) { // !col:
  163. if (!empty($currentMethod)) {
  164. $currentMethod->setColumnSpec(substr($line, 5), $exitURL, 'record');
  165. }
  166. }
  167. else if(strpos($line, "!qry:") === 0) { // !qry:
  168. if (!empty($currentMethod)) {
  169. $currentMethod->addQuery(substr($line, 5));
  170. }
  171. }
  172. else if (!empty($currentMethod) &&
  173. (strpos($currentMethod->name, 'add_new') === 0 ||
  174. $currentMethod->name === 'remove')) { // this is a field in add_new
  175. $currentMethod->data[] = $line;
  176. }
  177. break;
  178. case 12: // ACTIONS | SUB
  179. // check if this has show conditions
  180. $show = false;
  181. $isDashboard = 'unspecified';
  182. if(strpos($line, ":")) {
  183. $parts = explode(":", $line);
  184. $line = $parts[0];
  185. if($parts[1] === 'if') {
  186. $show = $parts[2];
  187. }
  188. else if($parts[1] === 'dashboard') {
  189. $isDashboard = true;
  190. }
  191. else if($parts[1] === 'custom') {
  192. $isDashboard = false;
  193. }
  194. }
  195. if($currentSubType === 'ACTIONS') {
  196. $currentMethod = $currentSubController->addMethod(
  197. "ACTION_" . $line,
  198. "/ACTION_" . $line
  199. );
  200. $currentMethod->type = 'action';
  201. $currentMethod->show = $show;
  202. $currentMethod->data = [];
  203. }
  204. else if($currentSubType === 'SUB') {
  205. $currentMethod = $currentSubController->addMethod(
  206. "SUB_" . $line,
  207. "/SUB_" . $line
  208. );
  209. $currentMethod->type = 'sub';
  210. $currentMethod->show = $show;
  211. $currentMethod->data = [];
  212. if($isDashboard !== 'unspecified') {
  213. $currentMethod->dashboard = $isDashboard;
  214. if($isDashboard) {
  215. $currentSubController->dashboardName = $line;
  216. if($currentController && $currentSubController && $currentController->name !== $currentSubController->name) {
  217. // change the redirect in /view/{uid} method of $currentController
  218. foreach($currentController->methods as $method) {
  219. if($method->name === 'view' && $method->redirect) {
  220. $method->redirect = $method->route . '/SUB_' . $line;
  221. break;
  222. }
  223. }
  224. }
  225. }
  226. /*dump("/SUB_" . $line . " ==> " . ($isDashboard ? "yes" : "no"));
  227. dump($currentMethod);
  228. dump($currentSubController->dashboardName);
  229. if($isDashboard) exit(1);*/
  230. }
  231. else if($line === 'dashboard') {
  232. $currentMethod->dashboard = true;
  233. }
  234. }
  235. break;
  236. case 16: // data for actions and subs
  237. $currentSubAdder = null;
  238. if(strpos($line, "!inc:") === 0) { // !inc:
  239. if (!empty($currentMethod)) {
  240. $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
  241. }
  242. }
  243. else if(strpos($line, "!exc:") === 0) { // !exc:
  244. if (!empty($currentMethod)) {
  245. $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
  246. }
  247. }
  248. else if(strpos($line, "!lnk:") === 0) { // !lnk:
  249. if (!empty($currentMethod)) {
  250. $currentMethod->viewLinkField = substr($line, 5);
  251. }
  252. }
  253. else if(strpos($line, "!col:") === 0) { // !col:
  254. if (!empty($currentMethod)) {
  255. $currentMethod->setColumnSpec(substr($line, 5), $exitURL,
  256. $currentMethod->dashboard ? 'record' : 'subRecord'
  257. );
  258. }
  259. }
  260. else if(strpos($line, "!qry:") === 0) { // !qry:
  261. if (!empty($currentMethod)) {
  262. $currentMethod->addQuery(substr($line, 5));
  263. }
  264. }
  265. else if(strpos($line, "!grp:") === 0) { // !grp:
  266. if (!empty($currentMethod)) {
  267. $currentMethod->addGroup(substr($line, 5), $exitURL);
  268. }
  269. }
  270. else if(strpos($line, "!act:") === 0) { // !act:
  271. if (!empty($currentMethod)) {
  272. $currentMethod->addAction(substr($line, 5), $exitURL);
  273. }
  274. }
  275. else if(strpos($line, "!nal:") === 0) { // !nal:
  276. if (!empty($currentMethod)) {
  277. $currentMethod->noActionLinks = true;
  278. }
  279. }
  280. else if(strpos($line, "add_new") === 0) { // sub add_new..
  281. if(!empty($currentMethod)) {
  282. $currentSubAdder = $currentMethod->addSubAdder(
  283. $line,
  284. $currentSubController->name,
  285. $currentController->snakeToTitleCase(explode(":", $line)[0]),
  286. $exitURL
  287. );
  288. }
  289. }
  290. else if(!empty($currentMethod)) {
  291. $currentMethod->data[] = $line;
  292. if($exitURL) {
  293. if(strpos("=", $line) !== FALSE) {
  294. $currentMethod->viewURL = $exitURL;
  295. }
  296. else {
  297. $currentMethod->exitURL = $exitURL;
  298. }
  299. }
  300. }
  301. break;
  302. case 20: // SUB add_new fields
  303. if(count($currentMethod->subAdders)) {
  304. $currentMethod->subAdders[count($currentMethod->subAdders) - 1]["data"][] = $line;
  305. }
  306. break;
  307. default:
  308. dump("ERROR: Cannot have $ls leading spaces!");
  309. dump("Line: $line");
  310. exit(1);
  311. }
  312. }
  313. }
  314. // do any pending saves
  315. if(!empty($currentSubController)) {
  316. $currentSubController->save();
  317. }
  318. if(!empty($currentController)) {
  319. $currentController->save();
  320. }
  321. echo "Saved " . base_path("routes/generated.php") . "\n";
  322. // save side links
  323. GenerateTreeCommand::save(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
  324. echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
  325. $this->humanizeRoutes();
  326. }
  327. private function numLS($line) {
  328. $count = 0;
  329. for ($i=0; $i<strlen($line); $i++) {
  330. if($line[$i] !== ' ') break;
  331. $count++;
  332. }
  333. return $count;
  334. }
  335. private function humanizeRoutes() {
  336. $path = base_path("routes/generated.php");
  337. $file = fopen($path, "r");
  338. $lines = [];
  339. $groups = [];
  340. $currentGroup = FALSE;
  341. $comment = '';
  342. $prefix = '';
  343. while (!feof($file)) {
  344. $line = rtrim(fgets($file));
  345. if($line === "") {
  346. if($currentGroup !== FALSE) {
  347. $groups[] = $currentGroup;
  348. $currentGroup = FALSE;
  349. }
  350. }
  351. else if(strpos($line, "// --- ") === 0) {
  352. $comment = $line;
  353. }
  354. else if(strpos($line, "Route::get('") === 0) {
  355. $parts = explode("'", $line);
  356. $route = $parts[1];
  357. $action = $parts[3];
  358. $name = $parts[5];
  359. if($currentGroup === FALSE) {
  360. $prefix = $route;
  361. if (($uidPos = strpos($route, "/{uid}/")) !== FALSE) {
  362. $prefix = substr($route, 0, $uidPos + 6);
  363. }
  364. }
  365. $route = substr($route, strlen($prefix));
  366. if(strlen($route) && $route[0] === "/") {
  367. $route = substr($route, 1);
  368. }
  369. if($currentGroup === FALSE) {
  370. $currentGroup = [
  371. "comment" => $comment,
  372. "prefix" => $prefix,
  373. "routes" => [
  374. [
  375. "route" => $route,
  376. "action" => $action,
  377. "name" => $name
  378. ]
  379. ]
  380. ];
  381. }
  382. else {
  383. $currentGroup["routes"][] = [
  384. "route" => $route,
  385. "action" => $action,
  386. "name" => $name
  387. ];
  388. }
  389. }
  390. }
  391. fclose($file);
  392. // write the routes
  393. $lines = ["<?php", "", "use Illuminate\Support\Facades\Route;", ""];
  394. foreach ($groups as $group) {
  395. $lines[] = $group["comment"];
  396. $lines[] = "Route::prefix('{$group["prefix"]}')->group(function () {";
  397. foreach ($group["routes"] as $route) {
  398. $lines[] = "\tRoute::get('{$route["route"]}', '{$route["action"]}')->name('{$route["name"]}');";
  399. }
  400. $lines[] = "});";
  401. $lines[] = "";
  402. }
  403. GenerateTreeCommand::save($path, implode("\n", $lines));
  404. echo "Cleaned " . base_path("routes/generated.php") . "\n";
  405. }
  406. public static function save($dir, $contents, $flags = FALSE){
  407. // if file exists, check if it has "DO NOT GENERATE" as the first line
  408. if(file_exists($dir) && is_file($dir)) {
  409. $file = fopen($dir, "r");
  410. $lines = [];
  411. $line = rtrim(fgets($file));
  412. if($line === '<?php /* DO NOT GENERATE */ ?>') {
  413. dump("Not writing to protected file: $dir");
  414. fclose($file);
  415. return;
  416. }
  417. fclose($file);
  418. $file = null;
  419. }
  420. $dir = str_replace("\\", "/", $dir);
  421. $dir = str_replace( '//', '/', $dir);
  422. $parts = explode('/', $dir);
  423. $file = array_pop($parts);
  424. $dir = '';
  425. foreach($parts as $part) {
  426. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  427. if(!is_dir($dir .= "/$part")) mkdir($dir);
  428. }
  429. }
  430. if($flags !== FALSE) {
  431. file_put_contents("$dir/$file", $contents, $flags);
  432. }
  433. else {
  434. file_put_contents("$dir/$file", $contents);
  435. }
  436. }
  437. }
  438. class GenController {
  439. public $root;
  440. public $saved = false;
  441. public $name;
  442. public $methods;
  443. public $parentRoute = "";
  444. public $dbTable = null;
  445. public $condition = null;
  446. public $hasAdd = false;
  447. public $hasView = false;
  448. public $hasRemove = false;
  449. public $sub = false;
  450. public $parentControllerName = '';
  451. public $parentController = false;
  452. public $subLinksSaved = false;
  453. public $actionLinksSaved = false;
  454. public $icon = "user";
  455. public $dashboardName = 'dashboard';
  456. public function __construct($root = null, $name = null, $icon = "user")
  457. {
  458. $this->root = $root;
  459. $this->name = $name;
  460. $this->icon = $icon;
  461. $this->methods = [];
  462. }
  463. public function addMethod($method, $route) {
  464. if($this->parentRoute) {
  465. $route = $this->parentRoute . $route;
  466. }
  467. $method = new GenControllerMethod($method, $route);
  468. $this->methods[] = $method;
  469. return $method;
  470. }
  471. public function save() {
  472. if(!$this->saved && !empty($this->root) && !empty($this->name)) {
  473. $this->saveController();
  474. $this->saveRoutes();
  475. $this->saved = true;
  476. // $this->log();
  477. }
  478. }
  479. public function saveController() {
  480. $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
  481. $code = [];
  482. // check if any method has a "sub add_new" in it, if yes, add action for the same
  483. $newMethods = [];
  484. foreach ($this->methods as $method) {
  485. if($method->type === 'sub' && count($method->subAdders) >= 1) {
  486. foreach ($method->subAdders as $subAdder) {
  487. $methodName = "ACTION_" . $subAdder["name"];
  488. $methodRoute = preg_replace("/\\/SUB_.+$/", '/' . $methodName, $method->route);
  489. $newMethod = new GenControllerMethod($methodName, $methodRoute);
  490. $newMethod->hasUID = true;
  491. $newMethod->redirect = false;
  492. $newMethod->type = 'action';
  493. $newMethod->data = $subAdder["data"];
  494. $newMethod->parentSub = $this->name . '-' . $method->name;
  495. $newMethod->table = $subAdder["table"];
  496. if(!empty($subAdder["api"])) {
  497. $newMethod->api = $subAdder["api"];
  498. }
  499. $newMethod->exitURL = $subAdder["link"];
  500. $newMethod->showLink = false;
  501. $newMethod->routeName = $this->name . '-' . $methodName;
  502. $newMethods[] = $newMethod;
  503. }
  504. }
  505. }
  506. $this->methods = array_merge($this->methods, $newMethods);
  507. foreach ($this->methods as $method) {
  508. $code[] = "";
  509. $code[] = "\t// GET {$method->route}";
  510. $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
  511. if($method->redirect) {
  512. $target = str_replace('{uid}', '$uid', $method->redirect);
  513. $code[] = "\t\t" . 'return redirect("' . $target . '");';
  514. }
  515. else {
  516. $input = [];
  517. if($method->hasUID) {
  518. $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
  519. $code[] = "\t\tif(!\$record) {";
  520. $code[] = "\t\t\t\$record = DB::table('{$this->dbTable}')->where('id', \$uid)->first();";
  521. $code[] = "\t\t\tif(\$record) return redirect('" . (str_replace("{uid}", "' . \$record->uid . '", $method->route)) . "');";
  522. $code[] = "\t\t}";
  523. $input[] = "'record'";
  524. // if sub-index controller, load subRecords
  525. if($method->type === 'sub' && count($method->data)) {
  526. $parts = explode(",", $method->data[0]);
  527. $loadingLine = [];
  528. // first 'where'
  529. $dbParts = explode("=", $parts[0]);
  530. $localField = $dbParts[0];
  531. $dbParts = explode(".", $dbParts[1]);
  532. $foreignTable = $dbParts[0];
  533. $foreignField = $dbParts[1];
  534. $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
  535. $loadingLine[] = "->where('$foreignField', \$record->$localField)";
  536. // other 'where's
  537. if(count($parts) > 1) {
  538. for ($i = 1; $i < count($parts); $i++) {
  539. $dbParts = explode("=", $parts[$i]);
  540. $field = $dbParts[0];
  541. $value = $dbParts[1];
  542. $loadingLine[] = "->where('$field', $value)";
  543. }
  544. }
  545. $loadingLine[] = "->get();";
  546. $code[] = implode("", $loadingLine);
  547. // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
  548. $input[] = "'subRecords'";
  549. }
  550. foreach ($method->queries as $key => $query) {
  551. // replace $x with " . ($record->x ? $record->x : "''") . "
  552. $query = preg_replace("/([^$])\\$([a-zA-Z0-9_]+)/", "$1\" . (\$record->$2 ? \$record->$2 : \"''\") . \"", $query);
  553. // replace $$x with " . ($subRecord->x ? $subRecord->x : "''") . "
  554. $query = preg_replace("/\\$\\$([a-zA-Z0-9_]+)/", "\" . (\$subRecord->$1 ? \$subRecord->$1 : \"''\") . \"", $query);
  555. $code[] = "\t\t\$result_$key = DB::select(\"$query\");";
  556. $input[] = "'result_$key'";
  557. }
  558. // return response()->view('pro/my_teams/add_new', compact('records'), session('message') ? 500 : 200)->header('Content-Type', 'text/html');
  559. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  560. "compact(" . implode(", ", $input) . "), " .
  561. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  562. }
  563. else {
  564. $loadingLine = [];
  565. $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
  566. if($this->condition) {
  567. $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
  568. }
  569. $loadingLine[] = "->get();";
  570. $input[] = "'records'";
  571. $code[] = implode("", $loadingLine);
  572. foreach ($method->queries as $key => $query) {
  573. // replace $x with " . ($record->x ? $record->x : "''") . "
  574. $query = preg_replace("/([^$])\\$([a-zA-Z0-9_]+)/", "$1\" . (\$record->$2 ? \$record->$2 : \"''\") . \"", $query);
  575. // replace $$x with " . ($subRecord->x ? $subRecord->x : "''") . "
  576. $query = preg_replace("/\\$\\$([a-zA-Z0-9_]+)/", "\" . (\$subRecord->$1 ? \$subRecord->$1 : \"''\") . \"", $query);
  577. $code[] = "\t\t\$result_$key = DB::select(\"$query\");";
  578. $input[] = "'result_$key'";
  579. }
  580. $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
  581. "compact(" . implode(", ", $input) . "), " .
  582. "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
  583. }
  584. }
  585. $this->saveView($this, $method);
  586. $code[] = "\t}";
  587. }
  588. $text = str_replace("__DASHBOARD_NAME__", $this->dashboardName, $text);
  589. $text = str_replace("__NAME__", "{$this->name}_Controller", $text);
  590. $text = str_replace("// __METHODS__", implode("\n", $code), $text);
  591. GenerateTreeCommand::save(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
  592. echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
  593. }
  594. public function saveView(GenController $controller, GenControllerMethod $method) {
  595. if($controller->sub) {
  596. $controller->saveSubLinks($controller, $method);
  597. $controller->saveActionLinks($controller, $method);
  598. if($method->type === 'action') {
  599. $this->saveSubActionView($controller, $method);
  600. }
  601. else if($method->type === 'sub' && count($method->data)) {
  602. $this->saveSubIndexView($controller, $method);
  603. }
  604. else {
  605. $this->saveSubDefaultView($controller, $method);
  606. }
  607. }
  608. else {
  609. if($method->name === 'view' && $controller->hasView) {
  610. $this->saveShowView($controller, $method);
  611. }
  612. else if($method->name === 'index') {
  613. $this->saveIndexView($controller, $method);
  614. }
  615. else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
  616. $this->saveAddNewView($controller, $method);
  617. }
  618. else if($method->name === 'remove' && $controller->hasRemove) {
  619. $this->saveAddNewView($controller, $method);
  620. }
  621. }
  622. }
  623. public function saveIndexView(GenController $controller, GenControllerMethod $method)
  624. {
  625. $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
  626. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  627. if($controller->hasAdd) {
  628. $addLinks = [];
  629. foreach ($controller->methods as $m) {
  630. if($m->type === 'add') {
  631. $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
  632. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  633. "href='/{$controller->name}/{$m->name}?optimised=1'>" .
  634. "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
  635. "{$this->snakeToTitleCase($m->name)}</a>";
  636. }
  637. }
  638. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
  639. }
  640. $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
  641. $ths = [];
  642. $tds = [];
  643. if($controller->hasRemove) {
  644. $ths[] = "<th></th>";
  645. $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
  646. "<i class='fa fa-trash'></i>" .
  647. "</a></td>";
  648. }
  649. // !inc/!exc
  650. if($method->incType === "include") {
  651. $columns = $method->incFields;
  652. }
  653. else if($method->incType === "exclude") {
  654. $columns = array_filter($columns, function($item) use ($method) {
  655. return in_array($item, $method->incFields) === FALSE;
  656. });
  657. }
  658. // ensure uid column is at the start
  659. $columns = array_merge(['uid'], array_filter($columns, function($x) {
  660. return $x !== 'uid';
  661. }));
  662. foreach ($columns as $column) {
  663. if($column === 'id') continue;
  664. $columnTitle = $this->snakeToTitleCase($column);
  665. $columnValue = "<?= \$record->$column ?>";
  666. $hasLink = $controller->hasView && $column === $method->viewLinkField;
  667. $linkTarget = "/{$controller->name}/view/<?= \$record->uid ?>";
  668. if(substr($column, -3) === '_at') {
  669. $columnValue = "<?= friendly_date_time(\$record->$column) ?>";
  670. }
  671. // check if this column has column spec
  672. if(isset($method->columns[$column])) {
  673. $columnTitle = $method->columns[$column]["label"];
  674. if(isset($method->columns[$column]["query"])) {
  675. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  676. "select(\"{$method->columns[$column]["query"]}\");\n" .
  677. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  678. }
  679. else if(isset($method->columns[$column]["getter"])) {
  680. $columnValue = $method->columns[$column]["getter"];
  681. }
  682. if(isset($method->columns[$column]["link"])) {
  683. $hasLink = true;
  684. $linkTarget = $method->columns[$column]["link"];
  685. }
  686. }
  687. else if($column === 'uid') {
  688. $columnTitle = '&nbsp;';
  689. $columnValue = '<i class="fas fa-share-square"></i>';
  690. $hasLink = true;
  691. }
  692. $ths[] = "<th>$columnTitle</th>";
  693. $tds[] = "<td>" .
  694. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  695. $columnValue .
  696. ($hasLink ? "</a>" : "") .
  697. "</td>";
  698. }
  699. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  700. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  701. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  702. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  703. }
  704. public function saveShowView(GenController $controller, GenControllerMethod $method)
  705. {
  706. // delete sub links and action links
  707. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  708. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  709. }
  710. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  711. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  712. }
  713. // write info view
  714. $text = file_get_contents(base_path('generatecv/tree-templates/info.template.blade.php'));
  715. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  716. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  717. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  718. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/info.blade.php"), $text);
  719. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/info.blade.php") . "\n";
  720. // write main view
  721. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  722. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  723. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  724. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  725. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  726. $text = str_replace("_INFO_VIEW_", "{$controller->root}/{$controller->name}/info", $text);
  727. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  728. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  729. }
  730. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  731. {
  732. if ($controller->subLinksSaved) return;
  733. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  734. $subLinks = [];
  735. foreach ($controller->methods as $meth) {
  736. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  737. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  738. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  739. "<a " .
  740. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  741. "class='d-block px-3 py-2 border-bottom stag-sublink " .
  742. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  743. (
  744. $meth->name === 'SUB_dashboard' ?
  745. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  746. ""
  747. )
  748. . "'>$display</a>" .
  749. ($meth->show ? " @endif" : "");
  750. }
  751. GenerateTreeCommand::save($subLinksView, implode("\n", $subLinks));
  752. echo "Generated " . $subLinksView . "\n";
  753. $controller->subLinksSaved = true;
  754. }
  755. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  756. {
  757. if ($controller->actionLinksSaved) return;
  758. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  759. $actionLinks = [];
  760. foreach ($controller->methods as $meth) {
  761. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  762. $display = $this->camelToTitleCase(substr($meth->name, 7));
  763. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  764. "<a " .
  765. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  766. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}?optimised=1' " .
  767. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  768. ($meth->show ? " @endif" : "");
  769. }
  770. GenerateTreeCommand::save($actionLinksView, implode("\n", $actionLinks));
  771. echo "Generated " . $actionLinksView . "\n";
  772. $controller->actionLinksSaved = true;
  773. }
  774. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  775. {
  776. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  777. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  778. $text = $this->generateSubContent($controller, $method, $text);
  779. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  780. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  781. }
  782. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  783. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  784. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  785. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  786. if(!$method->parentSub) {
  787. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  788. }
  789. else {
  790. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  791. }
  792. if(!$method->table) {
  793. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  794. }
  795. else {
  796. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  797. }
  798. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  799. $fields = [];
  800. if(count($method->data)) {
  801. foreach ($method->data as $field) {
  802. $fields[] = $this->generateFormField($field);
  803. }
  804. }
  805. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  806. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  807. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  808. }
  809. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  810. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  811. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  812. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  813. if(count($method->subAdders) >= 1) {
  814. $addLinks = [];
  815. foreach ($method->subAdders as $subAdder) {
  816. $addLink = '<a class="btn btn-primary btn-sm ml-2" ' .
  817. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  818. 'href="{{route(\'' . $subAdder["routeName"] . '\', [\'uid\' => $record->uid])}}?optimised=1">' .
  819. "<i class='fa fa-plus-circle' aria-hidden='true'></i> {$subAdder["buttonLabel"]}</a>";
  820. $addLinks[] = $addLink;
  821. }
  822. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("", $addLinks), $text);
  823. }
  824. $dbParts = explode("=", $method->data[0]);
  825. $dbParts = explode(".", $dbParts[1]);
  826. $table = $dbParts[0];
  827. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  828. $ths = [];
  829. $tds = [];
  830. // !inc/!exc
  831. if($method->incType === "include") {
  832. $columns = $method->incFields;
  833. }
  834. else if($method->incType === "exclude") {
  835. $columns = array_filter($columns, function($item) use ($method) {
  836. return in_array($item, $method->incFields) === FALSE;
  837. });
  838. }
  839. // ensure uid column is at the start
  840. $columns = array_merge(['uid'], array_filter($columns, function($x) {
  841. return $x !== 'uid';
  842. }));
  843. foreach ($columns as $column) {
  844. if($column === 'id') continue;
  845. $columnTitle = $this->snakeToTitleCase($column);
  846. $columnValue = "<?= \$subRecord->$column ?>";
  847. $hasLink = $method->exitURL && $column === $method->viewLinkField;
  848. $linkTarget = $method->exitURL;
  849. if(substr($column, -3) === '_at') {
  850. $columnValue = "<?= friendly_date_time(\$subRecord->$column) ?>";
  851. }
  852. // check if this column has column spec
  853. if(isset($method->columns[$column])) {
  854. $columnTitle = $method->columns[$column]["label"];
  855. if(isset($method->columns[$column]["query"])) {
  856. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  857. "select(\"{$method->columns[$column]["query"]}\");\n" .
  858. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  859. }
  860. else if(isset($method->columns[$column]["getter"])) {
  861. $columnValue = $method->columns[$column]["getter"];
  862. }
  863. if(isset($method->columns[$column]["link"])) {
  864. $hasLink = true;
  865. $linkTarget = $method->columns[$column]["link"];
  866. }
  867. }
  868. else if($column === 'uid') {
  869. $columnTitle = '&nbsp;';
  870. $columnValue = '<i class="fas fa-share-square"></i>';
  871. $hasLink = true;
  872. }
  873. $ths[] = "<th>$columnTitle</th>";
  874. $tds[] = "<td>" .
  875. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  876. $columnValue .
  877. ($hasLink ? "</a>" : "") .
  878. "</td>";
  879. }
  880. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  881. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  882. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  883. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  884. }
  885. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  886. if($method->dashboard) {
  887. if(!isset($method->groups) || !count($method->groups)) {
  888. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
  889. }
  890. else {
  891. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard-grouped' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
  892. $groupsHtml = [];
  893. $groupTemplate = file_get_contents(base_path('generatecv/tree-templates/dashboard-group.template.blade.php'));
  894. foreach ($method->groups as $group) {
  895. $groupHtml = $groupTemplate;
  896. $groupHtml = str_replace("<!-- __GROUP_NAME__ -->", $group["name"], $groupHtml);
  897. if (isset($group["action"])) {
  898. $action = $group["action"];
  899. $actionLine = [];
  900. if (isset($action["condition"])) {
  901. if ($action["condition"] === "if") {
  902. $actionLine[] = "@if(";
  903. } else {
  904. $actionLine[] = "@if(!";
  905. }
  906. $actionLine[] = "\$record->{$action["field"]})";
  907. }
  908. $title = $this->camelToTitleCase($action["label"]);
  909. $actionLine[] = "<a " .
  910. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  911. "href='{$action["link"]}' title='{$action["label"]}?optimised=1'" .
  912. "class='mx-2 font-weight-normal text-primary text-xs'>" .
  913. "<i class='fa fa-{$action["icon"]}'></i>&nbsp;" .
  914. "<span>{$title}</span>" .
  915. "</a>";
  916. if (isset($action["condition"])) {
  917. $actionLine[] = "@endif";
  918. }
  919. $actionLine = implode(" ", $actionLine);
  920. $groupHtml = str_replace("<!-- __GROUP_ACTION__ -->", $actionLine, $groupHtml);
  921. }
  922. $fields = [];
  923. foreach ($group["fields"] as $field) {
  924. if($field === 'id' || $field === 'uid') continue;
  925. $columnTitle = $this->snakeToTitleCase($field);
  926. $columnValue = "<?= \$record->$field ?>";
  927. $hasLink = false;
  928. $linkTarget = null;
  929. $actions = [];
  930. if(substr($field, -3) === '_at') {
  931. $columnValue = "<?= friendly_date_time(\$record->$field) ?>";
  932. }
  933. // check if this column has column spec
  934. if(isset($method->columns[$field])) {
  935. $columnTitle = $method->columns[$field]["label"];
  936. if(isset($method->columns[$field]["query"])) {
  937. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  938. "select(\"{$method->columns[$field]["query"]}\");\n" .
  939. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  940. }
  941. else if(isset($method->columns[$field]["getter"])) {
  942. $columnValue = $method->columns[$field]["getter"];
  943. }
  944. if(isset($method->columns[$field]["link"])) {
  945. $hasLink = true;
  946. $linkTarget = $method->columns[$field]["link"];
  947. }
  948. }
  949. if(isset($method->columnActions[$field])) {
  950. foreach($method->columnActions[$field] as $action) {
  951. $actionLine = [];
  952. if(isset($action["condition"])) {
  953. if($action["condition"] === "if") {
  954. $actionLine[] = "@if(";
  955. }
  956. else {
  957. $actionLine[] = "@if(!";
  958. }
  959. $actionLine[] = "\$record->{$action["field"]})";
  960. }
  961. $title = $this->camelToTitleCase($action["label"]);
  962. $actionLine[] = "<a " .
  963. 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
  964. "href='{$action["link"]}?optimised=1' title='{$action["label"]}' " .
  965. "class='mx-2 font-weight-normal text-primary text-xs'>" .
  966. "<i class='fa fa-{$action["icon"]}'></i>&nbsp;" .
  967. "<span>{$title}</span>" .
  968. "</a>";
  969. if(isset($action["condition"])) {
  970. $actionLine[] = "@endif";
  971. }
  972. $actionLine = implode(" ", $actionLine);
  973. $actions[] = $actionLine;
  974. }
  975. }
  976. $actions = implode("\n", $actions);
  977. $fields[] = "<tr>" .
  978. "<td class=\"w-25 px-2 text-secondary border-right\">$columnTitle</td>" .
  979. "<td class=\"w-75 px-2 font-weight-bold\">" .
  980. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  981. $columnValue .
  982. ($hasLink ? "</a>" : "") .
  983. $actions .
  984. "</td>" .
  985. "</tr>";
  986. }
  987. $groupHtml = str_replace("<!-- __GROUP_FIELDS__ -->", implode("\n", $fields), $groupHtml);
  988. $groupsHtml[] = $groupHtml;
  989. }
  990. $groupsHtml = implode("\n", $groupsHtml);
  991. $html = str_replace("<!-- _GROUPS_ -->", $groupsHtml, $html);
  992. }
  993. $text = str_replace("_SUB_VIEW_", $html, $text);
  994. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  995. }
  996. else {
  997. $text = str_replace("_SUB_VIEW_",
  998. "<h5 class='py-3 border-bottom'>" .
  999. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h5>" .
  1000. "Controller: <b>{$controller->name}</b><br>" .
  1001. "Action: <b>{$method->name}()</b><br>" .
  1002. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br><br>",
  1003. $text);
  1004. }
  1005. return $text;
  1006. }
  1007. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  1008. {
  1009. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  1010. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  1011. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  1012. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  1013. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  1014. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  1015. $columns = $method->data;
  1016. $fields = [];
  1017. foreach ($columns as $column) {
  1018. $fields[] = $this->generateFormField($column);
  1019. }
  1020. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  1021. GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  1022. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  1023. }
  1024. public function saveRoutes() {
  1025. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  1026. foreach ($this->methods as $method) {
  1027. // FORMAT:
  1028. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  1029. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  1030. }
  1031. $lines[] = '';
  1032. $lines[] = '';
  1033. GenerateTreeCommand::save(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  1034. }
  1035. public function log() {
  1036. $this->w('');
  1037. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  1038. $this->w("Table: {$this->dbTable}");
  1039. $this->w('---------------------------------------------');
  1040. foreach ($this->methods as $method) {
  1041. $this->w('Rout: ' . $method->route, 1);
  1042. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  1043. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  1044. // $this->w('Exit: ' . $method->exitURL, 1);
  1045. // $this->w('View: ' . $method->viewURL, 1);
  1046. dump($method->columns);
  1047. dump($method->queries);
  1048. if(!$method->redirect) {
  1049. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  1050. }
  1051. else {
  1052. $this->w('Redi: ' . $method->redirect, 1);
  1053. }
  1054. $this->w('---------------------------------------------');
  1055. }
  1056. }
  1057. public function w($line, $level = -1) {
  1058. for($i=0; $i<$level; $i++) echo "\t";
  1059. echo "$line\n";
  1060. }
  1061. public function snakeToTitleCase($text) {
  1062. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  1063. return ucwords(str_replace("_", " ", $text));
  1064. }
  1065. public function camelToTitleCase($text) {
  1066. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  1067. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  1068. return ucwords($text);
  1069. }
  1070. public function snakeToCamelCase($text) {
  1071. $text = ucwords(str_replace("_", " ", $text));
  1072. $text = str_replace(" ", "", $text);
  1073. $text[0] = strtolower($text[0]);
  1074. return $text;
  1075. }
  1076. private function generateFormField($line) {
  1077. $tokens = explode("=", $line);
  1078. $default = false;
  1079. if(count($tokens) > 1) {
  1080. $default = $tokens[1];
  1081. }
  1082. $tokens = explode(":", $tokens[0]);
  1083. $name = $tokens[0];
  1084. $required = false;
  1085. if($name[strlen($name) - 1] === '*') { // required field?
  1086. $required = true;
  1087. $name = substr($name, 0, strlen($name) - 1);
  1088. }
  1089. $display = $name;
  1090. $dotPos = strpos($name, ".");
  1091. if($dotPos !== FALSE) {
  1092. $display = substr($name, $dotPos + 1);
  1093. }
  1094. $display = preg_replace('/uid$/i', "", $display);
  1095. $type = "text";
  1096. $options = [];
  1097. if(count($tokens) > 1) {
  1098. $type = $tokens[1];
  1099. switch ($type) {
  1100. case "select":
  1101. $options = explode(",", $tokens[2]);
  1102. break;
  1103. case "record":
  1104. $options['table'] = $tokens[2];
  1105. $parts = explode(",", $tokens[3]);
  1106. $options['valueField'] = $parts[0];
  1107. $options['displayField'] = $parts[1];
  1108. break;
  1109. }
  1110. }
  1111. if($type !== 'hidden' && $type !== 'bool') {
  1112. $code[] = "<div class='form-group mb-3'>";
  1113. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  1114. ($required ? "*" : "") .
  1115. "</label>";
  1116. }
  1117. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  1118. switch ($type) {
  1119. case "select":
  1120. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  1121. ($required ? "required" : "") .
  1122. ">";
  1123. $code[] = "<option value=''>-- Select --</option>";
  1124. foreach ($options as $o) {
  1125. $code[] = "<option " .
  1126. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  1127. "value='$o'>$o</option>";
  1128. }
  1129. $code[] = "</select>";
  1130. break;
  1131. case "record":
  1132. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  1133. ($required ? "required" : "") .
  1134. ">";
  1135. $code[] = "<option value=''>-- Select --</option>";
  1136. if($options['table'][0] === '~') { // from named query
  1137. $code[] = "<?php foreach(\$result_" . substr($options['table'], 1) . " as \$o): ?>";
  1138. }
  1139. else { // select query
  1140. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  1141. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  1142. }
  1143. $code[] = "<option " .
  1144. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  1145. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  1146. $code[] = "<?php endforeach; ?>";
  1147. $code[] = "</select>";
  1148. break;
  1149. case "bool":
  1150. $code[] = "<div class='form-group mb-3'>";
  1151. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  1152. ($required ? "*" : "");
  1153. $code[] = "<input class='ml-2' type='checkbox' name='$name' " .
  1154. ($required ? "required" : "") .
  1155. ">";
  1156. $code[] = "</label>";
  1157. break;
  1158. default:
  1159. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
  1160. ($required ? "required" : "") .
  1161. ">";
  1162. }
  1163. if($type !== 'hidden') {
  1164. $code[] = "</div>";
  1165. }
  1166. return implode("\n", $code);
  1167. }
  1168. }
  1169. class GenControllerMethod {
  1170. public $name;
  1171. public $route;
  1172. public $hasUID = false;
  1173. public $redirect = false;
  1174. public $type = '';
  1175. public $data = [];
  1176. public $parentSub = false;
  1177. public $childAddRoute = false;
  1178. public $table = false;
  1179. public $api = 'create';
  1180. public $show = null;
  1181. public $viewURL = false;
  1182. public $exitURL = false;
  1183. public $showLink = true;
  1184. public $incType = null;
  1185. public $incFields = null;
  1186. public $viewLinkField = 'uid';
  1187. public $columns = [];
  1188. public $columnActions = [];
  1189. public $groups = [];
  1190. public $dashboard = false;
  1191. public $noActionLinks = false;
  1192. public $queries = [];
  1193. public $subAdders = [];
  1194. public function __construct($name, $route)
  1195. {
  1196. $this->name = $name;
  1197. $this->route = $route;
  1198. if(strpos($this->route, "{uid}") !== FALSE) {
  1199. $this->hasUID = true;
  1200. }
  1201. }
  1202. public function addSubAdder($line, $parentControllerName, $label, $link) {
  1203. $parts = explode(":", $line);
  1204. $newSubAdder = [
  1205. "name" => "{$parts[0]}_{$parts[1]}",
  1206. "table" => $parts[1],
  1207. "api" => count($parts) >= 3 ? $parts[2] : null,
  1208. "link" => $link,
  1209. "data" => [],
  1210. "routeName" => "$parentControllerName-ACTION_{$parts[0]}_{$parts[1]}",
  1211. "buttonLabel" => $label
  1212. ];
  1213. $this->subAdders[] = $newSubAdder;
  1214. return $newSubAdder;
  1215. }
  1216. public function setIncFields($type, $fields) {
  1217. $this->incType = $type;
  1218. $this->incFields = $fields;
  1219. for ($i = 0; $i < count($this->incFields); $i++) {
  1220. if($this->incFields[$i][0] === '@') {
  1221. $this->incFields[$i] = substr($this->incFields[$i], 1);
  1222. $this->viewLinkField = $this->incFields[$i];
  1223. }
  1224. }
  1225. }
  1226. public function setColumnSpec($line, $link, $recordVariable) {
  1227. // ally_pro_id:Ally Pro:select name_display as 'result' from pro where id = $ally_pro_id limit 1
  1228. $parts = explode(":", $line);
  1229. $spec = [
  1230. "label" => $parts[1]
  1231. ];
  1232. if(count($parts) > 2) {
  1233. $query = $parts[2];
  1234. // check if named query
  1235. if($query[0] === '~') {
  1236. // hcp_pro_id:HCP Pro:~pros:name_display:id,=,$hcp_pro_id;is_active,=,true:all
  1237. $recordSet = '$result_' . substr($query, 1);
  1238. $field = $parts[3];
  1239. $checkParts = explode(";", $parts[4]);
  1240. $checks = [];
  1241. foreach ($checkParts as $checkPart) {
  1242. $checkPart = explode(",", $checkPart);
  1243. $value = $checkPart[2];
  1244. if(strpos($value, '$$') === 0) {
  1245. $value = '$subRecord->' . substr($value, 2);
  1246. }
  1247. else if(strpos($value, '$') === 0) {
  1248. $value = '$record->' . substr($value, 1);
  1249. }
  1250. $checks[] = [
  1251. "field" => $checkPart[0],
  1252. "op" => $checkPart[1],
  1253. "value" => $value
  1254. ];
  1255. }
  1256. $condition = 'all';
  1257. if(count($parts) >= 6) {
  1258. $condition = $parts[5];
  1259. }
  1260. $checksArray = ["["];
  1261. foreach ($checks as $check) {
  1262. $checksArray[] = "[";
  1263. $checksArray[] = "'{$check['field']}'";
  1264. $checksArray[] = ", ";
  1265. $checksArray[] = "'{$check['op']}'";
  1266. $checksArray[] = ", ";
  1267. $checksArray[] = "{$check['value']}";
  1268. $checksArray[] = "], ";
  1269. }
  1270. $checksArray[] = "]";
  1271. $checks = implode("", $checksArray);
  1272. $spec['getter'] = "<?= value_from_rs($recordSet, '$field', " . $checks . ", '$condition'); ?>";
  1273. }
  1274. else {
  1275. $query = preg_replace("/\\$([a-zA-Z0-9_]+)/", "\" . ($$recordVariable->$1 ? $$recordVariable->$1 : -1) . \"", $query);
  1276. $spec['query'] = $query;
  1277. }
  1278. }
  1279. if($link) {
  1280. $spec['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$$recordVariable->$1 ?>", $link);
  1281. }
  1282. $this->columns[$parts[0]] = $spec;
  1283. }
  1284. public function addGroup($line, $link) {
  1285. // Basic Details:id,uid,created_at,clients_count
  1286. $parts = explode(":", $line);
  1287. $group = [
  1288. "name" => $parts[0],
  1289. "fields" => explode(",", $parts[1])
  1290. ];
  1291. // is there a group action
  1292. if(count($parts) > 2) {
  1293. $actionParts = ["-"];
  1294. for($i = 2; $i < count($parts); $i++) {
  1295. $actionParts[] = $parts[$i];
  1296. }
  1297. $actionParts = implode(":", $actionParts);
  1298. $group["action"] = $this->addAction($actionParts, $link, true);
  1299. }
  1300. $this->groups[] = $group;
  1301. $this->dashboard = true;
  1302. }
  1303. public function addAction($line, $link, $group = false) {
  1304. // is_active:Deactivate:deactivate:edit:if:is_active
  1305. $parts = explode(":", $line);
  1306. $action = [
  1307. "label" => $parts[1],
  1308. "icon" => isset($parts[2]) ? $parts[2] : 'edit'
  1309. ];
  1310. if(count($parts) >= 5 ) {
  1311. $action["condition"] = $parts[3];
  1312. $action["field"] = $parts[4];
  1313. }
  1314. if($link) {
  1315. $action['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$record->$1 ?>", $link);
  1316. }
  1317. if(!$group) {
  1318. if(!isset($this->columnActions[$parts[0]])) {
  1319. $this->columnActions[$parts[0]] = [];
  1320. }
  1321. $this->columnActions[$parts[0]][] = $action;
  1322. }
  1323. return $action;
  1324. }
  1325. public function addQuery($line) {
  1326. $parts = explode(":", $line);
  1327. $this->queries[$parts[0]] = $parts[1];
  1328. }
  1329. }