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);
... | @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();
// @codeCoverageIgnore... | 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 (emp... | 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');
i... | 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(),
... | 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 $relationDa... | 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)) {
... | 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 === $dat... | 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);
$t... | 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 ' ... | 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 = $... | 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 ($... | 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... | 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) {
... | 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
... | 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
@p... | 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() ?: '';
})
//... | 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 nes... | 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[] $attr... | 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... | 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 Va... | 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... | 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();
$t... | 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 ModelInformationFileWriteFailureExc... | 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);
# Repla... | 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) {
$bucke... | 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)) {
... | 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;
... | 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 fa... | 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;
}
... | 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) {
... | 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 objec... | 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... | 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:
... | 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... | 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... | 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
... | 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;
... | 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_P... | {@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');
... | @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-... | 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 ($str... | 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_e... | 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->setFormFie... | 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... | 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... | 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... | 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()) {
... | 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'],
[
'ign... | 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(... | 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)->d... | 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->getExportColumnStrategyFac... | 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) {
//... | 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);
}
$thi... | 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($thi... | 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;
... | 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('fileup... | 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... | 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($conditi... | 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;
}
... | {@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'],... | {@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 ( ! $referen... | 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 u... | 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.fiel... | 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)), '\\');
}
... | 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,
... | 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->ge... | Renders a form field.
@param Model $model
@param ModelFormFieldDataInterface|ModelFormFieldData $field
@param mixed $value
@param mixed $originalValue
@param array ... | 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($... | 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");
}
... | 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 mo... | 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 ... | 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->normalizeType... | 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) {
... | 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->normali... | 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;
... | @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 strat... | 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,... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.