sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function applyValue($query, $target, $value, $combineOr = null, $isFirst = false)
{
// If we're splitting terms, the terms will first be split by whitespace
// otherwise the whole search value will treated at a single string.
// Array values will always be treated as split string search terms.
$combineOr = ! $isFirst && ($combineOr === null ? $this->combineOr : $combineOr);
if ( ! $this->splitTerms && ! is_array($value)) {
return $this->applyTerm($query, $target, $value, $combineOr);
}
if ( ! is_array($value)) {
$value = $this->splitTerms($value);
}
$whereMethod = ! $isFirst && $combineOr ? 'orWhere' : 'where';
$query->{$whereMethod}(function ($query) use ($value, $target) {
foreach ($value as $index => $term) {
$this->applyTerm($query, $target, $term, $index < 1);
}
});
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 applyTerm($query, $target, $value, $combineOr = null, $isFirst = false)
{
$combineOr = ! $isFirst && ($combineOr === null ? $this->combineSplitTermsOr : $combineOr);
$combine = $combineOr ? 'or' : 'and';
if (is_array($value)) {
return $query->whereIn($target, $value, $combine);
}
if ( ! $this->exact) {
return $query->where($target, 'like', '%' . $value . '%', $combine);
}
// @codeCoverageIgnoreStart
return $query->where($target, '=', $value, $combine);
// @codeCoverageIgnoreEnd
} | Applies a single (potentially) split off value directly to a builder object.
@param Builder $query
@param string $target
@param mixed $value
@param null|bool $combineOr
@param bool $isFirst whether this is the first expression (between brackets)
@return mixed | entailment |
public function retrieve(Model $model, $source)
{
$this->model = $model;
if ($this->isTranslated()) {
$keys = [];
$localeKey = config('translatable.locale_key', 'locale');
foreach ($model->translations as $translation) {
/** @var Relation $relation */
$relation = $translation->{$source}();
$keys[ $translation->{$localeKey} ] = $this->getValueFromRelationQuery($relation);
}
return $keys;
}
$relation = $this->resolveModelSource($model, $source);
if ( ! ($relation instanceof Relation)) {
throw new UnexpectedValueException(
"{$source} did not resolve to a relation for " . get_class($this) . " on " . get_class($model)
);
}
try {
return $this->getValueFromRelationQuery($relation);
} catch (\Exception $e) {
throw new RuntimeException(
"Exception retrieving relation values for source '{$source}' "
. "for form field key '{$this->formFieldData->key}'",
0,
$e
);
}
} | Retrieves current values from a model
@param Model $model
@param string $source
@return mixed | entailment |
protected function detachRelatedModelsForOneOrMany($models, Relation $relation)
{
if ($models instanceof Model) {
$models = new Collection([ $models ]);
}
if ( ! $this->allowDetachingOfOneOrMany() || ! count($models)) {
return;
}
// If models that were previously attached but no longer should be
// have nullable foreign keys, we can 'detach' them safely by dissociating
// the reverse relation (if we know which relation that is, or nullifying the keys).
// Get the foreign key(s) (id/type for morph, otherwise just the id)
$foreignKeyNames = $this->getForeignKeyNamesForRelation($relation);
$nullableKey = $this->explicitlyConfiguredForeignKeysNullable();
if (null === $nullableKey) {
$nullableKey = $this->hasNullableForeignKeys($relation, $models->first(), $foreignKeyNames);
}
if ($nullableKey) {
// We can detach the models by setting their keys to null.
foreach ($models as $model) {
$this->setForeignKeysToNull($model, $relation, $foreignKeyNames);
}
return;
}
// If the related models do not have nullable keys, we cannot detach them
// without deleting them. This must be explicitly configured to prevent accidental deletions.
if ( ! $this->allowDeletionOfDetachedModels()) return;
// We can delete the previously related models entirely
foreach ($models as $model) {
$model->delete();
// todo: log?
}
} | Detaches models no longer to be related for *One and *Many relations.
Note that all models are expected to be of a single class.
@param Collection|Model[]|Model $models
@param Relation $relation | entailment |
protected function getForeignKeyNamesForRelation(Relation $relation)
{
if ( $relation instanceof BelongsTo
|| $relation instanceof HasOne
|| $relation instanceof HasMany
|| is_a($relation, '\\Znck\\Eloquent\\Relations\\BelongsToThrough', true)
) {
return [ $relation->getForeignKey() ];
}
if ($relation instanceof BelongsToMany) {
return [ $relation->getQualifiedForeignPivotKeyName(), $relation->getQualifiedRelatedPivotKeyName() ];
}
if ( $relation instanceof MorphTo
|| $relation instanceof MorphOne
|| $relation instanceof MorphMany
) {
return [ $relation->getForeignKey(), $relation->getMorphType() ];
}
if ($relation instanceof MorphToMany) {
return [
$relation->getQualifiedForeignPivotKeyName(),
$relation->getMorphType(),
$relation->getQualifiedRelatedPivotKeyName(),
];
}
return [];
} | Returns the foreign key names for a given relation class.
For BelongsToMany, this returns the key to the local model first, the other model second.
For Morph relations, this will return the id/key and type column names.
For MorphToMany the morph keys are followed by the other foreign key.
@param Relation $relation
@return string[] | entailment |
protected function hasNullableForeignKeys(Relation $relation, Model $model = null, array $keys = null)
{
if (null === $keys) {
$keys = $this->getForeignKeyNamesForRelation($relation);
}
if ( ! count($keys)) return false;
// Determine the model on which the foreign key is stored
if (null === $model) {
if ( $relation instanceof BelongsTo
|| $relation instanceof MorphTo
|| is_a($relation, '\\Znck\\Eloquent\\Relations\\BelongsToThrough', true)
) {
$model = $this->model;
} elseif ( $relation instanceof HasOne
|| $relation instanceof HasMany
|| $relation instanceof BelongsToMany
) {
$model = $relation->getRelated();
}
}
if ( ! $model) {
throw new RuntimeException('No model could be determined for nullable foreign key check');
}
$info = $this->getModelInformation($model);
// We can use the information to determine whether the model has nullable foreign key
if ($info) {
// For all relations, the first key value must be checked
$attribute = array_get($info->attributes, $this->normalizeForeignKey(head($keys)));
$nullable = $attribute ? $attribute->nullable : false;
// For morph relation types, we must also check the type column
if ( $nullable
&& count($keys) > 1
&& ( $relation instanceof MorphTo
|| $relation instanceof MorphOne
|| $relation instanceof MorphMany
)
) {
$attribute = array_get($info->attributes, $this->normalizeForeignKey(array_values($keys)[1]));
$nullable = $attribute ? $attribute->nullable : false;
}
return $nullable;
}
// We must somehow determine whether the foreign key is nullable on this
// model without having information about it.
// todo: for now, assume false, use the 'nullable_keys' option to configure this instead
return false;
} | Returns whether a relation's related model has nullable foreign keys.
@param Relation $relation
@param Model $model if the model with the keys should not be resolved, pass it in
@param string[]|null $keys if already known, the foreign keys for the relation
@return bool | entailment |
protected function setForeignKeysToNull(Model $model, Relation $relation, array $keys)
{
if ( ! count($keys)) return;
$key = $this->normalizeForeignKey(head($keys));
$model->{$key} = null;
if ( count($keys) > 1
&& ( $relation instanceof MorphTo
|| $relation instanceof MorphOne
|| $relation instanceof MorphMany
)
) {
$key = $this->normalizeForeignKey(array_values($keys)[1]);
$model->{$key} = null;
}
$model->save();
} | Sets the foreign keys to null on a given model.
@param Model $model
@param Relation $relation
@param string[] $keys | entailment |
protected function explicitlyConfiguredForeignKeysNullable()
{
$nullable = array_get($this->formFieldData->options(), 'nullable_key');
if (null === $nullable) return null;
return (bool) $nullable;
} | Returns whether the relation's foreign keys were configured nullable.
@return bool|null null if the nullabillity of the keys was not configured | entailment |
protected function prepareValue($value)
{
if ($this->hasMutator()) {
return call_user_func($this->getMutator(), $value);
} elseif ($value && $this->isElementOfDate() && $this->isDateCastable()) {
$value = $this->castValueAsDateTime($value);
if ($this instanceof Timestamp) {
$value = $value->getTimestamp();
}
return $value;
}
if (! is_null($value)) {
if ($this->isJsonCastable()) {
return $this->castValueAsJson($value);
} elseif ($this->isCommaCastable()) {
return $this->castValueAsCommaSeparated($value);
}
}
return $value;
} | @param mixed $value
@return mixed | entailment |
public function getValue()
{
$value = $this->getValueFromModel();
if (is_null($value)) {
return $this->getDefaultValue();
}
if ($this->isCastable()) {
$value = $this->castValue($value);
}
return $value;
} | {@inheritdoc} | entailment |
protected function performStep()
{
$attributes = [];
// Get the columns from the model's table
$tableFields = $this->databaseAnalyzer()->getColumns(
$this->model()->getTable(),
$this->model()->getConnectionName()
);
foreach ($tableFields as $field) {
$length = $field['length'];
$cast = $this->getAttributeCastForColumnType($field['type'], $length);
$attributes[ $field['name'] ] = new ModelAttributeData([
'name' => $field['name'],
'cast' => $cast,
'type' => $field['type'],
'nullable' => $field['nullable'],
'unsigned' => $field['unsigned'],
'length' => $length,
'values' => $field['values'],
]);
}
foreach ($this->model()->getFillable() as $attribute) {
if ( ! isset($attributes[ $attribute ])) {
continue;
}
$attributes[ $attribute ]['fillable'] = true;
}
foreach ($this->model()->getCasts() as $attribute => $cast) {
if ( ! isset($attributes[ $attribute ])) {
continue;
}
$attributes[ $attribute ]['cast'] = $this->normalizeCastString($cast);
}
$this->info->attributes = $attributes;
} | Performs the analyzer step on the stored model information instance. | entailment |
protected function getAttributeCastForColumnType($type, $length = null)
{
switch ($type) {
case 'bool':
return AttributeCast::BOOLEAN;
case 'tinyint':
if ($length === 1) {
return AttributeCast::BOOLEAN;
}
return AttributeCast::INTEGER;
case 'int':
case 'integer':
case 'mediumint':
case 'smallint':
case 'bigint':
return AttributeCast::INTEGER;
case 'dec':
case 'decimal':
case 'double':
case 'float':
case 'real':
return AttributeCast::FLOAT;
case 'varchar':
case 'char':
case 'enum':
case 'text':
case 'mediumtext':
case 'longtext':
case 'tinytext':
case 'year':
case 'blob';
case 'mediumblob';
case 'longblob';
case 'binary';
case 'varbinary';
return AttributeCast::STRING;
case 'date':
case 'datetime':
case 'time':
case 'timestamp':
return AttributeCast::DATE;
default:
return $type;
}
} | Returns cast enum value for database column type string and length.
@param string $type
@param null|int $length
@return string | entailment |
protected function normalizeCastString($cast)
{
switch ($cast) {
case 'bool':
case 'boolean':
$cast = AttributeCast::BOOLEAN;
break;
case 'decimal':
case 'double':
case 'float':
case 'real':
$cast = AttributeCast::FLOAT;
break;
case 'int':
case 'integer':
$cast = AttributeCast::INTEGER;
break;
case 'date':
case 'datetime':
$cast = AttributeCast::DATE;
break;
}
return $cast;
} | Normalizes a cast string to enum value if possible.
@param string $cast
@return string | entailment |
public function enrich(ModelInformationInterface $info, $allInformation = null)
{
$this->info = $info;
$class = $this->info->modelClass();
$this->model = new $class;
$this->allInfo = $allInformation;
$this->performEnrichment();
return $this->info;
} | Performs enrichment on model information.
Optionally takes all model information known as context.
@param ModelInformationInterface|ModelInformation $info
@param Collection|ModelInformationInterface[]|ModelInformation[]|null $allInformation
@return ModelInformationInterface|ModelInformation | entailment |
protected function shouldAttributeBeDisplayedByDefault(ModelAttributeData $attribute, ModelInformationInterface $info)
{
if (in_array($attribute->type, [
'text', 'longtext', 'mediumtext',
'blob', 'longblob', 'mediumblob',
])) {
return false;
}
// Hide active column if the model if activatable
if ($info->list->activatable && $info->list->active_column == $attribute->name) {
return false;
}
// Hide orderable position column if the model if orderable
if ($info->list->orderable && $info->list->order_column == $attribute->name) {
return false;
}
// Hide paperclip fields other than the main field
if ( preg_match('#^(?<field>[^_]+)_(file_name|file_size|content_type|updated_at)$#', $attribute->name, $matches)
&& array_has($info->attributes, $matches['field'])
) {
return $info->attributes[ $matches['field'] ]->cast !== AttributeCast::PAPERCLIP_ATTACHMENT;
}
// Any attribute that is a foreign key and should be handled with relation-based strategies
return ! $this->isAttributeForeignKey($attribute->name, $info);
} | Returns whether an attribute should be displayed if no user-defined list columns are configured.
@param ModelAttributeData $attribute
@param ModelInformationInterface|ModelInformation $info
@return bool | entailment |
public function mapWebRoutes(Router $router)
{
$router->group(
[
'prefix' => $this->getRoutePrefix(),
'as' => $this->getRouteNamePrefix(),
],
function (Router $router) {
$controller = $this->getModelWebController();
$router->post('references', [
'as' => 'references',
'uses' => $controller . '@references',
]);
}
);
} | Generates web routes for the module given a contextual router instance.
@param Router $router | entailment |
public function mapApiRoutes(Router $router)
{
$router->group(
[
'prefix' => $this->getRoutePrefix(),
'as' => $this->getRouteNamePrefix(),
],
function (Router $router) {
$controller = $this->getModelApiController();
$router->post('references', [
'as' => 'references',
'uses' => $controller . '@references',
]);
}
);
} | Generates API routes for the module given a contextual router instance.
@param Router $router | entailment |
public function store(Model $model, array $data)
{
if ( ! config('cms-models.transactions')) {
return $this->storeFormFieldValuesForModel($model, $data);
}
// Perform the whole store process in a transaction
DB::beginTransaction();
try {
$success = $this->storeFormFieldValuesForModel($model, $data);
if ($success) {
DB::commit();
} else {
DB::rollBack();
}
} catch (Exception $e) {
DB::rollBack();
throw $e;
}
return $success;
} | Stores submitted form field data on a model.
@param Model $model
@param array $data
@return bool
@throws Exception | entailment |
protected function storeFormFieldValuesForModel(Model $model, array $values)
{
// Prepare field data and strategies
/** @var ModelFormFieldDataInterface[]|ModelFormFieldData[] $fields */
/** @var FormFieldStoreStrategyInterface[] $strategies */
$fields = [];
$strategies = [];
foreach (array_keys($values) as $key) {
$field = $this->getModelFormFieldDataForKey($key);
if ( ! $this->allowedToUseFormFieldData($field)) continue;
$fields[ $key ] = $field;
$strategies[ $key ] = $this->getFormFieldStoreStrategyInstanceForField($fields[ $key ]);
$strategies[ $key ]->setFormFieldData($fields[ $key ]);
$strategies[ $key ]->setParameters(
$this->getFormFieldStoreStrategyParametersForField($fields[ $key ])
);
}
// First store values (such as necessary belongsTo-related instances),
// before storing the model
foreach ($values as $key => $value) {
if ( ! array_key_exists($key, $strategies)) continue;
try {
$strategies[ $key ]->store($model, $fields[ $key ]->source(), $value);
// @codeCoverageIgnoreStart
} catch (Exception $e) {
$class = get_class($strategies[ $key ]);
$message = "Failed storing value for form field '{$key}' (using $class): \n{$e->getMessage()}";
throw new StrategyApplicationException($message, $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
}
// Save the model itself
$success = $model->save();
if ( ! $success) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
// Then store values that can only be stored after the model exists
// and is succesfully saved
foreach ($values as $key => $value) {
if ( ! array_key_exists($key, $strategies)) continue;
try {
$strategies[ $key ]->storeAfter($model, $fields[ $key ]->source(), $value);
} catch (Exception $e) {
$class = get_class($strategies[ $key ]);
$message = "Failed storing value for form field '{$key}' (using $class (after)): \n{$e->getMessage()}";
throw new StrategyApplicationException($message, $e->getCode(), $e);
}
}
// If the model is still dirty after this, save it again
if ($model->isDirty()) {
$success = $model->save();
}
// Call hooks to finish store strategies
foreach ($values as $key => $value) {
if ( ! array_key_exists($key, $strategies)) continue;
try {
$strategies[ $key ]->finish();
} catch (Exception $e) {
$class = get_class($strategies[ $key ]);
$message = "Failed finishing strategy form field '{$key}' (using $class): \n{$e->getMessage()}";
throw new StrategyApplicationException($message, $e->getCode(), $e);
}
}
return $success;
} | Stores filled in form field data for a model instance.
Note that this will persist the model if it is a new instance.
@param Model $model
@param array $values associative array with form data, should only include actual field data
@return bool
@throws StrategyApplicationException | entailment |
protected function allowedToUseFormFieldData(ModelFormFieldDataInterface $field)
{
if ( ! $field->adminOnly() && ! count($field->permissions())) {
return true;
}
$auth = $this->core->auth();
if ($field->adminOnly() && ! $auth->admin()) {
return false;
}
if ($auth->admin() || ! count($field->permissions())) {
return true;
}
return $auth->can($field->permissions());
} | Returns whether current user has permission to use the form field.
@param ModelFormFieldDataInterface $field
@return bool | entailment |
public function make($strategy)
{
if ( ! $strategy) {
return $this->getDefaultStrategy();
}
// If the strategy indicates the FQN of display strategy,
// or a classname that can be found in the default strategy name path, use it.
if ($strategyClass = $this->resolveStrategyClass($strategy)) {
return app($strategyClass);
}
throw new RuntimeException("Could not create strategy instance for '{$strategy}'");
} | Makes a show field strategy instance.
@param string $strategy
@return ShowFieldInterface | entailment |
protected function resolveStrategyClass($strategy)
{
if ( ! str_contains($strategy, '.')
&& $aliasStrategy = config(
'cms-models.strategies.show.aliases.' . $strategy,
config('cms-models.strategies.list.aliases.' . $strategy)
)
) {
$strategy = $aliasStrategy;
}
if (class_exists($strategy) && is_a($strategy, ShowFieldInterface::class, true)) {
return $strategy;
}
$strategy = $this->prefixStrategyNamespace($strategy);
if (class_exists($strategy) && is_a($strategy, ShowFieldInterface::class, true)) {
return $strategy;
}
return false;
} | Resolves strategy assuming it is the class name or FQN of a show field interface
implementation or an alias for one.
@param string $strategy
@return string|false returns full class namespace if it was resolved succesfully | entailment |
protected function getValueFromRelationQuery($query)
{
// Query must be a relation in this case, since we need the related model
if ( ! ($query instanceof BelongsToMany)) {
throw new UnexpectedValueException("Query must be BelongsToMany Relation instance for " . get_class($this));
}
/** @var BelongsToMany $query */
$relatedModel = $query->getRelated();
$keyName = $relatedModel->getKeyName();
$table = $relatedModel->getTable();
$pivotTable = $query->getTable();
$orderColumn = $this->getPivotOrderColumn();
$query = $this->prepareRelationQuery(
$query
->withPivot([ $orderColumn ])
->orderBy($pivotTable . '.' . $orderColumn)
);
// Get only the relevant columns: key and pivot
return $query->pluck($pivotTable . '.' . $orderColumn, $table . '.' . $keyName);
} | Returns the value per relation for a given relation query builder.
@param Builder|Relation $query
@return mixed|null | entailment |
public function performStoreAfter(Model $model, $source, $value)
{
$relation = $this->resolveModelSource($model, $source);
if ( ! ($relation instanceof BelongsToMany)) {
throw new UnexpectedValueException("{$source} did not resolve to BelongsToMany relation");
}
$relation->sync(
$this->convertValueToSyncFormat($value)
);
} | 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 convertValueToSyncFormat($value)
{
if (null === $value) {
return [];
}
$orderColumn = $this->getPivotOrderColumn();
return array_map(
function ($position) use ($orderColumn) {
return [ $orderColumn => $position ];
},
$value
);
} | Converts submitted value array to sync() format.
@param array|null $value
@return array associative, keys are related model ids, values update values | entailment |
public function descendantFieldKeys(): array
{
$keys = [];
foreach ($this->children() as $key => $node) {
if ($node instanceof ModelFormLayoutNodeInterface) {
$keys = array_merge($keys, $node->descendantFieldKeys());
continue;
}
$keys[] = $node;
}
return $keys;
} | Returns list of keys of form fields that are descendants of this tab.
@return string[] | entailment |
protected function getUserString()
{
$user = $this->core->auth()->user();
if ( ! $user) return null;
return $user->getUsername();
} | Returns user name for currently logged in user, if known.
@return null|string | entailment |
protected function performEnrichment()
{
if ( ! count($this->info->export->columns)) {
$this->fillDataForEmpty();
} else {
$this->enrichCustomData();
}
// Separate strategies may have their own column setups.
// If not, the defaults should be copied for them.
foreach ($this->info->export->strategies as $key => $strategyData) {
if ( ! count($strategyData->columns)) {
$this->info->export->strategies[ $key ]->columns = $this->info->export->columns;
} else {
$this->enrichCustomData($key);
}
}
} | Performs enrichment. | entailment |
protected function fillDataForEmpty()
{
// Fill export columns if they are empty
$columns = [];
$foreignKeys = $this->collectForeignKeys();
// Add columns for attributes
foreach ($this->info->attributes as $attribute) {
if ($attribute->hidden || in_array($attribute->name, $foreignKeys)) {
continue;
}
$columns[ $attribute->name ] = $this->makeModelExportColumnDataForAttributeData($attribute);
}
$this->info->export->columns = $columns;
} | Fills column data if no custom data is set. | entailment |
protected function collectForeignKeys()
{
$keys = [];
foreach ($this->info->relations as $relation) {
if ( ! in_array(
$relation->type,
[ RelationType::BELONGS_TO, RelationType::MORPH_TO, RelationType::BELONGS_TO_THROUGH ]
)) {
continue;
}
$keys = array_merge($keys, $relation->foreign_keys);
}
return $keys;
} | Returns list of foreign key attribute names on this model.
@return string[] | entailment |
protected function enrichCustomData($strategy = null)
{
// Check filled columns and enrich them as required
// Note that these can be either attributes or relations
$columns = [];
if (null === $strategy) {
$columnsOrigin = $this->info->export->columns;
} else {
$columnsOrigin = $this->info->export->strategies[ $strategy ]->columns;
}
foreach ($columnsOrigin as $key => $column) {
try {
$this->enrichColumn($key, $column, $columns);
} catch (\Exception $e) {
$section = 'export' . ($strategy ? ".{$strategy}" : null) . '.columns';
$decoratedMessage = "Issue with export column '{$key}' "
. ($strategy ? " for strategy '{$strategy}' " : null)
. "({$section}.{$key}): \n{$e->getMessage()}";
// Wrap and decorate exceptions so it is easier to track the problem source
throw (new ModelInformationEnrichmentException($decoratedMessage, $e->getCode(), $e))
->setSection($section)
->setKey($key);
}
}
if (null === $strategy) {
$this->info->export->columns = $columns;
} else {
$this->info->export->strategies[ $strategy ]->columns = $columns;
}
} | Enriches existing user configured data.
@param string|null $strategy
@throws ModelInformationEnrichmentException | entailment |
protected function enrichColumn($key, ModelExportColumnDataInterface $column, array &$columns)
{
// Check if we can enrich, if we must.
if ( ! isset($this->info->attributes[ $key ])) {
// if the column data is fully set, no need to enrich
if ($this->isExportColumnDataComplete($column)) {
$columns[ $key ] = $column;
return;
}
throw new UnexpectedValueException(
"Incomplete data for for export column key that does not match known model attribute or relation method. "
. "Requires at least 'source' value."
);
}
$attributeColumnInfo = $this->makeModelExportColumnDataForAttributeData($this->info->attributes[ $key ]);
$attributeColumnInfo->merge($column);
$columns[ $key ] = $attributeColumnInfo;
} | Enriches a single export column and saves the data.
@param ModelExportColumnDataInterface $column
@param string $key
@param array $columns by reference, data array to build, updated with enriched data | entailment |
protected function makeModelExportColumnDataForAttributeData(ModelAttributeData $attribute)
{
return new ModelExportColumnData([
'hide' => false,
'source' => $attribute->name,
'strategy' => $this->determineExportColumnStrategyForAttribute($attribute),
]);
} | Makes data set for export column given attribute data.
@param ModelAttributeData $attribute
@return ModelExportColumnData | entailment |
public function toArray()
{
return [
'name' => $this->getName(),
'label' => $this->getLabel(),
'width' => $this->getWidth(),
'fixed' => $this->isFixed(),
'minWidth' => $this->getMinWidth(),
'sortable' => $this->getSortable(),
'type' => $this->getType(),
];
} | The column options
@return array | entailment |
public function getValue()
{
$value = $this->getModelValue();
if (is_null($value)) {
$value = $this->getDefaultValue();
}
return $value;
} | Get the column value
@return string|static | entailment |
protected function checkActiveSort($update = true)
{
$request = request();
if ($update && $request->has('sort')) {
$this->activeSort = $request->get('sort');
if ($request->filled('sortdir') && ! empty($request->get('sortdir'))) {
$this->activeSortDescending = strtolower($request->get('sortdir')) === 'desc';
} else {
$this->activeSortDescending = null;
}
$this->markResetActivePage()
->storeActiveSortInSession();
} elseif ($this->getListMemory()->hasSortData()) {
$this->retrieveActiveSortFromSession();
}
return $this;
} | Checks and sets the active sort settings.
@param bool $update
@return $this | entailment |
protected function storeActiveSortInSession()
{
if (null !== $this->activeSortDescending) {
$direction = $this->activeSortDescending ? 'desc' : 'asc';
} else {
$direction = null;
}
$this->getListMemory()->setSortData($this->activeSort, $direction);
} | Stores the currently active sort settings for the session. | entailment |
protected function retrieveActiveSortFromSession()
{
$sessionSort = $this->getListMemory()->getSortData();
if ( ! is_array($sessionSort)) return;
$this->activeSort = array_get($sessionSort, 'column');
$direction = array_get($sessionSort, 'direction');
if (null === $direction) {
$this->activeSortDescending = null;
} else {
$this->activeSortDescending = $direction === 'desc';
}
} | Retrieves the sort settings from the session and restores them as active. | entailment |
protected function getActualSortDirection($column = null)
{
$column = $column ?: $this->activeSort;
if (null !== $this->activeSortDescending) {
return $this->activeSortDescending ? 'desc' : 'asc';
}
if ( ! isset($this->getModelInformation()->list->columns[$column])) {
if (null === $column) {
return $this->getActualSortDirection($this->getDefaultSort());
}
return 'asc';
}
$direction = $this->getModelInformation()->list->columns[$column]->sort_direction;
return strtolower($direction) === 'desc' ? 'desc' : 'asc';
} | Returns the sort direction that is actually active, determined by
the specified sort direction with a fallback to the default.
@param string|null $column
@return string asc|desc | entailment |
protected function getModelSortCriteria()
{
$sort = $this->getActualSort();
$info = $this->getModelInformation();
// Sort by orderable strategy if we should and can
if ( $info->list->orderable
&& $sort == $info->list->getOrderableColumn()
&& ($orderableStrategy = $this->getOrderableSortStrategy())
) {
return $orderableStrategy;
}
// Otherwise, attempt to sort by any other list column
if ( ! isset($info->list->columns[$sort])) {
return false;
}
$strategy = $info->list->columns[$sort]->sort_strategy;
$source = $info->list->columns[$sort]->source ?: $sort;
return new ModelOrderStrategy($strategy, $source, $this->getActualSortDirection());
} | Returns the active model sorting criteria to apply to the model repository.
@return ModelOrderStrategy|false | entailment |
protected function applySort()
{
$sort = $this->getActualSort();
if ( ! $sort) return $this;
$criteria = $this->getModelSortCriteria();
if ( ! $criteria) return $this;
$this->getModelRepository()->pushCriteria($criteria, CriteriaKey::ORDER);
return $this;
} | Applies active sorting to model repository.
@return $this | entailment |
public function render(Model $model, $source)
{
return implode($this->getSeparator(), array_map('e', $model->tagNames()));
} | Renders a display value to print to the list view.
@param Model|Taggable $model
@param mixed $source source column, method name or value
@return string | entailment |
protected function performStep()
{
if ( ! $this->modelHasTrait($this->getListifyTraits())) {
return;
}
/** @var Listify $model */
$model = $this->model();
$this->info->list->orderable = true;
$this->info->list->order_strategy = 'listify';
$this->info->list->order_column = $model->positionColumn();
// Determine whether an (interpretable) scope is configured
if ( ! method_exists($model, 'getScopeName')) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
$scope = $model->getScopeName();
if ($scope instanceof Relation) {
// Attempt to resolve the relation method name from the relation instance
$this->info->list->order_scope_relation = $this->getRelationNameFromRelationInstance($scope);
}
} | Performs the analyzer step on the stored model information instance. | entailment |
protected function setSortingOrder()
{
if (null !== $this->info->list->default_sort) {
return $this;
}
if ($this->info->list->orderable && $this->info->list->getOrderableColumn()) {
$this->info->list->default_sort = $this->info->list->getOrderableColumn();
} elseif ($this->info->timestamps) {
$this->info->list->default_sort = $this->info->timestamp_created;
} elseif ($this->info->incrementing) {
$this->info->list->default_sort = $this->model->getKeyName();
}
return $this;
} | Sets default sorting order, if empty.
@return $this | entailment |
protected function setReferenceSource()
{
if (null !== $this->info->reference->source) {
return $this;
}
// No source is set, see if we can find a standard match
$matchAttributes = config('cms-models.analyzer.reference.sources', []);
foreach ($matchAttributes as $matchAttribute) {
if (array_key_exists($matchAttribute, $this->info->attributes)) {
$this->info->reference->source = $matchAttribute;
break;
}
}
return $this;
} | Sets default reference source, better than primary key, if possible.
@return $this | entailment |
protected function setDefaultRowActions()
{
$actions = $this->info->list->default_action ?: [];
if (count($actions)) {
return $this;
}
$addEditAction = config('cms-models.defaults.default-listing-action-edit', false);
$addShowAction = config('cms-models.defaults.default-listing-action-show', false);
if ( ! $addEditAction && ! $addShowAction) {
return $this;
}
// The edit and/or show action should be set as default index row click action.
$modelSlug = $this->getRouteHelper()->getRouteSlugForModelClass(get_class($this->model));
$permissionPrefix = $this->getRouteHelper()->getPermissionPrefixForModelSlug($modelSlug);
if ($addEditAction) {
$actions[] = [
'strategy' => ActionReferenceType::EDIT,
'permissions' => "{$permissionPrefix}edit",
];
}
if ($addShowAction) {
$actions[] = [
'strategy' => ActionReferenceType::SHOW,
'permissions' => "{$permissionPrefix}show",
];
}
$this->info->list->default_action = $actions;
return $this;
} | Sets default actions, if configured to and none are defined.
@return $this | entailment |
public function processedRules()
{
$decorator = $this->getRuleDecorator();
return $decorator->decorate(
$this->container->call([$this, 'rules'])
);
} | Returns post-processed validation rules.
@return array | entailment |
protected function failedValidation(Validator $validator)
{
throw (new ModelValidationException($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());
} | {@inheritdoc}
@throws \Czim\CmsModels\Exceptions\ModelValidationException | entailment |
protected function handlePaperclipAttachments()
{
// Paperclip / attachment attributes
$attachments = $this->detectPaperclipAttachments();
// Make a list of attributes to insert before the paperclip attributes
/** @var ModelAttributeData[] $inserts */
$inserts = [];
foreach ($attachments as $key => $attachment) {
$attribute = new ModelAttributeData([
'name' => $key,
'cast' => AttributeCast::PAPERCLIP_ATTACHMENT,
'type' => $attachment->image ? 'image' : 'file',
]);
$inserts[ $key . '_file_name' ] = $attribute;
}
if ( ! count($inserts)) {
return $this;
}
$attributes = $this->info->attributes;
foreach ($inserts as $before => $attribute) {
$attributes = $this->insertInArray($attributes, $attribute->name, $attribute, $before);
}
$this->info->attributes = $attributes;
return $this;
} | Handles analysis of paperclip attachments.
@return $this | entailment |
protected function detectPaperclipAttachments()
{
$model = $this->model();
if ( ! ($model instanceof PaperclippableInterface)) {
return [];
}
$files = $model->getAttachedFiles();
$attachments = [];
/** @var PaperclipAttachmentInstance[] $files */
foreach ($files as $attribute => $file) {
$variants = $file->variants();
$normalizedVariants = [];
foreach ($variants as $variant) {
if ($variant === 'original') {
continue;
}
$normalizedVariants[ $variant ] = $this->extractPaperclipVariantInfo($file, $variant);
}
$attachments[ $attribute ] = new PaperclipAttachmentData([
'image' => (is_array($variants) && count($variants) > 1),
'resizes' => array_pluck($normalizedVariants, 'dimensions'),
'variants' => $variants,
'extensions' => array_pluck($normalizedVariants, 'extension'),
'types' => array_pluck($normalizedVariants, 'mimeType'),
]);
}
return $attachments;
} | Returns list of paperclip attachments, if the model has any.
@return PaperclipAttachmentData[] assoc, keyed by attribute name | entailment |
protected function extractPaperclipVariantInfo(PaperclipAttachmentInstance $paperclip, $variant)
{
$config = $paperclip->getNormalizedConfig();
$variantSteps = array_get($config, "variants.{$variant}", []);
$dimensions = array_get($variantSteps, 'resize.dimensions');
$extension = array_get($variantSteps, "extensions.{$variant}");
$mimeType = array_get($variantSteps, "types.{$variant}");
return compact('dimensions', 'extension', 'mimeType');
} | Returns extracted data from the paperclip instance for a variant.
@param PaperclipAttachmentInstance $paperclip
@param string $variant
@return array associative | entailment |
protected function insertInArray($array, $key, $value, $beforeKey)
{
// Find the position of the array
$position = array_search($beforeKey, array_keys($array));
// Safeguard: silently append if injected position could not be found
if (false === $position) {
// @codeCoverageIgnoreStart
$array[ $key ] = $value;
return $array;
// @codeCoverageIgnoreEnd
}
if (0 === $position) {
return [ $key => $value ] + $array;
}
// Slice the array up with the new entry in between
return array_slice($array, 0, $position, true)
+ [ $key => $value ]
+ array_slice($array, $position, count($array) - $position, true);
} | Insert an item into an associative array at the position before a given key.
@param array $array
@param string $key
@param mixed $value
@param string $beforeKey
@return array | entailment |
public function render(Model $model, $source)
{
return view(static::VIEW, [
'color' => $this->resolveModelSource($model, $source),
]);
} | 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 performStep()
{
// Detect whether the model is translated; if not, skip this step
if ( ! $this->modelHasTrait($this->getTranslatableTraits())) {
return;
}
// Model is translated using translatable
$this->info->translated = true;
$this->info->translation_strategy = 'translatable';
$this->addIncludesDefault('translations');
$this->updateAttributesWithTranslated();
} | Performs the analyzer step on the stored model information instance. | entailment |
protected function updateAttributesWithTranslated()
{
$translationInfo = $this->translationAnalyzer()->analyze($this->model());
$attributes = $this->info['attributes'];
// Mark the fillable fields on the translation model
foreach ($translationInfo['attributes'] as $key => $attribute) {
/** @var ModelAttributeData $attribute */
if ( ! $attribute->translated) {
continue;
}
if ( ! isset($attributes[$key])) {
$attributes[$key] = $attribute;
}
/** @var ModelAttributeData $attributeData */
$attributeData = $attributes[$key];
$attributeData->merge($attribute);
$attributes[$key] = $attributeData;
}
$this->info['attributes'] = $attributes;
} | Updates model information attributes with translated attribute data. | entailment |
protected function applyRepositoryContext(
ModelRepositoryInterface $repository = null,
ModelInformationInterface $information = null
) {
$repository = $repository ?: call_user_func([ $this, 'getModelRepository' ]);
$information = $information ?: call_user_func([ $this, 'getModelInformation' ]);
$this->prepareRepositoryContextStrategy($repository, $information)
->disableGlobalScopes($repository, $information)
->applyIncludesToRepository($repository, $information);
return $this;
} | Applies criteria-based repository context strategies.
If repository or information are not given, they are read from standard
methods: getModelRepository() and getModelInformation respectively.
@param ModelRepositoryInterface|null $repository
@param ModelInformationInterface|ModelInformation|null $information
@return $this | entailment |
public function apply($query, $column, $direction = 'asc')
{
$direction = $direction === 'desc' ? 'desc' : 'asc';
if ($query instanceof Model) {
$query = $query->query();
}
$query = $this->applyNullLastQuery($query, $column);
return $query->orderBy($column, $direction);
} | 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 applyNullLastQuery($query, $column)
{
if ($this->databaseSupportsIf($query)) {
$query = $query->orderBy(DB::raw("IF(`{$column}` IS NULL,1,0)"));
}
return $query;
} | Applies logic to query builder to sort null or empty fields last.
@param Builder $query
@param string $column
@return Builder | entailment |
public function modules()
{
$modules = new Collection;
// Make meta module
$modules->push(
$this->makeMetaModuleInstance()
);
// Make model modules
foreach ($this->repository->getAll() as $modelInformation) {
$modules->push(
$this->makeModuleInstance($modelInformation)
);
}
return $modules;
} | Generates and returns module instances.
@return Collection|ModuleInterface[] | entailment |
protected function makeModuleInstance(ModelInformationInterface $information)
{
$modelClass = $information->modelClass();
$module = new ModelModule(
app(ModelInformationRepositoryInterface::class),
$this->moduleHelper,
app(RouteHelperInterface::class),
$this->makeModuleKey($modelClass),
$this->makeModuleName($modelClass)
);
$module->setAssociatedClass($modelClass);
if ($information->meta->controller) {
$module->setWebController($information->meta->controller);
}
if ($information->meta->controller_api) {
$module->setApiController($information->meta->controller_api);
}
return $module;
} | Makes a model module instance for model information.
@param ModelInformationInterface|ModelInformation $information
@return ModelModule | entailment |
public function extend($name, ExtensionInterface $extension)
{
$this->extensions->put($name, $extension);
return $this;
} | {@inheritdoc} | entailment |
public function getQuery()
{
$repository = $this->getRepository();
$query = $repository->getQuery();
if ($repository->isRestorable()) {
$query->withTrashed();
}
$this->apply($query);
return $query;
} | {@inheritdoc} | entailment |
public function orderBy($column, $direction = 'asc')
{
$this->addApply(function (Builder $query) use ($column, $direction) {
$query->orderBy($column, $direction);
});
return $this;
} | {@inheritdoc} | entailment |
public function get($key)
{
try {
$result = $this->bucket->get($this->resolveKey($key));
return $this->getMetaDoc($result);
} catch (CouchbaseException $e) {
return;
}
} | {@inheritdoc} | entailment |
public function add($key, $value, $minutes = 0): bool
{
$options = ($minutes === 0) ? [] : ['expiry' => ($minutes * 60)];
try {
$this->bucket->insert($this->resolveKey($key), $value, $options);
return true;
} catch (CouchbaseException $e) {
return false;
}
} | Store an item in the cache if the key doesn't exist.
@param string|array $key
@param mixed $value
@param int $minutes
@return bool | entailment |
public function put($key, $value, $minutes)
{
$this->bucket->upsert($this->resolveKey($key), $value, ['expiry' => $minutes * 60]);
} | {@inheritdoc} | entailment |
public function increment($key, $value = 1)
{
return $this->bucket
->counter($this->resolveKey($key), $value, ['initial' => abs($value)])->value;
} | {@inheritdoc} | entailment |
public function decrement($key, $value = 1)
{
return $this->bucket
->counter($this->resolveKey($key), (0 - abs($value)), ['initial' => (0 - abs($value))])->value;
} | {@inheritdoc} | entailment |
public function forever($key, $value)
{
try {
$this->bucket->insert($this->resolveKey($key), $value);
} catch (CouchbaseException $e) {
// bucket->insert when called from resetTag in TagSet can throw CAS exceptions, ignore.\
$this->bucket->upsert($this->resolveKey($key), $value);
}
} | {@inheritdoc} | entailment |
public function forget($key)
{
try {
$this->bucket->remove($this->resolveKey($key));
} catch (\Exception $e) {
// Ignore exceptions from remove
}
} | {@inheritdoc} | entailment |
public function flush()
{
$result = $this->bucket->manager()->flush();
if (isset($result['_'])) {
throw new FlushException($result);
}
} | flush bucket.
@throws FlushException
@codeCoverageIgnore | entailment |
public function setBucket(string $bucket, string $password = '', string $serialize = 'php'): CouchbaseStore
{
$this->bucket = $this->cluster->openBucket($bucket, $password);
if ($serialize === 'php') {
$this->bucket->setTranscoder('couchbase_php_serialize_encoder', 'couchbase_default_decoder');
}
return $this;
} | @param string $bucket
@param string $password
@param string $serialize
@return CouchbaseStore | entailment |
private function resolveKey($keys)
{
if (is_array($keys)) {
$result = [];
foreach ($keys as $key) {
$result[] = $this->prefix . $key;
}
return $result;
}
return $this->prefix . $keys;
} | @param $keys
@return array|string | entailment |
protected function getMetaDoc($meta)
{
if ($meta instanceof \Couchbase\Document) {
return $meta->value;
}
if (is_array($meta)) {
$result = [];
foreach ($meta as $row) {
$result[] = $this->getMetaDoc($row);
}
return $result;
}
return null;
} | @param $meta
@return array|null | entailment |
public function lock(string $name, int $seconds = 0): Lock
{
return new CouchbaseLock($this->bucket, $this->prefix.$name, $seconds);
} | Get a lock instance.
@param string $name
@param int $seconds
@return \Illuminate\Contracts\Cache\Lock | entailment |
protected function generateExport($path = null)
{
$temporary = $this->getTemporaryFilePath();
// Create new csv file
$resource = fopen($temporary, 'w');
if (false === $resource) {
throw new RuntimeException("Failed to open temporary export file '{$temporary}'");
}
try {
$this->writeCsvContent($resource);
} catch (Exception $e) {
throw $e;
} finally {
fclose($resource);
}
return $temporary;
} | Generates an export, download or local file.
@param null|string $path
@return mixed
@throws Exception | entailment |
protected function writeCsvContent($resource)
{
$columns = $this->exportInfo->columns;
$strategies = $this->getColumnStrategyInstances();
$delimiter = $this->getDelimiterSymbol();
$enclosure = $this->getEnclosureSymbol();
$escape = $this->getEscapeSymbol();
// Generate header row, if not disabled
if ($this->shouldHaveHeaderRow()) {
$headers = array_map(
function (ModelExportColumnDataInterface $column) {
return $column->header();
},
$columns
);
fputcsv($resource, $headers, $delimiter, $enclosure, $escape);
}
// For each query chunk: get a model instance,
// and for each column, generate the column content using the strategies
$this->query->chunk(
static::CHUNK_SIZE,
function ($records) use ($resource, $columns, $strategies, $delimiter, $enclosure, $escape) {
/** @var Collection|Model[] $records */
foreach ($records as $record) {
$fields = [];
foreach ($strategies as $key => $strategy) {
$fields[] = $strategy->render($record, $columns[$key]->source);
}
fputcsv($resource, $fields, $delimiter, $enclosure, $escape);
}
}
);
} | Writes CSV content to given file handle resource.
@param resource $resource | entailment |
protected function initializeDefaultValues()
{
$defaults = [];
$filters = $this->getFilterInformation();
foreach (array_keys($filters) as $key) {
$defaults[ $key ] = null;
}
$this->defaults = $defaults;
return $this;
} | Sets default values based on model information.
@return $this | entailment |
public function getElement($name)
{
$key = $this->getElements()->search(function (ElementInterface $item) use ($name
) {
return $item->getName() == $name;
});
if ($key === false) {
throw new InvalidArgumentException('Not found element');
}
return $this->getElements()->get($key);
} | {@inheritdoc} | entailment |
public function setModel(Model $model)
{
$this->model = $model;
$this->setElementModel($model);
return $this;
} | {@inheritdoc} | entailment |
public function setElementModel(Model $model)
{
$this->elements->each(function (ElementInterface $element) use ($model) {
//if ($element instanceof WithModel) {
$element->setModel($model);
//}
});
return $this;
} | {@inheritdoc} | entailment |
public function validate()
{
Validator::validate(
request()->all(),
$this->getValidationRules(),
$this->getValidationMessages(),
$this->getValidationTitles()
);
return $this;
} | {@inheritdoc} | entailment |
public function getValues()
{
return $this->elements->mapWithKeys(function (ElementInterface $element) {
return [
$element->getName() => $element->getValue(),
];
});
} | {@inheritdoc} | entailment |
protected function generateExport($path = null)
{
$temporary = $this->getTemporaryFilePath();
if ( ! app()->bound('excel')) {
throw new RuntimeException("Excel exporter strategy expected 'excel' to be bound for IoC");
}
/** @var Excel $excel */
$excel = app('excel');
$columns = $this->exportInfo->columns;
$strategies = $this->getColumnStrategyInstances();
$excel
->create(pathinfo($temporary, PATHINFO_FILENAME), function ($excel) use ($columns, $strategies) {
/** @var LaravelExcelWriter $excel */
$excel->setTitle($this->getTitle());
$excel->sheet($this->getWorksheetTitle(), function($sheet) use ($columns, $strategies) {
/** @var LaravelExcelWorksheet $sheet */
// Generate header row, if not disabled
if ($this->shouldHaveHeaderRow()) {
$headers = array_map(
function (ModelExportColumnDataInterface $column) {
return $column->header();
},
$columns
);
$sheet->appendRow($headers);
$sheet->freezeFirstRow();
// todo: style first row according to options
}
// For each query chunk: get a model instance,
// and for each column, generate the column content using the strategies
$this->query->chunk(
static::CHUNK_SIZE,
function ($records) use ($sheet, $columns, $strategies) {
/** @var Collection|Model[] $records */
foreach ($records as $record) {
$fields = [];
foreach ($strategies as $key => $strategy) {
$fields[] = $strategy->render($record, $columns[ $key ]->source);
}
$sheet->appendRow($fields);
// todo: style row according to options
}
}
);
});
})
->store($this->extension(), pathinfo($temporary, PATHINFO_DIRNAME));
return $temporary;
} | Generates an export, download or local file.
@param null|string $path
@return mixed
@throws Exception | entailment |
public function getOptionsModel()
{
$model = $this->options;
if (is_string($model)) {
$model = app($model);
}
if (! ($model instanceof Model)) {
throw new InvalidArgumentException(
sprintf(
'The %s element[%s] options class must be instanced of "%s".',
$this->getType(),
$this->getName(),
Model::class
)
);
}
return $model;
} | Get the options model.
@return Model | entailment |
protected function getOptionsFromModel()
{
if (is_null(($label = $this->getOptionsLabelAttribute()))) {
throw new InvalidArgumentException(
sprintf(
'The %s element[%s] options must set label attribute',
$this->getType(),
$this->getName()
)
);
}
$model = $this->getOptionsModel();
/**
* @var \Illuminate\Support\Collection $results
*/
$results = $model->get();
$key = $this->getOptionsValueAttribute() ?: $model->getKeyName();
return $results->pluck($label, $key);
} | Get the options from model.
@return \Illuminate\Support\Collection | entailment |
public function hasTable($table)
{
try {
$bucketInfo = $this->connection->openBucket($table)->manager()->info();
if (!is_null($bucketInfo['name'])) {
return true;
}
return true;
} catch (Exception $e) {
return false;
}
} | {@inheritdoc} | entailment |
public function create($collection, Closure $callback = null)
{
$blueprint = $this->createBlueprint($collection);
$blueprint->create();
sleep(10);
if ($callback) {
$callback($blueprint);
}
} | needs administrator password, user
@param string $collection
@param Closure|null $callback
@return void | entailment |
public function drop($collection)
{
$blueprint = $this->createBlueprint($collection);
$blueprint->drop();
sleep(10);
return true;
} | {@inheritdoc} | entailment |
protected function createBlueprint($table, Closure $callback = null): Blueprint
{
$blueprint = new Blueprint($table, $callback);
$blueprint->connector($this->connection);
return $blueprint;
} | {@inheritdoc} | entailment |
public function apply($query, $column, $direction = 'asc')
{
$direction = $direction === 'desc' ? 'desc' : 'asc';
$modelTable = $query->getModel()->getTable();
$modelKey = $query->getModel()->getKeyName();
$query->orderBy("{$modelTable}.{$modelKey}", $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 |
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'));
$fields = $this->argument('fields');
$whereClause = $this->option('where');
$name = $this->argument('name');
$bucket->manager()->createN1qlIndex(
$name,
$fields,
$whereClause,
$this->option('ignore'),
$this->option('defer')
);
$field = implode(",", $fields);
$this->info("created SECONDARY INDEX [{$name}] fields [{$field}], for [{$this->argument('bucket')}] bucket.");
if ($whereClause !== '') {
$this->comment("WHERE clause [{$whereClause}]");
}
}
return;
} | Execute the console command | entailment |
public function key()
{
if ( ! $this->isTranslated()) {
return $this->key;
}
$parts = explode('.', $this->key);
array_splice($parts, $this->localeIndex, 0, $this->getLocalePlaceholder());
return trim(implode('.', $parts), '.');
} | Returns the key in dot notation, with locale placeholder where relevant.
@return string|null | entailment |
public function prefixKey($prefix)
{
if (empty($this->key)) {
$this->key = $prefix;
} else {
$this->key = $prefix . '.' . $this->key;
}
return $this;
} | Prefixes the currently set key with a dot-notation parent.
The (final) dot (.) should not be included in the prefix string.
@param string $prefix
@return $this | entailment |
public function initialize()
{
if ($this->isInformationCached()) {
$this->information = $this->retrieveInformationFromCache();
} else {
$this->information = $this->collector->collect();
}
$this->fillModelClassIndex();
$this->initialized = true;
return $this;
} | Initializes the repository so it may provide model information.
@return $this | entailment |
public function getByModelClass($class)
{
$this->checkInitialization();
if ( ! array_key_exists($class, $this->modelClassIndex)) {
return false;
}
return $this->getByKey($this->modelClassIndex[$class]);
} | Returns model information by the model's FQN.
@param string $class
@return ModelInformation|false | entailment |
public function writeCache()
{
$this->getFileSystem()->put($this->getCachePath(), $this->serializedInformationForCache($this->information));
return $this;
} | Caches model information.
@return $this | entailment |
protected function fillModelClassIndex()
{
$this->modelClassIndex = [];
foreach ($this->information as $index => $information) {
$this->modelClassIndex[ $information->modelClass() ] = $index;
}
return $this;
} | Populates the index for associated class FQNs with the loaded information.
@return $this | entailment |
public function getDefaultAction()
{
// Determine the appliccable action
if ( ! $this->default_action) {
return null;
}
$actions = $this->default_action;
if ( ! is_array($actions)) {
$actions = [
new ModelActionReferenceData([
'strategy' => $actions,
]),
];
}
$core = $this->getCore();
foreach ($actions as $action) {
$permissions = $action->permissions();
if ( ! count($permissions)
|| $core->auth()->user()->isAdmin()
|| $core->auth()->user()->can($permissions)
) {
return $action;
}
}
return null;
} | Returns the default action for list rows.
@return ModelActionReferenceDataInterface|null | entailment |
public function render(Model $model, $source)
{
$relation = $this->getActualNestedRelation($model, $source);
$count = $this->getCount($relation);
if ( ! $count) {
return '<span class="relation-count count-empty"> </span>';
}
if ( ! $this->listColumnData) {
throw new RuntimeException('List column data must be set');
}
// Use the options or relation to get the relevant context for the link
$relationMethod = array_get($this->listColumnData->options(), 'relation');
$modelClass = array_get($this->listColumnData->options(), 'model', get_class($relation->getRelated()));
if ( ! $relationMethod) {
throw new RuntimeException(get_class($this) . ' requires option.relation to be set!');
}
$childrenName = $this->getVerboseChildrenName($modelClass);
if ($this->isMorphToRelation($modelClass, $relationMethod)) {
$parentIndicator = $this->getMorphTypeForModel($model) . ':' . $model->getKey();
} else {
$parentIndicator = $model->getKey();
}
return view(static::VIEW, [
'count' => $count,
'link' => $this->getChildrenLink($parentIndicator, $relationMethod, $modelClass),
'childrenName' => $childrenName,
]);
} | Renders a display value to print to the list view.
@param Model $model
@param mixed $source source column, method name or value
@return string|View | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.