GenerateTreeCommand.php 61 KB

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