GenerateTreeCommand.php 61 KB

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