GenerateTreeCommand.php 57 KB

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