Example #1
0
 /**
  * Update routes file
  *
  * @param  string $name
  *
  * @return boolean
  */
 public function updateRoutesFile($routesFile, $name, $templatePath)
 {
     $modelVars = GeneratorsServiceProvider::getModelVars($name);
     $routes = file_get_contents($routesFile);
     $newRouteDefault = '\\Route::resource(\'{{models}}\', \'{{Models}}Controller\');' . "\n";
     if ($this->file->exists($templatePath)) {
         $newRoute = file_get_contents($templatePath);
     } else {
         $newRoute = $newRouteDefault;
     }
     $newRoute = GeneratorsServiceProvider::replaceModelVars($newRoute, $modelVars);
     $newRouteDefault = GeneratorsServiceProvider::replaceModelVars($newRouteDefault, $modelVars);
     $routesNoSpaces = str_replace(['\\t', ' '], '', $routes);
     $newRouteNoSpaces = str_replace(['\\t', ' '], '', $newRoute);
     $newRouteDefaultNoSpaces = str_replace(['\\t', ' '], '', $newRouteDefault);
     if (str_contains($routesNoSpaces, $newRouteDefaultNoSpaces) && !str_contains($routesNoSpaces, $newRouteNoSpaces)) {
         if (substr($newRoute, -1) === "\n") {
             $newRoute = substr($newRoute, 0, -1);
         }
         $newRoute = '// ' . str_replace("\n", "\n// ", $newRoute) . "\n";
         $newRouteNoSpaces = str_replace(['\\t', ' '], '', $newRoute);
     }
     if (!str_contains($routesNoSpaces, $newRouteNoSpaces)) {
         if (!str_contains($routes, GeneratorsServiceProvider::GENERATOR_ROUTE_TAG)) {
             $this->file->append($routesFile, "\n{$newRoute}\n" . GeneratorsServiceProvider::GENERATOR_ROUTE_TAG . "\n\n");
         } else {
             $routes = str_replace(GeneratorsServiceProvider::GENERATOR_ROUTE_TAG, $newRoute . GeneratorsServiceProvider::GENERATOR_ROUTE_TAG, $routes);
             file_put_contents($routesFile, $routes);
         }
         return true;
     }
     return false;
 }
 /**
  * Fetch the compiled template for a model
  *
  * @param  string $template text to replace
  *
  * @return string Compiled template
  */
 public function getLangTemplate($template)
 {
     // Replace template vars
     $modelVars = GeneratorsServiceProvider::getModelVars($this->cache->getModelName());
     $template = GeneratorsServiceProvider::replaceModelVars($template, $modelVars);
     $template = $this->replaceStandardParams($template);
     return $template;
 }
Example #3
0
 /**
  * Fetch the compiled template for a test
  *
  * @param  string $template Path to template
  * @param  string $className
  * @return string Compiled template
  */
 protected function getTemplate($template, $className)
 {
     $template = $this->file->get($template);
     $name = $this->cache->getModelName();
     $modelVars = GeneratorsServiceProvider::getModelVars($name);
     $template = GeneratorsServiceProvider::replaceModelVars($template, $modelVars);
     return $this->replaceStandardParams($template);
 }
Example #4
0
 /**
  * Fetch the compiled template for a seed
  *
  * @param  string $template Path to template
  * @param  string $className
  *
  * @return string Compiled template
  */
 protected function getTemplate($template, $className)
 {
     $this->template = $this->file->get($template);
     $name = Pluralizer::singular(str_replace('TableSeeder', '', $className));
     $modelVars = GeneratorsServiceProvider::getModelVars($name);
     $this->template = str_replace('{{className}}', $className, $this->template);
     $template = GeneratorsServiceProvider::replaceModelVars($this->template, $modelVars);
     return $this->replaceStandardParams($template);
 }
Example #5
0
 /**
  * Save fields to cached file
  * for future use by other commands
  *
  * @param string $fields
  * @param string $path
  * @return mixed
  */
 public function fields($fields, $path = null)
 {
     if ($fields === null) {
         return;
     }
     $path = $path ?: __DIR__ . '/../tmp-fields.txt';
     $arrayFields = GeneratorsServiceProvider::splitFields($fields);
     return $this->file->put($path, json_encode($arrayFields));
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     $name = $this->argument('name');
     $path = $this->getPath();
     $this->generator->setOptions($this->option());
     // common error for field types
     $fields = $this->option('fields');
     $fields = GeneratorsServiceProvider::mapFieldTypes($fields);
     $this->fields = $fields;
     $created = $this->generator->parse($name, $fields)->make($path, null, $finalPath);
     //$this->call('dump-autoload');
     $this->printResult($created, $path, $finalPath);
 }
Example #7
0
 /**
  * Get the path to the file that should be generated.
  *
  * @param      $srcType         String  name of the directory type
  *                              code            - directory for code (app or workbench)
  *                              commands
  *                              config
  *                              controllers
  *                              lang
  *                              migrations
  *                              models
  *                              public
  *                              routes          - directory/file for the routes file
  *                              seeds
  *                              templates
  *                              tests
  *                              views
  *
  *                              The returned path will be adjusted for bench option to map the directory to the right location
  *                              in the workbench/vendor/package subdirectory based on laravel version
  *
  * @param null $suffix
  *
  * @return string
  */
 protected function getSrcPath($srcType, $suffix = null)
 {
     if ($this->option('path')) {
         $srcPath = $this->option('path');
     } else {
         $srcPath = GeneratorsServiceProvider::getSrcPath($srcType, $this->option('bench'));
     }
     return $suffix ? end_with($srcPath, '/') . $suffix : $srcPath;
 }
Example #8
0
    /**
     * Get template for a scaffold
     *
     * @param $className
     *
     * @return string
     */
    protected function getScaffoldedModel($className)
    {
        if (!($fields = $this->cache->getFields())) {
            return str_replace('{{rules}}', '', $this->template);
        }
        $template = $this->template;
        $template = str_replace('{{__construct}}', <<<'PHP'
protected $table = '{{snake_models}}';

    public function __construct($attributes = [])
    {
        {{prefixdef}}$this->table = {{prefix}}'{{snake_models}}';
        parent::__construct($attributes);
    }

PHP
, $this->template);
        $prefix = $this->options('prefix');
        $package = $this->options('bench');
        $template = GeneratorsServiceProvider::replacePrefixTemplate($prefix, $package, $template);
        $fieldRawText = implode(',', $fields);
        $fields = GeneratorsServiceProvider::splitFields($fieldRawText, true);
        $modelVars = GeneratorsServiceProvider::getModelVars($this->cache->getModelName());
        // Replace template vars
        $template = GeneratorsServiceProvider::replaceModelVars($template, $modelVars);
        $relationModelList = GeneratorsServiceProvider::getRelationsModelVarsList($fields);
        if (strpos($template, '{{relations') !== false) {
            $relations = '';
            foreach ($fields as $field) {
                // add foreign keys
                $name = $field->name;
                if (array_key_exists($name, $relationModelList)) {
                    $foreignModelVars = $relationModelList[$name];
                    $relations .= <<<PHP
    /**
     * @return \\Illuminate\\Database\\Eloquent\\Relations\\Relation
     */
    public
    function {$foreignModelVars['field_no_id']}()
    {
        return \$this->belongsTo('{{app_namespace}}\\{$foreignModelVars['CamelModel']}', '{$name}', '{$foreignModelVars['id']}');
    }


PHP;
                }
            }
            $template = str_replace('{{relations}}', $relations, $template);
            if ($relationModelList) {
                $relationsVars = [];
                foreach ($relationModelList as $name => $relationModelVars) {
                    foreach ($relationModelVars as $relationModel => $relationModelVar) {
                        // append
                        if (array_key_exists($relationModel, $relationsVars)) {
                            $relationsVars[$relationModel] .= ", '{$relationModelVar}'";
                        } else {
                            $relationsVars[$relationModel] = "'{$relationModelVar}'";
                        }
                    }
                }
                $template = GeneratorsServiceProvider::replaceModelVars($template, $relationsVars, '{{relations:', '}}');
                $template = GeneratorsServiceProvider::replaceTemplateLines($template, '{{relation:line}}', function ($line, $fieldVar) use($fields, $relationModelList) {
                    $fieldText = '';
                    $line = str_replace($fieldVar, '', $line);
                    foreach ($fields as $field) {
                        // add foreign keys
                        $name = $field->name;
                        if (array_key_exists($name, $relationModelList)) {
                            $relationsVars = $relationModelList[$name];
                            $fieldText .= GeneratorsServiceProvider::replaceModelVars($line, $relationsVars, '{{relation:', '}}') . "\n";
                        }
                    }
                    return $fieldText;
                });
            } else {
                $emptyVars = $modelVars;
                array_walk($emptyVars, function (&$val) {
                    $val = '';
                });
                $template = GeneratorsServiceProvider::replaceModelVars($template, $emptyVars, '{{relations:', '}}');
                $template = GeneratorsServiceProvider::replaceTemplateLines($template, '{{relation:line}}', function ($line, $fieldVar) {
                    return '';
                });
            }
        }
        if (strpos($template, '{{field:unique}}') !== false) {
            $uniqueField = '';
            $keyindices = [0];
            // first element is last used index number, keys are _i where i is passed from the parameters, or auto generated, _i => _n_f where n is from params and f index of the field in the fields list
            $fieldIndex = 0;
            foreach ($fields as $field) {
                $fieldIndex++;
                foreach ($field->options as $option) {
                    $isKey = null;
                    $isUnique = null;
                    if (($isUnique = strpos($option, 'unique') === 0) || ($isKey = strpos($option, 'keyindex') === 0)) {
                        MigrationGenerator::processIndexOption($keyindices, $option, $field->name, $fieldIndex);
                    }
                }
            }
            // we now have the key indices, we can take the first one
            if (count($keyindices) >= 1) {
                // skip the auto counter
                array_shift($keyindices);
                $indexValues = array_values($keyindices);
                if ($indexValues) {
                    $anyIndex = $indexValues[0];
                    $uniqueField = "'" . implode("','", array_values($anyIndex)) . "'";
                }
            } else {
                foreach ($fields as $field) {
                    if (hasIt($field->options, 'unique', HASIT_WANT_PREFIX)) {
                        $uniqueField = "'" . $field->name . "'";
                        break;
                    }
                }
            }
            if ($uniqueField === '') {
                $uniqueField = "'id'";
            }
            $template = str_replace('{{field:unique}}', $uniqueField, $template);
        }
        $template = GeneratorsServiceProvider::replaceTemplateLines($template, '{{field:line}}', function ($line, $fieldVar) use($fields) {
            $fieldText = '';
            foreach ($fields as $field) {
                $fieldText .= str_replace($fieldVar, $field->name, $line) . "\n";
            }
            if ($fieldText === '') {
                $fieldText = "''";
            }
            return $fieldText;
        });
        // add only unique lines
        $template = GeneratorsServiceProvider::replaceTemplateLines($template, '{{relations:line:with_model}}', function ($line, $fieldVar) use($fields, $relationModelList, $modelVars) {
            // we don't need the marker
            $line = str_replace($fieldVar, '', $line);
            $fieldText = '';
            $fieldTexts = [];
            if ($modelVars) {
                // add model
                $text = GeneratorsServiceProvider::replaceModelVars($line, $modelVars, '{{relations:', '}}') . "\n";
                if (array_search($text, $fieldTexts) === false) {
                    $fieldText .= $text;
                    $fieldTexts[] = $text;
                }
            }
            foreach ($fields as $field => $type) {
                // here we override for foreign keys
                if (array_key_exists($field, $relationModelList)) {
                    $relationModelVars = $relationModelList[$field];
                    // Replace template vars
                    $text = GeneratorsServiceProvider::replaceModelVars($line, $relationModelVars, '{{relations:', '}}') . "\n";
                    if (array_search($text, $fieldTexts) === false) {
                        $fieldText .= $text;
                        $fieldTexts[] = $text;
                    }
                }
            }
            return $fieldText;
        });
        $template = GeneratorsServiceProvider::replaceTemplateLines($template, '{{field:line:bool}}', function ($line, $fieldVar) use($fields, $modelVars) {
            $fieldText = '';
            foreach ($fields as $field) {
                if (GeneratorsServiceProvider::isFieldBoolean($field->type)) {
                    $fieldText .= str_replace($fieldVar, $field->name, $line) . "\n";
                }
            }
            return $fieldText;
        });
        $rules = [];
        $guarded = [];
        $hidden = [];
        $notrail = [];
        $notrailonly = [];
        $dates = [];
        $defaults = [];
        $fieldText = '';
        $bitsets = [];
        foreach ($fields as $field) {
            if ($field->name !== 'id') {
                if ($fieldText) {
                    $fieldText .= ', ';
                }
                $fieldText .= $field->name . ":" . implode(':', $field->options);
            }
            if (GeneratorsServiceProvider::isFieldDateTimeType($field->type)) {
                $dates[] = "'{$field->name}'";
            }
            if (!hasIt($field->options, ['hidden', 'guarded'], HASIT_WANT_PREFIX)) {
                $ruleBits = [];
                if ($rule = hasIt($field->options, 'rule', HASIT_WANT_PREFIX | HASIT_WANT_VALUE)) {
                    $rule = substr($rule, strlen('rule('), -1);
                    $ruleBits[] = $rule;
                }
                if ($default = hasIt($field->options, 'default', HASIT_WANT_PREFIX | HASIT_WANT_VALUE)) {
                    $default = substr($default, strlen('default('), -1);
                    $defaults[$field->name] = $default;
                } elseif (hasIt($field->options, 'nullable', HASIT_WANT_PREFIX)) {
                    $defaults[$field->name] = null;
                }
                if (array_search('sometimes', $ruleBits) === false && !array_key_exists($field->name, $defaults) && !GeneratorsServiceProvider::isFieldBoolean($field->type) && !hasIt($field->options, ['nullable', 'hidden', 'guarded'], HASIT_WANT_PREFIX)) {
                    $ruleBits[] = 'required';
                }
                if ($field->name === 'email') {
                    array_unshift($ruleBits, 'email');
                }
                $ruleType = GeneratorsServiceProvider::getFieldRuleType($field->type);
                if ($ruleType) {
                    array_unshift($ruleBits, $ruleType);
                }
                if (hasIt($field->options, ['unique'], HASIT_WANT_PREFIX)) {
                    $ruleBits[] = "unique:{$modelVars['snake_models']},{$field->name},{{id}}";
                }
                // here we override for foreign keys
                if (array_key_exists($field->name, $relationModelList)) {
                    $relationsVars = $relationModelList[$field->name];
                    $table_name = $relationsVars['snake_models'];
                    $ruleBits[] = "exists:{$table_name},id";
                }
                // Laravel 5.3 compatibility requirement
                if ($ruleBits && !array_search('required', $ruleBits) && array_key_exists($field->name, $defaults) && ($defaults[$field->name] === null || strtolower($defaults[$field->name]) === 'null')) {
                    array_unshift($ruleBits, 'nullable');
                }
                $rules[$field->name] = "'{$field->name}' => '" . implode('|', $ruleBits) . "'";
            }
            // bitset is an option so that the size of the field can be set with normal type
            if ($bitset = hasIt($field->options, 'bitset', HASIT_WANT_PREFIX | HASIT_WANT_VALUE)) {
                $bitsets[$field->name] = [];
                $params = preg_match('/bitset\\((.*)\\)/', $bitset, $matches) ? $matches[1] : '';
                if ($params === '') {
                    $params = $field->name;
                }
                $params = explode(',', $params);
                $bitMask = 1;
                foreach ($params as $param) {
                    $bitsets[$field->name][trim($param)] = $bitMask;
                    $bitMask <<= 1;
                }
            }
            if (hasIt($field->options, 'notrail', HASIT_WANT_PREFIX)) {
                $notrail[] = "'{$field->name}'";
            }
            if (hasIt($field->options, 'hidden', HASIT_WANT_PREFIX)) {
                $hidden[] = "'{$field->name}'";
            }
            if (hasIt($field->options, 'guarded', HASIT_WANT_PREFIX)) {
                $guarded[] = "'{$field->name}'";
            }
            if (hasIt($field->options, 'notrailonly', HASIT_WANT_PREFIX)) {
                $notrailonly[] = "'{$field->name}'";
            }
        }
        $defaultValues = [];
        foreach ($defaults as $field => $value) {
            if ($value === null || strtolower($value) === 'null') {
                $value = 'null';
            } elseif (!(GeneratorsServiceProvider::isFieldNumeric($fields[$field]->type) || GeneratorsServiceProvider::isFieldBoolean($fields[$field]->type))) {
                if (!(str_starts_with($value, "'") && str_ends_with($value, "'") || str_starts_with($value, '"') && str_ends_with($value, '"'))) {
                    $value = str_replace("'", "\\'", $value);
                    $value = "'{$value}'";
                }
            }
            $defaultValues[] = "'{$field}' => {$value}";
        }
        if (strpos($template, '{{bitset:') !== false) {
            // create the data for processing bitsets
            $bitsetData = '';
            $bitsetFields = [];
            $bitsetMaps = [];
            $bitsetAttributes = '';
            foreach ($bitsets as $bitset => $bits) {
                $bitsetName = strtoupper($bitset);
                $bitsetData .= "const {$bitsetName}_NONE = '';\n";
                foreach ($bits as $bit => $bitMask) {
                    $bitName = strtoupper($bit);
                    $bitsetData .= "\tconst {$bitsetName}_{$bitName} = '{$bit}';\n";
                    $bitModelVars = GeneratorsServiceProvider::getModelVars($bit);
                    $bitAttribute = $bitModelVars['CamelModel'];
                    $bitsetAttributes .= <<<PHP
    /**
     * @return boolean
     */
    public
    function get{$bitAttribute}Attribute()
    {
        return !!(\$this->{$bitset} & self::{$bitsetName}_{$bitName}_MASK);
    }

    /**
     * @param boolean \$value
     */
    public
    function set{$bitAttribute}Attribute(\$value)
    {
        if (\$value) {
            \$this->{$bitset} |= self::{$bitsetName}_{$bitName}_MASK;
        } else {
            \$this->{$bitset} &= ~self::{$bitsetName}_{$bitName}_MASK;
        }
    }

PHP;
                }
                $bitsetData .= "\n\tconst {$bitsetName}_NONE_MASK = 0;\n";
                foreach ($bits as $bit => $bitMask) {
                    $bitName = strtoupper($bit);
                    $bitsetData .= "\tconst {$bitsetName}_{$bitName}_MASK = {$bitMask};\n";
                }
                $bitsetData .= "\n\tpublic static \${$bitset}_bitset = [\n";
                foreach ($bits as $bit => $bitMask) {
                    $bitName = strtoupper($bit);
                    $bitsetData .= "\t\tself::{$bitsetName}_{$bitName} => self::{$bitsetName}_{$bitName}_MASK,\n";
                }
                $bitsetData .= "\t];\n";
                $bitsetFields[] = "'{$bitset}'";
                $bitsetMaps[] = "'{$bitset}' => self::\${$bitset}_bitset";
            }
            $template = str_replace('{{bitset:data}}', $bitsetData, $template);
            $template = str_replace('{{bitset:fields}}', implode(',', $bitsetFields), $template);
            $template = str_replace('{{bitset:maps}}', implode(',', $bitsetMaps), $template);
            $template = str_replace('{{bitset:attributes}}', $bitsetAttributes, $template);
            if (strpos($template, '{{bitset:line}}') !== false) {
                $template = GeneratorsServiceProvider::replaceTemplateLines($template, '{{bitset:line}}', function ($line, $fieldVar) use($fields, $modelVars) {
                    $line = str_replace($fieldVar, '', $line);
                    $text = '';
                    foreach ($fields as $field => $type) {
                        if (hasIt($type->options, 'bitset', HASIT_WANT_PREFIX | HASIT_WANT_VALUE)) {
                            $fieldModelVars = GeneratorsServiceProvider::getModelVars($field);
                            $allVars = array_merge($modelVars, $fieldModelVars);
                            $allVars['field'] = $field;
                            $text .= GeneratorsServiceProvider::replaceModelVars($line, $allVars, '{{bitset:', '}}') . "\n";
                        }
                    }
                    return $text;
                });
            }
        }
        $template = str_replace('{{fields}}', $fieldRawText, $template);
        $template = str_replace('{{rules}}', $this->implodeOneLineExpansion($rules), $template);
        $template = str_replace('{{hidden}}', $this->implodeOneLineExpansion($hidden), $template);
        $template = str_replace('{{guarded}}', $this->implodeOneLineExpansion($guarded), $template);
        $template = str_replace('{{dates}}', $this->implodeOneLineExpansion($dates), $template);
        $template = str_replace('{{notrail}}', $this->implodeOneLineExpansion($notrail), $template);
        $template = str_replace('{{notrailonly}}', $this->implodeOneLineExpansion($notrailonly), $template);
        $template = str_replace('{{defaults}}', $this->implodeOneLineExpansion($defaultValues), $template);
        return $template;
    }
Example #9
0
 /**
  * Get the console command options.
  *
  * @return array
  */
 protected function getOptions()
 {
     return $this->mergeOptions(array(array('path', null, InputOption::VALUE_OPTIONAL, 'Path to views directory.', ''), array('template', null, InputOption::VALUE_OPTIONAL, 'Path to template.', GeneratorsServiceProvider::getTemplatePath('view.txt'))));
 }
Example #10
0
    /**
     * Add Laravel methods, as string,
     * for the fields
     *
     * @param string $modelVars
     *
     * @param bool   $disable
     *
     * @param bool   $onlyBoolean
     * @param bool   $noBoolean
     * @param bool   $useOp
     *
     * @return string
     * @internal param $model
     */
    public function makeFormElements($modelVars, $disable = false, $onlyBoolean = false, $noBoolean = false, $useOp = false, $filterRows = false)
    {
        $formMethods = [];
        $relationModelList = GeneratorsServiceProvider::getRelationsModelVarsList(GeneratorsServiceProvider::splitFields($this->cache->getFields(), true));
        $fields = GeneratorsServiceProvider::splitFields($this->cache->getFields(), SCOPED_EXPLODE_WANT_ID_TYPE_OPTIONS | SCOPED_EXPLODE_WANT_TEXT);
        $models = $modelVars['models'];
        $model = $modelVars['model'];
        $camelModel = $modelVars['camelModel'];
        $CamelModel = $modelVars['CamelModel'];
        $narrowText = " input-narrow";
        $dash_models = $modelVars['dash-models'];
        foreach ($fields as $name => $values) {
            $type = $values['type'];
            $options = $values['options'];
            $nameModelVars = GeneratorsServiceProvider::getModelVars($name);
            if (strpos($options, 'hidden') !== false) {
                continue;
            }
            $nullable = strpos($options, 'nullable') !== false;
            if (strpos($options, 'guarded') !== false) {
                if ($useOp) {
                    $readonly = true ? "['readonly', " : '[';
                    $readonlyHalf = '[true ? \'readonly\' : ';
                    $readonlyClose = ']';
                    $disabled = true ? "'disabled', " : '';
                } else {
                    $readonly = $disable ? "['readonly', " : '[';
                    $readonlyHalf = "[{$disable} ? 'readonly' : ";
                    $readonlyClose = ']';
                    $disabled = $disable ? "'disabled', " : '';
                }
            } else {
                if ($useOp) {
                    $readonly = '[isViewOp($op) ? \'readonly\' : \'\',';
                    $readonlyHalf = '[isViewOp($op) ? \'readonly\' : ';
                    $readonlyClose = ']';
                    $disabled = 'isViewOp($op) ? \'disabled\' : \'\',';
                } else {
                    $readonly = $disable ? "['readonly', " : '[';
                    $readonlyHalf = "[{$disable} ? 'readonly' : ";
                    $readonlyClose = ']';
                    $disabled = $disable ? "'disabled', " : '';
                }
            }
            $limit = null;
            $useShort = false;
            if (str_contains($type, '[')) {
                if (preg_match('/([^\\[]+?)\\[(\\d+)(?:\\,\\d+)?\\]/', $type, $matches)) {
                    $type = $matches[1];
                    // string
                    $limit = $matches[2];
                    // 50{,...,}
                }
            }
            if (preg_match('/\\btextarea\\b/', $options)) {
                // treat it as text with multiple rows
                $type = 'text';
            }
            $foreignTable = '';
            if (preg_match('/\\btable\\(([^)]+)\\)\\b/', $options, $matches)) {
                // treat it as text with multiple rows
                $foreignTable = $matches[1];
            }
            $is_bitset_field = preg_match('/\\bbitset\\b/', $options);
            if (($type === 'boolean' || $is_bitset_field) && $noBoolean) {
                continue;
            }
            if ($type !== 'boolean' && !$is_bitset_field && $onlyBoolean) {
                continue;
            }
            $trans_name = $name;
            $labelName = $trans_name;
            $labelGroup = $dash_models;
            $afterElement = '';
            $afterElementFilter = '';
            $wrapRow = !$onlyBoolean;
            $inputNarrow = GeneratorsServiceProvider::isFieldNumeric($type) || $type === 'string' && $limit < 32 ? $narrowText : '';
            if ($is_bitset_field) {
                if ($filterRows) {
                    $formMethods[] = <<<PHP
                @foreach({{app_namespace}}\\{$CamelModel}::\${$name}_bitset as \$type => \$flag)
                <td>{!! \\Form::select(\$type, ['' => '&nbsp;', '0' => '0', '1' => '1', ], Input::get(\$type), ['form' => 'filter-{$models}', 'class' => 'form-control', ]) !!}</td>
                @endforeach
PHP;
                } else {
                    if ($wrapRow) {
                        $formMethods[] = <<<PHP
@foreach({{app_namespace}}\\{$CamelModel}::\${$name}_bitset as \$type => \$flag)
            <div class="row">
                <label>
                    {!! Form::checkbox(\$type, 1, Input::old(\$type), [{$disabled}]) !!} @lang('{$labelGroup}.{$labelName}')&nbsp;&nbsp;
                </label>
            </div>
                @endforeach
PHP;
                    } else {
                        $formMethods[] = <<<PHP
@foreach({{app_namespace}}\\{$CamelModel}::\${$name}_bitset as \$type => \$flag)
                <label>
                    {!! Form::checkbox(\$type, 1, Input::old(\$type), [{$disabled}]) !!} @lang('{$labelGroup}.{$labelName}')&nbsp;&nbsp;
                </label>
                @endforeach
PHP;
                    }
                }
            } else {
                switch ($type) {
                    case 'mediumInteger':
                    case 'smallInteger':
                    case 'tinyInteger':
                        $element = "{!! Form::input('number', '{$name}', Input::old('{$name}'), {$readonly}'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), {$readonlyClose}) !!}";
                        $elementFilter = "{!! Form::input('number', '{$name}', Input::get('{$name}'), ['form' => 'filter-{$models}', 'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), ]) !!}";
                        break;
                    case 'bigInteger':
                    case 'integer':
                        if (array_key_exists($name, $relationModelList)) {
                            // assume foreign key
                            $afterElement = "";
                            $foreignModelVars = $relationModelList[$name];
                            $foreignModels = $foreignModelVars['camelModels'];
                            $foreignmodels = $foreignModelVars['models'];
                            $foreign_model = $foreignModelVars['snake_model'];
                            $foreign_models = $foreignModelVars['snake_models'];
                            $foreign_display = $foreignModelVars['name'];
                            $plainName = trim_suffix($name, '_id');
                            $labelName = $plainName;
                            $element = "{!! Form::select('{$name}', [0 => ''], \${$foreignModels},  Input::old('{$name}'), [{$disabled}'class' => 'form-control', ]) !!}";
                            if ($nullable) {
                                $element .= "\n{!! Form::text('{$plainName}', \${$camelModel} ? (\${$camelModel}->{$plainName} ? \${$camelModel}->{$plainName}->{$foreign_display} : '') : '', {$readonlyHalf}'data-vsch_completion'=>'{$foreign_models}:{$foreign_display};id:{$name}','class' => 'form-control', {$readonlyClose}) !!}";
                            } else {
                                $element .= "\n{!! Form::text('{$plainName}', \${$camelModel} ? \${$camelModel}->{$plainName}->{$foreign_display} : '', {$readonlyHalf}'data-vsch_completion'=>'{$foreign_models}:{$foreign_display};id:{$name}','class' => 'form-control', {$readonlyClose}) !!}";
                            }
                            $elementFilter = "{!! Form::text('{$foreign_model}', Input::get('{$foreign_model}'), ['form' => 'filter-{$models}', 'data-vsch_completion'=>'{$foreign_models}:{$foreign_display};id:{$name}','class'=>'form-control', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), ]) !!}";
                            if ($filterRows) {
                                $afterElementFilter .= "{!! Form::hidden('{$name}', Input::old('{$name}'), ['form' => 'filter-{$models}', 'id'=>'{$name}']) !!}";
                            } else {
                                $afterElementFilter .= "{!! Form::hidden('{$name}', Input::old('{$name}'), ['id'=>'{$name}']) !!}";
                            }
                            //$labelName = $foreignModelVars['model'];
                            //$labelGroup = $foreignModelVars['dash-models'];
                            if ($useOp) {
                                $afterElement .= "\n\t\n@if(\$op === 'create' || \$op === 'edit')";
                            }
                            $afterElement .= "\n\t<div class='form-group col-sm-1'>\n\t\t\t<label>&nbsp;</label>\n\t\t\t<br>\n\t\t\t<a href=\"@route('{$foreignmodels}.create')\" @linkAsButton('warning')>@lang('messages.create')</a>\n</div>";
                            if ($useOp) {
                                $afterElement .= "\n@endif";
                            }
                            $element .= "\n\t\t\t" . $afterElementFilter;
                        } else {
                            $element = "{!! Form::input('number', '{$name}', Input::old('{$name}'), {$readonly}'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), {$readonlyClose}) !!}";
                            $elementFilter = "{!! Form::input('number', '{$name}', Input::get('{$name}'), ['form' => 'filter-{$models}', 'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), ]) !!}";
                        }
                        break;
                    case 'text':
                        $limit = empty($limit) ? 256 : $limit;
                        $rowAttr = (int) ($limit / 64) ?: 1;
                        $element = "{!! Form::textarea('{$name}', Input::old('{$name}'), {$readonly}'class'=>'form-control', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), 'rows'=>'{$rowAttr}', {$readonlyClose}) !!}";
                        $elementFilter = "{!! Form::text('{$name}', Input::get('{$name}'), ['form' => 'filter-{$models}', 'class'=>'form-control', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), ]) !!}";
                        break;
                    case 'boolean':
                        $element = "{!! Form::checkbox('{$name}', 1, Input::old('{$name}'), [{$disabled}]) !!}";
                        $elementFilter = "{!! Form::select('{$name}', ['' => '&nbsp;', '0' => '0', '1' => '1', ], Input::get('{$name}'), ['form' => 'filter-{$models}', 'class' => 'form-control', ]) !!}";
                        $useShort = true;
                        break;
                    case 'date':
                    case 'dateTime':
                        $element = <<<HTML
<div class="input-group input-group-sm date">
    {!! Form::text('{$name}', Input::old('{$name}'), {$readonly}'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), {$readonlyClose}) !!}
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></span>
</div>
HTML;
                        $elementFilter = <<<HTML
<div class="input-group date">
    {!! Form::text('{$name}', Input::get('{$name}'), ['form' => 'filter-{$models}', 'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), ]) !!}
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></span>
</div>
HTML;
                        break;
                    case 'decimal':
                    case 'double':
                    case 'float':
                    case 'time':
                    case 'string':
                    default:
                        $element = "{!! Form::text('{$name}', Input::old('{$name}'), {$readonly}'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), {$readonlyClose}) !!}";
                        $elementFilter = "{!! Form::text('{$name}', Input::get('{$name}'), ['form' => 'filter-{$models}', 'class'=>'form-control{$inputNarrow}', 'placeholder'=>noEditTrans('{$dash_models}.{$trans_name}'), ]) !!}";
                        break;
                }
                if ($filterRows) {
                    $afterElementFilter = $afterElementFilter ? "\n\t\t\t\t" . $afterElementFilter : $afterElementFilter;
                    $frag = "\t\t\t\t<td>{$elementFilter}{$afterElementFilter}</td>";
                } elseif ($useShort) {
                    if ($wrapRow) {
                        $frag = <<<EOT
        <div class="row">
            <label>
                  {$element} @lang('{$labelGroup}.{$labelName}')
                  &nbsp;&nbsp;
            </label>{$afterElement}
        </div>

EOT;
                    } else {
                        $frag = <<<EOT
            <label>
                  {$element} @lang('{$labelGroup}.{$labelName}')
                  &nbsp;&nbsp;
            </label>{$afterElement}
EOT;
                    }
                } else {
                    if ($wrapRow) {
                        $frag = <<<EOT
        <div class="row">
            <div class="form-group col-sm-3">
                <label for="{$name}">@lang('{$labelGroup}.{$labelName}'):</label>
                  {$element}
            </div>
        </div>
        {$afterElement}
EOT;
                    } else {
                        $frag = <<<EOT
        <div class="form-group">
            <label for="{$name}">@lang('{$labelGroup}.{$labelName}'):</label>
              {$element}{$afterElement}
        </div>

EOT;
                    }
                }
                $formMethods[] = $frag;
            }
        }
        return implode(PHP_EOL, $formMethods);
    }
 /**
  * Get the console command options.
  *
  * @return array
  */
 protected function getOptions()
 {
     return $this->mergeOptions(array(array('path', null, InputOption::VALUE_OPTIONAL, 'Path to the language translations directory.', ''), array('template', null, InputOption::VALUE_OPTIONAL, 'Path to template.', GeneratorsServiceProvider::getTemplatePath('translations.txt')), array('lang', null, InputOption::VALUE_OPTIONAL, 'Path to template/lang scaffold directory.', '')));
 }
Example #12
0
 protected function getPath($path)
 {
     $migrationFile = strtolower(basename($path));
     return GeneratorsServiceProvider::uniquify(dirname($path) . '/' . date('Y_m_d_His') . '*_' . $migrationFile);
 }
 public static function getFieldRuleType($typeText)
 {
     $ruleType = '';
     list($type, $options) = self::fieldTypeOptions($typeText);
     if (!str_contains($options, ['hidden', 'guarded'])) {
         if (GeneratorsServiceProvider::isFieldBoolean($typeText)) {
             $ruleType = 'boolean';
         } elseif (GeneratorsServiceProvider::isFieldNumeric($typeText)) {
             $ruleType = 'numeric';
         } else {
             $ruleTypes = ['date' => 'date'];
             if (array_key_exists($type, $ruleTypes)) {
                 $ruleType = $ruleTypes[$type];
             }
         }
     }
     return $ruleType;
 }
 /**
  * Get the path to the template for a view.
  *
  * @return string
  */
 protected function getViewTemplatePath($view = 'view')
 {
     return GeneratorsServiceProvider::getTemplatePath($this->templateDirs, "views/{$view}.txt");
 }
Example #15
0
 /**
  * Get a form template by name
  *
  * @param  string $type
  *
  * @return string
  */
 protected function getTemplate($type = 'list')
 {
     return $this->file->get(GeneratorsServiceProvider::getTemplatePath(static::$templatePath, "{$type}.txt"));
 }
Example #16
0
 /**
  * Get template for a scaffold
  *
  * @param  string $template Path to template
  * @param         $className
  *
  * @return string
  */
 protected function getScaffoldedController($template, $className)
 {
     $template = $this->template;
     $modelVars = GeneratorsServiceProvider::getModelVars($this->cache->getModelName());
     // Replace template vars
     $template = GeneratorsServiceProvider::replaceModelVars($template, $modelVars);
     $template = $this->replaceLines($template, $modelVars);
     return $template;
 }
 /**
  * Get the path to the template for a controller.
  *
  * @return string
  */
 protected function getTestTemplatePath()
 {
     return GeneratorsServiceProvider::getTemplatePath($this->templateDirs, 'controller-test.txt');
 }