sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function execute(ViewQuery $viewQuery, bool $jsonAsArray = false) { if (isset($this->dispatcher)) { $this->dispatcher->dispatch(new ViewQuerying($viewQuery)); } if (!is_null($this->consistency)) { $viewQuery = $viewQuery->consistency($this->consistency); } return $this->bucket->query($viewQuery, $jsonAsArray); }
@param ViewQuery $viewQuery @param bool $jsonAsArray @return mixed
entailment
public function render(Model $model, $source) { // Get all related records, if possible $relation = $this->getActualNestedRelation($model, $source); if ( ! $relation) { // @codeCoverageIgnoreStart return $this->getEmptyReference(); // @codeCoverageIgnoreEnd } // Note that there is no way we can reliably apply repository context for // a morph relation; we cannot know or sensibly generalize for the related models. if ($this->isMorphRelation($relation)) { $query = $relation; } else { $query = $this->modifyRelationQueryForContext($relation->getRelated(), $relation); } /** @var Collection|Model[] $models */ $models = $query->get(); if ( ! count($models)) { return $this->getEmptyReference(); } $references = []; // Convert records into reference strings foreach ($models as $model) { $references[] = $this->getReference($model); } return $this->implodeReferences($references); }
Renders a display value to print to the list view. @param Model $model @param mixed $source source column, method name or value @return string
entailment
protected function getReference(Model $model) { $reference = $this->getReferenceValue($model); return $this->wrapReference($reference); }
Returns a reference representation for a single model. @param Model $model @return string
entailment
protected function performInit() { /** @var RouteHelperInterface $routeHelper */ $routeHelper = app(RouteHelperInterface::class); $this->routePrefix = $routeHelper->getRouteNameForModelClass($this->modelClass, true); $permissions = $this->actionData->permissions(); if (empty($permissions)) { $this->isPermitted = true; } else { $this->isPermitted = cms_auth()->can($permissions); } }
Performs initialization. Override this to customize strategy implementations.
entailment
public function link(Model $model) { if ( ! $this->routePrefix || ! $this->isPermitted) { return false; } return route($this->routePrefix . static::ROUTE_POSTFIX, [ $model->getKey() ]); }
Returns the action link for a given model instance. @param Model $model @return string|false
entailment
public function analyze(ModelInformationInterface $information) { $this->info = $information; $this->performStep(); return $this->info; }
Performs analysis. @param ModelInformationInterface $information @return ModelInformationInterface
entailment
protected function databaseAnalyzer() { $driver = $this->model()->getConnection()->getDriverName(); $class = config("cms-models.analyzer.database.driver.{$driver}"); if ($class) { return app($class); } return app(DatabaseAnalyzerInterface::class); }
Returns configured or bound database analyzer. @return DatabaseAnalyzerInterface
entailment
protected function isAttributeBoolean(ModelAttributeData $attribute) { if ($attribute->cast == AttributeCast::BOOLEAN) { return true; } return $attribute->type === 'tinyint' && $attribute->length === 1; }
Returns whether an attribute should be taken for a boolean. @param ModelAttributeData $attribute @return bool
entailment
protected function getCmsDocBlockTags(ReflectionMethod $method) { if ( ! ($docBlock = $method->getDocComment())) { return []; } $factory = DocBlockFactory::createInstance(); $doc = $factory->create( $docBlock ); $tags = $doc->getTagsByName('cms'); if ( ! $tags || ! count($tags)) { return []; } $cmsTags = []; foreach ($tags as $tag) { if ( ! method_exists($tag, 'getDescription')) { // @codeCoverageIgnoreStart continue; // @codeCoverageIgnoreEnd } $description = trim($tag->getDescription()); if (preg_match('#\s+#', $description)) { list($firstWord, $parameters) = preg_split('#\s+#', $description, 2); } else { $firstWord = $description; $parameters = ''; } $firstWord = strtolower($firstWord); if ($firstWord == 'relation') { $cmsTags['relation'] = true; continue; } if ($firstWord == 'ignore') { $cmsTags['ignore'] = true; continue; } if ($firstWord == 'morph') { if ( ! $parameters) continue; $models = array_map('trim', explode(',', $parameters)); if ( ! array_key_exists('morph', $cmsTags)) { $cmsTags['morph'] = []; } $cmsTags['morph'] = array_merge($cmsTags['morph'], $models); $cmsTags['morph'] = array_unique($cmsTags['morph']); continue; } } return $cmsTags; }
Returns associative array representing the CMS docblock tag content. @param ReflectionMethod $method @return array
entailment
protected function getMethodBody(ReflectionMethod $method) { // Get file content for the method $file = new SplFileObject($method->getFileName()); $methodBodyLines = iterator_to_array( new LimitIterator( $file, $method->getStartLine(), $method->getEndLine() - $method->getStartLine() ) ); return implode("\n", $methodBodyLines); }
Returns the PHP code for a ReflectionMethod. @param ReflectionMethod $method @return string
entailment
protected function getRelationNameFromRelationInstance(Relation $relation) { // Get all relations, load instances and compare them loosely foreach ($this->info->relations as $relationData) { if ($relation == $this->model()->{$relationData->method}()) { return $relationData->method; } } // @codeCoverageIgnoreStart return null; // @codeCoverageIgnoreEnd }
Returns relation method name related to a relation instance. @param Relation $relation @return null|string
entailment
protected function addIncludesDefault($relation, $value = null) { $includes = array_get($this->info->includes, 'default', []); if (null !== $value) { $includes[ $relation ] = $value; } elseif ( ! array_key_exists($relation, $includes) && ! in_array($relation, $includes)) { $includes[] = $relation; } $this->info->includes['default'] = $includes; return $this; }
Adds an entry to the default includes. @param string $relation @param null|mixed $value @return $this
entailment
public function normalizeDateValue($date, $outFormat = 'Y-m-d H:i:s', $inFormat = null, $nullable = false) { if (empty($outFormat)) { $outFormat = 'Y-m-d H:i:s'; } if ($date instanceof DateTime) { return $date->format($outFormat); } if (null === $date) { if ($nullable) { return null; } return $this->makeEmptyStringDate($outFormat); } if (null === $inFormat) { try { $date = new Carbon($date); } catch (\Exception $e) { if ($nullable) { return null; } return $this->makeEmptyStringDate($outFormat); } } else { $date = DateTime::createFromFormat($inFormat, $date); } return $date->format($outFormat); }
Normalizes a date value to a given output string format. Optionally takes an expected incoming format, for string values. @param string|DateTime $date @param string $outFormat @param string|null $inFormat @param bool $nullable whether @return null|string
entailment
public function apply($query, $column, $direction = 'asc') { $direction = $direction === 'desc' ? 'desc' : 'asc'; $modelTable = $query->getModel()->getTable(); $modelKey = $query->getModel()->getKeyName(); $translationRelation = $this->getTranslationsRelation($query); $translationTable = $translationRelation->getRelated()->getTable(); $translationForeign = $translationRelation->getQualifiedForeignKeyName(); $locale = app()->getLocale(); $localeKey = $this->getLocaleKey(); $supportsIf = $this->databaseSupportsIf($query); // build translation subquery to join on, best match first $subQueryAlias = uniqid('trans'); $keyAlias = uniqid('fk'); $subQuery = DB::table($translationTable) ->select([ "{$translationForeign} as {$keyAlias}", "{$translationTable}.{$column}", ]) ->where(function ($query) use ($locale, $localeKey) { /** @var \Illuminate\Database\Query\Builder $query */ // Check if we need to work with a fallback locale $fallback = $this->getFallbackLocale(); $query->where($localeKey, '=', $locale); if ($fallback && $fallback != $locale) { $query->orWhere($localeKey, '=', $fallback); } }); if ($supportsIf) { $subQuery->orderByRaw("IF(`{$localeKey}` = ?,0,1)", [ $locale ]); } // build the main query, and join the sub $query = $query ->select("{$modelTable}.*") ->leftJoin( DB::raw("(" . $subQuery->toSql() . ") as `{$subQueryAlias}`"), function ($join) use ( $subQueryAlias, $keyAlias, $modelTable, $modelKey ) { /** @var JoinClause $join */ $join->on("{$subQueryAlias}.{$keyAlias}", '=', "{$modelTable}.{$modelKey}"); } ) ->addBinding($subQuery->getBindings(), 'join'); /** @var Builder $query */ if ($this->nullLast && $supportsIf) { $query->orderBy( DB::raw("IF(`{$subQueryAlias}`.`{$column}` IS NULL OR `{$subQueryAlias}`.`{$column}` = '',1,0)") ); } $query->orderBy("{$subQueryAlias}.{$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 getTranslationsRelation($query) { /** @var Builder $query */ /** @var Model|Translatable $model */ $model = $query->getModel(); if ( ! method_exists($model, 'translations')) { // @codeCoverageIgnoreStart throw new RuntimeException('Model ' . get_class($model) . ' is not a translated model.'); // @codeCoverageIgnoreEnd } return $model->translations(); }
Returns relation instance for translations. @param Builder $query @return \Illuminate\Database\Eloquent\Relations\HasMany
entailment
protected function renderedShowFieldStrategies(Model $model) { $views = []; foreach ($this->getModelInformation()->show->fields as $key => $data) { if ( ! $this->allowedToUseShowFieldData($data)) { continue; } try { $instance = $this->getShowFieldFactory()->make($data->strategy); // Feed any extra information we can gather to the instance $instance->setOptions($data->options()); if ($data->source) { if (isset($this->getModelInformation()->attributes[ $data->source ])) { $instance->setAttributeInformation( $this->getModelInformation()->attributes[ $data->source ] ); } } // @codeCoverageIgnoreStart } catch (Exception $e) { $message = "Failed to make show field strategy for '{$key}': \n{$e->getMessage()}"; throw new StrategyRenderException($message, $e->getCode(), $e); // @codeCoverageIgnoreEnd } try { $views[ $key ] = $instance->render($model, $data->source); // @codeCoverageIgnoreStart } catch (Exception $e) { $message = "Failed to render show field '{$key}' for strategy " . get_class($instance) . ": \n{$e->getMessage()}"; throw new StrategyRenderException($message, $e->getCode(), $e); // @codeCoverageIgnoreEnd } } return $views; }
Renders Vies or HTML for show field strategies. @param Model $model @return View[]|\string[] @throws StrategyRenderException
entailment
protected function allowedToUseShowFieldData(ModelShowFieldDataInterface $field) { if ( ! $field->adminOnly() && ! count($field->permissions())) { return true; } $user = $this->getCore()->auth()->user(); if ( ! $user) { return false; } if ($field->adminOnly() && ! $user->isAdmin()) { return false; } if ( ! count($field->permissions())) { return true; } return $user->can($field->permissions()); }
Returns whether current user has permission to use the form field. @param ModelShowFieldDataInterface $field @return bool
entailment
protected function isTranslatedTargetAttribute($target, Model $model) { // Normalize target as an array if (is_string($target)) { $target = explode('.', $target); } if ( ! is_array($target)) { throw new UnexpectedValueException("Target attribute/column should be a dot-notation string or array"); } $current = array_shift($target); // If it is a direct attribute of the model, check whether it is translated if ( ! count($target)) { return (method_exists($model, 'isTranslationAttribute') && $model->isTranslationAttribute($current)); } // Find the relations and the attribute, resolving relation methods where possible if (method_exists($model, $current)) { try { $relation = $model->{$current}(); } catch (\Exception $e) { $relation = false; } if ( ! $relation || ! ($relation instanceof Relation)) { return false; } // Recursively check nested relation return $this->isTranslatedTargetAttribute($target, $relation->getRelated()); } return false; }
Returns whether a (nested) target attribute is translated. @param string|array $target @param Model|Translatable $model @return bool
entailment
protected function applyLocaleRestriction($query, $locale = null, $allowFallback = true) { $localeKey = $this->getLocaleKey(); $locale = $locale ?: app()->getLocale(); $fallback = $this->getFallbackLocale(); if ($allowFallback && $fallback && $fallback != $locale) { $query->where(function ($query) use ($localeKey, $locale, $fallback) { $query ->where($localeKey, $locale) ->orWhere($localeKey, $fallback); }); return; } $query->where($localeKey, $locale); }
Applies locale-based restriction to a translations relation query. @param Builder $query @param null|string $locale @param bool $allowFallback
entailment
public function mergeSharedConfiguredRulesWithCreateOrUpdate($shared, $specific, $replace = false) { // If specific is flagged false, then base rules should be ignored. if ($specific === false) { return []; } // Otherwise, make sure the rules are merged as arrays if ($specific === null || $specific === true) { $specific = []; } // In replace mode, rules should be merged in from shared only per key, if present as value. // When shared rules are merged in specifically like this, their 'value-only' key marker is // replaced by the actual key-value pair from the shared rules. if ($replace) { $sharedKeys = array_filter( $specific, function ($value, $key) { return is_string($value) && is_numeric($key); }, ARRAY_FILTER_USE_BOTH ); // After this, there may still be string values in the array that do not have (non-numeric) // keys. These are explicit inclusions of form-field rules. $specific = array_filter( $specific, function ($value, $key) use ($shared) { return ! is_string($value) || ! is_numeric($key) || ! array_key_exists($value, $shared); }, ARRAY_FILTER_USE_BOTH ); return array_merge( array_only($shared, $sharedKeys), $specific ); } return array_merge( $shared ?: [], $specific ); }
Merges model configuration rules for the shared section with the create or update section. This results in user-specified validation rules, which may be further enriched. @param array $shared shared validation rules @param array|null|bool $specific specific validation rules for create or update @param bool $replace whether we're replacing or merging the rulesets @return array
entailment
public function collapseRulesForDuplicateKeys(array $rules) { $collection = (new Collection($rules)) // Group by key so we can process each key separately ->groupBy(function (ValidationRuleDataInterface $rule) { return $rule->key() ?: ''; }) // Collapse by merging separate rules into the first data item in the list, per key. ->transform(function (Collection $rules) { /** @var ValidationRuleDataInterface $data */ /** @var Collection|ValidationRuleDataInterface[] $rules */ $data = $rules->shift(); foreach ($rules as $rule) { $data->setRules(array_merge($data->rules(), $rule->rules())); } return $data; }); $array = []; foreach ($collection as $rule) { $array[] = $rule; } return $array; }
Takes any duplicate presence of a key() in a set of rules and collapses the rules into a single entry per key. @param ValidationRuleDataInterface[] $rules @return ValidationRuleDataInterface[]
entailment
public function mergeStrategyAndAttributeBased(array $strategyRules, array $attributeRules) { if (empty($strategyRules)) { return $attributeRules; } if (empty($attributeRules)) { return $strategyRules; } // Detect if any of the specific rules are nested, in which case the normal merging process should be skipped. // Though it is technically possible that these nested properties will match an attribute directly, // this should not be assumed -- configure validation rules manually for the best results. if ($this->rulesArrayContainsAnyNestedRules($strategyRules)) { return $strategyRules; } $attributeRules = new Collection($attributeRules); /** @var ValidationRuleDataInterface[]|Collection $attributeRules */ $attributeRules = $attributeRules->keyBy( function (ValidationRuleDataInterface $rule) { return $rule->key(); } ); // Todo: This needs to be cleaned up and ready to deal with much more complicated // scenario's than will currently occur. Right now the following are not // taken into account: // - localeIndex, translated, and requiredWith translated differences // For now, the strategy rules are kept mostly as-is. foreach ($strategyRules as &$rule) { if ( ! $attributeRules->has($rule->key())) { continue; } $rule = $this->mergeIndividualStrategyAndAttributeBasedRule($rule, $attributeRules->get($rule->key())); } unset ($rule); return $strategyRules; }
Merges together the validation rules defined for a strategy, with rules defined for a form field's attribute (or relation). Before passing arrays of rule objects to this class, they must be normalized and collapsed per key. @param ValidationRuleDataInterface[] $strategyRules @param ValidationRuleDataInterface[] $attributeRules @return ValidationRuleDataInterface[]
entailment
public function convertRequiredForTranslatedFields(array $rules) { $isTranslatedKeys = []; // list of rule keys that are translated $hasRequiredKeys = []; // list of rule keys that are translated and 'required' foreach ($rules as $index => $rule) { if ( ! $rule->isTranslated()) { continue; } $isTranslatedKeys[] = $rule->key() ?: ''; if (in_array('required', $rule->rules())) { $hasRequiredKeys[ $index ] = $rule->key() ?: ''; } } // For each required translated rule, // get all the keys for all other translated field rules (except itself) // and inject them into a required_with rule, that replaces the required rule. foreach ($hasRequiredKeys as $index => $key) { $rule = $rules[ $index ]; $this->replaceRequiredForRequiredWith($rule, array_diff($isTranslatedKeys, [ $key ])); } return $rules; }
Updates a list of validation rules to make required fields work in a per-locale context. The challenge here is to prevent a required translated field to be required *for all available locales* -- instead requiring it only if *anything* for that locale is entered. @param ValidationRuleDataInterface[] $rules @return ValidationRuleDataInterface[]
entailment
protected function replaceRequiredForRequiredWith(ValidationRuleDataInterface $rule, array $requiredWithKeys) { $rules = array_diff($rule->rules(), ['required']); // If there are no required_with keys to replace it with, leave the rule out if (count($requiredWithKeys)) { $rules[] = 'required_with:' . implode(',', $requiredWithKeys); } $rule->setRules($rules); }
Updates the rules in a validation data object to replace the required rule with a required_with rule for multiple fields. @param ValidationRuleDataInterface $rule @param array $requiredWithKeys
entailment
protected function rulesArrayContainsAnyNestedRules(array $rules) { foreach ($rules as $rule) { if ( ! empty($rule->key())) { return true; } } return false; }
Validation rule data instances with (any) nonempty keys have nested rules. @param ValidationRuleDataInterface[] $rules @return bool
entailment
protected function getRuleType($rule) { if ( ! is_string($rule)) { return ''; } if (false === ($pos = strpos($rule, ':'))) { return $rule; } return substr($rule, 0, $pos); }
Returns a rule type for a given validation rule. @param string $rule @return string
entailment
public function write(ModelInformationInterface $information, array $config = []) { $this->information = $information; $this->config = $config; $this->content = []; $this->path = $this->getInformationTargetPath(); $keys = $this->getKeysToWrite(); $this->checkWhetherFileAlreadyExists(); foreach ($keys as $key) { $this->writeKey($key); } $this->writeContentToFile(); return $this->path; }
Writes model information basics to a cms model file. @param ModelInformationInterface $information @param array $config @return string path to written file
entailment
protected function writeContentToFile() { $content = '<?php' . PHP_EOL . PHP_EOL . 'return ' . $this->getCleanContent() . ';' . PHP_EOL; try { File::put($this->path, $content); } catch (Exception $e) { throw (new ModelInformationFileWriteFailureException( "Failed to write '{$this->path}', make sure the directory exists and is writable", $e->getCode(), $e ))->setModelClass($this->information->modelClass()); } }
Writes the array model information content to file.
entailment
protected function getCleanContent() { $content = var_export($this->content, true); # Replace the array openers with square brackets $content = preg_replace('#^(\s*)array\s*\(#i', '\\1[', $content); $content = preg_replace('#=>(\s*)array\s*\(#is', '=> [', $content); # Replace the array closers with square brackets $content = preg_replace('#^(\s*)\),#im', '\\1],', $content); $content = substr($content, 0, -1) . ']'; // Remove integer indexes for unassociative array lists $content = preg_replace('#(\s*)\d+\s*=>\s*(.*)#i', '\\1\\2', $content); $content = $this->replaceDoubleSpaceIndentWithCustomSpaceIndent($content); return $content; }
Returns clean writable php array content. @return string
entailment
protected function getInformationTargetPath() { if ($path = array_get($this->config, 'path')) { return $path; } return rtrim($this->getInformationTargetBasePath(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $this->getInformationTargetRelativePath(); }
Returns the path where the models should be stored. @return string
entailment
protected function getKeysToWrite() { $keys = array_get($this->config, 'keys', ['*']); if (in_array('*', $keys)) { return $this->getWritableDefaultKeys(); } return $keys; }
Returns the keys that should be written. @return string[]
entailment
public function handle() { $row = []; $tableRows = []; /** @var \Illuminate\Database\Connection|CouchbaseConnection $connection */ $connection = $this->databaseManager->connection($this->option('database')); if ($connection instanceof CouchbaseConnection) { $bucket = $connection->getCouchbase()->openBucket($this->argument('bucket')); $indexes = $bucket->manager()->listN1qlIndexes(); foreach ($indexes as $index) { foreach ($index as $key => $value) { if (array_search($key, $this->headers) !== false) { $row[] = (!is_array($value)) ? $value : implode(",", $value); } } $tableRows[] = $row; $row = []; } $this->table($this->headers, $tableRows); } return; }
Execute the console command
entailment
public function display() { if ($this->label_translated) { return cms_trans($this->label_translated); } if ($this->label) { return $this->label; } return snake_case($this->method, ' '); }
Returns display text for the scope. @return string
entailment
protected function performEnrichment() { if ($this->info->form->layout && count($this->info->form->layout)) { $this->markRequiredForNestedLayoutChildren(null, 'layout'); } }
Performs enrichment.
entailment
protected function markRequiredForNestedLayoutChildren($nodes = null, $parentKey = null) { if (null === $nodes) { $nodes = $this->info->form->layout(); } // If the data is an array walk through it and return whether any children are required if (is_array($nodes)) { $required = null; foreach ($nodes as $key => $value) { try { $oneRequired = $this->markRequiredForNestedLayoutChildren($value, 'children.' . $key); } catch (ModelConfigurationDataException $e) { throw $e->setDotKey( $parentKey . ($e->getDotKey() ? '.' . $e->getDotKey() : null) ); } if ( ! $required && $oneRequired) { $required = true; } } return $required; } if ($nodes instanceof ModelFormLayoutNodeInterface) { if ($nodes instanceof ModelFormFieldLabelData) { return false; } /** @var ModelFormTabData|ModelFormFieldsetData|ModelFormFieldGroupData $nodes */ $required = $this->markRequiredForNestedLayoutChildren($nodes->children(), $parentKey); // Only set the required status if not explicitly set in configuration if (null === $nodes->required) { $nodes->required = $required; } return $nodes->required; } // If the node is a string, it's a field key if (is_string($nodes)) { if (array_key_exists($nodes, $this->info->form->fields)) { return $this->info->form->fields[ $nodes ]->required(); } return false; } // @codeCoverageIgnoreStart return null; // @codeCoverageIgnoreEnd }
Enriches existing layout data with required state for parent nodes. @param mixed $nodes an array, layout node or string field key @param string|null $parentKey @return bool|null true if any children are required, null if unknown @throws ModelConfigurationDataException
entailment
public function getValue() { $value = parent::getValue(); if (empty($value) || ! $this->existsFile($value)) { return []; } return $this->getFileInfo($value); }
{@inheritdoc}
entailment
public function setPosition(Model $model, $position) { if ($position === $model->getListifyPosition()) { return $position; } switch ($position) { case null: case OrderablePosition::REMOVE: $model->removeFromList(); break; case OrderablePosition::UP: $model->moveHigher(); break; case OrderablePosition::DOWN: $model->moveLower(); break; case OrderablePosition::TOP: if ($model->isInList()) { $model->moveToTop(); } else { $model->insertAt(); } break; case OrderablePosition::BOTTOM: if ($model->isInList()) { $model->moveToBottom(); } else { $model->insertAt(); $model->moveToBottom(); } break; default: $position = (int) $position; $model->insertAt($position); } return $model->getListifyPosition(); }
Sets a new orderable position for a model. @param Model|\Czim\Listify\Contracts\ListifyInterface $model @param mixed $position @return mixed|false
entailment
public function options() { if ($this->options && count($this->options)) { return $this->options; } if ( ! $this->exportColumnData) { return []; } return $this->exportColumnData->options(); }
Returns custom options. @return array
entailment
public function hasTabs(): bool { if ( ! $this->layout || ! count($this->layout)) { return false; } foreach ($this->layout as $key => $value) { if ($value instanceof ModelFormTabDataInterface) { return true; } } return false; }
Returns whether a layout with tabs is set. @return bool
entailment
public function tabs(): array { if ( ! $this->layout || ! count($this->layout)) { return []; } $tabs = []; foreach ($this->layout as $key => $value) { if ($value instanceof ModelFormTabDataInterface) { $tabs[ $key ] = $value; } } return $tabs; }
Returns only the tabs from the layout set. @return array|ModelFormTabData[]
entailment
public function layout(): array { if ($this->layout && count($this->layout)) { return $this->layout; } return array_keys($this->fields); }
Returns the layout that should be used for displaying the edit form. @return array|mixed[]
entailment
protected function getNestedFormFieldKeys(ModelFormLayoutNodeInterface $node = null): array { if (null === $node) { $children = $this->layout(); } else { $children = $node->children(); } $fieldKeys = []; foreach ($children as $key => $value) { if ($value instanceof ModelFormLayoutNodeInterface) { $fieldKeys = array_merge($fieldKeys, $this->getNestedFormFieldKeys($value)); continue; } if (is_string($value)) { $fieldKeys[] = $value; } } return $fieldKeys; }
Returns a list of form field keys recursively for a given layout node. @param ModelFormLayoutNodeInterface $node @return string[]
entailment
public function &getAttributeValue(string $key) { if ($key !== 'layout') { return parent::getAttributeValue($key); } if ( ! isset($this->attributes[$key]) || ! is_array($this->attributes[$key])) { $null = null; return $null; } // If object is an array, interpret it by type and make the corresponding data object. $this->decorateLayoutAttribute($key); return $this->attributes[$key]; }
Converts attributes to specific dataobjects if configured to @param string $key @return mixed|DataObjectInterface
entailment
public function determineListDisplayStrategy(ModelRelationData $data) { switch ($data->type) { case RelationType::BELONGS_TO: case RelationType::BELONGS_TO_THROUGH: case RelationType::HAS_ONE: case RelationType::MORPH_ONE: case RelationType::MORPH_TO: return ListDisplayStrategy::RELATION_REFERENCE; case RelationType::BELONGS_TO_MANY: case RelationType::HAS_MANY: case RelationType::MORPH_MANY: case RelationType::MORPH_TO_MANY: case RelationType::MORPHED_BY_MANY: return ListDisplayStrategy::RELATION_COUNT; } return null; }
Determines a list display strategy string for given relation data. @param ModelRelationData $data @return string|null
entailment
public function determineFormDisplayStrategy(ModelRelationData $data) { $type = null; switch ($data->type) { case RelationType::BELONGS_TO: case RelationType::BELONGS_TO_THROUGH: case RelationType::MORPH_ONE: case RelationType::HAS_ONE: $type = FormDisplayStrategy::RELATION_SINGLE_AUTOCOMPLETE; break; case RelationType::BELONGS_TO_MANY: case RelationType::HAS_MANY: case RelationType::MORPH_MANY: case RelationType::MORPH_TO_MANY: case RelationType::MORPHED_BY_MANY: $type = FormDisplayStrategy::RELATION_PLURAL_AUTOCOMPLETE; break; case RelationType::MORPH_TO: $type = FormDisplayStrategy::RELATION_SINGLE_MORPH_AUTOCOMPLETE; break; } return $type; }
Determines a form display strategy string for given relation data. @param ModelRelationData $data @return string|null
entailment
public function determineFormStoreStrategy(ModelRelationData $data) { $type = null; $parameters = []; // Determine strategy alias switch ($data->type) { case RelationType::BELONGS_TO: case RelationType::BELONGS_TO_THROUGH: case RelationType::MORPH_ONE: case RelationType::HAS_ONE: $type = FormStoreStrategy::RELATION_SINGLE_KEY; break; case RelationType::BELONGS_TO_MANY: case RelationType::HAS_MANY: case RelationType::MORPH_MANY: case RelationType::MORPH_TO_MANY: case RelationType::MORPHED_BY_MANY: $type = FormStoreStrategy::RELATION_PLURAL_KEYS; break; case RelationType::MORPH_TO: $type = FormStoreStrategy::RELATION_SINGLE_MORPH; break; } // Determine parameters if ($data->translated) { $parameters[] = 'translated'; } if (count($parameters)) { $type .= ':' . implode(',', $parameters); } return $type; }
Determines a form store strategy string for given relation data. @param ModelRelationData $data @return string|null
entailment
public function determineFormStoreOptions(ModelRelationData $data) { $options = []; switch ($data->type) { case RelationType::MORPH_TO: // Set special morph options to mark the targetable model classes $models = $this->determineMorphModelsForRelationData($data); if (count($models)) { $options['models'] = $models; } break; } return $options; }
Determines a form store's options for given relation data. @param ModelRelationData $data @return array
entailment
protected function determineMorphModelsForRelationData(ModelRelationData $data) { // If models were set during analysis, trust them if ($data->morphModels && count($data->morphModels)) { return $data->morphModels; } // We do not have access to modelinformation here, so // if it cannot be derived from data, the enrichment step must handle this using context info. return []; }
Determines models for MorphTo relation data. @param ModelRelationData $data @return string[]
entailment
public function increment($key, $value = 1) { if ($integer = $this->get($key)) { $this->put($key, $integer + $value, 0); return $integer + $value; } $this->put($key, $value, 0); return $value; }
Increment the value of an item in the cache. @param string $key @param mixed $value @return int|bool
entailment
public function decrement($key, $value = 1) { $decrement = 0; if ($integer = $this->get($key)) { $decrement = $integer - $value; if ($decrement <= 0) { $decrement = 0; } $this->put($key, $decrement, 0); return $decrement; } $this->put($key, $decrement, 0); return $decrement; }
Decrement the value of an item in the cache. @param string $key @param mixed $value @return int|bool
entailment
public function flush() { $handler = curl_multi_init(); foreach ($this->servers as $server) { $initialize = curl_init(); $configureOption = (isset($server['options'])) ? $server['options'] : []; $options = array_replace($this->options, [ CURLOPT_POST => true, CURLOPT_URL => $server['host'] . sprintf($this->flushEndpoint, $this->port, $server['bucket']), ], $configureOption, $this->setCredential()); curl_setopt_array($initialize, $options); curl_multi_add_handle($handler, $initialize); } $this->callMulti($handler); }
{@inheritdoc}
entailment
protected function callMulti($handler) { $running = null; do { $stat = curl_multi_exec($handler, $running); } while ($stat === CURLM_CALL_MULTI_PERFORM); if (!$running || $stat !== CURLM_OK) { throw new \RuntimeException('failed to initialized cURL'); } do { curl_multi_select($handler, $this->timeout); do { $stat = curl_multi_exec($handler, $running); } while ($stat === CURLM_CALL_MULTI_PERFORM); do { if ($read = curl_multi_info_read($handler, $remains)) { $response = curl_multi_getcontent($read['handle']); if ($response === false) { $info = curl_getinfo($read['handle']); throw new \RuntimeException("error: {$info['url']}: {$info['http_code']}"); } curl_multi_remove_handle($handler, $read['handle']); curl_close($read['handle']); } } while ($remains); } while ($running); curl_multi_close($handler); }
@param $handler @throws \RuntimeException
entailment
protected function getAvailableExportStrategyKeys() { if (empty($this->getModelInformation()->export->strategies)) { return []; } $keys = array_keys($this->getModelInformation()->export->strategies); return array_filter($keys, [ $this, 'isExportStrategyAvailable']); }
Returns list of export strategy keys that are availabe for the current user. @return string[]
entailment
protected function getExportDownloadFilename($strategy, $extension) { return Carbon::now()->format('Y-m-d_H-i') . ' - ' . $this->getModelSlug() . '.' . ltrim($extension, '.'); }
Returns filename for an export download. @param string $strategy @param string $extension @return string
entailment
protected function isExportStrategyAvailable($strategy) { if ( ! array_key_exists($strategy, $this->getModelInformation()->export->strategies)) { return false; } $strategyInfo = $this->getModelInformation()->export->strategies[ $strategy ]; $permissions = $strategyInfo->permissions(); if (false === $permissions) { $permissions = [ $this->getPermissionPrefix() . 'export' ]; } if (count($permissions) && ! $this->getCore()->auth()->can($permissions)) { return false; } return true; }
Returns whether a given strategy key corresponds to a usable export strategy. @param string $strategy @return bool
entailment
protected function getExportStrategyInstance($strategy) { /** @var ModelExportStrategyData $strategyData */ $strategyData = array_get($this->getModelInformation()->export->strategies, $strategy); $instance = $this->getExportStrategyFactory()->make($strategyData->strategy); if ($strategyData) { $instance->setStrategyData($strategyData); } return $instance; }
Returns prepared exporter strategy instance for a given strategy string. @param string $strategy @return ModelExporterInterface
entailment
protected function getRelevantFormFieldKeys($creating = false) { $fieldKeys = $this->getModelInformation()->form->getLayoutFormFieldKeys(); // Filter out keys that should not be available $fieldKeys = array_filter($fieldKeys, function ($key) use ($creating) { if ( ! array_key_exists($key, $this->getModelInformation()->form->fields)) { throw new UnexpectedValueException( "Layout field key '{$key}' not found in fields form data for " . $this->getModelInformation()->modelClass() ); } $fieldData = $this->getModelInformation()->form->fields[$key]; if ( ! $this->allowedToUseFormFieldData($fieldData)) { return false; } if ($creating) { return $fieldData->create(); } return $fieldData->update(); }); return $fieldKeys; }
Returns a list of form field keys relevant for the current context, depending on whether the model is being created or updated. @param bool $creating @return string[]
entailment
protected function getFormFieldValuesFromModel(Model $model, array $keys) { $values = []; foreach ($keys as $key) { $field = $this->getModelFormFieldDataForKey($key); $instance = $this->getFormFieldStoreStrategyInstanceForField($field); $instance->setFormFieldData($field); $instance->setParameters( $this->getFormFieldStoreStrategyParametersForField($field) ); // If we're creating a new model, pre-select the form field for the active list parent if ( ! $model->exists && $this->isFieldValueBeDerivableFromListParent($field->key)) { try { $values[ $key ] = $instance->valueForListParentKey($this->getListParentRecordKey()); // @codeCoverageIgnoreStart } catch (Exception $e) { $message = "Failed retrieving value for form field '{$key}' (using " . get_class($instance) . " (valueForListParentKey)): \n{$e->getMessage()}"; throw new StrategyRetrievalException($message, $e->getCode(), $e); // @codeCoverageIgnoreEnd } continue; } try { $values[ $key ] = $instance->retrieve($model, $field->source ?: $field->key); // @codeCoverageIgnoreStart } catch (Exception $e) { $message = "Failed retrieving value for form field '{$key}' (using " . get_class($instance) . "): \n{$e->getMessage()}"; throw new StrategyRetrievalException($message, $e->getCode(), $e); // @codeCoverageIgnoreEnd } } return $values; }
Collects and returns current values for fields by key from a model. @param Model $model @param string[] $keys @return array @throws StrategyRetrievalException
entailment
protected function getNormalizedFormFieldErrors() { $viewBags = session('errors'); if ( ! ($viewBags instanceof ViewErrorBag) || ! count($viewBags)) { return []; } /** @var MessageBag $errorBag */ $errorBag = head($viewBags->getBags()); if ( ! $errorBag->any()) { return []; } $normalized = []; foreach ($errorBag->toArray() as $field => $errors) { array_set($normalized, $field, $errors); } return $normalized; }
Returns associative array with form validation errors, keyed by field keys. This normalizes the errors to a nested structure that may be handled for display by form field strategies. @return array
entailment
protected function getErrorCountsPerTabPane() { $normalizedErrorKeys = array_keys($this->getNormalizedFormFieldErrors()); if ( ! count($normalizedErrorKeys)) { return []; } $errorCount = []; foreach ($this->getModelInformation()->form->layout() as $key => $node) { if ( ! ($node instanceof ModelFormTabDataInterface)) { continue; } $fieldKeys = $this->getFieldKeysForTab($key); $errorCount[ $key ] = count(array_intersect($normalizedErrorKeys, $fieldKeys)); } return $errorCount; }
Returns the error count keyed by tab pane keys. @return array
entailment
protected function getFieldKeysForTab($tab) { $layout = $this->getModelInformation()->form->layout(); if ( ! array_key_exists($tab, $layout)) { return []; } $tabData = $layout[ $tab ]; if ( ! ($tabData instanceof ModelFormTabDataInterface)) { return []; } return $tabData->descendantFieldKeys(); }
Returns the form field keys that are descendants of a given tab pane. @param string $tab key for a tab pane @return string[]
entailment
protected function allowedToUseFormFieldData(ModelFormFieldDataInterface $field) { if ( ! $field->adminOnly() && ! count($field->permissions())) { return true; } $user = $this->getCore()->auth()->user(); if ( ! $user || $field->adminOnly() && ! $user->isAdmin()) { return false; } if ($user->isAdmin() || ! count($field->permissions())) { return true; } return $user->can($field->permissions()); }
Returns whether current user has permission to use the form field. @param ModelFormFieldDataInterface $field @return bool
entailment
public function setMax(int $value) { $this->max = $value; $this->addValidationRule('max:' . $value); return $this; }
Set maximum number. @param int $value @return $this
entailment
public function setMin(int $value) { $this->min = $value; $this->addValidationRule('min:' . $value); return $this; }
Set minimum number. @param int $value @return $this
entailment
protected function getOptions() { return [ ['database', 'db', InputOption::VALUE_REQUIRED, 'The database connection to use.', $this->defaultDatabase], ['name', null, InputOption::VALUE_REQUIRED, 'the custom name for the primary index.', '#primary'], [ 'ignore', 'ig', InputOption::VALUE_NONE, 'if a primary index already exists, an exception will be thrown unless this is set to true.', ], ]; }
Get the console command options. @return array
entailment
public function handle() { /** @var \Illuminate\Database\Connection|CouchbaseConnection $connection */ $connection = $this->databaseManager->connection($this->option('database')); if ($connection instanceof CouchbaseConnection) { $bucket = $connection->openBucket($this->argument('bucket')); $bucket->manager()->dropN1qlPrimaryIndex( $this->option('name'), $this->option('ignore') ); $this->info("dropped PRIMARY INDEX [{$this->option('name')}] for [{$this->argument('bucket')}] bucket."); } return; }
Execute the console command
entailment
public function export($query, $path) { $this->query = $query; $this->modelClass = get_class($query->getModel()); return $this->generateExport($path); }
Exports data returned by a model listing query to a file. @param EloquentBuilder|QueryBuilder $query @param string $path full path to save the output to @return string|false full path string if successful
entailment
public function download($query, $filename) { $this->query = $query; $this->modelClass = get_class($query->getModel()); $temporary = $this->generateExport(); if ( ! $temporary) { return false; } return response()->download($temporary, $filename)->deleteFileAfterSend(true); }
Exports data returned by listing query and returns a download response for it. @param EloquentBuilder|QueryBuilder $query @param string $filename name the download should be given @return mixed|false
entailment
protected function getColumnStrategyInstances() { if ( ! $this->exportInfo) { throw new UnexpectedValueException("No export information set, cannot determine column strategies"); } $information = $this->getModelInformation(); $factory = $this->getExportColumnStrategyFactory(); $instances = []; foreach ($this->exportInfo->columns as $key => $columnData) { $instance = $factory->make($columnData->strategy); $instance->setColumnInformation($columnData); if ($columnData->source) { if (isset($information->attributes[ $columnData->source ])) { $instance->setAttributeInformation( $information->attributes[ $columnData->source ] ); } } $instances[ $key ] = $instance->initialize($this->modelClass); } if ( ! count($instances)) { throw new UnexpectedValueException("No strategies for any columns, cannot perform export"); } return $instances; }
Returns list of export column strategy instances in order. @return ExportColumnInterface[] keyed by export column key
entailment
public function handle(ModelInformationRepositoryInterface $repository) { $model = $this->argument('model'); if ($this->option('keys') && ! $this->option('pluck')) { $this->displayKeys($repository->getAll()->keys()); return; } if ( ! $model) { // Show all models $this->displayAll($repository->getAll()->toArray()); return; } // Try by key first $info = $repository->getByKey($model); if ($info) { $this->display($model, $info->toArray()); return; } // Try by class $info = $repository->getByModelClass($model); if ($info) { $this->display($model, $info->toArray()); return; } $this->error("Unable to find information for model by key or class '{$model}'"); }
Execute the console command. @param ModelInformationRepositoryInterface $repository
entailment
protected function displayKeys($keys) { $this->info('Model keys:'); foreach ($keys as $key) { $this->comment(' ' . $key); } $this->info(''); }
Display model keys in console. @param \Iterator|\IteratorAggregate|string[] $keys
entailment
protected function displayAll(array $data) { foreach ($data as $key => $single) { $this->display($key, $single); } }
Displays data in console for a list of model information arrays. @param array $data
entailment
protected function display($key, array $data) { if ($pluck = $this->option('pluck')) { if ( ! array_has($data, $pluck)) { $this->warn("Nothing to pluck for '{$pluck}'."); return; } $data = array_get($data, $pluck); } $this->comment($key); if ($this->option('keys') && is_array($data)) { $data = array_keys($data); } $this->getDumper()->dump($data); $this->info(''); }
Displays data in the console for a single information array. @param string $key model key or class for display only @param array $data
entailment
protected function applyValue($query, $target, $value, $combineOr = null, $isFirst = false) { // Normalize the value according to the expected format // If the column is not date-only, do a between start/end time for the date set if ($this->filterData) { $format = array_get($this->filterData->options(), 'format'); } else { $format = null; } $value = $this->normalizeDateValue($value, $format); // If the format the value is in is date-only, then we can do a simple equals check // if not, the date should be looked up as a range from start to end. if ($this->isTargetDateOnly()) { $query->where($target, '=', $value); } else { $dayStart = (new Carbon($value))->startOfDay(); $dayEnd = (new Carbon($value))->endOfDay(); $query ->where($target, '>=', $dayStart) ->where($target, '<=', $dayEnd); } return $query; }
Applies a value directly to a builder object. @param Builder $query @param string $target @param mixed $value @param null|bool $combineOr overrides global value if non-null @param bool $isFirst whether this is the first expression (between brackets) @return mixed
entailment
protected function isTargetDateOnly() { if ( ! $this->filterData) { return false; } $target = $this->filterData->target(); if ( ! array_key_exists($target, $this->getModelInformation()->attributes)) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } // Everything but 'date' has time element ('datetime', 'timestamp', 'time') return ($this->getModelInformation()->attributes[ $target ]->type == 'date'); }
Returns whether the target date column is date only. @return bool defaults to false if unknown.
entailment
protected function decorateFieldData(array $data) { $data['accept'] = array_get($data['options'], 'accept', static::DEFAULT_ACCEPT); if ($this->useFileUploader()) { $data['uploadUrl'] = cms_route('fileupload.file.upload'); $data['uploadDeleteUrl'] = cms_route('fileupload.file.delete', ['ID_PLACEHOLDER']); $data['uploadValidation'] = $this->getFileValidationRules(); } return $data; }
Enriches field data before passing it on to the view. @param array $data @return array
entailment
protected function isModelDeletable(Model $model) { $this->lastUnmetDeleteConditionMessage = null; // access rights if ( ! $this->isAuthorizedToDelete()) { $this->lastUnmetDeleteConditionMessage = $this->getUnmetConditionMessageForAuthorizationFailure(); return false; } // delete condition & model configuration $info = $this->getModelInformation(); if ( ! $info->allowDelete()) { $this->lastUnmetDeleteConditionMessage = $this->getUnmetConditionMessageForDisallowedFailure(); return false; } $condition = $info->deleteCondition(); if ( ! $condition) { return true; } // Resolve condition and check. $strategies = $this->interpretDeleteCondition($condition); foreach ($strategies as $strategy => $parameters) { /** @var DeleteConditionStrategyFactoryInterface $factory */ $factory = app(DeleteConditionStrategyFactoryInterface::class); $strategy = $factory->make($strategy); if ( ! $strategy->check($model, $parameters)) { $this->lastUnmetDeleteConditionMessage = $strategy->message(); return false; } } return true; }
Returns whether a given model may be deleted. @param Model $model @return bool
entailment
protected function interpretDeleteCondition($condition) { // Allow pipe symbol to split strategies if (false !== strpos($condition, '|')) { $condition = explode('|', $condition); } // Normalize arrays, handle each string condition separately if (is_array($condition)) { $normalized = []; foreach ($condition as $partialCondition) { $normalized = array_merge($normalized, $this->interpretDeleteCondition($partialCondition)); } return $normalized; } // Split strategy & parameters if (false !== strpos($condition, ':')) { list($strategy, $parameters) = explode(':', $condition, 2); $parameters = explode(',', $parameters); } else { $strategy = $condition; $parameters = []; } /** @var string $strategy */ return [ $strategy => $parameters ]; }
Interprets delete condition value and returns an array of delete condition classes @param $condition @return array associative: returns key-value pairs: 'strategy' => parameters
entailment
public function log($file, $batch) { $record = ['migration' => $file, 'batch' => $batch]; $builder = $this->table(); if ($builder instanceof QueryBuilder) { /** @var Builder */ $builder->key("{$file}:{$batch}")->insert($record); return; } $builder->insert($record); }
{@inheritdoc}
entailment
public function createRepository() { $schema = $this->getConnection()->getSchemaBuilder(); if ($schema instanceof Builder) { $schema->create($this->table, function (CouchbaseBlueprint $table) { $table->primaryIndex(); $table->index(['migration', 'batch'], 'migration_secondary_index'); }); return; } $schema->create($this->table, function (Blueprint $table) { $table->string('migration'); $table->integer('batch'); }); }
{@inheritdoc}
entailment
public function references(ModelMetaReferenceRequest $request) { $modelClass = $request->input('model'); $type = $request->input('type'); $key = $request->input('key'); $referenceData = $this->getModelMetaReferenceData($modelClass, $type, $key); if ( ! $referenceData) { // @codeCoverageIgnoreStart abort(404, "Could not determine reference for {$modelClass} (type: {$type}, key: {$key})"); // @codeCoverageIgnoreEnd } $search = $request->input('search'); if (is_array($referenceData)) { $references = []; foreach ($referenceData as $singleReferenceData) { $references[ $singleReferenceData->model ] = $this->getReferencesByMetaData($singleReferenceData, $search); } } else { $references = $this->getReferencesByMetaData($referenceData, $search); } // For now, always return json data, even if the request was not AJAX. return response()->json($references); }
Looks up model references by an optional search term. Targets model information (such as a form field strategy definition) to get the details for looking up references. Useful for relation (autocomplete) select strategies. @param ModelMetaReferenceRequest $request @return mixed
entailment
protected function getReferencesByMetaData(ModelMetaReference $data, $search = null) { $references = $this->referenceRepository->getReferencesForModelMetaReference($data, $search)->all(); return $this->formatReferenceOutput($references); }
Returns references by meta reference data. @param ModelMetaReference $data @param string|null $search @return string[]
entailment
protected function getModelMetaReferenceData($modelClass, $type, $key) { // Find out of the model is part of the CMS $info = $this->getCmsModelInformation($modelClass); // Model information is required, since it is used to determine the returned // reference strategy and source to use. if ( ! $info) { abort(404, "{$modelClass} is not a CMS model"); } // If multiple models are defined, get reference data for each model $nestedModels = $this->referenceDataProvider->getNestedModelClassesByType($info, $type, $key); if (false !== $nestedModels) { $data = []; foreach ($nestedModels as $nestedModelClass) { $data[ $nestedModelClass ] = $this->referenceDataProvider ->getForInformationByType($info, $type, $key, $nestedModelClass); } } else { $data = $this->referenceDataProvider->getForInformationByType($info, $type, $key); } if ( ! $data) { abort(404, "Could not retrieve reference data for {$type}, key: {$key}"); } return $data; }
Returns reference data from CMS model information, by type. Note that this may return either a single reference object, or an array of them, depending on the type of form field data. @param $modelClass @param $type @param $key @return ModelMetaReference|ModelMetaReference[]|false
entailment
protected function getReferencesForModelKeys(array $keys, $targetModel = null) { $keys = array_filter($keys); if ( ! count($keys)) { return []; } $referenceData = $this->getReferenceDataProvider()->getForModelClassByType( $this->model, 'form.field', $this->field->key(), $targetModel ); if ( ! $referenceData) { return []; } $references = []; foreach ($keys as $key) { $references[ $key ] = $this->getReferenceRepository() ->getReferenceForModelMetaReferenceByKey($referenceData, $key); } return $references; }
Returns references for model keys as an array keyed per model key. @param mixed[] $keys @param string|null $targetModel the nested model class, if multiple model definitions set @return string[] associative
entailment
protected function getModelDisplayLabel($modelClass) { $info = $this->getModelInformation($modelClass); if ($info) { return ucfirst($info->labelPlural()); } return $this->makeModelDisplayValueFromModelClass($modelClass); }
Get displayable text for a given model class. @param string $modelClass @return string
entailment
protected function makeModelDisplayValueFromModelClass($modelClass) { $stripPrefix = config('cms-models.collector.models-namespace'); if ($stripPrefix && starts_with($modelClass, $stripPrefix)) { $modelClass = trim(substr($modelClass, 0, strlen($stripPrefix)), '\\'); } return ucfirst(str_replace('\\', ' ', $modelClass)); }
Returns displayable text for a given model class, based only on the class name. @param string $modelClass @return string
entailment
protected function determineBestMinimumInputLength() { $info = $this->getModelInformation(get_class($this->model)); // Check if this is a multiple-model (morphTo), get the target models. $models = $this->getReferenceDataProvider()->getNestedModelClassesByType( $info, 'form.field', $this->field->key() ); if ($models && count($models)) { $total = array_reduce($models, function ($carry, $modelClass) { return $carry + $this->getCountForModel($modelClass); }); } else { // Otherwise, rely on the reference data to provide $referenceData = $this->getReferenceDataProvider() ->getForInformationByType($info, 'form.field', $this->field->key()); if (false === $referenceData) { return 1; } $total = $this->getCountForModel($referenceData->model()); } if (null === $total) { return 1; } if ($total > static::AUTOCOMPLETE_INPUT_THRESHOLD_THREE) { return 3; } if ($total > static::AUTOCOMPLETE_INPUT_THRESHOLD_TWO) { return 2; } if ($total > static::AUTOCOMPLETE_INPUT_THRESHOLD_ONE) { return 1; } return 0; }
Returns the best minimum input length for autocomplete input ajax triggers. @return int
entailment
protected function getCountForModel($modelClass) { if ( ! is_a($modelClass, Model::class, true)) { throw new UnexpectedValueException("'{$modelClass}' is not an Eloquent model class."); } return $modelClass::withoutGlobalScopes()->count() ?: 0; }
Returns total count for a model classname. @param string $modelClass @return int
entailment
public function render( Model $model, ModelFormFieldDataInterface $field, $value, $originalValue, array $errors = [] ) { $this->model = $model; $this->field = $field; if ($field->translated) { return $this->renderTranslatedFields($this->getRelevantLocales(), $value, $originalValue, $errors); } return $this->renderField($value, $originalValue, $errors); }
Renders a form field. @param Model $model @param ModelFormFieldDataInterface|ModelFormFieldData $field @param mixed $value @param mixed $originalValue @param array $errors @return string
entailment
protected function renderTranslatedFields(array $locales, $value, $originalValue, array $errors) { // Render the inputs for all relevant locales $rendered = []; foreach ($locales as $locale) { $rendered[ $locale ] = $this->renderField( $this->getValueForLocale($locale, $value), $this->getValueForLocale($locale, $originalValue), $this->getErrorsForLocale($locale, $errors), $locale ); } return view(static::FORM_FIELD_TRANSLATED_VIEW, [ 'field' => $this->field, 'locales' => $locales, 'value' => $value, 'errors' => $errors, 'localeRendered' => $rendered, ]); }
Returns a rendered set of translated form fields. @param array $locales @param mixed $value @param mixed $originalValue @param array $errors @return string|View
entailment
protected function initializeForModelRoute() { $routeHelper = $this->getRouteHelper(); $this->modelSlug = $routeHelper->getModelSlugForCurrentRoute(); if ( ! $this->modelSlug) { throw new RuntimeException("Could not determine model slug for route in request"); } $this->modelInformation = $this->getModelInformationRepository()->getByKey($this->modelSlug); if ( ! $this->modelInformation) { throw new RuntimeException( "Could not load information for model slug '{$this->modelSlug}' in request" ); } return $this; }
Initializes form request and checks context expecting a model route. @return $this
entailment
protected function getRedirectUrl() { if ($this->ajax()) { $lastSegment = last($this->segments()); $routePrefix = $this->getRouteHelper()->getRouteNameForModelClass( $this->modelInformation->modelClass(), true ); // If the model slug is the last segment, and this is a POST request, this is the STORE action. if ($lastSegment == $this->getRouteHelper()->getModelSlugForCurrentRoute() && $this->method() == 'POST') { $this->redirect = cms_route("{$routePrefix}.create"); } elseif ($lastSegment == 'update') { $this->redirect = cms_route("{$routePrefix}.edit"); } } return parent::getRedirectUrl(); }
Overridden to make sure AJAX calls don't redirect based on session where it can be prevented. For POST to <model-slug>/ we should be redirected back to /create For POST to <model-slug>/update we should be redirected back to /edit {@inheritdoc}
entailment
public function performStoreAfter(Model $model, $source, $value) { $relation = $this->resolveModelSource($model, $source); if ( ! ($relation instanceof Relation)) { throw new UnexpectedValueException("{$source} did not resolve to relation"); } // Belongs to are handled before the model is saved if ($relation instanceof BelongsTo) return; // Should not be used, since this is for singular relations.. if ($relation instanceof BelongsToMany) { $relation->sync([ $value ]); return; } // For *One and *Many relations, we need to handle detachment for currently related models. if ( $relation instanceof HasOne || $relation instanceof HasMany || $relation instanceof MorphOne || $relation instanceof MorphMany ) { // Detach only the models that shouldn't stay attached (ie. don't match the new value) /** @var Collection|Model[] $currentlyRelated */ $currentlyRelated = $relation->get(); if ($value) { $currentlyRelated = $currentlyRelated->filter(function (Model $model) use ($value) { return ! $model->getKey() == $value; }); } $this->detachRelatedModelsForOneOrMany($currentlyRelated, $relation); } if ( ! $value) return; // For HasOne (and HasMany), the related model must be found, // and then it should be saved on the relation. $relatedModel = $this->getModelByKey($relation->getRelated(), $value); if ( ! $relatedModel) return; if ( $relation instanceof HasOne || $relation instanceof HasMany || $relation instanceof MorphOne || $relation instanceof MorphMany ) { $relation->save($relatedModel); return; } throw new UnexpectedValueException( 'Unexpected relation class ' . get_class($relation) . " for {$source}" ); }
Stores a submitted value on a model, after it has been created (or saved). @param Model $model @param mixed $source @param mixed $value
entailment
protected function getValueFromRelationQuery($query) { $query = $this->prepareRelationQuery($query); return $this->getValueFromModel( $query->first() ); }
Returns the value per relation for a given relation query builder. @param Builder|Relation $query @return mixed|null
entailment
public function getColumns($table, $connection = null) { $this->updateConnection($connection)->setUpDoctrineSchema(); $columns = $this->getParsedColumnTable($table); $columnData = []; foreach ($columns as $name => $column) { list($type, $length) = $this->normalizeTypeAndLength(array_get($column, 'type')); $columnData[] = [ 'name' => $name, 'type' => $type, 'length' => $length, 'values' => false, 'unsigned' => false, 'nullable' => ! (bool) array_get($column, 'notnull', false), ]; } return $columnData; }
Returns column information for a given table. @param string $table @param string|null $connection optional connection name @return array
entailment
protected function getParsedColumnTable($table) { $this->validateTableName($table); $table = DB::connection($this->connection)->select( DB::connection($this->connection)->raw("PRAGMA table_info({$table});") ); $columns = []; foreach ($table as $columnData) { $columns[ $columnData->name ] = (array) $columnData; } return $columns; }
Returns a parsed set of columns for a table. @param string $table @return array associative, keyed by column name
entailment
protected function normalizeTypeAndLength($type) { if (empty($type)) { // @codeCoverageIgnoreStart return [null, null]; // @codeCoverageIgnoreEnd } if (preg_match('#^(?<type>.*)\((?<length>\d+)\)$#', $type, $matches)) { return [ $this->normalizeType($matches['type']), (int) $matches['length'] ]; } return [ $this->normalizeType($type), $this->getDefaultLengthForType($type) ]; }
Returns clean type string and length value. @param string $type sqlite type @return array [ type, length (int) ]
entailment
public function getNodesTree($nodes, $parentId) { return collect($nodes)->filter(function ($value) use ($parentId) { if (isset($value['parent_id'])) { if ($value['parent_id'] == $parentId) { return true; } return false; } return true; })->mapWithKeys(function ($value, $key) use ($nodes) { $data = [ 'id' => (string) $value['id'], 'label' => $value['label'], ]; if (isset($value['parent_id'])) { $children = $this->getNodesTree($nodes, $value['id']); if ($children->isNotEmpty()) { $data['children'] = $children; } } return [ $key => $data, ]; })->values(); }
@param $nodes @param $parentId @return \Illuminate\Support\Collection
entailment
public function make($strategy, $key = null, ModelFilterDataInterface $info = null) { // A filter must have a resolvable strategy for displaying if ( ! ($strategyClass = $this->resolveStrategyClass($strategy))) { throw new RuntimeException( "Could not resolve filter strategy class for {$key}: '{$strategy}'" ); } /** @var FilterStrategyInterface $instance */ $instance = app($strategyClass); if (null !== $info) { $instance->setFilterInformation($info); } return $instance; }
Makes a filter display instance. @param string $strategy @param string|null $key @param ModelFilterDataInterface|null $info @return FilterStrategyInterface
entailment
protected function applyValue($query, $target, $value, $combineOr = null, $isFirst = false) { $combineOr = ! $isFirst && ($combineOr === null ? $this->combineOr : $combineOr); $combine = $combineOr ? 'or' : 'and'; if (is_array($value)) { return $query->whereIn($target, $value, $combine); } return $query->where($target, '=', $value, $combine); }
Applies a value directly to a builder object. @param Builder $query @param string $target @param mixed $value @param null|bool $combineOr overrides global value if non-null @param bool $isFirst whether this is the first expression (between brackets) @return mixed
entailment