123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766 |
- <?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;', '', ''];
- file_put_contents(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;
- foreach ($lines as $line) {
- // 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);
- 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);
- $currentController->dbTable = $dbTable;
- $currentController->condition = $condition;
- $currentController->hasAdd = $hasAdd;
- $currentController->hasView = $hasView;
- $currentController->hasRemove = $hasRemove;
- $currentController->addMethod("index", "/$line");
- if(!empty($currentSubController)) {
- $currentSubController->save();
- }
- $currentSubType = '';
- $currentSubController = new GenController();
- $sideLinks[] = "<li class='nav-item'><a href='/{$currentController->name}' " .
- "class='nav-link " .
- "{{ (isset(request()->route()->getController()->selfName) && strpos(request()->route()->getController()->selfName, '{$currentController->name}') === 0 ? 'active' : '') }}" . " '>" .
- "<i class='nav-icon fa fa-user'></i>" .
- "<p>" . $currentController->snakeToTitleCase($currentController->name) . "</p>" .
- "</a></li>";
- }
- break;
- case 8: // sub-type declaration | add_new fields
- if($line === 'ACTIONS' || $line === 'SUB') {
- $currentSubType = $line;
- }
- 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;
- if(strpos($line, ":")) {
- $parts = explode(":", $line);
- $line = $parts[0];
- if($parts[1] === 'if') {
- $show = $parts[2];
- }
- }
- 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 = [];
- }
- break;
- case 16: // data for actions and subs
- 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(!empty($currentMethod)) {
- $currentMethod->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
- file_put_contents(resource_path("views/layouts/generated-links.blade.php"), implode("\n", $sideLinks));
- echo "Saved " . resource_path("views/layouts/generated-links.blade.php") . "\n";
- }
- private function numLS($line) {
- $count = 0;
- for ($i=0; $i<strlen($line); $i++) {
- if($line[$i] !== ' ') break;
- $count++;
- }
- return $count;
- }
- }
- 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 $subLinksSaved = false;
- public $actionLinksSaved = false;
- public function __construct($root = null, $name = null)
- {
- $this->root = $root;
- $this->name = $name;
- $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->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
- $methodName = preg_replace("/^SUB_/", "ACTION_", $method->name) . 'AddNew';
- $methodRoute = str_replace("/SUB_", "/ACTION_", $method->route) . 'AddNew';
- $newMethod = new GenControllerMethod($methodName, $methodRoute);
- $newMethod->hasUID = true;
- $newMethod->redirect = false;
- $newMethod->type = 'action';
- $newMethod->data = [];
- for($i = 2; $i<count($method->data); $i++) {
- $newMethod->data[] = $method->data[$i];
- }
- $newMethod->parentSub = $this->name . '-' . $method->name;
- $parts = explode(":", $method->data[1]);
- $newMethod->table = $parts[1];
- if(count($parts) === 3) {
- $newMethod->api = $parts[2];
- }
- $newMethod->exitURL = $method->exitURL;
- $newMethod->showLink = false;
- $newMethods[] = $newMethod;
- $method->childAddRoute = $this->name . '-' . $methodName;
- }
- }
- $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 {
- 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)) {
- $dbParts = explode("=", $method->data[0]);
- $localField = $dbParts[0];
- $dbParts = explode(".", $dbParts[1]);
- $foreignTable = $dbParts[0];
- $foreignField = $dbParts[1];
- $code[] = "\t\t\$subRecords = DB::table('$foreignTable')->where('$foreignField', \$record->$localField)->get();";
- $input[] = "'subRecords'";
- }
- $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', " .
- "compact(" . implode(", ", $input) . "));";
- }
- else {
- $loadingLine[] = "\t\t\$records = DB::table('{$this->dbTable}')";
- if($this->condition) {
- $loadingLine[] = "->where('{$this->condition['field']}', {$this->condition['value']})";
- }
- $loadingLine[] = "->get();";
- $code[] = implode("", $loadingLine);
- $code[] = "\t\treturn view('{$this->root}/{$this->name}/{$method->name}', " .
- "compact('records'));";
- }
- }
- $this->saveView($this, $method);
- $code[] = "\t}";
- }
- $text = str_replace("_NAME_", "{$this->name}_Controller", $text);
- $text = str_replace("// __METHODS__", implode("\n", $code), $text);
- file_put_contents(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' " .
- "href='/{$controller->name}/{$m->name}'>" .
- "<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>";
- }
- foreach ($columns as $column) {
- $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
- $tds[] = "<td>" .
- ($controller->hasView && $column === 'uid' ? '<a href="/' . $controller->name . '/view/<?= $record->uid ?>">' : '') .
- "<?= \$record->$column ?>" .
- ($controller->hasView && $column === 'uid' ? '</a>' : '') .
- "</td>";
- }
- $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
- $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
- $this->file_force_contents(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"));
- }
- $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);
- $this->file_force_contents(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 " .
- "{{ 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" : "");
- }
- $this->file_force_contents($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 " .
- "href='/{$controller->parentControllerName}/view/<?= \$record->uid ?>/{$meth->name}' " .
- "class='d-block btn btn-sm btn-default mb-3'>$display</a>" .
- ($meth->show ? " @endif" : "");
- }
- $this->file_force_contents($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);
- $this->file_force_contents(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);
- $this->file_force_contents(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->data) > 1 && strpos($method->data[1], 'add_new') === 0) {
- $addLink = '<a class="btn btn-primary btn-sm" ' .
- 'href="{{route(\'' . $method->childAddRoute . '\', [\'uid\' => $record->uid])}}">' .
- "<i class='fa fa-plus-circle' aria-hidden='true'></i> Add New</a>";
- $text = str_replace("<!-- _ADD_NEW_LINK_ -->", $addLink, $text);
- }
- $dbParts = explode("=", $method->data[0]);
- $dbParts = explode(".", $dbParts[1]);
- $table = $dbParts[0];
- $columns = DB::getSchemaBuilder()->getColumnListing($table);
- $ths = [];
- $tds = [];
- foreach ($columns as $column) {
- $ths[] = "<th>{$this->snakeToTitleCase($column)}</th>";
- $tds[] = "<td>" .
- ($method->exitURL && $column === 'uid' ? '<a href="' . $method->exitURL . '">' : '') .
- "<?= \$subRecord->$column ?>" .
- ($method->exitURL && $column === 'uid' ? '</a>' : '') .
- "</td>";
- }
- $text = str_replace("<!-- __SCAFFOLD_THS__ -->", implode("\n", $ths), $text);
- $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", implode("\n", $tds), $text);
- $this->file_force_contents(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->name === 'SUB_dashboard') {
- $html = file_get_contents(base_path('generatecv/tree-templates/dashboard.template.blade.php'));
- $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_",
- "<h4 class='py-3 border-bottom'>" .
- $this->camelToTitleCase($this->snakeToTitleCase($method->name)) . "</h4>" .
- "Controller: <b>{$controller->name}</b><br>" .
- "Action: <b>{$method->name}()</b><br>" .
- "View: <b>{$controller->root}/{$controller->name}/{$method->name}.blade.php</b><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);
- $this->file_force_contents(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[] = '';
- file_put_contents(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);
- 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 file_force_contents($dir, $contents){
- $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);
- }
- }
- file_put_contents("$dir/$file", $contents);
- }
- private function generateFormField($line) {
- $tokens = explode("=", $line);
- $default = false;
- if(count($tokens) > 1) {
- $default = $tokens[1];
- }
- $tokens = explode(":", $tokens[0]);
- $name = $tokens[0];
- $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') {
- $code[] = "<div class='form-group mb-3'>";
- $code[] = "<label class='control-label'>{$this->camelToTitleCase($this->snakeToTitleCase($display))}</label>";
- }
- $valueLine = "value='{{ old('$name') ? old('$name') : " . ($default ? "\$record->$default" : '\'\'') . " }}' ";
- switch ($type) {
- case "select":
- $code[] = "<select class='form-control' name='$name' " . $valueLine .
- ">";
- $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 .
- ">";
- $code[] = "<option value=''>-- Select --</option>";
- $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;
- default:
- $code[] = "<input class='form-control' type='$type' name='$name' " . $valueLine .
- ">";
- }
- 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 function __construct($name, $route)
- {
- $this->name = $name;
- $this->route = $route;
- if(strpos($this->route, "{uid}") !== FALSE) {
- $this->hasUID = true;
- }
- }
- }
|