GenerateTreeCommand.php 64 KB

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