GenerateTreeCommand.php 55 KB

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