GenerateTreeCommand.php 57 KB

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