sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setMaxFileSize(int $value) { $this->maxFileSize = $value; $this->addValidationRule('max:' . $this->maxFileSize); return $this; }
The maximum size allowed for an uploaded file in kilobytes @param int $value @return $this
entailment
public function setFileExtensions(string $value) { $this->fileExtensions = $value; $this->addValidationRule('mimes:' . $value); return $this; }
A list of allowable extensions that can be uploaded. @param string $value @return $this
entailment
public function saveFile(UploadedFile $file) { Validator::validate( [$this->getName() => $file], $this->getUploadValidationRules(), $this->getUploadValidationMessages(), $this->getUploadValidationTitles() ); $path = $file->storeAs( $this->getUploadPath($file), $this->getUploadFileName($file), $this->getDisk() ); return $this->getFileInfo($path); }
Save file to storage @param \Illuminate\Http\UploadedFile $file @return array @throws \Illuminate\Validation\ValidationException
entailment
protected function getFileInfo($path) { return [ 'name' => substr($path, strrpos($path, '/') + 1), 'path' => $path, 'url' => $this->getFileUrl($path), ]; }
Get file info(name,path,url) @param $path @return array
entailment
public function check(Model $model, array $parameters = []) { $this->model = $model; $this->parameters = $parameters; return $this->performCheck(); }
Returns whether deletion is allowed. @param Model $model @param array $parameters strategy-dependent parameters @return bool
entailment
protected function adjustValue($value) { $useUpload = $this->useFileUploader(); // Normalize to an array if required if ( ! is_array($value)) { $value = [ 'keep' => 0, 'upload' => $useUpload ? null : $value, 'upload_id' => $useUpload ? $value : null, ]; } // If the value is empty, use the stapler null value instead if (empty($value['upload'])) { // @codeCoverageIgnoreStart $value['upload'] = $this->getNullAttachmentHash(); // @codeCoverageIgnoreEnd } return $value; }
Adjusts or normalizes a value before storing it. @param mixed $value @return mixed
entailment
protected function getStrategySpecificRules(ModelFormFieldDataInterface $field = null) { // Build up validation rules $fileRules = $this->getFileValidationRules(); if ( ! is_array($fileRules)) { $fileRules = explode('|', $fileRules); } if ( ! in_array('file', $fileRules)) { $fileRules[] = 'file'; } $keepRules = ['boolean']; $fileIdRules = ['integer']; // Modify rules for required fields that may be either uploaded directly or asynchronously. if ($this->formFieldData->required && ! $this->formFieldData->translated) { $fileRules[] = 'required_without_all:<field>.upload_id,<field>.keep'; $keepRules[] = 'required_without_all:<field>.upload,<field>.upload_id'; $fileIdRules[] = 'required_without_all:<field>.upload,<field>.keep'; } else { if ( ! in_array('nullable', $fileRules)) { $fileRules[] = 'nullable'; } $keepRules[] = 'nullable'; $fileIdRules[] = 'nullable'; } return [ 'keep' => $keepRules, 'upload' => $fileRules, 'upload_id' => $fileIdRules, ]; }
Returns validation rules specific for the strategy. @param ModelFormFieldDataInterface|ModelFormFieldData $field @return array|false|null null to fall back to default rules.
entailment
protected function markJobAsReserved($job) { $bucket = $this->table; /** @var \Couchbase\Bucket $openBucket */ $openBucket = $this->database->openBucket($bucket); // lock bucket $meta = $openBucket->getAndLock($job->id, 10); $meta->value->attempts = $job->$bucket->attempts + 1; $meta->value->reserved_at = $job->touch(); $openBucket->replace($job->id, $meta->value, ['cas' => $meta->cas]); return $meta->value; }
{@inheritdoc}
entailment
public function deleteReserved($queue, $id) { $this->database->table($this->table)->where('id', $id)->delete(); }
{@inheritdoc}
entailment
protected function pushToDatabase($queue, $payload, $delay = 0, $attempts = 0) { $attributes = $this->buildDatabaseRecord( $this->getQueue($queue), $payload, $this->availableAt($delay), $attempts ); $increment = $this->incrementKey(); $attributes['id'] = $increment; $result = $this->database->table($this->table) ->key($this->uniqueKey($attributes))->insert($attributes); if ($result) { return $increment; } return false; }
{@inheritdoc}
entailment
protected function incrementKey($initial = 1) { $result = $this->database->openBucket($this->table) ->counter($this->identifier(), $initial, ['initial' => abs($initial)]); return $result->value; }
generate increment key @param int $initial @return int
entailment
public function insert(array $values) { if (empty($values)) { return true; } $values = $this->detectValues($values); $bindings = []; foreach ($values as $record) { foreach ($record as $key => $value) { $bindings[$key] = $value; } } $sql = $this->grammar->compileInsert($this, $values); return $this->connection->insert($sql, $bindings); }
Insert a new record into the database. @param array $values @return bool
entailment
public function upsert(array $values) { if (empty($values)) { return true; } $values = $this->detectValues($values); $bindings = []; foreach ($values as $record) { foreach ($record as $key => $value) { $bindings[$key] = $value; } } $sql = $this->grammar->compileUpsert($this, $values); return $this->connection->upsert($sql, $bindings); }
supported N1QL upsert query. @param array $values @return bool|mixed
entailment
protected function detectValues($values): array { if (!is_array(reset($values))) { $values = [$values]; } else { foreach ($values as $key => $value) { ksort($value); $values[$key] = $value; } } return $values; }
@param string|int|array $values @return array
entailment
public function retrieve(Model $model, $source) { return [ 'from' => parent::retrieve($model, $this->getAttributeFrom()), 'to' => parent::retrieve($model, $this->getAttributeTo()), ]; }
Retrieves current values from a model @param Model $model @param string $source @return mixed
entailment
protected function adjustValue($value) { if (preg_match('#^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$#', $value, $matches)) { $value .= ':00'; } elseif (preg_match('#^\d{4}-\d{2}-\d{2}$#', $value, $matches)) { $value .= ' 00:00:00'; } return $value; }
Adjusts or normalizes a value before storing it. Makes sure the date format is what Carbon expects. @param mixed $value @return mixed
entailment
protected function getStrategySpecificRules(ModelFormFieldDataInterface $field = null) { $format = $this->getExpectedDateFormat(); $base = $this->isNullable() ? ['nullable'] : []; if ( ! $format) { return [ new ValidationRuleData(array_merge($base, [ 'date' ]), 'from'), new ValidationRuleData(array_merge($base, [ 'date' ]), 'to'), ]; } return [ new ValidationRuleData(array_merge($base, [ 'date_format:' . $format ]), 'from'), new ValidationRuleData(array_merge($base, [ 'date_format:' . $format ]), 'to'), ]; }
Returns validation rules specific for the strategy. @param ModelFormFieldDataInterface|ModelFormFieldData $field @return array|false|null null to fall back to default rules.
entailment
protected function getAttributeFrom() { $attribute = array_get($this->formFieldData->options(), 'from', $this->formFieldData->source()); if ( ! $attribute) { throw new UnexpectedValueException("DateRangeStrategy must have 'date_from' option set"); } return $attribute; }
Returns attribute name for the 'from' date. @return string
entailment
protected function makeModelRepository() { $repository = new ModelRepository($this->modelInformation->modelClass()); $this->applyRepositoryContext($repository, $this->modelInformation); return $repository; }
Sets up the model repository for the relevant model. @return ModelRepositoryInterface
entailment
public function register() { $configPath = __DIR__ . '/config/couchbase.php'; $this->mergeConfigFrom($configPath, 'couchbase'); $this->publishes([$configPath => config_path('couchbase.php')], 'couchbase'); $this->registerCouchbaseComponent(); }
{@inheritdoc}
entailment
protected function registerCouchbaseBucketCacheDriver(): void { $this->app['cache']->extend('couchbase', function ($app, $config) { /** @var \Couchbase\Cluster $cluster */ $cluster = $app['db']->connection($config['driver'])->getCouchbase(); $password = (isset($config['bucket_password'])) ? $config['bucket_password'] : ''; return new Repository( new CouchbaseStore( $cluster, $config['bucket'], $password, $app['config']->get('cache.prefix') ) ); }); }
register 'couchbase' cache driver. for bucket type couchbase.
entailment
protected function registerMemcachedBucketCacheDriver(): void { $this->app['cache']->extend('couchbase-memcached', function ($app, $config) { $prefix = $app['config']['cache.prefix']; $credential = $config['sasl'] ?? []; $memcachedBucket = $this->app['couchbase.memcached.connector'] ->connect($config['servers']); return new Repository( new MemcachedBucketStore( $memcachedBucket, strval($prefix), $config['servers'], $credential ) ); }); }
register 'couchbase' cache driver. for bucket type memcached.
entailment
protected function registerCouchbaseQueueDriver(): void { /** @var QueueManager $queueManager */ $queueManager = $this->app['queue']; $queueManager->addConnector('couchbase', function () { /** @var DatabaseManager $databaseManager */ $databaseManager = $this->app['db']; return new QueueConnector($databaseManager); }); }
register custom queue 'couchbase' driver
entailment
public function getName() { if (is_null($this->name)) { $this->setName($this->getDefaultName()); } return $this->name; }
{@inheritdoc}
entailment
public function getModel() { if (is_null($this->model)) { $this->setModel($this->makeModel()); } return $this->model; }
{@inheritdoc}
entailment
public function getRepository() { if (is_null($this->repository)) { $this->setRepository($this->makeRepository()); } return $this->repository; }
{@inheritdoc}
entailment
final public function fireDisplay() { if (! method_exists($this, 'callDisplay')) { return; } $display = $this->app->call([$this, 'callDisplay']); if (! ($display instanceof DisplayInterface)) { throw new InvalidArgumentException( sprintf( 'callDisplay must be instanced of "%s".', DisplayInterface::class ) ); } $display->setModel($this->getModel()); return $display; }
{@inheritdoc}
entailment
final public function fireCreate() { if (! method_exists($this, 'callCreate')) { return; } $form = $this->app->call([$this, 'callCreate']); if (! $form instanceof FormInterface) { throw new InvalidArgumentException( sprintf( 'callCreate must be instanced of "%s".', FormInterface::class ) ); } $form->setModel($this->getModel()); return $form; }
{@inheritdoc}
entailment
final public function fireEdit($id) { if (! method_exists($this, 'callEdit')) { return; } $form = $this->app->call([$this, 'callEdit'], ['id' => $id]); if (! $form instanceof FormInterface) { throw new InvalidArgumentException( sprintf( 'callEdit must be instanced of "%s".', FormInterface::class ) ); } $model = $this->getRepository()->findOrFail($id); $form->setModel($model); return $form; }
{@inheritdoc}
entailment
public function update($id) { $form = $this->fireEdit($id); if ($form) { return $form->validate()->save(); } return; }
{@inheritdoc}
entailment
protected function bootTraits() { foreach (class_uses_recursive($this) as $trait) { if (method_exists($this, $method = 'boot' . class_basename($trait))) { $this->$method(); } } }
Boot all of the bootable traits on the model. @return void
entailment
public function getColumns($table, $connection = null) { $this->updateConnection($connection)->setUpDoctrineSchema(); $this->validateTableName($table); $columns = DB::connection($this->connection)->select( DB::connection($this->connection)->raw("show columns from `{$table}`") ); $columnData = []; foreach ($columns as $column) { $columnData[] = [ 'name' => $column->Field, 'type' => $this->getColumnBaseTypeFromType($column->Type), 'length' => $this->getColumnLengthFromType($column->Type), 'values' => $this->getEnumValuesFromType($column->Type), 'unsigned' => $this->getColumnIsNullableFromType($column->Type), 'nullable' => ! preg_match('#^\s*no\s*$#i', $column->Null), ]; } return $columnData; }
Returns column information for a given table. @param string $table @param string|null $connection optional connection name @return array
entailment
protected function getEnumValuesFromType($type) { if ( ! preg_match('#^enum\((?<values>.*)\)$#i', $type, $matches)) { return false; } $enum = []; foreach (explode(',', $matches['values']) as $value) { $v = trim( $value, "'" ); $enum[] = $v; } return $enum; }
Returns enum values for column type string. @param string $type @return array|bool
entailment
public function setFilters(array $filters) { if (empty($filters)) { return $this->clearFilters(); } session()->put($this->getSessionKey(static::TYPE_FILTERS), $filters); return $this; }
Sets filter data for the current context. @param array $filters @return $this
entailment
public function setSortData($column, $direction = null) { if (null === $column) { return $this->clearSortData(); } session()->put($this->getSessionKey(static::TYPE_SORT), [ 'column' => $column, 'direction' => $direction, ]); return $this; }
Sets filter data for the current context. @param string $column @param null|string $direction @return $this
entailment
public function setPage($page) { if (empty($page)) { return $this->clearPage(); } session()->put($this->getSessionKey(static::TYPE_PAGE), $page); return $this; }
Sets active page for the current context. @param int $page @return $this
entailment
public function setPageSize($size) { if ( ! $size) { return $this->clearPageSize(); } session()->put($this->getSessionKey(static::TYPE_PAGESIZE), $size); return $this; }
Sets active page size for the current context. @param int $size @return $this
entailment
public function setScope($scope) { if (empty($scope)) { return $this->clearScope(); } session()->put($this->getSessionKey(static::TYPE_SCOPE), $scope); return $this; }
Sets active scope for the current context. @param string $scope @return $this
entailment
public function getListParent() { $parent = session()->get($this->getSessionKey(static::TYPE_PARENT)); if (null === $parent) { return null; } if (static::PARENT_DISABLE === $parent) { return false; } list($relation, $key) = explode(':', $parent, 2); return compact('relation', 'key'); }
Returns active parent for current context. @return null|false|array associative: 'relation', 'key'; false for disabled filter; null for default/unset
entailment
public function setListParent($relation, $recordKey = null) { if (false !== $relation && empty($relation)) { return $this->clearListParent(); } if (false === $relation) { session()->put($this->getSessionKey(static::TYPE_PARENT), static::PARENT_DISABLE); } else { session()->put($this->getSessionKey(static::TYPE_PARENT), $relation . ':' . $recordKey); } return $this; }
Sets active parent for the current context. @param string|false $relation false to disable default top-level only filter, otherwise model key string @param mixed $recordKey @return $this
entailment
protected function getSessionKey($type = null) { return $this->context . ($this->contextSub ? '[' . $this->contextSub . ']' : null) . ($type ? ':' . $type : null); }
Returns session key, optionally for a given type of data. @param string|null $type @return string
entailment
protected function isUploadModuleAvailable() { if ($this->isUploadModuleAvailable === null) { $this->isUploadModuleAvailable = false !== $this->getUploadModule() && app()->bound(FileRepositoryInterface::class); } return $this->isUploadModuleAvailable; }
Returns whether the upload module is loaded. @return bool
entailment
protected function checkFileUploadWithSessionGuard($id) { $guard = $this->getFileUploadSesssionGuard(); return ! $guard->enabled() || $guard->check($id); }
Returns whether file upload is allowed to be used within this session. @param int $id @return bool
entailment
protected function checkAttributeAssignable($attribute): void { if ( ! $this->exceptionOnUnknown || empty($this->known)) { // @codeCoverageIgnoreStart return; // @codeCoverageIgnoreEnd } if (is_array($attribute)) { foreach ($attribute as $singleAttribute) { $this->checkAttributeAssignable($singleAttribute); } return; } if ( ! in_array($attribute, $this->known, true)) { throw (new ModelConfigurationDataException( "Unknown model configuration data key: '{$attribute}' in " . get_class($this) )) ->setDotKey($attribute); } }
Overridden to use for known nested attribute checks {@inheritdoc} @throws ModelConfigurationDataException
entailment
public function modelSlug($model) { if (is_object($model)) { $model = get_class($model); } return str_replace('\\', '-', strtolower($model)); }
Returns the model slug for a model or model FQN. @param string|Model $model @return string
entailment
public function connect(array $servers): Cluster { $configure = array_merge($this->configure, $servers); $cluster = new Cluster($configure['host']); if (!empty($configure['user']) && !empty($configure['password'])) { $cluster->authenticateAs(strval($configure['user']), strval($configure['password'])); } return $cluster; }
@param array $servers @return Cluster
entailment
public function dropPrimary($index = null, $ignoreIfNotExist = false) { $this->connection->openBucket($this->getTable()) ->manager()->dropN1qlPrimaryIndex($this->detectIndexName($index), $ignoreIfNotExist); }
drop for N1QL primary index @param string $index @param bool $ignoreIfNotExist @return mixed
entailment
public function dropIndex($index, $ignoreIfNotExist = false) { $this->connection->openBucket($this->getTable()) ->manager()->dropN1qlIndex($index, $ignoreIfNotExist); }
drop for N1QL secondary index @param string $index @param bool $ignoreIfNotExist @return mixed
entailment
public function primaryIndex($name = null, $ignoreIfExist = false, $defer = false) { $this->connection->openBucket($this->getTable()) ->manager()->createN1qlPrimaryIndex( $this->detectIndexName($name), $ignoreIfExist, $defer ); }
Specify the primary index for the current bucket. @param string|null $name @param boolean $ignoreIfExist if a primary index already exists, an exception will be thrown unless this is set to true. @param boolean $defer true to defer building of the index until buildN1qlDeferredIndexes()}is called (or a direct call to the corresponding query service API).
entailment
public function index($columns, $name = null, $whereClause = '', $ignoreIfExist = false, $defer = false) { $name = (is_null($name)) ? $this->getTable() . "_secondary_index" : $name; return $this->connection->openBucket($this->getTable()) ->manager()->createN1qlIndex( $name, $columns, $whereClause, $ignoreIfExist, $defer ); }
Specify a secondary index for the current bucket. @param array $columns the JSON fields to index. @param string $name the name of the index. @param string $whereClause the WHERE clause of the index. @param boolean $ignoreIfExist if a secondary index already exists with that name, an exception will be thrown unless this is set to true. @param boolean $defer true to defer building of the index until buildN1qlDeferredIndexes() is called (or a direct call to the corresponding query service API). @return mixed
entailment
protected function resolveModelSource(Model $model, $source) { // If the strategy indicates a method to be called on the model itself, do so if ($method = $this->parseAsModelMethodStrategyString($source, $model)) { return $model->{$method}(); } // If the strategy indicates an instantiable/callable 'class@method' combination if ($data = $this->parseAsInstantiableClassMethodStrategyString($source)) { $method = $data['method']; $instance = $data['instance']; return $instance->{$method}($model); } // If the name matches a method name on the model, call it if (method_exists($model, $source)) { return $model->{$source}(); } return $model->{$source}; }
Resolves and returns source content for a list strategy. @param Model $model @param string $source @return mixed
entailment
public function getRouteNameForModelInformation(ModelInformationInterface $information, $prefix = false) { if ( ! $information->modelClass()) { throw new \UnexpectedValueException("No model class in information, cannot make route name"); } return $this->getRouteNameForModelClass($information->modelClass(), $prefix); }
Returns the route name for a given set of model information. @param ModelInformationInterface $information @param bool $prefix @return string
entailment
public function getRouteNameForModelClass($modelClass, $prefix = false) { $modelSlug = static::MODEL_ROUTE_NAME_PREFIX . $this->getRouteSlugForModelClass($modelClass); if ( ! $prefix) { return $modelSlug; } return config('cms-core.route.name-prefix') . config('cms-models.route.name-prefix') . $modelSlug; }
Returns the route name for a given model FQN. @param string $modelClass @param bool $prefix whether to include CMS & model module prefixes @return string
entailment
public function getRoutePathForModelInformation(ModelInformationInterface $information, $prefix = false) { if ( ! $information->modelClass()) { throw new \UnexpectedValueException("No model class in information, cannot make route path"); } return $this->getRoutePathForModelClass($information->modelClass(), $prefix); }
Returns the route path for a given set of model information. @param ModelInformationInterface $information @param bool $prefix @return string
entailment
public function getRoutePathForModelClass($modelClass, $prefix = false) { $modelSlug = $this->getRouteSlugForModelClass($modelClass); if ( ! $prefix) { return $modelSlug; } return config('cms-core.route.prefix') . config('cms-models.route.prefix') . '/' . $modelSlug; }
Returns the route path for a given model FQN. @param string $modelClass @param bool $prefix whether to include CMS & model module prefixes @return string
entailment
public function getPermissionPrefixForModuleKey($key) { if (starts_with($key, ModuleHelper::MODULE_PREFIX)) { $key = substr($key, strlen(ModuleHelper::MODULE_PREFIX)); } return $this->getPermissionPrefixForModelSlug($key); }
Returns the full permission prefix for a model module's key. @param string $key full module key to add to the prefix @return string
entailment
protected function getModelModuleKeyForRouteNameSegment($nameSegment) { if (false === $nameSegment) { return false; } return ModuleHelper::MODULE_PREFIX . $this->getModelSlugForRouteNameSegment($nameSegment); }
Returns the model module key for a model route name segment. This includes the 'models.' prefix, it is a full module key. @param string $nameSegment @return string
entailment
protected function getModelSlugForRouteNameSegment($nameSegment) { $dotPosition = strpos($nameSegment, '.'); if (false === $dotPosition) { return $nameSegment; } return substr($nameSegment, 0, $dotPosition); }
Returns the model slug for a model route name segment. @param string $nameSegment @return string
entailment
protected function getModelRouteNameSegment($routeName = null) { $routeName = $routeName ?: $this->getRouteName(); $combinedPrefix = config('cms-core.route.name-prefix') . config('cms-models.route.name-prefix') . static::MODEL_ROUTE_NAME_PREFIX; if ( ! starts_with($routeName, $combinedPrefix)) { return false; } return substr($routeName, strlen($combinedPrefix)); }
Returns the route name part that represents the model. @param string|null $routeName if not set, uses current route @return false|string
entailment
public function get($name, $default = null) { return isset($this->attributes[$name]) ? $this->attributes[$name] : $default; }
Returns the value of an attribute. @param string $name The name for the attribute @param string $default Default value if attribute is not set. @return string|mixed The attribute value
entailment
protected function resolveStrategyClass($strategy) { if (empty($strategy)) { return false; } if ( ! str_contains($strategy, '.')) { $strategy = config($this->getAliasesBaseConfigKey() . $strategy, $strategy); } if (class_exists($strategy) && is_a($strategy, $this->getStrategyInterfaceClass(), true)) { return $strategy; } $strategy = $this->prefixStrategyNamespace($strategy); if (class_exists($strategy) && is_a($strategy, $this->getStrategyInterfaceClass(), true)) { return $strategy; } return false; }
Resolves strategy assuming it is the class name or FQN of an action strategy 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 getNestedRelation(Model $model, $source, $actual = false) { if ($source instanceof Relation) { return $source; } // If the source is user-configured, resolve it $relationNames = explode('.', $source); $relationName = array_shift($relationNames); if ( ! method_exists($model, $relationName)) { throw new UnexpectedValueException( 'Model ' . get_class($model) . " does not have relation method {$relationName}" ); } /** @var Relation $relation */ $relation = $model->{$relationName}(); if ( ! ($relation instanceof Relation)) { throw new UnexpectedValueException( 'Model ' . get_class($model) . ".{$relationName} is not an Eloquent relation" ); } if ( ! count($relationNames)) { return $relation; } // Handle nested relation count if dot notation is used // We can do nesting for translations, if we assume the current locale's translation // todo if ($actual && ! $this->isRelationSingle($relation)) { throw new UnexpectedValueException( 'Model ' . get_class($model) . ".{$relationName} does not allow deeper nesting (not to-one)" ); } // Retrieve nested relation for actual or abstract context if ($actual) { $model = $relation->first(); } else { $model = $relation->getRelated(); } if ( ! $model) return null; return $this->getNestedRelation($model, implode('.', $relationNames)); }
Returns relation nested to any level for a dot notation source. Note that actual relation resolution can only be done for singular nested relations (all the way down). @param Model $model @param string $source @param bool $actual whether the relation should be returned for an actual model @return Relation|null
entailment
public function setColumns(array $columns) { foreach ($columns as $column) { $this->columns->push($column); } return $this; }
@param array $columns @return $this
entailment
public function apply($query, $target, $value, $parameters = []) { $this->model = $query->getModel(); $this->parameters = $parameters; $targets = $this->parseTargets($target); // If there is only a single target, do not group the condition. if (count($targets) == 1) { $this->applyForSingleTarget($query, head($targets), $value, true); return; } // If we combine with the 'or' operator, group the filter's conditions // so the relation with the other filters is kept inclusive. $query->where(function ($query) use ($targets, $value) { $this->combineOr = true; foreach ($targets as $index => $singleTarget) { $this->applyForSingleTarget($query, $singleTarget, $value, $index < 1); } }); }
Applies the filter value to the query. @param Builder $query @param string $target @param mixed $value @param array $parameters
entailment
protected function applyForSingleTarget($query, array $targetParts, $value, $isFirst = false) { $this->translated = $this->isTranslatedTargetAttribute($targetParts, $query->getModel()); $this->applyRecursive($query, $targetParts, $value, $isFirst); }
Applies the filter for a single part of multiple targets @param Builder $query @param array $targetParts @param mixed $value @param bool $isFirst whether this is the first expression (between brackets)
entailment
protected function parseTargets($targets) { $targets = array_map( [$this, 'parseTarget'], explode(',', $targets) ); return $this->interpretSpecialTargets($targets); }
Parses string of (potentially) multiple targets to make a normalized array. @param string $targets @return array array of normalized target array
entailment
protected function applyRecursive($query, array $targetParts, $value, $isFirst = false) { if (count($targetParts) < 2) { if ($this->translated) { return $this->applyTranslatedValue($query, head($targetParts), $value, $isFirst); } return $this->applyValue($query, head($targetParts), $value, null, $isFirst); } $relation = array_shift($targetParts); $whereHasMethod = ! $isFirst && $this->combineOr ? 'orWhereHas' : 'whereHas'; return $query->{$whereHasMethod}( $relation, function ($query) use ($targetParts, $value) { return $this->applyRecursive($query, $targetParts, $value, true); } ); }
Applies a the filter value recursively for normalized target segments. @param Builder $query @param string[] $targetParts @param mixed $value @param bool $isFirst whether this is the first expression (between brackets) @return mixed
entailment
protected function applyTranslatedValue($query, $target, $value, $isFirst = false) { $whereHasMethod = ! $isFirst && $this->combineOr ? 'orWhereHas' : 'whereHas'; return $query->{$whereHasMethod}('translations', function ($query) use ($target, $value) { $this->applyLocaleRestriction($query); return $this->applyValue($query, $target, $value, false, true); }); }
Applies a value directly to a builder object. @param Builder $query @param string $target @param mixed $value @param bool $isFirst whether this is the first expression (between brackets) @return mixed
entailment
protected function interpretSpecialTargets(array $targets) { $normalized = []; foreach ($targets as $targetParts) { // Detect '*' and convert to all attributes if (count($targetParts) == 1 && trim(head($targetParts)) == '*') { $normalized += $this->makeTargetsForAllAttributes(); continue; } $normalized[] = $targetParts; } return $normalized; }
Interprets and translates special targets into separate target arrays. Think of a special target like '*', which should be translated into separate condition targets for each (relevant) attribute of the model. @param array $targets @return array
entailment
protected function makeTargetsForAllAttributes() { $modelInfo = $this->getModelInformation(); if ( ! $modelInfo) { // @codeCoverageIgnoreStart return []; // @codeCoverageIgnoreEnd } $targets = []; foreach ($modelInfo->attributes as $key => $attribute) { if ( ! $this->isAttributeRelevant($attribute)) continue; $targets[] = $this->parseTarget($key); } return $targets; }
Returns a targets array with normalized target parts for all relevant attributes of the main query model. @return array
entailment
protected function getModelInformation() { if (null === $this->model) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } return $this->getModelInformationRepository()->getByModel($this->model); }
Returns model information instance for query, if possible. @return ModelInformation|false
entailment
public function register() { $this->app->singleton('migration.repository', function ($app) { $table = $app['config']['database.migrations']; return new CouchbaseMigrationRepository($app['db'], $table); }); }
{@inheritdoc}
entailment
protected function registerCommands(): void { $this->app->singleton('command.couchbase.indexes', function ($app) { return new IndexFinderCommand($app['Illuminate\Database\DatabaseManager']); }); $this->app->singleton('command.couchbase.primary.index.create', function ($app) { return new PrimaryIndexCreatorCommand($app['Illuminate\Database\DatabaseManager']); }); $this->app->singleton('command.couchbase.primary.index.drop', function ($app) { return new PrimaryIndexRemoverCommand($app['Illuminate\Database\DatabaseManager']); }); $this->app->singleton('command.couchbase.index.create', function ($app) { return new IndexCreatorCommand($app['Illuminate\Database\DatabaseManager']); }); $this->app->singleton('command.couchbase.index.drop', function ($app) { return new IndexRemoverCommand($app['Illuminate\Database\DatabaseManager']); }); $this->app->singleton('command.couchbase.queue.index.create', function ($app) { return new QueueCreatorCommand($app['Illuminate\Database\DatabaseManager']); }); $this->app->singleton('command.couchbase.design.document.create', function ($app) { return new DesignCreatorCommand( $app['Illuminate\Database\DatabaseManager'], $app['config']->get('couchbase.design') ); }); $this->commands([ 'command.couchbase.indexes', 'command.couchbase.primary.index.create', 'command.couchbase.primary.index.drop', 'command.couchbase.index.create', 'command.couchbase.index.drop', 'command.couchbase.queue.index.create', 'command.couchbase.design.document.create', ]); }
register laravel-couchbase commands
entailment
protected function performEnrichment() { if ( ! count($this->info->show->fields)) { $this->fillDataForEmpty(); } else { $this->enrichCustomData(); } }
Performs enrichment.
entailment
protected function fillDataForEmpty() { // Fill list references if they are empty $fields = []; // Add fields for attributes foreach ($this->info->attributes as $attribute) { if ($attribute->hidden || ! $this->shouldAttributeBeDisplayedByDefault($attribute, $this->info)) { continue; } $fields[ $attribute->name ] = $this->makeModelShowFieldDataForAttributeData($attribute, $this->info); } // Add fields for relations? // Perhaps, though it may be fine to leave this up to manual configuration. // todo: consider $this->info->show->fields = $fields; }
Fills field data if no custom data is set.
entailment
protected function enrichCustomData() { // Check filled fields and enrich them as required // Note that these can be either attributes or relations $fields = []; foreach ($this->info->show->fields as $key => $field) { try { $this->enrichField($key, $field, $fields); } catch (\Exception $e) { // Wrap and decorate exceptions so it is easier to track the problem source throw (new ModelInformationEnrichmentException( "Issue with show field '{$key}' (show.fields.{$key}): \n{$e->getMessage()}", $e->getCode(), $e )) ->setSection('show.fields') ->setKey($key); } } $this->info->show->fields = $fields; }
Enriches existing user configured data.
entailment
protected function enrichField($key, ModelShowFieldDataInterface $field, array &$fields) { $normalizedRelationName = $this->normalizeRelationName($key); // Check if we can enrich, if we must. if ( ! isset($this->info->attributes[ $key ]) && ! isset($this->info->relations[ $normalizedRelationName ]) ) { // If the field data is fully set, no need to enrich if ($this->isShowFieldDataComplete($field)) { $fields[ $key ] = $field; return; } throw new UnexpectedValueException( "Incomplete data for for show field key that does not match known model attribute or relation method. " . "Requires at least 'source' and 'strategy' values." ); } if (isset($this->info->attributes[ $key ])) { $attributeFieldInfo = $this->makeModelShowFieldDataForAttributeData($this->info->attributes[ $key ], $this->info); } else { // get from relation data $attributeFieldInfo = $this->makeModelShowFieldDataForRelationData( $this->info->relations[ $normalizedRelationName ], $this->info ); } $attributeFieldInfo->merge($field); $fields[ $key ] = $attributeFieldInfo; }
Enriches a single show field and saves the data. @param ModelShowFieldDataInterface $field @param string $key @param array $fields by reference, data array to build, updated with enriched data
entailment
protected function makeModelShowFieldDataForAttributeData(ModelAttributeData $attribute, ModelInformationInterface $info) { $primaryIncrementing = $attribute->name === $this->model->getKeyName() && $info->incrementing; return new ModelShowFieldData([ 'source' => $attribute->name, 'strategy' => $this->determineListDisplayStrategyForAttribute($attribute), 'style' => $primaryIncrementing ? 'primary-id' : null, 'label' => ucfirst(str_replace('_', ' ', snake_case($attribute->name))), ]); }
Makes data set for show field given attribute data. @param ModelAttributeData $attribute @param ModelInformationInterface|ModelInformation $info @return ModelShowFieldData
entailment
protected function makeModelShowFieldDataForRelationData(ModelRelationData $relation, ModelInformationInterface $info) { return new ModelShowFieldData([ 'source' => $relation->method, 'strategy' => $this->determineListDisplayStrategyForRelation($relation), 'label' => ucfirst(str_replace('_', ' ', snake_case($relation->method))), ]); }
Makes data set for list field given relation data. @param ModelRelationData $relation @param ModelInformationInterface|ModelInformation $info @return ModelShowFieldData
entailment
protected function performEnrichment() { if ( ! count($this->info->list->filters)) { $this->fillDataForEmpty(); } else { $this->enrichCustomData(); } }
Performs enrichment.
entailment
protected function fillDataForEmpty() { // We either create separate filters, or combine strings in a single 'any' field if (config('cms-models.analyzer.filters.single-any-string')) { $filters = $this->makeCombinedFiltersWithAnyStringFilter(); } else { $filters = $this->makeFiltersForAllAttributes(); } $this->info->list->filters = $filters; }
Fills filter data if no custom data is set.
entailment
protected function makeFiltersForAllAttributes() { $filters = []; foreach ($this->info->attributes as $attribute) { if ($attribute->hidden || ! $this->shouldAttributeBeFilterable($attribute)) { continue; } $filterData = $this->makeModelListFilterDataForAttributeData($attribute, $this->info); if ( ! $filterData) continue; $filters[$attribute->name] = $filterData; } return $filters; }
Makes separate filter data sets for all attributes. @return ModelListFilterData[]
entailment
protected function enrichCustomData() { // Check set filters and enrich them as required $filters = []; foreach ($this->info->list->filters as $key => $filter) { try { $this->enrichFilter($key, $filter, $filters); } catch (\Exception $e) { // Wrap and decorate exceptions so it is easier to track the problem source throw (new ModelInformationEnrichmentException( "Issue with list filter '{$key}' (list.filters.{$key}): \n{$e->getMessage()}", $e->getCode(), $e )) ->setSection('list.filters') ->setKey($key); } } $this->info->list->filters = $filters; }
Enriches existing user configured data.
entailment
protected function enrichFilter($key, ModelFilterDataInterface $filter, array &$filters) { // If the filter information is fully provided, do not try to enrich if ($this->isListFilterDataComplete($filter)) { $filters[ $key ] = $filter; return; } if ( ! isset($this->info->attributes[ $key ])) { throw new UnexpectedValueException( "Incomplete data for for list filter key that does not match known model attribute or relation method. " . "Requires at least 'strategy' and 'target' values." ); } $attributeFilterInfo = $this->makeModelListFilterDataForAttributeData($this->info->attributes[ $key ], $this->info); if (false === $attributeFilterInfo) { throw new UnexpectedValueException( "Uninterpretable data for for list filter key, cannot determine defaults based on model attribute or relation method name. " . "Requires at least 'strategy' and 'target' values." ); } $attributeFilterInfo->merge($filter); $filters[ $key ] = $attributeFilterInfo; }
Enriches a single list column and saves the data. @param ModelFilterDataInterface $filter @param string $key @param array $filters by reference, data array to build, updated with enriched data
entailment
protected function shouldAttributeBeFilterable(ModelAttributeDataInterface $attribute) { // If an attribute is a foreign key, it shouldn't be a filter by default. foreach ($this->info->relations as $key => $relation) { switch ($relation->type) { case RelationType::MORPH_TO: case RelationType::BELONGS_TO: case RelationType::BELONGS_TO_THROUGH: $keys = $relation->foreign_keys ?: []; if (in_array($attribute->name, $keys)) { return false; } break; } } return true; }
Returns whether a given attribute should be filterable by default. @param ModelAttributeDataInterface|ModelAttributeData $attribute @return bool
entailment
protected function makeModelListFilterDataForAttributeData(ModelAttributeData $attribute, ModelInformationInterface $info) { $strategy = false; $options = []; if ($attribute->cast === AttributeCast::BOOLEAN) { $strategy = FilterStrategy::BOOLEAN; } elseif ($attribute->type === 'enum') { $strategy = FilterStrategy::DROPDOWN; $options['values'] = $attribute->values; } elseif ($attribute->cast === AttributeCast::STRING) { $strategy = FilterStrategy::STRING; } elseif ($attribute->cast === AttributeCast::DATE) { $strategy = FilterStrategy::DATE; } if ( ! $strategy) { return false; } return new ModelListFilterData([ 'source' => $attribute->name, 'label' => str_replace('_', ' ', snake_case($attribute->name)), 'target' => $attribute->name, 'strategy' => $strategy, 'options' => $options, ]); }
Makes list filter data given attribute data. @param ModelAttributeData $attribute @param ModelInformationInterface|ModelInformation $info @return ModelListFilterData|false
entailment
public function labelPlural($translated = true) { if ($translated && $key = $this->getAttribute('translated_name_plural')) { if (($label = cms_trans($key)) !== $key) { return $label; } } return $this->getAttribute('verbose_name_plural'); }
Returns label for multiple items. @param bool $translated return translated if possible @return string
entailment
public function deleteCondition() { if (null === $this->delete_condition || false === $this->delete_condition) { return false; } return $this->delete_condition; }
Returns delete condition if set, or false if not. @return string|string[]|false
entailment
public function deleteStrategy() { if (null === $this->delete_strategy || false === $this->delete_strategy) { return false; } return $this->delete_strategy; }
Returns delete strategy if set, or false if not. @return string|false
entailment
public function confirmDelete() { if (null === $this->confirm_delete) { return (bool) config('cms-models.defaults.confirm_delete', false); } return (bool) $this->confirm_delete; }
Returns whether deletions should be confirmed by the user. @return bool
entailment
public function merge(ModelInformationInterface $with) { if ( ! empty($with->model)) { $this->model = $with->model; } if ( ! empty($with->original_model)) { $this->original_model = $with->original_model; } $mergeAttributes = [ 'single', 'meta', 'verbose_name', 'translated_name', 'verbose_name_plural', 'translated_name_plural', 'allow_delete', 'delete_condition', 'delete_strategy', 'confirm_delete', 'list', 'form', 'show', 'export', 'reference', 'includes', ]; foreach ($mergeAttributes as $attribute) { $this->mergeAttribute($attribute, $with->{$attribute}); } }
Merges information into this information set, with the new information being leading. @param ModelInformationInterface|ModelInformation $with
entailment
public function determineValidationRules(ModelRelationData $relation, ModelFormFieldData $field) { $rules = []; if ($field->required() && ! $field->translated()) { $rules[] = 'required'; } else { // Anything that is not required should by default be explicitly nullable // since Laravel 5.4. $rules[] = 'nullable'; } // todo // make validation rules as far as possible, based on the key type (incrementing?) // or using exists:: ... return $rules; }
Determines validation rules for given relation data. @param ModelRelationData $relation @param ModelFormFieldData $field @return array|false
entailment
public function shouldDisplay(): bool { if ($this->before || $this->after) { return true; } return (bool) count($this->children); }
Returns whether the tab-pane should be displayed @return bool
entailment
protected function performStep() { $activeColumn = $this->getActivateColumnName(); foreach ($this->info->attributes as $name => $attribute) { if ($name !== $activeColumn || ! $this->isAttributeBoolean($attribute)) { continue; } $this->info->list->activatable = true; $this->info->list->active_column = $name; } }
Performs the analyzer step on the stored model information instance.
entailment
protected function decorateFieldData(array $data) { // Format the date value according to what the datepicker expects if ($data['value'] instanceof DateTime) { /** @var DateTime $value */ $value = $data['value']; $format = array_get($data, 'options.format', $this->defaultDateFormat()); if ($format) { $data['value'] = $value->format($format); } } // Prepare the momentJS date format, if not explicitly set if ( ! array_get($data, 'options.moment_format')) { $format = array_get($data, 'options.format'); $momentFormat = $format ? $this->convertDateFormatToMoment($format) : $this->defaultMomentDateFormat(); array_set($data, 'options.moment_format', $momentFormat); } // Prepare special properties for datepicker if ($indicator = array_get($data, 'options.minimum_date')) { $data['minimumDate'] = $this->interpretDateIndicator($indicator); } if ($indicator = array_get($data, 'options.maximum_date')) { $data['maximumDate'] = $this->interpretDateIndicator($indicator); } $data['excludedDates'] = []; if (($indicators = array_get($data, 'options.excluded_dates')) && is_array($indicators)) { $data['excludedDates'] = array_map([ $this, 'interpretDateIndicator' ], $indicators); } return $data; }
Enriches field data before passing it on to the view. @param array $data @return array
entailment
protected function interpretDateIndicator($indicator) { if ( ! is_string($indicator)) { throw new \UnexpectedValueException('Unexpected date indicator value: ' . print_r($indicator, true)); } if ('now' === strtolower($indicator)) { return Carbon::now()->format('Y-m-d H:i:s'); } if (starts_with($indicator, '-')) { return Carbon::now()->sub( new \DateInterval(substr($indicator, 1)) )->format('Y-m-d H:i:s'); } if (starts_with($indicator, '+')) { return Carbon::now()->add( new \DateInterval(substr($indicator, 1)) )->format('Y-m-d H:i:s'); } return (new Carbon($indicator))->format('Y-m-d H:i:s'); }
Interprets a date indicator string value as a date time string relative to the current date. @param string $indicator @return string
entailment
protected function convertDateFormatToMoment($format) { $replacements = [ 'd' => 'DD', 'D' => 'ddd', 'j' => 'D', 'l' => 'dddd', 'N' => 'E', 'S' => 'o', 'w' => 'e', 'z' => 'DDD', 'W' => 'W', 'F' => 'MMMM', 'm' => 'MM', 'M' => 'MMM', 'n' => 'M', 't' => '', // no equivalent 'L' => '', // no equivalent 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'a' => 'a', 'A' => 'A', 'B' => '', // no equivalent 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', 'u' => 'SSS', 'e' => 'zz', // deprecated since version 1.6.0 of moment.js 'I' => '', // no equivalent 'O' => '', // no equivalent 'P' => '', // no equivalent 'T' => '', // no equivalent 'Z' => '', // no equivalent 'c' => '', // no equivalent 'r' => '', // no equivalent 'U' => 'X', ]; foreach ($replacements as $from => $to) { $replacements['\\' . $from] = '[' . $from . ']'; } return strtr($format, $replacements); }
Converts PHP date format to MommentJS date format. @param string $format PHP date format string @return string
entailment
public function render(Model $model, $source) { $count = $this->getCount( $this->getActualNestedRelation($model, $source) ); if ( ! $count) { return '<span class="relation-count count-empty">&nbsp;</span>'; } return '<span class="relation-count">' . $count . '</span>'; }
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 getCount(Relation $relation) { if ( ! $relation) return 0; $query = $this->modifyRelationQueryForContext($relation->getRelated(), $relation->getQuery()); return $query->count(); }
Returns the count for a given relation. @param Relation $relation @return int
entailment
public function apply(Builder $query) { $this->each(function ($apply) use ($query) { if (is_callable($apply)) { call_user_func($apply, $query); } }); }
{@inheritdoc}
entailment