/** * {@inheritdoc} */ public function getSearchType() { if (property_exists($this, 'documentType')) { return $this->documentType; } return Str::singular($this->getTable()); }
/** * Render the field. * * @access public * @return mixed|string */ public function render() { switch ($this->getContext()) { case BaseField::CONTEXT_LIST: $values = []; foreach ($this->getValue() as $item) { $values[] = $item->{$this->getDisplayField()}; } return implode(', ', $values); break; case BaseField::CONTEXT_FORM: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel(); $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $relatedModel = get_class($relatedModel); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } $id = $this->getAdmin()->getFormBuilder()->getIdentifier(); $values = []; foreach ($relatedModel::where(Str::singular($baseModel->getTable()) . '_id', $id)->get() as $item) { $values[] = (string) $item->{$primaryKey}; } return View::make('krafthaus/bauhaus::models.fields._has_many')->with('field', $this)->with('items', $items)->with('values', $values); break; } }
/** * Get the table associated with the model. * * @return string */ public function getTable() { if (isset($this->table)) { return $this->table; } return str_replace('\\', '', Str::snake(Str::singular(class_basename($this)))); }
/** * Get the model related to the controller. * * @return string */ public function model() { $model = $this->getShortName(); $model = str_replace('Controller', null, $model); $model = Str::singular($model); return $model; }
/** * Format an Eloquent model. * * @param \Illuminate\Database\Eloquent\Model $model * * @return string */ public function formatEloquentModel($model) { $key = Str::singular($model->getTable()); if (!$model::$snakeAttributes) { $key = Str::camel($key); } return $this->encode([$key => $model->toArray()]); }
protected static function loadFixtures() { $system = new Filesystem(); foreach ($system->files(__DIR__ . '/../fixtures') as $file) { $fixture_name = Str::singular(basename($file, '.php')); $fixtures = (require $file); static::createFixtures($fixture_name, $fixtures); } }
public function setApiName($name) { $this->_api_name = Pluralizer::singular($name); $this->_collection_name = Str::studly(Str::singular(Str::slug($this->_api_name, " "))); if (!class_exists("AndrewLamers\\Chargify\\" . $this->_collection_name)) { eval("namespace Andrewlamers\\Chargify; class " . $this->_collection_name . " extends \\Andrewlamers\\Chargify\\Fluent {}"); } $this->_collection_name = "Andrewlamers\\Chargify\\" . $this->_collection_name; }
/** * Get resource. * * @return string */ protected function getResourceOption() { $name = $this->getNameInput(); $resource = $this->option('resource') ?: $name; if (Str::contains($resource, '/')) { $segments = explode('/', $resource); $resource = is_array($segments) ? end($segments) : $resource; } return Str::singular($resource); }
/** * get the names of the parent or nested resource */ private function getModelsName($nested = false) { $classBaseName = class_basename($this); $segments = explode('_', snake_case($classBaseName)); //the last segment should be the string 'controller' $modelName = $segments[0]; $nestedModelName = $segments[1]; $name = $nested ? $nestedModelName : $modelName; return Str::singular($name); }
/** * @param $name * @param bool $usePrefix * * @return bool|ModelEx */ public function getModel($name, bool $usePrefix = false) { try { $prefix = $usePrefix ? defined('MODEL_PREFIX') ? MODEL_PREFIX : 'M' : ''; $class = $this->normalize($prefix . ucfirst(Str::camel(Str::singular("{$name}"))), defined('MODEL_DIR') ? MODEL_DIR : 'App\\Model'); return class_exists($class) ? $class : false; } catch (\Throwable $e) { } return false; }
private function generateFields() { $fieldTemplate = $this->commandData->templatesHelper->getTemplate('field.blade', $this->viewsPath); $fieldsStr = ''; foreach ($this->commandData->inputFields as $field) { switch ($field['type']) { case 'text': $fieldsStr .= FormFieldsGenerator::text($fieldTemplate, $field) . "\n\n"; break; case 'textarea': $fieldsStr .= FormFieldsGenerator::textarea($fieldTemplate, $field) . "\n\n"; break; case 'password': $fieldsStr .= FormFieldsGenerator::password($fieldTemplate, $field) . "\n\n"; break; case 'email': $fieldsStr .= FormFieldsGenerator::email($fieldTemplate, $field) . "\n\n"; break; case 'file': $fieldsStr .= FormFieldsGenerator::file($fieldTemplate, $field) . "\n\n"; break; case 'checkbox': $fieldsStr .= FormFieldsGenerator::checkbox($fieldTemplate, $field) . "\n\n"; break; case 'radio': $fieldsStr .= FormFieldsGenerator::radio($fieldTemplate, $field) . "\n\n"; break; case 'number': $fieldsStr .= FormFieldsGenerator::number($fieldTemplate, $field) . "\n\n"; break; case 'date': if ($this->commandData->fromTable) { $fieldsStr .= FormFieldsGenerator::date2($fieldTemplate, $field) . "\n\n"; } else { $fieldsStr .= FormFieldsGenerator::date($fieldTemplate, $field) . "\n\n"; } break; case 'select': if ($this->commandData->fromTable) { $modelName = Str::lower(Str::singular($this->commandData->modelName)); $fieldsStr .= FormFieldsGenerator::select2($fieldTemplate, $field, false, $modelName) . "\n\n"; } else { $fieldsStr .= FormFieldsGenerator::select($fieldTemplate, $field) . "\n\n"; } break; } } $templateData = $this->commandData->templatesHelper->getTemplate('fields.blade', $this->viewsPath); $templateData = str_replace('$FIELDS$', $fieldsStr, $templateData); $templateData = str_replace('$MODEL_NAME_PLURAL_CAMEL$', $this->commandData->modelNamePluralCamel, $templateData); $fileName = 'fields.blade.php'; $path = $this->path . $fileName; $this->commandData->fileHelper->writeFile($path, $templateData); $this->commandData->commandObj->info('field.blade.php created'); }
/** * Function to get the minimum template variables * * @return array */ public function getTemplateVars() { $entity = $this->getEntityName(); $fieldData = $this->getFieldData(); $instance = Str::singular(Str::snake($entity)); $cols = array_keys($fieldData); $cells = array_map(function ($x) use($instance) { return "\${$instance}->{$x}"; }, $cols); return ['Entity' => Str::studly($entity), 'Entities' => Str::plural(Str::studly($entity)), 'collection' => Str::plural(Str::snake($entity)), 'instance' => $instance, 'fields' => $fieldData, 'headings' => $cols, 'cells' => $cells]; }
/** * Build the class with the given name. * * @param string $name * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException * @return string */ protected function buildClass($name) { $stub = parent::buildClass($name); list($resourceStub, $actionStub) = explode('#split', $stub); if ($this->option('model')) { $modelClass = Str::singular(str_replace('.', '\\', $this->getNameInput())); $resourceStub = str_replace(['DummyModelClass'], [$modelClass], $resourceStub); return trim($resourceStub); } return trim($actionStub); }
/** * Run a seeder. * * @param string $table */ public function seed($table) { $timer = microtime(true); $this->command->info('Seeding ' . $table); $this->call($table . 'TableSeeder'); // Log results $results = Str::singular($table); $results = $this->container['arrounded']->qualifyModel($results); if (class_exists($results)) { $timer = round(microtime(true) - $timer, 2); $this->command->comment(sprintf('-- %s entries created (%ss)', $results::count(), $timer)); } }
/** * Function to get the minimum template variables * * @return array */ public function getTemplateVars() { $entity = $this->getEntityName(); $fieldData = $this->getFieldData(); $form_rows = []; foreach ($fieldData as $property => $meta) { $display = Str::title(str_replace('_', ' ', $property)); $result['label'] = "{{ Form::label('{$property}', '{$display}:') }}"; $elementType = $this->getElementType($meta['type']); $result['element'] = "{{ Form::{$elementType}('{$property}') }}"; $form_rows[] = $result; } return ['Entity' => Str::studly($entity), 'Entities' => Str::plural(Str::studly($entity)), 'collection' => Str::plural(Str::snake($entity)), 'instance' => Str::singular(Str::snake($entity)), 'fields' => $fieldData, 'form_rows' => $form_rows]; }
public function write() { $pdo = $this->database->getConnection(); $tables = $pdo->select(sprintf("SELECT TABLE_NAME as `table`, COLUMN_NAME as pk FROM information_schema.columns WHERE table_schema = '%s' AND COLUMN_KEY = 'PRI'", $pdo->getDatabaseName())); foreach ($tables as $table) { $name = $table->table; if (!$this->resolver->getModel($name)) { $path = sprintf('%s/app/Model/%s.php', $this->bootLoader->getBaseDir(), ucfirst(Str::camel(Str::singular("{$name}")))); if (!file_exists($path)) { $this->writer->write($path, ['class' => $this->utils->filename($path), 'table' => $table->table, 'pk' => $table->pk], 'Created new model'); } } } }
public function process($data, $parentIdentifier = null, $parentModel = null, $isCollection = false) { $ids = array(); if ($data instanceof Collection) { foreach ($data as $model) { $this->process($model, $parentIdentifier, $parentModel, true); } } elseif ($data instanceof Model) { $key = $data->getKey(); foreach ($data->getRelations() as $relationIdentifier => $collection) { $this->process($collection, $relationIdentifier, $data); } $resolvedIdentifier = $this->getIdentifierFromModel($data, $parentModel); $identifier = is_null($resolvedIdentifier) ? $parentIdentifier : $resolvedIdentifier; if (!isset($this->response[$identifier][$key])) { $this->response[$identifier][$key] = $data->toArray(); } elseif (!is_null($parentModel)) { if ($isCollection) { $ids = array($key); $column = $resolvedIdentifier . '_ids'; } else { $ids = $key; $column = $resolvedIdentifier . '_id'; } if ($isCollection && isset($this->response[$identifier][$key][$column])) { $this->response[$identifier][$key][$column] = array_merge($this->response[$identifier][$key][$column], array($ids)); } elseif (!isset($this->response[$identifier][$key][$column])) { $this->response[$identifier][$key][$column] = $ids; } } if (!is_null($parentModel)) { $parentModel->setRelation($parentIdentifier, false); } if (!is_null($parentModel) && !$isCollection) { $column = $parentIdentifier . '_id'; $parentModel->{$column} = $ids; } } else { if (!is_null($parentModel)) { $parentModel->setRelation($parentIdentifier, false); $column = Str::singular($parentIdentifier) . '_id'; $parentModel->{$column} = null; } } return $this->response; }
/** * To XML conversion * * @param mixed $data * @param null $structure * @param null|string $basenode * @return string */ private function xmlify($data, $structure = null, $basenode = 'xml') { // turn off compatibility mode as simple xml throws a wobbly if you don't. if (ini_get('zend.ze1_compatibility_mode') == 1) { ini_set('zend.ze1_compatibility_mode', 0); } if ($structure == null) { $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><{$basenode} />"); } // Force it to be something useful if (!is_array($data) && !is_object($data)) { $data = (array) $data; } foreach ($data as $key => $value) { // convert our booleans to 0/1 integer values so they are // not converted to blanks. if (is_bool($value)) { $value = (int) $value; } // no numeric keys in our xml please! if (is_numeric($key)) { // make string key... $key = Str::singular($basenode) != $basenode ? Str::singular($basenode) : 'item'; } // replace anything not alpha numeric $key = preg_replace('/[^a-z_\\-0-9]/i', '', $key); // if there is another array found recrusively call this function if (is_array($value) or is_object($value)) { $node = $structure->addChild($key); // recursive call if value is not empty if (!empty($value)) { $this->xmlify($value, $node, $key); } } else { // add single node. $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8"); $structure->addChild($key, $value); } } // pass back as string. or simple xml object if you want! return $structure->asXML(); }
/** * Render the field. * * @access public * @return mixed|string */ public function render() { if ($this->getDisplayField() === null) { throw new \InvalidArgumentException(sprintf('Please provide a display field for the `%s` relation via the display(); method.', $this->getName())); } switch ($this->getContext()) { case BaseField::CONTEXT_LIST: $value = $this->getValue(); return $value->{$this->getDisplayField()}; break; case BaseField::CONTEXT_FILTER: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel(); $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } $column = Str::singular($relatedModel->getTable()) . '_id'; if (Input::has($column)) { $this->setValue(Input::get($column)); } return View::make('krafthaus/bauhaus::models.fields._belongs_to')->with('field', $this)->with('items', $items); break; case BaseField::CONTEXT_FORM: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel(); $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } if ($this->getValue() !== null) { $this->setValue($this->getValue()->{$primaryKey}); } return View::make('krafthaus/bauhaus::models.fields._belongs_to')->with('field', $this)->with('items', $items); break; } return $this->getValue(); }
/** * Function to get the minimum template variables * * @return array */ public function getTemplateVars() { $entity = $this->getEntityName(); $fieldData = $this->getFieldData(); $attributes = []; //get fake data for each property foreach ($fieldData as $property => $meta) { $attributes[$property] = $this->getAttributeMockValue($meta['type']); } //add override for specific cases like id, created_at etc $attributes['id'] = 1; $attributes['created_at'] = "'" . date('Y-m-d H:00:00') . "'"; $attributes['updated_at'] = "'" . date('Y-m-d H:00:00') . "'"; $mock_attribute_rows = []; //create a "row" for each entry foreach ($attributes as $key => $value) { $mock_attribute_rows[] = "'{$key}' => {$value},"; } return ['Entity' => Str::studly($entity), 'Entities' => Str::plural(Str::studly($entity)), 'collection' => Str::plural(Str::snake($entity)), 'instance' => Str::singular(Str::snake($entity)), 'fields' => $fieldData, 'mock_attributes' => $mock_attribute_rows, 'year' => (new DateTime())->format('Y')]; }
/** * Fill Options * * Boilerplate method to inflate generator options using defaults. * @param array $options Variables to pass to the view * @return array Options * @throws BadFunctionCallException If missing element/collection from $options */ protected function fillOptions($options) { // Need at least a name to use if (!isset($options['collection']) && !isset($options['element'])) { throw new BadFunctionCallException('A collection or element name is required.'); } // Set the default base path if none is if (!isset($options['basePath'])) { $options['basePath'] = $this->path; } $options['basePath'] = $this->trailingSeparator($options['basePath']); if (!isset($options['collection'])) { // Pluralize the element $options['collection'] = Str::plural($options['element']); } elseif (!isset($options['element'])) { // Singularize the collection $options['element'] = Str::singular($options['collection']); } // Set the model from the element if (!isset($options['model'])) { $options['model'] = Str::studly($options['element']); } // Set the controller from the model if (!isset($options['controller'])) { $options['controller'] = $options['model'] . 'Controller'; } // Assume an element if neither is specified if (!isset($options['isCollection']) && !isset($options['isElement'])) { $options['isElement'] = true; } // Assume PUT collection is false if (!isset($options['allowPutAll'])) { $options['allowPutAll'] = false; } // Assume DELETE collection is false if (!isset($options['allowDeleteAll'])) { $options['allowDeleteAll'] = false; } return $options; }
/** * Get the singular form of an English word. * * @param string $value * @return string */ function str_singular($value) { return Str::singular($value); }
/** * Get all models as a dictionary, alphabetically ordered. * * @param string $model * * @return array */ protected function getEntries($model, $orderBy = 'id') { $model = ucfirst($model); $model = Str::singular($model); return $model::orderBy($orderBy, 'ASC')->get()->lists('name', 'id'); }
/** * Get foreign key column name for the model. * * @param \Illuminate\Database\Eloquent\Model $model * * @return string */ protected function getForeignKey(Model $model) { return Str::singular($model->getTable()) . '_id'; }
/** * @return null|string Nested model relationship name. */ protected function nestedRelationshipColumn() { if (!$this->isValidNestedModelName()) { return null; } $singular = $this->pluralizedModels ? Str::singular($this->nestedModelName) : $this->nestedModelName; return Str::snake($singular) . '_id'; }
/** * Get foreign key column name for the model. * * @param \Illuminate\Database\Eloquent\Model $model * * @return string */ protected function getForeignKey(Model $model) { $table = $model->getTable(); if (array_key_exists($table, $this->foreignKeyLookup)) { return $this->foreignKeyLookup[$table]; } return Str::singular($table) . '_id'; }
/** * @param string $tableOne * @param string $tableTwo * @return string */ public function getDefaultJoinTableName($tableOne, $tableTwo) { $tables = [Str::singular($tableOne), Str::singular($tableTwo)]; sort($tables); return sprintf(implode('_', $tables)); }
/** * Format a resource parameter for usage. * * @param string $value * @return string */ public function getResourceWildcard($value) { if (isset($this->parameters[$value])) { $value = $this->parameters[$value]; } elseif (isset(static::$parameterMap[$value])) { $value = static::$parameterMap[$value]; } elseif ($this->parameters === 'singular' || static::$singularParameters) { $value = Str::singular($value); } return str_replace('-', '_', $value); }
/** * Take a guess at what the basic labels will be, based on the given name. * @return $this */ protected function guessLabels($name) { return $this->labels(['singular' => str_replace("_", " ", Str::singular($name)), 'plural' => str_replace("_", " ", Str::plural($name)), 'navigation' => str_replace("_", " ", Str::ucfirst($name)), 'slug' => Str::slug(Str::plural($name))]); }
/** * Get the contents of the model stub. * * @return string */ protected function getModelStub() { $stub = file_get_contents(__DIR__ . '/../Stubs/MetaModel.stub.php'); $name_parts = explode('_', $this->tableName()); $namespace = ''; for ($i = 0; $i < count($name_parts) - 1; $i++) { $namespace .= '\\' . Str::studly(Str::singular($name_parts[$i])); } $namespace = trim($namespace, '\\'); $class = Str::studly(Str::singular(end($name_parts))); $stub = str_replace('{{namespace}}', empty($namespace) ? '' : " namespace {$namespace};", $stub); $stub = str_replace('{{class}}', $class, $stub); $stub = str_replace('{{table}}', $this->tableName(), $stub); return $stub; }