GenerateTreeCommand.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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. // ensure uid column is at the start
  512. $columns = array_merge(['uid'], array_filter($columns, function($x) {
  513. return $x !== 'uid';
  514. }));
  515. foreach ($columns as $column) {
  516. if($column === 'id') continue;
  517. $columnTitle = $this->snakeToTitleCase($column);
  518. $columnValue = "<?= \$record->$column ?>";
  519. $hasLink = $controller->hasView && $column === $method->viewLinkField;
  520. $linkTarget = "/{$controller->name}/view/<?= \$record->uid ?>";
  521. if(substr($column, -3) === '_at') {
  522. $columnValue = "<?= friendly_date_time(\$record->$column) ?>";
  523. }
  524. // check if this column has column spec
  525. if(isset($method->columns[$column])) {
  526. $columnTitle = $method->columns[$column]["label"];
  527. if(isset($method->columns[$column]["query"])) {
  528. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  529. "select(\"{$method->columns[$column]["query"]}\");\n" .
  530. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  531. }
  532. else if(isset($method->columns[$column]["getter"])) {
  533. $columnValue = $method->columns[$column]["getter"];
  534. }
  535. if(isset($method->columns[$column]["link"])) {
  536. $hasLink = true;
  537. $linkTarget = $method->columns[$column]["link"];
  538. }
  539. }
  540. else if($column === 'uid') {
  541. $columnTitle = '&nbsp;';
  542. $columnValue = '<i class="fas fa-share-square"></i>';
  543. $hasLink = true;
  544. }
  545. $ths[] = "<th>$columnTitle</th>";
  546. $tds[] = "<td>" .
  547. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  548. $columnValue .
  549. ($hasLink ? "</a>" : "") .
  550. "</td>";
  551. }
  552. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  553. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  554. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  555. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  556. }
  557. public function saveShowView(GenController $controller, GenControllerMethod $method)
  558. {
  559. // delete sub links and action links
  560. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
  561. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
  562. }
  563. if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
  564. unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
  565. }
  566. // write info view
  567. $text = file_get_contents(base_path('generatecv/tree-templates/info.template.blade.php'));
  568. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  569. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  570. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  571. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/info.blade.php"), $text);
  572. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/info.blade.php") . "\n";
  573. // write main view
  574. $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
  575. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  576. $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
  577. $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
  578. $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
  579. $text = str_replace("_INFO_VIEW_", "{$controller->root}/{$controller->name}/info", $text);
  580. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  581. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  582. }
  583. public function saveSubLinks(GenController $controller, GenControllerMethod $method)
  584. {
  585. if ($controller->subLinksSaved) return;
  586. $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
  587. $subLinks = [];
  588. foreach ($controller->methods as $meth) {
  589. if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
  590. $display = $this->snakeToTitleCase(substr($meth->name, 4));
  591. $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  592. "<a " .
  593. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  594. "class='d-block px-3 py-2 border-bottom stag-sublink " .
  595. "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
  596. (
  597. $meth->name === 'SUB_dashboard' ?
  598. "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
  599. ""
  600. )
  601. . "'>$display</a>" .
  602. ($meth->show ? " @endif" : "");
  603. }
  604. $this->file_force_contents($subLinksView, implode("\n", $subLinks));
  605. echo "Generated " . $subLinksView . "\n";
  606. $controller->subLinksSaved = true;
  607. }
  608. public function saveActionLinks(GenController $controller, GenControllerMethod $method)
  609. {
  610. if ($controller->actionLinksSaved) return;
  611. $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
  612. $actionLinks = [];
  613. foreach ($controller->methods as $meth) {
  614. if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
  615. $display = $this->camelToTitleCase(substr($meth->name, 7));
  616. $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
  617. "<a " .
  618. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  619. "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
  620. "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
  621. ($meth->show ? " @endif" : "");
  622. }
  623. $this->file_force_contents($actionLinksView, implode("\n", $actionLinks));
  624. echo "Generated " . $actionLinksView . "\n";
  625. $controller->actionLinksSaved = true;
  626. }
  627. public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
  628. {
  629. $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
  630. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  631. $text = $this->generateSubContent($controller, $method, $text);
  632. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  633. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  634. }
  635. public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
  636. $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
  637. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  638. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  639. if(!$method->parentSub) {
  640. $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
  641. }
  642. else {
  643. $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
  644. }
  645. if(!$method->table) {
  646. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
  647. }
  648. else {
  649. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
  650. }
  651. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  652. $fields = [];
  653. if(count($method->data)) {
  654. foreach ($method->data as $field) {
  655. $fields[] = $this->generateFormField($field);
  656. }
  657. }
  658. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  659. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  660. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  661. }
  662. public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
  663. $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
  664. $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
  665. $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
  666. if(count($method->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
  667. $addLink = '<a class="btn btn-primary btn-sm" ' .
  668. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  669. 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
  670. "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
  671. $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
  672. }
  673. $dbParts = explode("=", $method->data[0]);
  674. $dbParts = explode(".", $dbParts[1]);
  675. $table = $dbParts[0];
  676. $columns = DB::getSchemaBuilder()->getColumnListing($table);
  677. $ths = [];
  678. $tds = [];
  679. // !inc/!exc
  680. if($method->incType === "include") {
  681. $columns = $method->incFields;
  682. }
  683. else if($method->incType === "exclude") {
  684. $columns = array_filter($columns, function($item) use ($method) {
  685. return in_array($item, $method->incFields) === FALSE;
  686. });
  687. }
  688. // ensure uid column is at the start
  689. $columns = array_merge(['uid'], array_filter($columns, function($x) {
  690. return $x !== 'uid';
  691. }));
  692. foreach ($columns as $column) {
  693. if($column === 'id') continue;
  694. $columnTitle = $this->snakeToTitleCase($column);
  695. $columnValue = "<?= \$subRecord->$column ?>";
  696. $hasLink = $method->exitURL && $column === $method->viewLinkField;
  697. $linkTarget = $method->exitURL;
  698. if(substr($column, -3) === '_at') {
  699. $columnValue = "<?= friendly_date_time(\$record->$column) ?>";
  700. }
  701. // check if this column has column spec
  702. if(isset($method->columns[$column])) {
  703. $columnTitle = $method->columns[$column]["label"];
  704. if(isset($method->columns[$column]["query"])) {
  705. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  706. "select(\"{$method->columns[$column]["query"]}\");\n" .
  707. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  708. }
  709. if(isset($method->columns[$column]["link"])) {
  710. $hasLink = true;
  711. $linkTarget = $method->columns[$column]["link"];
  712. }
  713. }
  714. else if($column === 'uid') {
  715. $columnTitle = '&nbsp;';
  716. $columnValue = '<i class="fas fa-share-square"></i>';
  717. $hasLink = true;
  718. }
  719. $ths[] = "<th>$columnTitle</th>";
  720. $tds[] = "<td>" .
  721. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  722. $columnValue .
  723. ($hasLink ? "</a>" : "") .
  724. "</td>";
  725. }
  726. $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
  727. $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
  728. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  729. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  730. }
  731. public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
  732. if($method->dashboard) {
  733. if(!isset($method->groups) || !count($method->groups)) {
  734. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
  735. }
  736. else {
  737. $html = file_get_contents(base_path('generatecv/tree-templates/dashboard-grouped' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
  738. $groupsHtml = [];
  739. $groupTemplate = file_get_contents(base_path('generatecv/tree-templates/dashboard-group.template.blade.php'));
  740. foreach ($method->groups as $group) {
  741. $groupHtml = $groupTemplate;
  742. $groupHtml = str_replace("<!-- __GROUP_NAME__ -->", $group["name"], $groupHtml);
  743. if (isset($group["action"])) {
  744. $action = $group["action"];
  745. $actionLine = [];
  746. if (isset($action["condition"])) {
  747. if ($action["condition"] === "if") {
  748. $actionLine[] = "@if(";
  749. } else {
  750. $actionLine[] = "@if(!";
  751. }
  752. $actionLine[] = "\$record->{$action["field"]})";
  753. }
  754. $actionLine[] = "<a " .
  755. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  756. "href='{$action["link"]}' title='{$action["label"]}' class='ml-2 text-dark font-weight-normal'>" .
  757. "<i class='fa fa-{$action["icon"]} text-sm'></i>" .
  758. "</a>";
  759. if (isset($action["condition"])) {
  760. $actionLine[] = "@endif";
  761. }
  762. $actionLine = implode(" ", $actionLine);
  763. $groupHtml = str_replace("<!-- __GROUP_ACTION__ -->", $actionLine, $groupHtml);
  764. }
  765. $fields = [];
  766. foreach ($group["fields"] as $field) {
  767. $columnTitle = $this->snakeToTitleCase($field);
  768. $columnValue = "<?= \$record->$field ?>";
  769. $hasLink = false;
  770. $linkTarget = null;
  771. $actions = [];
  772. // check if this column has column spec
  773. if(isset($method->columns[$field])) {
  774. $columnTitle = $method->columns[$field]["label"];
  775. if(isset($method->columns[$field]["query"])) {
  776. $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
  777. "select(\"{$method->columns[$field]["query"]}\");\n" .
  778. "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
  779. }
  780. else if(isset($method->columns[$field]["getter"])) {
  781. $columnValue = $method->columns[$field]["getter"];
  782. }
  783. if(isset($method->columns[$field]["link"])) {
  784. $hasLink = true;
  785. $linkTarget = $method->columns[$field]["link"];
  786. }
  787. }
  788. if(isset($method->columnActions[$field])) {
  789. foreach($method->columnActions[$field] as $action) {
  790. $actionLine = [];
  791. if(isset($action["condition"])) {
  792. if($action["condition"] === "if") {
  793. $actionLine[] = "@if(";
  794. }
  795. else {
  796. $actionLine[] = "@if(!";
  797. }
  798. $actionLine[] = "\$record->{$action["field"]})";
  799. }
  800. $actionLine[] = "<a " .
  801. 'up-modal=".form-contents" up-width="800" up-history="false" ' .
  802. "href='{$action["link"]}' title='{$action["label"]}' class='ml-2 text-dark font-weight-normal'>" .
  803. "<i class='fa fa-{$action["icon"]} text-sm'></i>" .
  804. "</a>";
  805. if(isset($action["condition"])) {
  806. $actionLine[] = "@endif";
  807. }
  808. $actionLine = implode(" ", $actionLine);
  809. $actions[] = $actionLine;
  810. }
  811. }
  812. $actions = implode("\n", $actions);
  813. $fields[] = "<tr>" .
  814. "<td class=\"w-25 px-2 text-secondary border-right\">$columnTitle</td>" .
  815. "<td class=\"w-75 px-2 font-weight-bold\">" .
  816. ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
  817. $columnValue .
  818. ($hasLink ? "</a>" : "") .
  819. $actions .
  820. "</td>" .
  821. "</tr>";
  822. }
  823. $groupHtml = str_replace("<!-- __GROUP_FIELDS__ -->", implode("\n", $fields), $groupHtml);
  824. $groupsHtml[] = $groupHtml;
  825. }
  826. $groupsHtml = implode("\n", $groupsHtml);
  827. $html = str_replace("<!-- _GROUPS_ -->", $groupsHtml, $html);
  828. }
  829. $text = str_replace("_SUB_VIEW_", $html, $text);
  830. $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
  831. }
  832. else {
  833. $text = str_replace("_SUB_VIEW_",
  834. "<h5 class='py-3 border-bottom'>" .
  835. $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h5>" .
  836. "Controller: <b>{$controller->name}</b><br>" .
  837. "Action: <b>{$method->name}()</b><br>" .
  838. "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br><br>",
  839. $text);
  840. }
  841. return $text;
  842. }
  843. public function saveAddNewView(GenController $controller, GenControllerMethod $method)
  844. {
  845. $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
  846. $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
  847. $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
  848. $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
  849. $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
  850. $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
  851. $columns = $method->data;
  852. $fields = [];
  853. foreach ($columns as $column) {
  854. $fields[] = $this->generateFormField($column);
  855. }
  856. $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
  857. $this->file_force_contents(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
  858. echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
  859. }
  860. public function saveRoutes() {
  861. $lines = ["// --- {$this->root}: {$this->name} --- //"];
  862. foreach ($this->methods as $method) {
  863. // FORMAT:
  864. // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
  865. $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
  866. }
  867. $lines[] = '';
  868. $lines[] = '';
  869. file_put_contents(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
  870. }
  871. public function log() {
  872. $this->w('');
  873. $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
  874. $this->w("Table: {$this->dbTable}");
  875. $this->w('---------------------------------------------');
  876. foreach ($this->methods as $method) {
  877. $this->w('Rout: ' . $method->route, 1);
  878. $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
  879. if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
  880. // $this->w('Exit: ' . $method->exitURL, 1);
  881. // $this->w('View: ' . $method->viewURL, 1);
  882. dump($method->columns);
  883. dump($method->queries);
  884. if(!$method->redirect) {
  885. $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
  886. }
  887. else {
  888. $this->w('Redi: ' . $method->redirect, 1);
  889. }
  890. $this->w('---------------------------------------------');
  891. }
  892. }
  893. public function w($line, $level = -1) {
  894. for($i=0; $i<$level; $i++) echo "\t";
  895. echo "$line\n";
  896. }
  897. public function snakeToTitleCase($text) {
  898. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  899. return ucwords(str_replace("_", " ", $text));
  900. }
  901. public function camelToTitleCase($text) {
  902. $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
  903. $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
  904. return ucwords($text);
  905. }
  906. public function snakeToCamelCase($text) {
  907. $text = ucwords(str_replace("_", " ", $text));
  908. $text = str_replace(" ", "", $text);
  909. $text[0] = strtolower($text[0]);
  910. return $text;
  911. }
  912. private function file_force_contents($dir, $contents){
  913. $dir = str_replace("\\", "/", $dir);
  914. $dir = str_replace( '//', '/', $dir);
  915. $parts = explode('/', $dir);
  916. $file = array_pop($parts);
  917. $dir = '';
  918. foreach($parts as $part) {
  919. if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
  920. if(!is_dir($dir .= "/$part")) mkdir($dir);
  921. }
  922. }
  923. file_put_contents("$dir/$file", $contents);
  924. }
  925. private function generateFormField($line) {
  926. $tokens = explode("=", $line);
  927. $default = false;
  928. if(count($tokens) > 1) {
  929. $default = $tokens[1];
  930. }
  931. $tokens = explode(":", $tokens[0]);
  932. $name = $tokens[0];
  933. $required = false;
  934. if($name[strlen($name) - 1] === '*') { // required field?
  935. $required = true;
  936. $name = substr($name, 0, strlen($name) - 1);
  937. }
  938. $display = $name;
  939. $dotPos = strpos($name, ".");
  940. if($dotPos !== FALSE) {
  941. $display = substr($name, $dotPos + 1);
  942. }
  943. $display = preg_replace('/uid$/i', "", $display);
  944. $type = "text";
  945. $options = [];
  946. if(count($tokens) > 1) {
  947. $type = $tokens[1];
  948. switch ($type) {
  949. case "select":
  950. $options = explode(",", $tokens[2]);
  951. break;
  952. case "record":
  953. $options['table'] = $tokens[2];
  954. $parts = explode(",", $tokens[3]);
  955. $options['valueField'] = $parts[0];
  956. $options['displayField'] = $parts[1];
  957. break;
  958. }
  959. }
  960. if($type !== 'hidden' && $type !== 'bool') {
  961. $code[] = "<div class='form-group mb-3'>";
  962. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  963. ($required ? "*" : "") .
  964. "</label>";
  965. }
  966. $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
  967. switch ($type) {
  968. case "select":
  969. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  970. ($required ? "required" : "") .
  971. ">";
  972. $code[] = "<option value=''>-- Select --</option>";
  973. foreach ($options as $o) {
  974. $code[] = "<option " .
  975. "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  976. "value='$o'>$o</option>";
  977. }
  978. $code[] = "</select>";
  979. break;
  980. case "record":
  981. $code[] = "<select class='form-control' name='$name' " . $valueLine .
  982. ($required ? "required" : "") .
  983. ">";
  984. $code[] = "<option value=''>-- Select --</option>";
  985. if($options['table'][0] === '~') { // from named query
  986. $code[] = "<?php foreach(\$result_" . substr($options['table'], 1) . " as \$o): ?>";
  987. }
  988. else { // select query
  989. $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
  990. $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
  991. }
  992. $code[] = "<option " .
  993. "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
  994. "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
  995. $code[] = "<?php endforeach; ?>";
  996. $code[] = "</select>";
  997. break;
  998. case "bool":
  999. $code[] = "<div class='form-group mb-3'>";
  1000. $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
  1001. ($required ? "*" : "");
  1002. $code[] = "<input class='ml-2' type='checkbox' name='$name' " .
  1003. ($required ? "required" : "") .
  1004. ">";
  1005. $code[] = "</label>";
  1006. break;
  1007. default:
  1008. $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
  1009. ($required ? "required" : "") .
  1010. ">";
  1011. }
  1012. if($type !== 'hidden') {
  1013. $code[] = "</div>";
  1014. }
  1015. return implode("\n", $code);
  1016. }
  1017. }
  1018. class GenControllerMethod {
  1019. public $name;
  1020. public $route;
  1021. public $hasUID = false;
  1022. public $redirect = false;
  1023. public $type = '';
  1024. public $data = [];
  1025. public $parentSub = false;
  1026. public $childAddRoute = false;
  1027. public $table = false;
  1028. public $api = 'create';
  1029. public $show = null;
  1030. public $viewURL = false;
  1031. public $exitURL = false;
  1032. public $showLink = true;
  1033. public $incType = null;
  1034. public $incFields = null;
  1035. public $viewLinkField = 'uid';
  1036. public $columns = [];
  1037. public $columnActions = [];
  1038. public $groups = [];
  1039. public $dashboard = false;
  1040. public $noActionLinks = false;
  1041. public $queries = [];
  1042. public function __construct($name, $route)
  1043. {
  1044. $this->name = $name;
  1045. $this->route = $route;
  1046. if(strpos($this->route, "{uid}") !== FALSE) {
  1047. $this->hasUID = true;
  1048. }
  1049. }
  1050. public function setIncFields($type, $fields) {
  1051. $this->incType = $type;
  1052. $this->incFields = $fields;
  1053. for ($i = 0; $i < count($this->incFields); $i++) {
  1054. if($this->incFields[$i][0] === '@') {
  1055. $this->incFields[$i] = substr($this->incFields[$i], 1);
  1056. $this->viewLinkField = $this->incFields[$i];
  1057. }
  1058. }
  1059. }
  1060. public function setColumnSpec($line, $link, $recordVariable) {
  1061. // ally_pro_id:Ally Pro:select name_display as 'result' from pro where id = $ally_pro_id limit 1
  1062. $parts = explode(":", $line);
  1063. $spec = [
  1064. "label" => $parts[1]
  1065. ];
  1066. if(count($parts) > 2) {
  1067. $query = $parts[2];
  1068. // check if named query
  1069. if($query[0] === '~') {
  1070. // hcp_pro_id:HCP Pro:~pros:name_display:id,=,$hcp_pro_id;is_active,=,true:all
  1071. $recordSet = '$result_' . substr($query, 1);
  1072. $field = $parts[3];
  1073. $checkParts = explode(";", $parts[4]);
  1074. $checks = [];
  1075. foreach ($checkParts as $checkPart) {
  1076. $checkPart = explode(",", $checkPart);
  1077. $value = $checkPart[2];
  1078. if(strpos($value, '$$') === 0) {
  1079. $value = '$subRecord->' . substr($value, 2);
  1080. }
  1081. else if(strpos($value, '$') === 0) {
  1082. $value = '$record->' . substr($value, 1);
  1083. }
  1084. $checks[] = [
  1085. "field" => $checkPart[0],
  1086. "op" => $checkPart[1],
  1087. "value" => $value
  1088. ];
  1089. }
  1090. $condition = 'all';
  1091. if(count($parts) >= 6) {
  1092. $condition = $parts[5];
  1093. }
  1094. $checksArray = ["["];
  1095. foreach ($checks as $check) {
  1096. $checksArray[] = "[";
  1097. $checksArray[] = "'{$check['field']}'";
  1098. $checksArray[] = ", ";
  1099. $checksArray[] = "'{$check['op']}'";
  1100. $checksArray[] = ", ";
  1101. $checksArray[] = "{$check['value']}";
  1102. $checksArray[] = "], ";
  1103. }
  1104. $checksArray[] = "]";
  1105. $checks = implode("", $checksArray);
  1106. $spec['getter'] = "<?= value_from_rs($recordSet, '$field', " . $checks . ", '$condition'); ?>";
  1107. }
  1108. else {
  1109. $query = preg_replace("/\\$([a-zA-Z0-9_]+)/", "\" . ($$recordVariable->$1 ? $$recordVariable->$1 : -1) . \"", $query);
  1110. $spec['query'] = $query;
  1111. }
  1112. }
  1113. if($link) {
  1114. $spec['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$$recordVariable->$1 ?>", $link);
  1115. }
  1116. $this->columns[$parts[0]] = $spec;
  1117. }
  1118. public function addGroup($line, $link) {
  1119. // Basic Details:id,uid,created_at,clients_count
  1120. $parts = explode(":", $line);
  1121. $group = [
  1122. "name" => $parts[0],
  1123. "fields" => explode(",", $parts[1])
  1124. ];
  1125. // is there a group action
  1126. if(count($parts) > 2) {
  1127. $actionParts = ["-"];
  1128. for($i = 2; $i < count($parts); $i++) {
  1129. $actionParts[] = $parts[$i];
  1130. }
  1131. $actionParts = implode(":", $actionParts);
  1132. $group["action"] = $this->addAction($actionParts, $link, true);
  1133. }
  1134. $this->groups[] = $group;
  1135. $this->dashboard = true;
  1136. }
  1137. public function addAction($line, $link, $group = false) {
  1138. // is_active:Deactivate:deactivate:edit:if:is_active
  1139. $parts = explode(":", $line);
  1140. $action = [
  1141. "label" => $parts[1],
  1142. "icon" => isset($parts[2]) ? $parts[2] : 'edit'
  1143. ];
  1144. if(count($parts) >= 5 ) {
  1145. $action["condition"] = $parts[3];
  1146. $action["field"] = $parts[4];
  1147. }
  1148. if($link) {
  1149. $action['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$record->$1 ?>", $link);
  1150. }
  1151. if(!$group) {
  1152. if(!isset($this->columnActions[$parts[0]])) {
  1153. $this->columnActions[$parts[0]] = [];
  1154. }
  1155. $this->columnActions[$parts[0]][] = $action;
  1156. }
  1157. return $action;
  1158. }
  1159. public function addQuery($line) {
  1160. $parts = explode(":", $line);
  1161. $this->queries[$parts[0]] = $parts[1];
  1162. }
  1163. }