sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function getDropdownValuesFromSource($source) { if (is_a($source, Enum::class, true)) { /** @var Enum $source */ return array_map( function ($value) { return (string) $value; }, $source::values() ); } if (is_a($source, DropdownStrategyInterface::class, true)) { /** @var DropdownStrategyInterface $source */ $source = app($source); return $source->values(); } return false; }
Returns values from a source FQN, if possible. @param string $source @return string[]|false
entailment
protected function getDropdownLabelsFromSource($source) { if (is_a($source, DropdownStrategyInterface::class, true)) { /** @var DropdownStrategyInterface $source */ $source = app($source); return $source->labels(); } return false; }
Returns display labels from a source FQN, if possible. @param string $source @return string[]|false
entailment
public function label() { if ($this->label_translated) { return cms_trans($this->label_translated); } if ($this->label) { return $this->label; } return ucfirst(str_replace('_', ' ', snake_case($this->key))); }
Returns display label for form field. @return string
entailment
public function permissions() { if (is_array($this->permissions)) { return $this->permissions; } if ($this->permissions) { return [ $this->permissions ]; } return []; }
Returns permissions required to use the field. @return string[]
entailment
protected function performCheck() { // Parameter overrules automatic detection $column = head($this->parameters) ?: $this->determineActiveColumn(); return ! $this->model->{$column}; }
Returns whether deletion is allowed. @return bool
entailment
protected function determineActiveColumn() { $info = $this->getModelInformation(); if ($info && $info->list->activatable && $info->list->active_column) { return $info->list->active_column; } return 'active'; }
Determines and returns name of active column. @return string
entailment
public function retrieve(Model $model, $source) { if ($this->isTranslated()) { return $model->translations->mapWithKeys(function (Model $model) { /** @var Taggable $model */ return [ $model->{config('translatable.locale_key', 'locale')} => $model->tagNames() ]; }); } return $model->tagNames(); }
Retrieves current values from a model @param Model|Taggable $model @param string $source @return mixed
entailment
protected function adjustValue($value) { if (is_string($value)) { $value = explode(';', $value); } if ( ! $value) { $value = []; } return array_filter($value); }
Adjusts a value for compatibility with taggable methods. @param mixed $value @return array
entailment
public function performStoreAfter(Model $model, $source, $value) { $value = $this->adjustValue($value); $model->retag($value); }
Stores a submitted value on a model, after it has been created (or saved). @param Model|Taggable $model @param mixed $source @param mixed $value
entailment
public function connect(array $config) { /** @var CouchbaseConnection $connection */ $connection = $this->connectionResolver->connection($config['driver']); return new CouchbaseQueue( $connection, $config['bucket'], $config['queue'], Arr::get($config, 'retry_after', 60) ); }
@param array $config @return CouchbaseQueue|\Illuminate\Contracts\Queue\Queue
entailment
protected function decorateFieldData(array $data) { $strategy = array_get($this->field->options, 'strategy'); $data['displayStrategy'] = null; $data['displaySource'] = $this->field->source() ?: $this->field->key(); if ($strategy) { $instance = $this->getListDisplayFactory()->make($strategy); // todo: resolve attribute information if we can? //$instance->setAttributeInformation(); $instance->setOptions(array_get($this->field->options, 'strategy_options', [])); $data['displayStrategy'] = $instance; $data['displaySource'] = array_get($this->field->options, 'strategy_source', $data['displaySource']); } return $data; }
Enriches field data before passing it on to the view. @param array $data @return array
entailment
protected function performCheck() { $relations = $this->determineRelations(); if ( ! count($relations)) { return true; } foreach ($relations as $relation) { if ($this->model->{$relation}()->count()) { return false; } } return true; }
Returns whether deletion is allowed. @return bool
entailment
protected function determineRelations() { if (count($this->parameters)) { return $this->parameters; } if ( ! ($info = $this->getModelInformation())) { return []; } return array_pluck($info->relations, 'method'); }
Determines and returns relation method names that should be checked. @return string[]
entailment
public function apply($query, array $parameters = []) { $info = $this->getModelInformation($query->getModel()); $column = $info && $info->list->active_column ?: 'active'; return $query->where($column, true); }
Applies contextual setup to a query/model. @param \Illuminate\Database\Eloquent\Builder $query @param array $parameters @return \Illuminate\Database\Eloquent\Builder
entailment
protected function loadComponents($paths) { $paths = array_unique(is_array($paths) ? $paths : (array) $paths); $paths = array_filter($paths, function ($path) { return is_dir($path); }); if (empty($paths)) { return; } $namespace = $this->app->getNamespace(); foreach ((new Finder())->in($paths)->exclude('Observers')->files() as $file) { $class = trim($namespace, '\\') . '\\' . str_replace( ['/', '.php'], ['\\', ''], Str::after( realpath($file->getPathname()), app_path() . DIRECTORY_SEPARATOR ) ); if (is_subclass_of($class, Component::class) && ! (new \ReflectionClass($class))->isAbstract() ) { $this->registerComponent($class); } } }
Load component class from the paths @param mixed $paths @throws \ReflectionException
entailment
protected function registerComponent($class) { $component = $this->app->make($class); if (! ($component instanceof ComponentInterface)) { throw new InvalidArgumentException( sprintf( 'Class "%s" must be instanced of "%s".', $component, ComponentInterface::class ) ); } if ($component instanceof Initializable) { $component->initialize(); } $component->addToNavigation(); $this->app['admin.components']->put($component->getName(), $component); }
register the component class @param string $class
entailment
public function getColumns($table, $connection = null) { $this->updateConnection($connection)->setUpDoctrineSchema(); $schema = $this->getSchemaBuilder(); $columns = $schema->getColumnListing($table); $columnData = []; foreach ($columns as $name) { $column = $schema->getConnection()->getDoctrineColumn($table, $name); $columnData[] = [ 'name' => $column->getName(), 'type' => $column->getType()->getName(), 'length' => $column->getLength(), 'values' => false, 'unsigned' => $column->getUnsigned(), 'nullable' => ! $column->getNotnull(), ]; } return $columnData; }
Returns column information for a given table. @param string $table @param string|null $connection optional connection name @return array
entailment
protected function updateConnection($connection) { if ($this->connection !== $connection) { $this->connection = $connection; $this->schemaSetUp = false; } return $this; }
Updates the connection name to use. @param null|string $connection @return $this
entailment
protected function setUpDoctrineSchema() { if ($this->schemaSetUp) { // @codeCoverageIgnoreStart return; // @codeCoverageIgnoreEnd } DB::connection($this->connection) ->getDoctrineSchemaManager() ->getDatabasePlatform() ->registerDoctrineTypeMapping('enum', 'string'); $this->schemaSetUp = true; }
Sets up the schema for the current connection.
entailment
public function getUploadPath(UploadedFile $file) { if (($path = $this->uploadPath)) { if (is_callable($path)) { $path = call_user_func($path, $file); } return trim($path, '/'); } return $this->getDefaultUploadPath($file); }
Get relative path of the upload file. @param \Illuminate\Http\UploadedFile $file @return \Closure|mixed|null|string
entailment
public function getUploadFileName(UploadedFile $file) { if (is_callable($this->uploadFileNameRule)) { return call_user_func($this->uploadFileNameRule, $file); } return $this->getDefaultFileName($file); }
Get a file name of the upload file. @param \Illuminate\Http\UploadedFile $file @return mixed|string
entailment
protected function checkScope($update = true) { $request = request(); if ($update && $request->exists('scope')) { $this->activeScope = $request->get('scope'); $this->markResetActivePage(); $this->storeActiveScopeInSession(); } else { $this->retrieveActiveScopeFromSession(); } // Check if active is valid, reset it othwerwise if ($this->activeScope && ! $this->isValidScopeKey($this->activeScope)) { $this->activeScope = null; $this->storeActiveScopeInSession(); } return $this; }
Checks for the active scope. @param bool $update @return $this
entailment
protected function applyScope(ExtendedRepositoryInterface $repository, $scope = null) { $scope = (null === $scope) ? $this->activeScope : $scope; $repository->clearScopes(); if ($this->hasActiveListParent()) { return $this; } if ($scope) { $info = $this->getModelInformation(); $method = $info->list->scopes[ $scope ]->method ?: $scope; $repository->addScope($method); } return $this; }
Applies the currently active scope to a repository. @param ExtendedRepositoryInterface $repository @param null|string $scope active if not given @return $this
entailment
protected function getScopeCounts() { if ( ! $this->areScopesEnabled()) { return []; } $info = $this->getModelInformation(); if ( ! $info->list->scopes || ! count($info->list->scopes)) { // @codeCoverageIgnoreStart return []; // @codeCoverageIgnoreEnd } $counts = []; $repository = $this->getModelRepository(); foreach (array_keys($info->list->scopes) as $key) { $this->applyScope($repository, $key); $query = $this->getModelRepository()->query(); $this->applyListParentToQuery($query); $counts[ $key ] = $query->count(); } return $counts; }
Returns total amount of matches for each available scope. @return int[] assoc, keyed by scope key
entailment
public function apply($query, $column, $direction = 'asc') { // Determine the best strategy to use for the column // (which may not even be a column on the model's own table) $strategy = $this->determineStrategy($query->getModel(), $column); if ($strategy) { $instance = app($strategy); if ( ! ($instance instanceof SortStrategyInterface)) { throw new UnexpectedValueException("{$strategy} is not a sort strategy"); } $instance->apply($query, $column, $direction); } return $query; }
Applies the sort to a query/model. @param \Illuminate\Database\Eloquent\Builder $query @param string $column @param string $direction asc|desc @return Builder
entailment
protected function determineStrategy(Model $model, $column) { if ($this->isColumnTranslated($model, $column)) { return $this->getStrategyForTranslated(); } if ($this->isColumnOnRelatedModel($model, $column)) { return $this->getStrategyForRelatedModelAttribute(); } if ($this->isColumnOnModelTable($model, $column)) { return $this->getStrategyForDirectAttribute(); } return false; }
Returns classname for the strategy to use or false if no strategy could be determined. @param Model $model @param string $column @return false|string
entailment
protected function isColumnTranslated(Model $model, $column) { $info = $this->getModelInformation($model); if ($info) { return ( $info->translated && array_key_exists($column, $info->attributes) && $info->attributes[$column]->translated ); } // Determine based on model itself if ( ! $this->hasTranslatableTrait($model)) return false; /** @var Translatable $model */ return $model->isTranslationAttribute($column); }
Returns whether the column is a translated attribute of the model. @param Model $model @param string $column @return bool
entailment
protected function isColumnOnModelTable(Model $model, $column) { $info = $this->getModelInformation($model); if ($info) { return ( array_key_exists($column, $info->attributes) && ! $info->attributes[$column]->translated ); } // Determine based on model itself return ($model->getKeyName() == $column || $model->isFillable($column) || $model->isGuarded($column)); }
Returns whether the column is a direct attribute of model. @param Model $model @param string $column @return bool
entailment
protected function hasTranslatableTrait($class) { $translatable = config('cms-models.analyzer.traits.translatable', []); if ( ! count($translatable)) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } return (bool) count(array_intersect($this->classUsesDeep($class), $translatable)); }
Returns whether a class has the translatable trait. @param mixed $class @return bool
entailment
protected function classUsesDeep($class) { $traits = []; // Get traits of all parent classes do { $traits = array_merge(class_uses($class), $traits); } while ($class = get_parent_class($class)); // Get traits of all parent traits $traitsToSearch = $traits; while ( ! empty($traitsToSearch)) { $newTraits = class_uses(array_pop($traitsToSearch)); $traits = array_merge($newTraits, $traits); $traitsToSearch = array_merge($newTraits, $traitsToSearch); }; foreach ($traits as $trait => $same) { $traits = array_merge(class_uses($trait), $traits); } return array_unique($traits); }
Returns all traits used by a class (at any level). @param mixed $class @return string[]
entailment
protected function registerCommands() { $this->app->singleton('cms.commands.models.cache-information', Commands\CacheModelInformation::class); $this->app->singleton('cms.commands.models.clear-information-cache', Commands\ClearModelInformationCache::class); $this->app->singleton('cms.commands.models.show-information', Commands\ShowModelInformation::class); $this->app->singleton('cms.commands.models.write-information', Commands\WriteModelInformation::class); $this->commands([ 'cms.commands.models.cache-information', 'cms.commands.models.clear-information-cache', 'cms.commands.models.show-information', 'cms.commands.models.write-information', ]); return $this; }
Register Model related CMS commands @return $this
entailment
protected function registerInterfaceBindings() { $this->app->bind(RepositoriesContracts\ModelRepositoryInterface::class, Repositories\ModelRepository::class); $this->app->bind(FactoriesContracts\ModelRepositoryFactoryInterface::class, Factories\ModelRepositoryFactory::class); $this->app->singleton(RepositoriesContracts\ModelReferenceRepositoryInterface::class, Repositories\ModelReferenceRepository::class); $this->app->bind(FormDataStorerInterface::class, FormDataStorer::class); $this->registerHelperInterfaceBindings() ->registerModelInformationInterfaceBindings() ->registerStrategyInterfaceBindings() ->registerFacadeBindings(); return $this; }
Registers interface bindings for various components. @return $this
entailment
protected function registerHelperInterfaceBindings() { $this->app->singleton(RouteHelperInterface::class, RouteHelper::class); $this->app->singleton(ModuleHelperInterface::class, ModuleHelper::class); $this->app->singleton(MetaReferenceDataProviderInterface::class, MetaReferenceDataProvider::class); $this->app->singleton(TranslationLocaleHelperInterface::class, TranslationLocaleHelper::class); $this->app->singleton(ModelListMemoryInterface::class, ModelListMemory::class); $this->app->singleton(ValidationRuleDecoratorInterface::class, ValidationRuleDecorator::class); $this->app->bind(ValidationRuleMergerInterface::class, ValidationRuleMerger::class); return $this; }
Registers interface bindings for helpers classes. @return $this
entailment
protected function registerModelInformationInterfaceBindings() { $this->app->singleton(RepositoriesContracts\ModelInformationRepositoryInterface::class, Repositories\ModelInformationRepository::class); $this->app->singleton(ModelInfoContracts\Collector\ModelInformationFileReaderInterface::class, ModelInformation\Collector\ModelInformationFileReader::class); $this->app->singleton(ModelInfoContracts\ModelInformationEnricherInterface::class, ModelInformation\Enricher\ModelInformationEnricher::class); $this->app->singleton(ModelInfoContracts\ModelInformationInterpreterInterface::class, ModelInformation\Interpreter\CmsModelInformationInterpreter::class); $this->app->singleton(ModelAnalyzerInterface::class, ModelAnalyzer::class); $this->app->singleton(DatabaseAnalyzerInterface::class, SimpleDatabaseAnalyzer::class); $this->app->singleton(ModelInfoContracts\Writer\ModelInformationWriterInterface::class, ModelInformation\Writer\CmsModelWriter::class); $this->app->singleton(RepositoriesContracts\CurrentModelInformationInterface::class, Repositories\CurrentModelInformation::class); return $this; }
Registers interface bindings for model information handling. @return $this
entailment
protected function registerStrategyInterfaceBindings() { $this->app->singleton(RepositoriesContracts\ActivateStrategyResolverInterface::class, Repositories\ActivateStrategies\ActivateStrategyResolver::class); $this->app->singleton(RepositoriesContracts\OrderableStrategyResolverInterface::class, Repositories\OrderableStrategies\OrderableStrategyResolver::class); $this->app->singleton(FactoriesContracts\FilterStrategyFactoryInterface::class, Factories\FilterStrategyFactory::class); $this->app->singleton(FactoriesContracts\ListDisplayStrategyFactoryInterface::class, Factories\ListDisplayStrategyFactory::class); $this->app->singleton(FactoriesContracts\ShowFieldStrategyFactoryInterface::class, Factories\ShowFieldStrategyFactory::class); $this->app->singleton(FactoriesContracts\FormFieldStrategyFactoryInterface::class, Factories\FormFieldStrategyFactory::class); $this->app->singleton(FactoriesContracts\FormStoreStrategyFactoryInterface::class, Factories\FormStoreStrategyFactory::class); $this->app->singleton(FactoriesContracts\ActionStrategyFactoryInterface::class, Factories\ActionStrategyFactory::class); $this->app->singleton(FactoriesContracts\DeleteStrategyFactoryInterface::class, Factories\DeleteStrategyFactory::class); $this->app->singleton(FactoriesContracts\DeleteConditionStrategyFactoryInterface::class, Factories\DeleteConditionStrategyFactory::class); $this->app->singleton(FactoriesContracts\ExportColumnStrategyFactoryInterface::class, Factories\ExportColumnStrategyFactory::class); $this->app->singleton(FactoriesContracts\ExportStrategyFactoryInterface::class, Factories\ExportStrategyFactory::class); return $this; }
Registers interface bindings for various strategies. @return $this
entailment
protected function registerFacadeBindings() { $this->app->bind('cms-models-modelinfo', RepositoriesContracts\CurrentModelInformationInterface::class); $this->app->bind('cms-translation-locale-helper', TranslationLocaleHelperInterface::class); return $this; }
Registers bindings for facade service names. @return $this
entailment
protected function registerEventListeners() { foreach ($this->events as $event => $listener) { Event::listen($event, $listener); } return $this; }
Registers listeners for events. @return $this
entailment
public function label() { if ($this->label_translated) { return cms_trans($this->label_translated); } if ($this->label) { return $this->label; } return ucfirst(str_replace('_', ' ', snake_case($this->source))); }
Returns display label for show field. @return string
entailment
public function get($id) { foreach ($this->instructions as $instruction) { if (!$instruction instanceof Node && !$instruction instanceof Subgraph) { continue; } if ($instruction->getId() == $id) { return $instruction; } } throw new \InvalidArgumentException(sprintf('Found no node or graph with id "%s" in "%s".', $id, $this->id)); }
Returns a node or a subgraph, given his id. @param string $id the identifier of the node/graph to fetch @return Node|Graph @throws InvalidArgumentException node or graph not found
entailment
public function getEdge(array $edge) { foreach ($this->instructions as $instruction) { if (!$instruction instanceof Edge) { continue; } if ($instruction->getList() == $edge) { return $instruction; } } $label = implode(' -> ', array_map(function ($edge) { if (is_string($edge)) { return $edge; } return implode(':', $edge); }, $edge)); throw new \InvalidArgumentException(sprintf('Found no edge "%s".', $label)); }
Returns an edge by its path. @param (string|string[])[] a path @return Edge @throws InvalidArgumentException path not found
entailment
public function set($name, $value) { if (in_array($name, array('graph', 'node', 'edge'))) { throw new \InvalidArgumentException(sprintf('Use method attr for setting %s', $name)); } $this->instructions[] = new Assign($name, $value); return $this; }
Adds an assignment instruction. @param string $name Name of the value to assign @param string $value Value to assign @throws \InvalidArgumentException @return Graph Fluid-interface
entailment
public function node($id, array $attributes = array()) { $this->instructions[] = new Node($id, $attributes, $this); return $this; }
Created a new node on graph. @param string $id Identifier of node @param array $attributes Attributes to set on node @return Graph Fluid-interface
entailment
public function edge($list, array $attributes = array()) { $this->instructions[] = $this->createEdge($list, $attributes, $this); return $this; }
Created a new edge on graph. @param array $list List of edges @param array $attributes Attributes to set on edge @return Graph Fluid-interface
entailment
public function beginEdge($list, array $attributes = array()) { return $this->instructions[] = $this->createEdge($list, $attributes, $this); }
Created a new edge on graph. @param array $list List of edges @param array $attributes Attributes to set on edge @return Edge
entailment
public function style(Model $model, $source) { if ( ! $this->attributeData) { return null; } switch ($this->attributeData->cast) { case AttributeCast::INTEGER: case AttributeCast::FLOAT: return 'column-right'; case AttributeCast::DATE: return 'column-date'; // default omitted on purpose } return null; }
Returns an optional style string for the list display value container. @param Model $model @param string $source source column, method name or value @return string|null
entailment
public function options() { if ($this->options && count($this->options)) { return $this->options; } if ( ! $this->listColumnData) { return []; } return $this->listColumnData->options(); }
Returns custom options. @return array
entailment
protected function getDropdownOptions() { $values = $this->getDropdownValues(); $labels = $this->getDropdownLabels(); // Make sure that labels are set for each value foreach ($values as $value) { if (isset($labels[ $value ])) continue; $labels[ $value ] = $value; } return array_intersect_key($labels, array_flip($values)); }
Returns dropdown options as an associative array with display labels for values. @return array
entailment
protected function getDropdownValues() { if ($source = array_get($this->field->options(), 'value_source')) { $values = $this->getDropdownValuesFromSource($source); if (false !== $values) { return $values; } } return array_get($this->field->options(), 'values', []); }
Returns values to include in the dropdown. @return string[]
entailment
protected function getDropdownLabels() { if ($source = array_get($this->field->options(), 'label_source')) { $labels = $this->getDropdownLabelsFromSource($source); if (false !== $labels) { return $labels; } } $labels = array_get($this->field->options(), 'labels_translated', []); if (count($labels)) { return array_map('cms_trans', $labels); } return array_get($this->field->options(), 'labels', []); }
Returns display labels to show in the dropdown, keyed by value. @return string[]
entailment
protected function getReferenceValue(Model $model, $strategy = null, $source = null) { $strategy = $this->determineModelReferenceStrategy($model, $strategy); // If we have no strategy at all to fall back on, use a hard-coded reference if ( ! $strategy) { return $this->getReferenceFallback($model); } if ( ! $source) { $source = $this->determineModelReferenceSource($model); } return $strategy->render($model, $source); }
Returns the model reference as a string. @param Model $model @param string|null $strategy optional reference strategy that overrides default @param string|null $source optional reference source that overrides default @return string
entailment
protected function determineModelReferenceStrategy(Model $model, $strategy = null) { if (null !== $strategy) { $strategy = $this->makeReferenceStrategyInstance($strategy); } if ( ! $strategy) { $strategy = $this->makeReferenceStrategy($model); } if ( ! $strategy) { $strategy = $this->getDefaultReferenceStrategyInstance(); } return $strategy; }
Returns the strategy reference instance for a model. @param Model $model @param string|null $strategy @return ReferenceStrategyInterface|null
entailment
protected function determineModelReferenceSource(Model $model) { $source = $this->getReferenceSource($model); // If we have no source to fall back on at all, use the model key if ( ! $source) { $source = $model->getKeyName(); } return $source; }
Returns the reference source string. @param Model $model @return null|string
entailment
protected function getReferenceFallback(Model $model) { // Use reference method if the model has one if (method_exists($model, 'getReferenceAttribute')) { return $model->reference; } if (method_exists($model, 'getReference')) { return $model->getReference(); } return (string) $model->getKey(); }
Returns the fall-back (for when no reference strategy is available). @param Model $model @return mixed|string
entailment
protected function makeReferenceStrategy(Model $model) { // Get model information for the model $information = $this->getInformationRepository()->getByModel($model); // If the model is not part of the CMS, fall back if ( ! $information) return null; $strategy = $information->reference->strategy; if ( ! $strategy) { $strategy = config('cms-models.strategies.reference.default-strategy'); } return $this->makeReferenceStrategyInstance($strategy); }
Returns strategy instance for getting reference string. @param Model $model @return null|ReferenceStrategyInterface
entailment
protected function getReferenceSource(Model $model, $source = null) { if (null === $source) { // Get model information for the model $information = $this->getInformationRepository()->getByModel($model); if ($information && $information->reference->source) { $source = $information->reference->source; } } if ( ! $source) return null; return $source; }
Returns the source to feed to the reference strategy. @param Model $model @param string|null $source @return string|null
entailment
protected function resolveReferenceStrategyClass($strategy) { if ( ! empty($strategy)) { if ( ! str_contains($strategy, '.')) { $strategy = config('cms-models.strategies.reference.aliases.' . $strategy, $strategy); } if (class_exists($strategy) && is_a($strategy, ReferenceStrategyInterface::class, true)) { return $strategy; } $strategy = $this->prefixReferenceStrategyNamespace($strategy); if (class_exists($strategy) && is_a($strategy, ReferenceStrategyInterface::class, true)) { return $strategy; } } return false; }
Resolves strategy assuming it is the class name or FQN of a sort interface implementation, or a configured alias. @param string $strategy @return string|false returns full class namespace if it was resolved succesfully
entailment
public function retrieve(Model $model, $source) { $data = [ 'longitude' => null, 'latitude' => null, 'location' => null, ]; if ($latitude = $this->getAttributeLatitude()) { $data['latitude'] = (float) parent::retrieve($model, $latitude); } if ($longitude = $this->getAttributeLongitude()) { $data['longitude'] = (float) parent::retrieve($model, $longitude); } if ($text = $this->getAttributeText()) { $data['location'] = parent::retrieve($model, $text); } return $data; }
Retrieves current values from a model @param Model $model @param string $source @return mixed
entailment
protected function getStrategySpecificRules(ModelFormFieldDataInterface $field = null) { $key = $this->formFieldData->key(); $rules = [ 'longitude' => [ 'numeric' ], 'latitude' => [ 'numeric' ], 'text' => [ 'string', 'nullable' ], ]; // Always require long/lat if the field itself is required // If not, only require them if the attributes are non-nullable (todo) $required = $this->formFieldData->required(); if ($required) { $rules[ 'longitude' ][] = 'required'; $rules[ 'latitude' ][] = 'required'; } else { $rules[ 'longitude' ][] = 'nullable'; $rules[ 'latitude' ][] = 'nullable'; } // todo: determine whether text column, if made available, is required return array_map( function (array $rules, $key) { return new ValidationRuleData($rules, $key); }, array_values($rules), array_keys($rules) ); }
Returns validation rules specific for the strategy. @param ModelFormFieldDataInterface|ModelFormFieldData $field @return array|false|null null to fall back to default rules.
entailment
protected function getAttributeLatitude() { $attribute = array_get($this->formFieldData->options(), 'latitude_name', 'latitude'); if ( ! $attribute) { $attribute = false; } return $attribute; }
Returns attribute name for the 'latitude' attribute. @return string|false
entailment
protected function getAttributeLongitude() { $attribute = array_get($this->formFieldData->options(), 'longitude_name', 'longitude'); if ( ! $attribute) { $attribute = false; } return $attribute; }
Returns attribute name for the 'longitude' attribute. @return string|false
entailment
protected function getAttributeText() { $attribute = array_get($this->formFieldData->options(), 'location_name', 'location'); if ( ! $attribute) { $attribute = false; } return $attribute; }
Returns attribute name for the 'location' text attribute. This stores a textual representation of the location. @return string|false
entailment
protected function renderedListFilterStrategies(array $values) { if ($this->getModelInformation()->list->disable_filters) { return []; } $views = []; foreach ($this->getModelInformation()->list->filters as $key => $data) { try { $instance = $this->getFilterFactory()->make($data->strategy, $key, $data); // @codeCoverageIgnoreStart } catch (\Exception $e) { $message = "Failed to make list filter strategy for '{$key}': \n{$e->getMessage()}"; throw new StrategyRenderException($message, $e->getCode(), $e); // @codeCoverageIgnoreEnd } try { $views[ $key ] = $instance->render($key, array_get($values, $key)); // @codeCoverageIgnoreStart } catch (\Exception $e) { $message = "Failed to render list filter '{$key}' for strategy " . get_class($instance) . ": \n{$e->getMessage()}"; throw new StrategyRenderException($message, $e->getCode(), $e); // @codeCoverageIgnoreEnd } } return $views; }
Renders Vies or HTML for list filter strategies. @param array $values active filter values @return View[]|\string[] @throws StrategyRenderException
entailment
protected function changeModelOrderablePosition(Model $model, $position) { /** @var OrderableStrategyResolverInterface $resolver */ $resolver = app(OrderableStrategyResolverInterface::class); $strategy = $resolver->resolve($this->getModelInformation()); return $strategy->setPosition($model, $position); }
Changes the orderable position for a model. @param Model $model @param string|int|null $position @return bool the new position of the model
entailment
public function openBucket(string $name): Bucket { $couchbase = $this->getCouchbase(); if ($this->bucketPassword === '') { return $couchbase->openBucket($name); } return $couchbase->openBucket($name, $this->bucketPassword); }
@param string $name @return Bucket
entailment
public function getOptions(Bucket $bucket): array { $options = []; foreach ($this->properties as $property) { $options[$property] = $bucket->$property; } return $options; }
@param Bucket $bucket @return string[]
entailment
protected function executeQuery(N1qlQuery $query) { $bucket = $this->openBucket($this->bucket); $this->registerOption($bucket); $this->firePreparedQuery($query); $result = $bucket->query($query); $this->fireReturning($result); return $result; }
@param N1qlQuery $query @return mixed
entailment
protected function execute(string $query, array $bindings = []) { $query = N1qlQuery::fromString($query); $query->consistency($this->consistency); $query->crossBucket($this->crossBucket); $query->positionalParams($bindings); $result = $this->executeQuery($query); $this->metrics = $result->metrics ?? []; return $result; }
@param string $query @param array $bindings @return \stdClass
entailment
public function select($query, $bindings = [], $useReadPdo = true) { return $this->run($query, $bindings, function ($query, $bindings) { if ($this->pretending()) { return []; } $result = $this->execute($query, $bindings); $returning = []; if (isset($result->rows)) { foreach ($result->rows as $row) { if (!isset($row->{$this->bucket})) { return [$row]; } $returning[] = $row; } } return $returning; }); }
{@inheritdoc}
entailment
public function affectingStatement($query, $bindings = []) { return $this->run($query, $bindings, function ($query, $bindings) { if ($this->pretending()) { return 0; } $query = N1qlQuery::fromString($query); $query->consistency($this->consistency); $query->crossBucket($this->crossBucket); $query->namedParams(['parameters' => $bindings]); $result = $this->executeQuery($query); $this->metrics = $result->metrics ?? []; if (!count($result->rows)) { return false; } return $result->rows[0]->{$this->bucket} ?? $result->rows[0]; }); }
{@inheritdoc}
entailment
public function positionalStatement(string $query, array $bindings = []) { return $this->run($query, $bindings, function ($query, $bindings) { if ($this->pretending()) { return 0; } $query = N1qlQuery::fromString($query); $query->consistency($this->consistency); $query->crossBucket($this->crossBucket); $query->positionalParams($bindings); $result = $this->executeQuery($query); $this->metrics = $result->metrics ?? []; if (!count($result->rows)) { return false; } return $result->rows[0]->{$this->bucket} ?? $result->rows[0]; }); }
@param string $query @param array $bindings @return mixed
entailment
public function view(string $bucket = null): View { $bucket = is_null($bucket) ? $this->bucket : $bucket; return new View($this->openBucket($bucket), $this->events); }
@param string|null $bucket @return View
entailment
public function setPdo($pdo) { $this->connection = $this->createConnection(); $this->getManagedConfigure($this->config); $this->useDefaultQueryGrammar(); $this->useDefaultPostProcessor(); return $this; }
@param null|\PDO $pdo @return $this
entailment
protected function performStep() { $this->info['verbose_name'] = strtolower(snake_case(class_basename($this->model()), ' ')); $this->info['verbose_name_plural'] = str_plural($this->info['verbose_name']); $this->info['translated_name'] = 'models.name.' . $this->info['verbose_name']; $this->info['translated_name_plural'] = 'models.name.' . $this->info['verbose_name_plural']; $this->info['incrementing'] = $this->model()->getIncrementing(); $this->info['timestamps'] = $this->model()->usesTimestamps(); $this->info['timestamp_created'] = $this->model()->getCreatedAtColumn(); $this->info['timestamp_updated'] = $this->model()->getUpdatedAtColumn(); }
Performs the analyzer step on the stored model information instance.
entailment
public function render(Model $model, $source) { $source = $this->resolveModelSource($model, $source); if ( ! ($source instanceof AttachmentInterface)) { throw new UnexpectedValueException("Paperclip strategy expects Attachment as source"); } return view(static::VIEW, [ 'exists' => $source->size() > 0, 'filename' => $source->originalFilename(), 'url' => $source->url(), ]); }
Renders a display value to print to the list view. @param Model $model @param mixed|AttachmentInterface $source source column, method name or value @return string|View
entailment
protected function generateExport($path = null) { $temporary = $this->getTemporaryFilePath(); // Prepare columns/strategies $this->columns = $this->exportInfo->columns; $this->columnStrategies = $this->getColumnStrategyInstances(); // Prepare headers/field keys $this->columnHeaders = array_map( function (ModelExportColumnDataInterface $column) { return $column->header(); }, $this->columns ); // Create data array $data = []; $this->fillDataArray($data); $formatter = Formatter::make($data, Formatter::ARR); file_put_contents($temporary, $formatter->toXml()); return $temporary; }
Generates an export, download or local file. @param null|string $path @return mixed @throws Exception
entailment
protected function fillDataArray(array &$data) { $this->query->chunk( static::CHUNK_SIZE, function ($records) use (&$data) { /** @var Collection|Model[] $records */ foreach ($records as $record) { $fields = []; foreach ($this->columnStrategies as $key => $strategy) { $fields[] = $strategy->render($record, $this->columns[$key]->source); } $data[] = array_combine($this->columnHeaders, $fields); } } ); }
Fills a data array with entries of key/value pairs ready for exporting. @param array $data by reference
entailment
public function index() { // For single-item display only, redirect to the relevant show/edit page if ($this->modelInformation->single) { return $this->returnViewForSingleDisplay(); } $this->resetStateBeforeIndexAction() ->checkListParents() ->applyListParentContext() ->checkActiveSort() ->checkScope() ->checkFilters() ->checkActivePage(); $totalCount = $this->getTotalCount(); $scopeCounts = $this->getScopeCounts(); $this->applySort() ->applyScope($this->modelRepository); $query = $this->getModelRepository()->query(); $this->applyFilter($query) ->applyListParentToQuery($query); $records = $query->paginate($this->getActualPageSize(), ['*'], 'page', $this->getActualPage()); // Check and whether page is out of bounds and adjust if ($this->getActualPage() > $records->lastPage()) { $records = $query->paginate($this->getActualPageSize(), ['*'], 'page', $records->lastPage()); } $currentCount = method_exists($records, 'total') ? $records->total() : 0; return view($this->getIndexView(), [ 'moduleKey' => $this->moduleKey, 'routePrefix' => $this->routePrefix, 'permissionPrefix' => $this->permissionPrefix, 'model' => $this->modelInformation, 'records' => $records, 'recordReferences' => $this->getReferenceRepository()->getReferencesForModels($records->items()), 'totalCount' => $totalCount, 'currentCount' => $currentCount, 'listStrategies' => $this->getListColumnStrategyInstances(), 'sortColumn' => $this->getActualSort(), 'sortDirection' => $this->getActualSortDirection(), 'pageSize' => $this->getActualPageSize(), 'pageSizeOptions' => $this->getPageSizeOptions(), 'filterStrategies' => $this->renderedListFilterStrategies($this->getActiveFilters()), 'activeScope' => $this->getActiveScope(), 'scopeCounts' => $scopeCounts, 'unconditionalDelete' => $this->isUnconditionallyDeletable(), 'defaultRowAction' => $this->getDefaultRowActionInstance(), 'hasActiveListParent' => (bool) $this->listParentRelation, 'listParents' => $this->listParents, 'topListParentOnly' => $this->showsTopParentsOnly(), 'draggableOrderable' => $this->isListOrderDraggable($totalCount, $currentCount), 'availableExportKeys' => $this->getAvailableExportStrategyKeys(), ]); }
Returns listing of filtered, sorted records. @return mixed
entailment
public function show($id) { $record = $this->modelRepository->findOrFail($id); $this->checkListParents(false); return view($this->getShowView(), [ 'moduleKey' => $this->moduleKey, 'routePrefix' => $this->routePrefix, 'permissionPrefix' => $this->permissionPrefix, 'model' => $this->modelInformation, 'record' => $record, 'recordReference' => $this->getReferenceRepository()->getReferenceForModel($record), 'fieldStrategies' => $this->renderedShowFieldStrategies($record), 'hasActiveListParent' => (bool) $this->listParentRelation, 'topListParentOnly' => $this->showsTopParentsOnly(), 'listParents' => $this->listParents, ]); }
Displays a single record. @param mixed $id @return mixed
entailment
public function create() { $record = $this->getNewModelInstance(); $fields = array_only( $this->modelInformation->form->fields, $this->getRelevantFormFieldKeys(true) ); $this->checkListParents(false); $values = $this->getFormFieldValuesFromModel($record, array_keys($fields)); $errors = $this->getNormalizedFormFieldErrors(); $renderedFields = $this->renderedFormFieldStrategies($record, $fields, $values, $errors); return view($this->getCreateView(), [ 'moduleKey' => $this->moduleKey, 'routePrefix' => $this->routePrefix, 'permissionPrefix' => $this->permissionPrefix, 'model' => $this->modelInformation, 'record' => $record, 'recordReference' => null, 'creating' => true, 'fields' => $fields, 'fieldStrategies' => $renderedFields, 'values' => $values, 'fieldErrors' => $errors, 'activeTab' => $this->getActiveTab(), 'errorsPerTab' => $this->getErrorCountsPerTabPane(), 'hasActiveListParent' => (bool) $this->listParentRelation, 'topListParentOnly' => $this->showsTopParentsOnly(), 'listParents' => $this->listParents, ]); }
Displays form to create a new record. @return mixed
entailment
public function store() { /** @var FormRequest $request */ $request = app($this->getCreateRequestClass()); $record = $this->getNewModelInstance(); $data = $request->only($this->getRelevantFormFieldKeys(true)); /** @var FormDataStorerInterface $storer */ $storer = app(FormDataStorerInterface::class); $storer->setModelInformation($this->getModelInformation()); if ( ! $storer->store($record, $data)) { // @codeCoverageIgnoreStart return redirect()->back() ->withInput() ->withErrors([ static::GENERAL_ERRORS_KEY => [ $this->getGeneralStoreFailureError() ], ]); // @codeCoverageIgnoreEnd } $this->storeActiveTab($request->input(static::ACTIVE_TAB_PANE_KEY)); cms_flash( cms_trans( 'models.store.success-message-create', [ 'record' => $this->getSimpleRecordReference($record->getKey(), $record) ] ), FlashLevel::SUCCESS ); event( new Events\ModelCreatedInCms($record) ); if ($request->input(static::SAVE_AND_CLOSE_KEY)) { return redirect()->route("{$this->routePrefix}.index"); } return redirect()->route("{$this->routePrefix}.edit", [ $record->getKey() ]); }
Processes submitted form to create a new record. @return mixed @event ModelCreatedInCms
entailment
public function edit($id) { $record = $this->modelRepository->findOrFail($id); $fields = array_only( $this->modelInformation->form->fields, $this->getRelevantFormFieldKeys() ); $this->checkListParents(false); $values = $this->getFormFieldValuesFromModel($record, array_keys($fields)); $errors = $this->getNormalizedFormFieldErrors(); $renderedFields = $this->renderedFormFieldStrategies($record, $fields, $values, $errors); return view($this->getEditView(), [ 'moduleKey' => $this->moduleKey, 'routePrefix' => $this->routePrefix, 'permissionPrefix' => $this->permissionPrefix, 'model' => $this->modelInformation, 'record' => $record, 'recordReference' => $this->getReferenceRepository()->getReferenceForModel($record), 'creating' => false, 'fields' => $fields, 'fieldStrategies' => $renderedFields, 'values' => $values, 'fieldErrors' => $errors, 'activeTab' => $this->getActiveTab(), 'errorsPerTab' => $this->getErrorCountsPerTabPane(), 'hasActiveListParent' => (bool) $this->listParentRelation, 'topListParentOnly' => $this->showsTopParentsOnly(), 'listParents' => $this->listParents, ]); }
Displays form to edit an existing record. @param mixed $id @return mixed
entailment
public function update($id) { /** @var FormRequest $request */ $request = app($this->getUpdateRequestClass()); $record = $this->modelRepository->findOrFail($id); $data = $request->only($this->getRelevantFormFieldKeys()); /** @var FormDataStorerInterface $storer */ $storer = app(FormDataStorerInterface::class); $storer->setModelInformation($this->getModelInformation()); if ( ! $storer->store($record, $data)) { // @codeCoverageIgnoreStart return redirect()->back() ->withInput() ->withErrors([ static::GENERAL_ERRORS_KEY => [ $this->getGeneralStoreFailureError() ], ]); // @codeCoverageIgnoreEnd } $this->storeActiveTab($request->input(static::ACTIVE_TAB_PANE_KEY)); cms_flash( cms_trans( 'models.store.success-message-edit', [ 'record' => $this->getSimpleRecordReference($id, $record) ] ), FlashLevel::SUCCESS ); event( new Events\ModelUpdatedInCms($record) ); if ($request->input(static::SAVE_AND_CLOSE_KEY)) { return redirect()->route("{$this->routePrefix}.index"); } return redirect()->route("{$this->routePrefix}.edit", [ $record->getKey() ]); }
Processes a submitted for to edit an existing record. @param mixed $id @return mixed @event ModelUpdatedInCms
entailment
public function destroy($id) { $record = $this->modelRepository->findOrFail($id); if ( ! $this->isModelDeletable($record)) { return $this->failureResponse( $this->getLastUnmetDeleteConditionMessage() ); } event( new Events\DeletingModelInCms($record) ); if ( ! $this->deleteModel($record)) { // @codeCoverageIgnoreStart return $this->failureResponse( cms_trans('models.delete.failure.unknown') ); // @codeCoverageIgnoreEnd } event( new Events\ModelDeletedInCms($this->getModelInformation()->modelClass(), $id) ); if (request()->ajax()) { return response()->json([ 'success' => true, ]); } cms_flash( cms_trans( 'models.delete.success-message', [ 'record' => $this->getSimpleRecordReference($id, $record) ] ), FlashLevel::SUCCESS ); return redirect()->back(); }
Deletes a record, if allowed. @param mixed $id @return mixed @event DeletingModelInCms @event ModelDeletedInCms
entailment
public function deletable($id) { $record = $this->modelRepository->findOrFail($id); if ( ! $this->isModelDeletable($record)) { return $this->failureResponse( $this->getLastUnmetDeleteConditionMessage() ); } return $this->successResponse(); }
Checks whether a model is deletable. @param mixed $id @return mixed
entailment
public function filter() { $this->updateFilters() ->checkActivePage(); $previousUrl = app('url')->previous(); $previousUrl = $this->removePageQueryFromUrl($previousUrl); return redirect()->to($previousUrl); }
Applies posted filters. @return mixed
entailment
public function activate(ActivateRequest $request, $id) { $record = $this->modelRepository->findOrFail($id); $success = false; $result = null; $activated = $request->get('activate'); if ($this->getModelInformation()->list->activatable) { $success = true; $result = $this->changeModelActiveState($record, $activated); } if ($activated) { event( new Events\ModelActivatedInCms($record) ); } else { event( new Events\ModelDeactivatedInCms($record) ); } if (request()->ajax()) { return response()->json([ 'success' => $success, 'active' => $result ]); } if ($success && config('cms-models.notifications.flash.activate')) { cms_flash( cms_trans( 'models.store.success-message-' . ($result ? 'activate' : 'deactivate'), [ 'record' => $this->getSimpleRecordReference($id, $record) ] ), FlashLevel::SUCCESS ); } return redirect()->back(); }
Activates/enables a record. @param ActivateRequest $request @param int $id @return mixed @event ModelActivatedInCms @event ModelDeactivatedInCms
entailment
public function position(OrderUpdateRequest $request, $id) { $record = $this->modelRepository->findOrFail($id); $success = false; $result = null; if ($this->getModelInformation()->list->orderable) { $success = true; $result = $this->changeModelOrderablePosition($record, $request->get('position')); } if ($success && config('cms-models.notifications.flash.position')) { cms_flash( cms_trans( 'models.store.success-message-position', [ 'record' => $this->getSimpleRecordReference($id, $record) ] ), FlashLevel::SUCCESS ); } event( new Events\ModelPositionUpdatedInCms($record) ); if (request()->ajax()) { return response()->json([ 'success' => $success, 'position' => $result ]); } return redirect()->back(); }
Changes orderable position for a record. @param OrderUpdateRequest $request @param int $id @return mixed @event ModelPositionUpdatedInCms
entailment
public function export($strategy) { // Check if the strategy is available and allowed to be used if ( ! $this->isExportStrategyAvailable($strategy)) { abort(403, "Not possible or allowed to perform export '{$strategy}'"); } // Prepare the strategy instance $exporter = $this->getExportStrategyInstance($strategy); $filename = $this->getExportDownloadFilename($strategy, $exporter->extension()); $this->checkListParents() ->checkActiveSort(false) ->checkScope(false) ->checkFilters() ->checkActivePage(false) ->applySort() ->applyScope($this->modelRepository); $query = $this->getModelRepository()->query(); $this->applyFilter($query) ->applyListParentToQuery($query); $download = $exporter->download($query, $filename); if (false === $download) { // @codeCoverageIgnoreStart abort(500, "Failed to export model listing for strategy '{$strategy}'"); // @codeCoverageIgnoreEnd } event( new Events\ModelListExportedInCms($this->modelInformation->modelClass(), $strategy) ); return $download; }
Exports the current listing with a given strategy. @param string $strategy @return false|mixed
entailment
protected function resetStateBeforeIndexAction() { $this->activeSort = null; $this->activeSortDescending = null; $this->activeScope = null; $this->filters = []; $this->activePage = null; $this->activePageSize = null; $this->resetActivePage = false; return $this; }
Resets the controller's state before handling the index action. @return $this
entailment
protected function removePageQueryFromUrl($url) { $parts = parse_url($url); $query = preg_replace('#page=\d+&?#i', '', array_get($parts, 'query', '')); return array_get($parts, 'path') . ($query ? '?' . $query : null); }
Removes the page query parameter from a full URL. @param string $url @return string
entailment
protected function getTotalCount() { $query = $this->modelRepository->query(); $this->applyListParentToQuery($query); return $query->count(); }
Returns total count of all models. @return int
entailment
protected function isListOrderDraggable($totalCount, $currentCount) { $info = $this->getModelInformation(); if ( ! $info->list->orderable) { return false; } $showTopParentsOnly = $this->showsTopParentsOnly(); $scopedRelation = $info->list->order_scope_relation; if ($showTopParentsOnly || $this->hasActiveListParent()) { // Check if the listify scope relation matches on the actively scoped list parent relation if ( ! $scopedRelation) { return false; } if ($showTopParentsOnly) { if ($scopedRelation != $info->list->default_top_relation) { return false; } } else { /** @var ListParentData $parent */ $parent = head($this->listParents); if ($scopedRelation != $parent->relation) { return false; } } } elseif ($scopedRelation) { // If there is a listify relation scope and the list is not scoped at all, never draggable return false; } $hasScope = (bool) $this->getActiveScope(); $hasFilters = ! empty($this->getActiveFilters()); return $info->list->getOrderableColumn() === $this->getActualSort() && ( $totalCount == $currentCount || ( ! $hasScope && ! $hasFilters) ); }
Returns whether, given the current circumstances, the list may be ordered by dragging rows. @param int $totalCount @param int $currentCount @return bool
entailment
protected function returnViewForSingleDisplay() { $record = $this->modelRepository->first(); if ($record) { return $this->edit($record->getKey()); } return $this->create(); }
Returns a create/edit view for a single-item only model record setup. @return mixed
entailment
protected function failureResponse($error = null) { if (request()->ajax()) { return response()->json([ 'success' => false, 'error' => $error, ]); } return redirect()->back()->withErrors([ 'general' => $error, ]); }
Returns standard failure response. @param string|null $error @return mixed
entailment
protected function getSimpleRecordReference($key, Model $record = null) { return ucfirst($this->modelInformation->label()) . ' #' . $key; }
Returns a simple reference. @param mixed $key @param Model|null $record @return string
entailment
protected function getModelSessionKey($modelSlug = null) { $modelSlug = (null === $modelSlug) ? $this->getModelSlug() : $modelSlug; return $this->core->config('session.prefix') . 'model:' . $modelSlug; }
Returns session key to use for storing information about the model (listing). This is used as the 'context' by the list memory. @param string|null $modelSlug defaults to current model @return string
entailment
protected function getActiveTab($pull = true) { $key = $this->getModelSessionKey() . ':' . static::ACTIVE_TAB_SESSION_KEY; if ($pull) { return session()->pull($key); } return session()->get($key); }
Returns the active edit form tab pane key, if it is set. @param bool $pull if true, pulls the value from the session @return null|string
entailment
protected function storeActiveTab($tab) { $key = $this->getModelSessionKey() . ':' . static::ACTIVE_TAB_SESSION_KEY; if (null === $tab) { session()->forget($key); } else { session()->put($key, $tab); } return $this; }
Stores the currently active edit form tab pane key. @param string|null $tab @return $this
entailment
protected function deleteModel(Model $model) { $strategy = $this->getModelInformation()->deleteStrategy(); if ( ! $strategy) { return $model->delete(); } /** @var DeleteStrategyFactoryInterface $factory */ $factory = app(DeleteStrategyFactoryInterface::class); $strategy = $factory->make($strategy); return $strategy->delete($model); }
Deletes model. Note that this does not check authorization, conditions, etc. @param Model $model @return bool
entailment
public function render($key, $value) { return view( 'cms-models::model.partials.filters.basic-string', [ 'label' => $this->filterData ? $this->filterData->label() : $key, 'key' => $key, 'value' => $value, ] ); }
Applies a strategy to render a filter field. @param string $key @param mixed $value @return string|View
entailment