12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436 |
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\DB;
- class GenerateTreeCommand extends Command
- {
- private $routesFile = null;
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'generatetree
- {path: /path/to/tree.txt}';
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- $lines = ['<?php', '', 'use Illuminate\Support\Facades\Route;', '', ''];
- GenerateTreeCommand::save(base_path("routes/generated.php"), implode("\n", $lines));
- $sideLinks = [];
- global $argv;
- $file = fopen($argv[2], "r");
- $lines = [];
- while (!feof($file)) {
- $line = rtrim(fgets($file));
- if(trim($line) !== '') {
- $lines[] = str_replace("\t", " ", $line);
- }
- }
- fclose($file);
- $currentRoot = "";
- $currentController = new GenController();
- $currentSubController = new GenController();
- $currentSubType = "";
- $currentView = "";
- $currentMethod = null;
- $currentSubAdder = null;
- foreach ($lines as $line) {
- // stop (debugging)
- if(trim($line) === '##stop') {
- exit(0);
- }
- // skip comments
- if(trim($line)[0] === '#') continue;
- $lineType = null;
- // no leading space - root specifier
- if($line[0] !== ' ') {
- $currentRoot = strtolower(trim($line));
- }
- else {
- $ls = $this->numLS($line);
- $line = trim($line);
- $exitURL = false;
- if(strpos($line, "=>") !== FALSE) {
- $parts = explode("=>", $line);
- $exitURL = str_replace("UID", "{{ \$subRecord->uid }}", $parts[1]);
- $line = $parts[0];
- }
- $tokens = explode("|", $line);
- $line = $tokens[0];
- $dbTable = null;
- $condition = null;
- if(count($tokens) >= 2) {
- $dbTable = $tokens[1];
- // check if table has loading conditions
- if(strpos($dbTable, ":")) {
- $parts = explode(":", $dbTable);
- $dbTable = $parts[0];
- $parts = explode("=", $parts[1]);
- $condition = [
- "field" => $parts[0],
- "value" => str_replace("OWN", "session('proId')" , $parts[1])
- ];
- }
- }
- $hasAdd = in_array("add", $tokens);
- $hasView = in_array("view", $tokens);
- $hasRemove = in_array("remove", $tokens);
- $icon = "user";
- if(strpos($tokens[count($tokens) - 1], "icon:") === 0) {
- $icon = substr($tokens[count($tokens) - 1], 5);
- }
- switch($ls) {
- case 4: // top level controller OR top level controller action
- // top level controller-action
- if(strpos($line, "/") !== FALSE) {
- if(!empty($currentController)) {
- $parts = explode(":", $line);
- $line = $parts[0];
- $method = explode("/", $line)[1];
- $newMethod = $currentController->addMethod($method, "/" . $line);
- if(count($parts) > 1) {
- $newMethod->api = $parts[count($parts) - 1];
- }
- // create _SINGLE_ controller if view
- if($method === "view") {
- $currentSubController = new GenController($currentRoot, $currentController->name . "_SINGLE");
- $currentSubController->dbTable = $currentController->dbTable;
- $currentSubController->parentRoute = "/" . $line;
- $currentSubController->parentControllerName = $currentController->name;
- $currentSubController->sub = true;
- $newMethod->redirect = "/" . $line . "/SUB_dashboard";
- }
- else if(strpos($method, "add_new") === 0) {
- $newMethod->type = 'add';
- }
- else if(strpos($method, "remove") === 0) {
- $newMethod->type = 'remove';
- }
- $currentMethod = $newMethod;
- }
- }
- // new top level controller
- else if(empty($currentController) || $line !== $currentController->name) {
- if(!empty($currentController)) {
- $currentController->save();
- }
- $currentController = new GenController($currentRoot, $line, $icon);
- $currentController->dbTable = $dbTable;
- $currentController->condition = $condition;
- $currentController->hasAdd = $hasAdd;
- $currentController->hasView = $hasView;
- $currentController->hasRemove = $hasRemove;
- $currentMethod = $currentController->addMethod("index", "/$line");
- if(!empty($currentSubController)) {
- $currentSubController->save();
- }
- $currentSubType = '';
- $currentSubController = new GenController();
- $sideLinks[] = "<li class='nav-item'>\n" .
- "\t<a href='/{$currentController->name}' " .
- "class='nav-link " .
- "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>\n" .
- "\t\t<i class='nav-icon fa fa-$icon'></i>\n" .
- "\t\t<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>\n" .
- "\t</a>\n</li>\n";
- }
- break;
- case 8: // sub-type declaration | add_new fields | !inc/!exc
- if($line === 'ACTIONS' || $line === 'SUB') {
- $currentSubType = $line;
- }
- else if(strpos($line, "!inc:") === 0) { // !inc:
- if (!empty($currentMethod)) {
- $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
- }
- }
- else if(strpos($line, "!exc:") === 0) { // !exc:
- if (!empty($currentMethod)) {
- $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
- }
- }
- else if(strpos($line, "!lnk:") === 0) { // !lnk:
- if (!empty($currentMethod)) {
- $currentMethod->viewLinkField = substr($line, 5);
- }
- }
- else if(strpos($line, "!col:") === 0) { // !col:
- if (!empty($currentMethod)) {
- $currentMethod->setColumnSpec(substr($line, 5), $exitURL, 'record');
- }
- }
- else if(strpos($line, "!qry:") === 0) { // !qry:
- if (!empty($currentMethod)) {
- $currentMethod->addQuery(substr($line, 5));
- }
- }
- else if (!empty($currentMethod) &&
- (strpos($currentMethod->name, 'add_new') === 0 ||
- $currentMethod->name === 'remove')) { // this is a field in add_new
- $currentMethod->data[] = $line;
- }
- break;
- case 12: // ACTIONS | SUB
- // check if this has show conditions
- $show = false;
- $isDashboard = 'unspecified';
- if(strpos($line, ":")) {
- $parts = explode(":", $line);
- $line = $parts[0];
- if($parts[1] === 'if') {
- $show = $parts[2];
- }
- else if($parts[1] === 'dashboard') {
- $isDashboard = true;
- }
- else if($parts[1] === 'custom') {
- $isDashboard = false;
- }
- }
- if($currentSubType === 'ACTIONS') {
- $currentMethod = $currentSubController->addMethod(
- "ACTION_" . $line,
- "/ACTION_" . $line
- );
- $currentMethod->type = 'action';
- $currentMethod->show = $show;
- $currentMethod->data = [];
- }
- else if($currentSubType === 'SUB') {
- $currentMethod = $currentSubController->addMethod(
- "SUB_" . $line,
- "/SUB_" . $line
- );
- $currentMethod->type = 'sub';
- $currentMethod->show = $show;
- $currentMethod->data = [];
- if($isDashboard !== 'unspecified') {
- $currentMethod->dashboard = $isDashboard;
- if($isDashboard) {
- $currentSubController->dashboardName = $line;
- if($currentController && $currentSubController && $currentController->name !== $currentSubController->name) {
- // change the redirect in /view/{uid} method of $currentController
- foreach($currentController->methods as $method) {
- if($method->name === 'view' && $method->redirect) {
- $method->redirect = $method->route . '/SUB_' . $line;
- break;
- }
- }
- }
- }
- /*dump("/SUB_" . $line . " ==> " . ($isDashboard ? "yes" : "no"));
- dump($currentMethod);
- dump($currentSubController->dashboardName);
- if($isDashboard) exit(1);*/
- }
- else if($line === 'dashboard') {
- $currentMethod->dashboard = true;
- }
- }
- break;
- case 16: // data for actions and subs
- $currentSubAdder = null;
- if(strpos($line, "!inc:") === 0) { // !inc:
- if (!empty($currentMethod)) {
- $currentMethod->setIncFields('include', explode(",", substr($line, 5)));
- }
- }
- else if(strpos($line, "!exc:") === 0) { // !exc:
- if (!empty($currentMethod)) {
- $currentMethod->setIncFields('exclude', explode(",", substr($line, 5)));
- }
- }
- else if(strpos($line, "!lnk:") === 0) { // !lnk:
- if (!empty($currentMethod)) {
- $currentMethod->viewLinkField = substr($line, 5);
- }
- }
- else if(strpos($line, "!col:") === 0) { // !col:
- if (!empty($currentMethod)) {
- $currentMethod->setColumnSpec(substr($line, 5), $exitURL,
- $currentMethod->dashboard ? 'record' : 'subRecord'
- );
- }
- }
- else if(strpos($line, "!qry:") === 0) { // !qry:
- if (!empty($currentMethod)) {
- $currentMethod->addQuery(substr($line, 5));
- }
- }
- else if(strpos($line, "!grp:") === 0) { // !grp:
- if (!empty($currentMethod)) {
- $currentMethod->addGroup(substr($line, 5), $exitURL);
- }
- }
- else if(strpos($line, "!act:") === 0) { // !act:
- if (!empty($currentMethod)) {
- $currentMethod->addAction(substr($line, 5), $exitURL);
- }
- }
- else if(strpos($line, "!nal:") === 0) { // !nal:
- if (!empty($currentMethod)) {
- $currentMethod->noActionLinks = true;
- }
- }
- else if(strpos($line, "add_new") === 0) { // sub add_new..
- if(!empty($currentMethod)) {
- $currentSubAdder = $currentMethod->addSubAdder(
- $line,
- $currentSubController->name,
- $currentController->snakeToTitleCase(explode(":", $line)[0]),
- $exitURL
- );
- }
- }
- else if(!empty($currentMethod)) {
- $currentMethod->data[] = $line;
- if($exitURL) {
- if(strpos("=", $line) !== FALSE) {
- $currentMethod->viewURL = $exitURL;
- }
- else {
- $currentMethod->exitURL = $exitURL;
- }
- }
- }
- break;
- case 20: // SUB add_new fields
- if(count($currentMethod->subAdders)) {
- $currentMethod->subAdders[count($currentMethod->subAdders) - 1]["data"][] = $line;
- }
- break;
- default:
- dump("ERROR: Cannot have $ls leading spaces!");
- dump("Line: $line");
- exit(1);
- }
- }
- }
- // do any pending saves
- if(!empty($currentSubController)) {
- $currentSubController->save();
- }
- if(!empty($currentController)) {
- $currentController->save();
- }
- echo "Saved " . base_path("routes/generated.php") . "\n";
- // save side links
- GenerateTreeCommand::save(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
- echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
- $this->humanizeRoutes();
- }
- private function numLS($line) {
- $count = 0;
- for ($i=0; $i<strlen($line); $i++) {
- if($line[$i] !== ' ') break;
- $count++;
- }
- return $count;
- }
- private function humanizeRoutes() {
- $path = base_path("routes/generated.php");
- $file = fopen($path, "r");
- $lines = [];
- $groups = [];
- $currentGroup = FALSE;
- $comment = '';
- $prefix = '';
- while (!feof($file)) {
- $line = rtrim(fgets($file));
- if($line === "") {
- if($currentGroup !== FALSE) {
- $groups[] = $currentGroup;
- $currentGroup = FALSE;
- }
- }
- else if(strpos($line, "// --- ") === 0) {
- $comment = $line;
- }
- else if(strpos($line, "Route::get('") === 0) {
- $parts = explode("'", $line);
- $route = $parts[1];
- $action = $parts[3];
- $name = $parts[5];
- if($currentGroup === FALSE) {
- $prefix = $route;
- if (($uidPos = strpos($route, "/{uid}/")) !== FALSE) {
- $prefix = substr($route, 0, $uidPos + 6);
- }
- }
- $route = substr($route, strlen($prefix));
- if(strlen($route) && $route[0] === "/") {
- $route = substr($route, 1);
- }
- if($currentGroup === FALSE) {
- $currentGroup = [
- "comment" => $comment,
- "prefix" => $prefix,
- "routes" => [
- [
- "route" => $route,
- "action" => $action,
- "name" => $name
- ]
- ]
- ];
- }
- else {
- $currentGroup["routes"][] = [
- "route" => $route,
- "action" => $action,
- "name" => $name
- ];
- }
- }
- }
- fclose($file);
- // write the routes
- $lines = ["<?php", "", "use Illuminate\Support\Facades\Route;", ""];
- foreach ($groups as $group) {
- $lines[] = $group["comment"];
- $lines[] = "Route::prefix('{$group["prefix"]}')->group(function () {";
- foreach ($group["routes"] as $route) {
- $lines[] = "\tRoute::get('{$route["route"]}', '{$route["action"]}')->name('{$route["name"]}');";
- }
- $lines[] = "});";
- $lines[] = "";
- }
- GenerateTreeCommand::save($path, implode("\n", $lines));
- echo "Cleaned " . base_path("routes/generated.php") . "\n";
- }
- public static function save($dir, $contents, $flags = FALSE){
- // if file exists, check if it has "DO NOT GENERATE" as the first line
- if(file_exists($dir) && is_file($dir)) {
- $file = fopen($dir, "r");
- $lines = [];
- $line = rtrim(fgets($file));
- if($line === '<?php /* DO NOT GENERATE */ ?>') {
- dump("Not writing to protected file: $dir");
- fclose($file);
- return;
- }
- fclose($file);
- $file = null;
- }
- $dir = str_replace("\\", "/", $dir);
- $dir = str_replace( '//', '/', $dir);
- $parts = explode('/', $dir);
- $file = array_pop($parts);
- $dir = '';
- foreach($parts as $part) {
- if(strlen($part) === 0 || $part[strlen($part) - 1] !== ':') {
- if(!is_dir($dir .= "/$part")) mkdir($dir);
- }
- }
- if($flags !== FALSE) {
- file_put_contents("$dir/$file", $contents, $flags);
- }
- else {
- file_put_contents("$dir/$file", $contents);
- }
- }
- }
- class GenController {
- public $root;
- public $saved = false;
- public $name;
- public $methods;
- public $parentRoute = "";
- public $dbTable = null;
- public $condition = null;
- public $hasAdd = false;
- public $hasView = false;
- public $hasRemove = false;
- public $sub = false;
- public $parentControllerName = '';
- public $parentController = false;
- public $subLinksSaved = false;
- public $actionLinksSaved = false;
- public $icon = "user";
- public $dashboardName = 'dashboard';
- public function __construct($root = null, $name = null, $icon = "user")
- {
- $this->root = $root;
- $this->name = $name;
- $this->icon = $icon;
- $this->methods = [];
- }
- public function addMethod($method, $route) {
- if($this->parentRoute) {
- $route = $this->parentRoute . $route;
- }
- $method = new GenControllerMethod($method, $route);
- $this->methods[] = $method;
- return $method;
- }
- public function save() {
- if(!$this->saved && !empty($this->root) && !empty($this->name)) {
- $this->saveController();
- $this->saveRoutes();
- $this->saved = true;
- // $this->log();
- }
- }
- public function saveController() {
- $text = file_get_contents(base_path('generatecv/tree-templates/controller.template.php'));
- $code = [];
- // check if any method has a "sub add_new" in it, if yes, add action for the same
- $newMethods = [];
- foreach ($this->methods as $method) {
- if($method->type === 'sub' && count($method->subAdders) >= 1) {
- foreach ($method->subAdders as $subAdder) {
- $methodName = "ACTION_" . $subAdder["name"];
- $methodRoute = preg_replace("/\\/SUB_.+$/", '/' . $methodName, $method->route);
- $newMethod = new GenControllerMethod($methodName, $methodRoute);
- $newMethod->hasUID = true;
- $newMethod->redirect = false;
- $newMethod->type = 'action';
- $newMethod->data = $subAdder["data"];
- $newMethod->parentSub = $this->name . '-' . $method->name;
- $newMethod->table = $subAdder["table"];
- if(!empty($subAdder["api"])) {
- $newMethod->api = $subAdder["api"];
- }
- $newMethod->exitURL = $subAdder["link"];
- $newMethod->showLink = false;
- $newMethod->routeName = $this->name . '-' . $methodName;
- $newMethods[] = $newMethod;
- }
- }
- }
- $this->methods = array_merge($this->methods, $newMethods);
- foreach ($this->methods as $method) {
- $code[] = "";
- $code[] = "\t// GET {$method->route}";
- $code[] = "\t" . 'public function ' . $method->name . '(Request $request' . ($method->hasUID ? ', $uid' : '') . ') {';
- if($method->redirect) {
- $target = str_replace('{uid}', '$uid', $method->redirect);
- $code[] = "\t\t" . 'return redirect("' . $target . '");';
- }
- else {
- $input = [];
- if($method->hasUID) {
- $code[] = "\t\t\$record = DB::table('{$this->dbTable}')->where('uid', \$uid)->first();";
- $input[] = "'record'";
- // if sub-index controller, load subRecords
- if($method->type === 'sub' && count($method->data)) {
- $parts = explode(",", $method->data[0]);
- $loadingLine = [];
- // first 'where'
- $dbParts = explode("=", $parts[0]);
- $localField = $dbParts[0];
- $dbParts = explode(".", $dbParts[1]);
- $foreignTable = $dbParts[0];
- $foreignField = $dbParts[1];
- $loadingLine[] = "\t\t\$subRecords = DB::table('$foreignTable')";
- $loadingLine[] = "->where('$foreignField', \$record->$localField)";
- // other 'where's
- if(count($parts) > 1) {
- for ($i = 1; $i < count($parts); $i++) {
- $dbParts = explode("=", $parts[$i]);
- $field = $dbParts[0];
- $value = $dbParts[1];
- $loadingLine[] = "->where('$field', $value)";
- }
- }
- $loadingLine[] = "->get();";
- $code[] = implode("", $loadingLine);
- // $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
- $input[] = "'subRecords'";
- }
- foreach ($method->queries as $key => $query) {
- // replace $x with " . ($record->x ? $record->x : "''") . "
- $query = preg_replace("/([^$])\\$([a-zA-Z0-9_]+)/", "$1\" . (\$record->$2 ? \$record->$2 : \"''\") . \"", $query);
- // replace $$x with " . ($subRecord->x ? $subRecord->x : "''") . "
- $query = preg_replace("/\\$\\$([a-zA-Z0-9_]+)/", "\" . (\$subRecord->$1 ? \$subRecord->$1 : \"''\") . \"", $query);
- $code[] = "\t\t\$result_$key = DB::select(\"$query\");";
- $input[] = "'result_$key'";
- }
- // return response()->view('pro/my_teams/add_new', compact('records'), session('message') ? 500 : 200)->header('Content-Type', 'text/html');
- $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
- "compact(" . implode(", ", $input) . "), " .
- "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
- }
- else {
- $loadingLine = [];
- $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
- if($this->condition) {
- $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
- }
- $loadingLine[] = "->get();";
- $input[] = "'records'";
- $code[] = implode("", $loadingLine);
- foreach ($method->queries as $key => $query) {
- // replace $x with " . ($record->x ? $record->x : "''") . "
- $query = preg_replace("/([^$])\\$([a-zA-Z0-9_]+)/", "$1\" . (\$record->$2 ? \$record->$2 : \"''\") . \"", $query);
- // replace $$x with " . ($subRecord->x ? $subRecord->x : "''") . "
- $query = preg_replace("/\\$\\$([a-zA-Z0-9_]+)/", "\" . (\$subRecord->$1 ? \$subRecord->$1 : \"''\") . \"", $query);
- $code[] = "\t\t\$result_$key = DB::select(\"$query\");";
- $input[] = "'result_$key'";
- }
- $code[] = "\t\treturn response()->view('{$this->root}/{$this->name}/{$method->name}', " .
- "compact(" . implode(", ", $input) . "), " .
- "session('message') ? 500 : 200)->header('Content-Type', 'text/html');";
- }
- }
- $this->saveView($this, $method);
- $code[] = "\t}";
- }
- $text = str_replace("__DASHBOARD_NAME__", $this->dashboardName, $text);
- $text = str_replace("__NAME__", "{$this->name}_Controller", $text);
- $text = str_replace("// __METHODS__", implode("\n", $code), $text);
- GenerateTreeCommand::save(app_path("Http/Controllers/{$this->name}_Controller.php"), $text);
- echo "Generated " . app_path("Http/Controllers/{$this->name}_Controller.php") . "\n";
- }
- public function saveView(GenController $controller, GenControllerMethod $method) {
- if($controller->sub) {
- $controller->saveSubLinks($controller, $method);
- $controller->saveActionLinks($controller, $method);
- if($method->type === 'action') {
- $this->saveSubActionView($controller, $method);
- }
- else if($method->type === 'sub' && count($method->data)) {
- $this->saveSubIndexView($controller, $method);
- }
- else {
- $this->saveSubDefaultView($controller, $method);
- }
- }
- else {
- if($method->name === 'view' && $controller->hasView) {
- $this->saveShowView($controller, $method);
- }
- else if($method->name === 'index') {
- $this->saveIndexView($controller, $method);
- }
- else if(strpos($method->name, 'add_new') === 0 && $controller->hasAdd) {
- $this->saveAddNewView($controller, $method);
- }
- else if($method->name === 'remove' && $controller->hasRemove) {
- $this->saveAddNewView($controller, $method);
- }
- }
- }
- public function saveIndexView(GenController $controller, GenControllerMethod $method)
- {
- $text = file_get_contents(base_path('generatecv/tree-templates/index.template.blade.php'));
- $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
- if($controller->hasAdd) {
- $addLinks = [];
- foreach ($controller->methods as $m) {
- if($m->type === 'add') {
- $addLinks[] = "<a class='btn btn-primary btn-sm ml-2' " .
- 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
- "href='/{$controller->name}/{$m->name}?optimised=1'>" .
- "<i class='fa fa-plus-circle' aria-hidden='true'></i> " .
- "{$this->snakeToTitleCase($m->name)}</a>";
- }
- }
- $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("\n", $addLinks), $text);
- }
- $columns = DB::getSchemaBuilder()->getColumnListing($controller->dbTable);
- $ths = [];
- $tds = [];
- if($controller->hasRemove) {
- $ths[] = "<th></th>";
- $tds[] = "<td><a href='/{$controller->name}/remove/<?= \$record->uid ?>'>" .
- "<i class='fa fa-trash'></i>" .
- "</a></td>";
- }
- // !inc/!exc
- if($method->incType === "include") {
- $columns = $method->incFields;
- }
- else if($method->incType === "exclude") {
- $columns = array_filter($columns, function($item) use ($method) {
- return in_array($item, $method->incFields) === FALSE;
- });
- }
- // ensure uid column is at the start
- $columns = array_merge(['uid'], array_filter($columns, function($x) {
- return $x !== 'uid';
- }));
- foreach ($columns as $column) {
- if($column === 'id') continue;
- $columnTitle = $this->snakeToTitleCase($column);
- $columnValue = "<?= \$record->$column ?>";
- $hasLink = $controller->hasView && $column === $method->viewLinkField;
- $linkTarget = "/{$controller->name}/view/<?= \$record->uid ?>";
- if(substr($column, -3) === '_at') {
- $columnValue = "<?= friendly_date_time(\$record->$column) ?>";
- }
- // check if this column has column spec
- if(isset($method->columns[$column])) {
- $columnTitle = $method->columns[$column]["label"];
- if(isset($method->columns[$column]["query"])) {
- $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
- "select(\"{$method->columns[$column]["query"]}\");\n" .
- "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
- }
- else if(isset($method->columns[$column]["getter"])) {
- $columnValue = $method->columns[$column]["getter"];
- }
- if(isset($method->columns[$column]["link"])) {
- $hasLink = true;
- $linkTarget = $method->columns[$column]["link"];
- }
- }
- else if($column === 'uid') {
- $columnTitle = ' ';
- $columnValue = '<i class="fas fa-share-square"></i>';
- $hasLink = true;
- }
- $ths[] = "<th>$columnTitle</th>";
- $tds[] = "<td>" .
- ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
- $columnValue .
- ($hasLink ? "</a>" : "") .
- "</td>";
- }
- $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
- $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
- }
- public function saveShowView(GenController $controller, GenControllerMethod $method)
- {
- // delete sub links and action links
- if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"))) {
- unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php"));
- }
- if(file_exists(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"))) {
- unlink(resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php"));
- }
- // write info view
- $text = file_get_contents(base_path('generatecv/tree-templates/info.template.blade.php'));
- $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
- $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
- $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/info.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/info.blade.php") . "\n";
- // write main view
- $text = file_get_contents(base_path('generatecv/tree-templates/show.template.blade.php'));
- $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
- $text = str_replace("_UID_", '<?= $record->uid ?>', $text);
- $text = str_replace("_INDEX_ROUTE_", $controller->name . '-index', $text);
- $text = str_replace("_SUB_LINKS_VIEW_", "{$controller->root}/{$controller->name}/subs", $text);
- $text = str_replace("_INFO_VIEW_", "{$controller->root}/{$controller->name}/info", $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
- }
- public function saveSubLinks(GenController $controller, GenControllerMethod $method)
- {
- if ($controller->subLinksSaved) return;
- $subLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/subs.blade.php");
- $subLinks = [];
- foreach ($controller->methods as $meth) {
- if (strpos($meth->name, "SUB_") !== 0 || $meth->showLink === false) continue;
- $display = $this->snakeToTitleCase(substr($meth->name, 4));
- $subLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
- "<a " .
- "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
- "class='d-block px-3 py-2 border-bottom stag-sublink " .
- "{{ request()->route()->getActionMethod() === '{$meth->name}' ? 'bg-secondary text-white font-weight-bold' : '' }}" .
- (
- $meth->name === 'SUB_dashboard' ?
- "{{ strpos(request()->route()->getActionMethod(), 'ACTION_') === 0 ? 'bg-secondary text-white font-weight-bold' : '' }}" :
- ""
- )
- . "'>$display</a>" .
- ($meth->show ? " @endif" : "");
- }
- GenerateTreeCommand::save($subLinksView, implode("\n", $subLinks));
- echo "Generated " . $subLinksView . "\n";
- $controller->subLinksSaved = true;
- }
- public function saveActionLinks(GenController $controller, GenControllerMethod $method)
- {
- if ($controller->actionLinksSaved) return;
- $actionLinksView = resource_path("views/{$controller->root}/{$controller->parentControllerName}/actions.blade.php");
- $actionLinks = [];
- foreach ($controller->methods as $meth) {
- if (strpos($meth->name, "ACTION_") !== 0 || $meth->showLink === false) continue;
- $display = $this->camelToTitleCase(substr($meth->name, 7));
- $actionLinks[] = ($meth->show ? "@if(\$record->{$meth->show}) " : "") .
- "<a " .
- 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
- "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}?optimised=1' " .
- "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
- ($meth->show ? " @endif" : "");
- }
- GenerateTreeCommand::save($actionLinksView, implode("\n", $actionLinks));
- echo "Generated " . $actionLinksView . "\n";
- $controller->actionLinksSaved = true;
- }
- public function saveSubDefaultView(GenController $controller, GenControllerMethod $method)
- {
- $text = file_get_contents(base_path('generatecv/tree-templates/sub.template.blade.php'));
- $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
- $text = $this->generateSubContent($controller, $method, $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
- }
- public function saveSubActionView(GenController $controller, GenControllerMethod $method) {
- $text = file_get_contents(base_path('generatecv/tree-templates/sub-action.template.blade.php'));
- $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
- $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
- if(!$method->parentSub) {
- $text = str_replace("_BACK_ROUTE_", "{$controller->parentControllerName}-view", $text);
- }
- else {
- $text = str_replace("_BACK_ROUTE_", $method->parentSub, $text);
- }
- if(!$method->table) {
- $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/" . substr($method->name, 7), $text);
- }
- else {
- $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($method->table)}/{$method->api}", $text);
- }
- $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
- $fields = [];
- if(count($method->data)) {
- foreach ($method->data as $field) {
- $fields[] = $this->generateFormField($field);
- }
- }
- $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
- }
- public function saveSubIndexView(GenController $controller, GenControllerMethod $method) {
- $text = file_get_contents(base_path('generatecv/tree-templates/sub-index.template.blade.php'));
- $text = str_replace("_LAYOUT_", "{$controller->root}.{$controller->parentControllerName}.view", $text);
- $text = str_replace("_NAME_", $this->camelToTitleCase($this->snakeToTitleCase($method->name)), $text);
- if(count($method->subAdders) >= 1) {
- $addLinks = [];
- foreach ($method->subAdders as $subAdder) {
- $addLink = '<a class="btn btn-primary btn-sm ml-2" ' .
- 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
- 'href="{{route(\'' . $subAdder["routeName"] . '\', [\'uid\' => $record->uid])}}?optimised=1">' .
- "<i class='fa fa-plus-circle' aria-hidden='true'></i> {$subAdder["buttonLabel"]}</a>";
- $addLinks[] = $addLink;
- }
- $text = str_replace("<!-- _ADD_NEW_LINK_ -->", implode("", $addLinks), $text);
- }
- $dbParts = explode("=", $method->data[0]);
- $dbParts = explode(".", $dbParts[1]);
- $table = $dbParts[0];
- $columns = DB::getSchemaBuilder()->getColumnListing($table);
- $ths = [];
- $tds = [];
- // !inc/!exc
- if($method->incType === "include") {
- $columns = $method->incFields;
- }
- else if($method->incType === "exclude") {
- $columns = array_filter($columns, function($item) use ($method) {
- return in_array($item, $method->incFields) === FALSE;
- });
- }
- // ensure uid column is at the start
- $columns = array_merge(['uid'], array_filter($columns, function($x) {
- return $x !== 'uid';
- }));
- foreach ($columns as $column) {
- if($column === 'id') continue;
- $columnTitle = $this->snakeToTitleCase($column);
- $columnValue = "<?= \$subRecord->$column ?>";
- $hasLink = $method->exitURL && $column === $method->viewLinkField;
- $linkTarget = $method->exitURL;
- if(substr($column, -3) === '_at') {
- $columnValue = "<?= friendly_date_time(\$subRecord->$column) ?>";
- }
- // check if this column has column spec
- if(isset($method->columns[$column])) {
- $columnTitle = $method->columns[$column]["label"];
- if(isset($method->columns[$column]["query"])) {
- $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
- "select(\"{$method->columns[$column]["query"]}\");\n" .
- "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
- }
- else if(isset($method->columns[$column]["getter"])) {
- $columnValue = $method->columns[$column]["getter"];
- }
- if(isset($method->columns[$column]["link"])) {
- $hasLink = true;
- $linkTarget = $method->columns[$column]["link"];
- }
- }
- else if($column === 'uid') {
- $columnTitle = ' ';
- $columnValue = '<i class="fas fa-share-square"></i>';
- $hasLink = true;
- }
- $ths[] = "<th>$columnTitle</th>";
- $tds[] = "<td>" .
- ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
- $columnValue .
- ($hasLink ? "</a>" : "") .
- "</td>";
- }
- $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
- $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
- }
- public function generateSubContent(GenController $controller, GenControllerMethod $method, $text) {
- if($method->dashboard) {
- if(!isset($method->groups) || !count($method->groups)) {
- $html = file_get_contents(base_path('generatecv/tree-templates/dashboard' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
- }
- else {
- $html = file_get_contents(base_path('generatecv/tree-templates/dashboard-grouped' . ($method->noActionLinks ? '-nal' : '') . '.template.blade.php'));
- $groupsHtml = [];
- $groupTemplate = file_get_contents(base_path('generatecv/tree-templates/dashboard-group.template.blade.php'));
- foreach ($method->groups as $group) {
- $groupHtml = $groupTemplate;
- $groupHtml = str_replace("<!-- __GROUP_NAME__ -->", $group["name"], $groupHtml);
- if (isset($group["action"])) {
- $action = $group["action"];
- $actionLine = [];
- if (isset($action["condition"])) {
- if ($action["condition"] === "if") {
- $actionLine[] = "@if(";
- } else {
- $actionLine[] = "@if(!";
- }
- $actionLine[] = "\$record->{$action["field"]})";
- }
- $title = $this->camelToTitleCase($action["label"]);
- $actionLine[] = "<a " .
- 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
- "href='{$action["link"]}' title='{$action["label"]}?optimised=1'" .
- "class='mx-2 font-weight-normal text-primary text-xs'>" .
- "<i class='fa fa-{$action["icon"]}'></i> " .
- "<span>{$title}</span>" .
- "</a>";
- if (isset($action["condition"])) {
- $actionLine[] = "@endif";
- }
- $actionLine = implode(" ", $actionLine);
- $groupHtml = str_replace("<!-- __GROUP_ACTION__ -->", $actionLine, $groupHtml);
- }
- $fields = [];
- foreach ($group["fields"] as $field) {
- if($field === 'id' || $field === 'uid') continue;
- $columnTitle = $this->snakeToTitleCase($field);
- $columnValue = "<?= \$record->$field ?>";
- $hasLink = false;
- $linkTarget = null;
- $actions = [];
- if(substr($field, -3) === '_at') {
- $columnValue = "<?= friendly_date_time(\$record->$field) ?>";
- }
- // check if this column has column spec
- if(isset($method->columns[$field])) {
- $columnTitle = $method->columns[$field]["label"];
- if(isset($method->columns[$field]["query"])) {
- $columnValue = "<?php \$_r = \Illuminate\Support\Facades\DB::" .
- "select(\"{$method->columns[$field]["query"]}\");\n" .
- "echo (\$_r && count(\$_r)) ? \$_r[0]->result : '-'; ?>";
- }
- else if(isset($method->columns[$field]["getter"])) {
- $columnValue = $method->columns[$field]["getter"];
- }
- if(isset($method->columns[$field]["link"])) {
- $hasLink = true;
- $linkTarget = $method->columns[$field]["link"];
- }
- }
- if(isset($method->columnActions[$field])) {
- foreach($method->columnActions[$field] as $action) {
- $actionLine = [];
- if(isset($action["condition"])) {
- if($action["condition"] === "if") {
- $actionLine[] = "@if(";
- }
- else {
- $actionLine[] = "@if(!";
- }
- $actionLine[] = "\$record->{$action["field"]})";
- }
- $title = $this->camelToTitleCase($action["label"]);
- $actionLine[] = "<a " .
- 'up-modal=".form-contents" up-preload up-delay="25" up-width="800" up-history="false" ' .
- "href='{$action["link"]}?optimised=1' title='{$action["label"]}' " .
- "class='mx-2 font-weight-normal text-primary text-xs'>" .
- "<i class='fa fa-{$action["icon"]}'></i> " .
- "<span>{$title}</span>" .
- "</a>";
- if(isset($action["condition"])) {
- $actionLine[] = "@endif";
- }
- $actionLine = implode(" ", $actionLine);
- $actions[] = $actionLine;
- }
- }
- $actions = implode("\n", $actions);
- $fields[] = "<tr>" .
- "<td class=\"w-25 px-2 text-secondary border-right\">$columnTitle</td>" .
- "<td class=\"w-75 px-2 font-weight-bold\">" .
- ($hasLink ? "<a href=\"{$linkTarget}\">" : "") .
- $columnValue .
- ($hasLink ? "</a>" : "") .
- $actions .
- "</td>" .
- "</tr>";
- }
- $groupHtml = str_replace("<!-- __GROUP_FIELDS__ -->", implode("\n", $fields), $groupHtml);
- $groupsHtml[] = $groupHtml;
- }
- $groupsHtml = implode("\n", $groupsHtml);
- $html = str_replace("<!-- _GROUPS_ -->", $groupsHtml, $html);
- }
- $text = str_replace("_SUB_VIEW_", $html, $text);
- $text = str_replace("_ACTION_LINKS_VIEW_", "{$controller->root}/{$controller->parentControllerName}/actions", $text);
- }
- else {
- $text = str_replace("_SUB_VIEW_",
- "<h5 class='py-3 border-bottom'>" .
- $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h5>" .
- "Controller: <b>{$controller->name}</b><br>" .
- "Action: <b>{$method->name}()</b><br>" .
- "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><br><br>",
- $text);
- }
- return $text;
- }
- public function saveAddNewView(GenController $controller, GenControllerMethod $method)
- {
- $text = file_get_contents(base_path('generatecv/tree-templates/add_new.template.blade.php'));
- $text = str_replace("_NAME_", $this->snakeToTitleCase($controller->name), $text);
- $text = str_replace("_ADD_TITLE_", $this->snakeToTitleCase($method->name), $text);
- $text = str_replace("_API_", "/api/{$this->snakeToCamelCase($controller->dbTable)}/{$method->api}", $text);
- $text = str_replace("_BACK_ROUTE_", "{$controller->name}-index", $text);
- $text = str_replace("_RETURN_ROUTE_", "{$controller->name}-{$method->name}", $text);
- $columns = $method->data;
- $fields = [];
- foreach ($columns as $column) {
- $fields[] = $this->generateFormField($column);
- }
- $text = str_replace("<!-- _SCAFFOLD_FIELDS_ -->", implode("\n", $fields), $text);
- GenerateTreeCommand::save(resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php"), $text);
- echo "Generated " . resource_path("views/{$controller->root}/{$controller->name}/{$method->name}.blade.php") . "\n";
- }
- public function saveRoutes() {
- $lines = ["// --- {$this->root}: {$this->name} --- //"];
- foreach ($this->methods as $method) {
- // FORMAT:
- // Route::get('/foo/bar/{uid}', 'FooController@bar')->name('foo-action');
- $lines[] = "Route::get('{$method->route}', '{$this->name}_Controller@{$method->name}')->name('{$this->name}-{$method->name}');";
- }
- $lines[] = '';
- $lines[] = '';
- GenerateTreeCommand::save(base_path("routes/generated.php"), implode("\n", $lines), FILE_APPEND);
- }
- public function log() {
- $this->w('');
- $this->w("Controller: app/Http/Controllers/{$this->name}_Controller");
- $this->w("Table: {$this->dbTable}");
- $this->w('---------------------------------------------');
- foreach ($this->methods as $method) {
- $this->w('Rout: ' . $method->route, 1);
- $this->w('Meth: ' . $method->name . '($request' . ($method->hasUID ? ', $uid' : '') . ')', 1);
- if(!empty($method->data)) $this->w('Data: ' . implode(", ", $method->data), 1);
- // $this->w('Exit: ' . $method->exitURL, 1);
- // $this->w('View: ' . $method->viewURL, 1);
- dump($method->columns);
- dump($method->queries);
- if(!$method->redirect) {
- $this->w('View: ' . resource_path("views/{$this->root}/{$this->name}/{$method->name}.blade.php"), 1);
- }
- else {
- $this->w('Redi: ' . $method->redirect, 1);
- }
- $this->w('---------------------------------------------');
- }
- }
- public function w($line, $level = -1) {
- for($i=0; $i<$level; $i++) echo "\t";
- echo "$line\n";
- }
- public function snakeToTitleCase($text) {
- $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
- return ucwords(str_replace("_", " ", $text));
- }
- public function camelToTitleCase($text) {
- $text = preg_replace("/^(SUB|ACTION)_/", "", $text);
- $text = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $text);
- return ucwords($text);
- }
- public function snakeToCamelCase($text) {
- $text = ucwords(str_replace("_", " ", $text));
- $text = str_replace(" ", "", $text);
- $text[0] = strtolower($text[0]);
- return $text;
- }
- private function generateFormField($line) {
- $tokens = explode("=", $line);
- $default = false;
- if(count($tokens) > 1) {
- $default = $tokens[1];
- }
- $tokens = explode(":", $tokens[0]);
- $name = $tokens[0];
- $required = false;
- if($name[strlen($name) - 1] === '*') { // required field?
- $required = true;
- $name = substr($name, 0, strlen($name) - 1);
- }
- $display = $name;
- $dotPos = strpos($name, ".");
- if($dotPos !== FALSE) {
- $display = substr($name, $dotPos + 1);
- }
- $display = preg_replace('/uid$/i', "", $display);
- $type = "text";
- $options = [];
- if(count($tokens) > 1) {
- $type = $tokens[1];
- switch ($type) {
- case "select":
- $options = explode(",", $tokens[2]);
- break;
- case "record":
- $options['table'] = $tokens[2];
- $parts = explode(",", $tokens[3]);
- $options['valueField'] = $parts[0];
- $options['displayField'] = $parts[1];
- break;
- }
- }
- if($type !== 'hidden' && $type !== 'bool') {
- $code[] = "<div class='form-group mb-3'>";
- $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
- ($required ? "*" : "") .
- "</label>";
- }
- $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
- switch ($type) {
- case "select":
- $code[] = "<select class='form-control' name='$name' " . $valueLine .
- ($required ? "required" : "") .
- ">";
- $code[] = "<option value=''>-- Select --</option>";
- foreach ($options as $o) {
- $code[] = "<option " .
- "<?= '$o' === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
- "value='$o'>$o</option>";
- }
- $code[] = "</select>";
- break;
- case "record":
- $code[] = "<select class='form-control' name='$name' " . $valueLine .
- ($required ? "required" : "") .
- ">";
- $code[] = "<option value=''>-- Select --</option>";
- if($options['table'][0] === '~') { // from named query
- $code[] = "<?php foreach(\$result_" . substr($options['table'], 1) . " as \$o): ?>";
- }
- else { // select query
- $code[] = "<?php \$dbOptions = \Illuminate\Support\Facades\DB::table('{$options['table']}')->get(); ?>";
- $code[] = "<?php foreach(\$dbOptions as \$o): ?>";
- }
- $code[] = "<option " .
- "<?= \$o->{$options['valueField']} === (old('$name') ? old('$name') : " . ($default ? "\$record->$default" : "''") . ") ? 'selected' : '' ?> " .
- "value='<?= \$o->{$options['valueField']} ?>'><?= \$o->{$options['displayField']} ?> (<?= \$o->{$options['valueField']} ?>)</option>";
- $code[] = "<?php endforeach; ?>";
- $code[] = "</select>";
- break;
- case "bool":
- $code[] = "<div class='form-group mb-3'>";
- $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))} " .
- ($required ? "*" : "");
- $code[] = "<input class='ml-2' type='checkbox' name='$name' " .
- ($required ? "required" : "") .
- ">";
- $code[] = "</label>";
- break;
- default:
- $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
- ($required ? "required" : "") .
- ">";
- }
- if($type !== 'hidden') {
- $code[] = "</div>";
- }
- return implode("\n", $code);
- }
- }
- class GenControllerMethod {
- public $name;
- public $route;
- public $hasUID = false;
- public $redirect = false;
- public $type = '';
- public $data = [];
- public $parentSub = false;
- public $childAddRoute = false;
- public $table = false;
- public $api = 'create';
- public $show = null;
- public $viewURL = false;
- public $exitURL = false;
- public $showLink = true;
- public $incType = null;
- public $incFields = null;
- public $viewLinkField = 'uid';
- public $columns = [];
- public $columnActions = [];
- public $groups = [];
- public $dashboard = false;
- public $noActionLinks = false;
- public $queries = [];
- public $subAdders = [];
- public function __construct($name, $route)
- {
- $this->name = $name;
- $this->route = $route;
- if(strpos($this->route, "{uid}") !== FALSE) {
- $this->hasUID = true;
- }
- }
- public function addSubAdder($line, $parentControllerName, $label, $link) {
- $parts = explode(":", $line);
- $newSubAdder = [
- "name" => $parts[0],
- "table" => $parts[1],
- "api" => count($parts) >= 3 ? $parts[2] : null,
- "link" => $link,
- "data" => [],
- "routeName" => "$parentControllerName-ACTION_{$parts[0]}",
- "buttonLabel" => $label
- ];
- $this->subAdders[] = $newSubAdder;
- return $newSubAdder;
- }
- public function setIncFields($type, $fields) {
- $this->incType = $type;
- $this->incFields = $fields;
- for ($i = 0; $i < count($this->incFields); $i++) {
- if($this->incFields[$i][0] === '@') {
- $this->incFields[$i] = substr($this->incFields[$i], 1);
- $this->viewLinkField = $this->incFields[$i];
- }
- }
- }
- public function setColumnSpec($line, $link, $recordVariable) {
- // ally_pro_id:Ally Pro:select name_display as 'result' from pro where id = $ally_pro_id limit 1
- $parts = explode(":", $line);
- $spec = [
- "label" => $parts[1]
- ];
- if(count($parts) > 2) {
- $query = $parts[2];
- // check if named query
- if($query[0] === '~') {
- // hcp_pro_id:HCP Pro:~pros:name_display:id,=,$hcp_pro_id;is_active,=,true:all
- $recordSet = '$result_' . substr($query, 1);
- $field = $parts[3];
- $checkParts = explode(";", $parts[4]);
- $checks = [];
- foreach ($checkParts as $checkPart) {
- $checkPart = explode(",", $checkPart);
- $value = $checkPart[2];
- if(strpos($value, '$$') === 0) {
- $value = '$subRecord->' . substr($value, 2);
- }
- else if(strpos($value, '$') === 0) {
- $value = '$record->' . substr($value, 1);
- }
- $checks[] = [
- "field" => $checkPart[0],
- "op" => $checkPart[1],
- "value" => $value
- ];
- }
- $condition = 'all';
- if(count($parts) >= 6) {
- $condition = $parts[5];
- }
- $checksArray = ["["];
- foreach ($checks as $check) {
- $checksArray[] = "[";
- $checksArray[] = "'{$check['field']}'";
- $checksArray[] = ", ";
- $checksArray[] = "'{$check['op']}'";
- $checksArray[] = ", ";
- $checksArray[] = "{$check['value']}";
- $checksArray[] = "], ";
- }
- $checksArray[] = "]";
- $checks = implode("", $checksArray);
- $spec['getter'] = "<?= value_from_rs($recordSet, '$field', " . $checks . ", '$condition'); ?>";
- }
- else {
- $query = preg_replace("/\\$([a-zA-Z0-9_]+)/", "\" . ($$recordVariable->$1 ? $$recordVariable->$1 : -1) . \"", $query);
- $spec['query'] = $query;
- }
- }
- if($link) {
- $spec['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$$recordVariable->$1 ?>", $link);
- }
- $this->columns[$parts[0]] = $spec;
- }
- public function addGroup($line, $link) {
- // Basic Details:id,uid,created_at,clients_count
- $parts = explode(":", $line);
- $group = [
- "name" => $parts[0],
- "fields" => explode(",", $parts[1])
- ];
- // is there a group action
- if(count($parts) > 2) {
- $actionParts = ["-"];
- for($i = 2; $i < count($parts); $i++) {
- $actionParts[] = $parts[$i];
- }
- $actionParts = implode(":", $actionParts);
- $group["action"] = $this->addAction($actionParts, $link, true);
- }
- $this->groups[] = $group;
- $this->dashboard = true;
- }
- public function addAction($line, $link, $group = false) {
- // is_active:Deactivate:deactivate:edit:if:is_active
- $parts = explode(":", $line);
- $action = [
- "label" => $parts[1],
- "icon" => isset($parts[2]) ? $parts[2] : 'edit'
- ];
- if(count($parts) >= 5 ) {
- $action["condition"] = $parts[3];
- $action["field"] = $parts[4];
- }
- if($link) {
- $action['link'] = preg_replace("/\\$([a-zA-Z0-9_]+)/", "<?= \$record->$1 ?>", $link);
- }
- if(!$group) {
- if(!isset($this->columnActions[$parts[0]])) {
- $this->columnActions[$parts[0]] = [];
- }
- $this->columnActions[$parts[0]][] = $action;
- }
- return $action;
- }
- public function addQuery($line) {
- $parts = explode(":", $line);
- $this->queries[$parts[0]] = $parts[1];
- }
- }
|