sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function render(Model $model, $source)
{
$attachment = $this->resolveModelSource($model, $source);
if ( ! ($attachment instanceof AttachmentInterface)) {
return null;
}
return $attachment->url();
} | Renders a display value to print to the export.
@param Model $model
@param mixed $source source column, method name or value
@return string | entailment |
public function addToNavigation($badge = null)
{
$nav = $this->getNavigation();
if ($this->hasParentPageId()) {
$nav = $nav->getPages()->findById($this->getParentPageId());
if (is_null($nav)) {
throw new InvalidArgumentException(
sprintf(
'Not Found "%s" navigation',
$this->getParentPageId()
)
);
}
}
$page = $this->makePage($badge);
$nav->addPage($page);
return $page;
} | {@inheritdoc} | entailment |
protected function makePage($badge = null)
{
$page = new Page($this);
$page->setPriority($this->getPriority())
->setIcon($this->getIcon())
->setId($this->getPageId())
->setAccessLogic(function () {
return $this->isDisplay();
});
if ($badge) {
if (! ($badge instanceof BadgeInterface)) {
$badge = new Badge($badge);
}
$page->addBadge($badge);
}
return $page;
} | Make page
@param string|Closure|null $badge
@return \Sco\Admin\Navigation\Page | entailment |
protected function performInit()
{
$this->prepareTargetRoute()
->prepareParentParameter()
->checkForMorphToRelation();
// Check permissions
$permissions = $this->actionData->permissions();
if (empty($permissions)) {
$this->isPermitted = true;
} else {
$this->isPermitted = cms_auth()->can($permissions);
}
} | Performs initialization.
Override this to customize strategy implementations. | entailment |
public function link(Model $model)
{
if ( ! $this->routePrefix || ! $this->isPermitted) {
return false;
}
// If the relation is morphTo, the key needs to be prepared with type:key identicator
if ($this->isMorphTo) {
// todo: this needs to be fixed
$parentIndicator = $this->getMorphTypeForModel($this->modelClass) . ':' . $model->getKey();
} else {
$parentIndicator = $model->getKey();
}
return route($this->routePrefix . static::ROUTE_POSTFIX)
. '?parent=' . $this->relation . ':' . $parentIndicator;
} | Returns the action link for a given model instance.
@param Model $model
@return string|false | entailment |
protected function getOtherModelClass()
{
$this->otherModelClass = array_get($this->actionData->options(), 'model');
if ( ! $this->otherModelClass) {
throw new UnexpectedValueException("No target model class set in options");
}
if ( ! is_a($this->otherModelClass, Model::class, true)) {
throw new UnexpectedValueException("{$this->otherModelClass} is not a valid target model class");
}
/** @var ModelInformationRepositoryInterface $infoRepository */
$infoRepository = app(ModelInformationRepositoryInterface::class);
$info = $infoRepository->getByModelClass($this->otherModelClass);
if ( ! $info) {
throw new UnexpectedValueException("{$this->otherModelClass} is not a CMS model");
}
return $this->otherModelClass;
} | Returns the model FQN for the target model for the link.
If the relationship is MorphTo, we cannot know the model class in every case.
@return string | entailment |
protected function getRelationName()
{
$relation = array_get($this->actionData->options(), 'relation');
if ($relation) {
return $relation;
}
/** @var ModelInformationRepositoryInterface $infoRepository */
$infoRepository = app(ModelInformationRepositoryInterface::class);
$info = $infoRepository->getByModelClass($this->otherModelClass);
if ( ! $info || empty($info->list->parents) || count($info->list->parents) !== 1) {
return false;
}
return head($info->list->parents)->relation;
} | Returns configured relation name for children link.
Falls back to list.parents relation name if exactly one given.
@return string|false | entailment |
public function index()
{
if ($this->luceneIndex->count() !== 0) {
$this->luceneIndex = Lucene::create($this->indexDirectory);
}
/** @var \yii\db\ActiveRecord $modelName */
foreach ($this->models as $modelName) {
/** @var behaviors\SearchBehavior $model */
/** @var array $page */
$model = new $modelName;
if ($model->hasMethod('getSearchModels')) {
foreach ($model->getSearchModels()->all() as $pageModel) {
$this->luceneIndex->addDocument($this->createDocument(
call_user_func($model->searchFields, $pageModel)
));
}
} else {
throw new InvalidConfigException(
"Not found right `SearchBehavior` behavior in `{$modelName}`."
);
}
}
} | Indexing the contents of the specified models.
@throws InvalidConfigException | entailment |
public function find($term, $fields = [])
{
Wildcard::setMinPrefixLength($this->minPrefixLength);
Lucene::setResultSetLimit($this->resultsLimit);
if (empty($fields)) {
return [
'results' => $this->luceneIndex->find($term),
'query' => $term
];
}
$fieldTerms[] = new IndexTerm($term);
foreach ($fields as $field => $fieldText) {
$fieldTerms[] = new IndexTerm($fieldText, $field);
}
return [
'results' => $this->luceneIndex->find(new MultiTerm($fieldTerms)),
'query' => $term
];
} | Search page for the term in the index.
@param string $term
@param array $fields (string => string)
@return array ('results' => \ZendSearch\Lucene\Search\QueryHit[], 'query' => string) | entailment |
public function delete($text, $field = null)
{
$query = new Term(new IndexTerm($text, $field));
$hits = $this->luceneIndex->find($query);
foreach ($hits as $hit) {
$this->luceneIndex->delete($hit);
}
} | Delete document from the index.
@param string $text
@param string|null $field | entailment |
protected function checkListParents($update = true)
{
if (empty($this->getModelInformation()->list->parents)) {
return $this;
}
$this->retrieveActiveParentFromSession();
$this->collectListParentHierarchy();
if ($update) {
$this->updateActiveParent();
}
$this->enrichListParents();
return $this;
} | Checks and loads list parent from the session.
@param bool $update whether to check for updates through the 'parent' request param
@return $this | entailment |
protected function showsTopParentsOnly()
{
$relation = $this->getModelInformation()->list->default_top_relation;
// If the default is to restrict to top-level only,
// or the reverse with a user-initiated reversal (relation = false):
// Restrict the query to top level.
return $relation && false !== $this->listParentRelation;
} | Returns whether the index will only show the top level parents.
@return bool | entailment |
protected function applyListParentContext()
{
$parents = $this->getModelInformation()->list->parents;
if (empty($parents)) {
return $this;
}
if ($this->listParentRelation) {
$contextKey = $this->listParentRelation . $this->getListParentSeparator() . $this->listParentRecordKey;
} else {
$contextKey = null;
}
$this->getListMemory()->setSubContext($contextKey);
return $this;
} | Applies the context for the current list parent scope.
Must be called before other list memory is accessed, since it affects the sub-context of the memory.
@return $this | entailment |
protected function applyListParentToQuery($query)
{
if ( ! $this->listParentRelation) {
if ($this->showsTopParentsOnly()) {
$query->has($this->getModelInformation()->list->default_top_relation, '<', 1);
}
return $this;
}
// Use list parent information collected to get the model
/** @var ListParentData $parentInfo */
$parentInfo = array_last($this->listParents);
if ( ! $parentInfo) {
return $this;
}
// For morph relation, we need a special query
$relationInstance = $query->getModel()->{$this->listParentRelation}();
if ($relationInstance instanceof MorphTo) {
$separator = $this->getListParentMorphKeySeparator();
// If parent record indicator $key does not contain class/key separator symbol, ignore
if (false === strpos($this->listParentRecordKey, $separator)) {
return $this;
}
list($parentType, $parentKey) = explode($separator, $this->listParentRecordKey, 2);
$parentType = $this->getRelationMappedMorphType($parentType);
$query
->withoutGlobalScopes()
->where($query->getModel()->getTable() . '.' . $relationInstance->getMorphType(), $parentType)
->where($relationInstance->getQualifiedForeignKey(), $parentKey);
return $this;
}
$query->whereHas($this->listParentRelation, function ($query) use ($parentInfo) {
/** @var Builder $query */
$query
->withoutGlobalScopes()
->where($parentInfo->model->getKeyName(), $this->listParentRecordKey);
});
return $this;
} | Applies the active list parent as a filter on a query builder.
@param Builder $query
@return $this | entailment |
protected function collectListParentHierarchy($relation = null, $key = null)
{
$this->listParents = [];
if (null === $relation) {
$relation = $this->listParentRelation;
$key = $this->listParentRecordKey;
}
if ( ! $relation || null === $key) {
return;
}
$model = $this->getNewModelInstance();
$info = $this->getModelInformationForModel($model);
$this->listParents = $this->getListParentInformation(
$model,
$this->listParentRelation,
$this->listParentRecordKey,
$info,
true
);
} | Looks up the current full list parent hierarchy chain to the top level.
@param string|null $relation if not set, uses currently stored values
@param mixed|null $key | entailment |
protected function updateActiveParent()
{
// If no update is required, return immediately
if ( ! request()->has('parents') && ! request()->filled('home') && ! request()->has('parent')) {
return $this;
}
$separator = $this->getListParentSeparator();
// Check for either a full hierarchy or a 'current level' update
if (request()->has('parents') || request()->filled('home')) {
$parents = request()->get('parents');
if ($parents === 'all' || empty($parents)) {
// No need to update if no current memorized parent chain
if (count($this->listParents)) {
$this->clearEntireListParentHierarchy();
}
$defaultTopRelation = $this->getModelInformation()->list->default_top_relation;
// Toggling display to all for relations that limit to top by default,
// which should reset on a home reset aswell.
if ($parents == 'all') {
$this->listParentRelation = false;
$this->listParentRecordKey = null;
} elseif (request()->filled('home') && $defaultTopRelation) {
$this->listParentRelation = null;
$this->listParentRecordKey = null;
}
} else {
if (is_string($parents)) {
$parents = explode(';', $parents);
}
$parents = array_values($parents);
// No need to update if everything is the same down the chain
if (count($this->listParents) == count($parents)) {
$same = true;
foreach ($this->listParents as $index => $currentParent) {
if ($currentParent->relation . $separator . $currentParent->key !== $parents[$index]) {
$same = false;
break;
}
}
if ($same) {
return $this;
}
}
$this->clearEntireListParentHierarchy();
// Update, working backwards, starting at the current list; then re-collect the active parent chain
$this->updateActiveParents(array_reverse($parents));
}
} elseif (request()->has('parent')) {
$parent = request()->get('parent');
// Interpret special parent values
$parent = $this->normalizeListParentParameter($parent);
// If nothing has changed, no need to update
if ( ! $parent && $this->listParentRelation == $parent
|| $parent == $this->listParentRelation . $separator . $this->listParentRecordKey
) {
return $this;
}
if ( ! $parent) {
// Reset this level to its previous list parent, if any
$this->listParentRelation = $parent;
$this->listParentRecordKey = null;
} else {
// If the parent is already present in the current history, switch to it
if ( ! count(array_filter(
$this->listParents,
function ($checkParent) use ($parent, $separator) {
/** @var ListParentData $checkParent */
return $checkParent->relation . $separator . $checkParent->key == $parent;
}
))) {
// Not set yet, prepare old parent as one layer deeper
$this->setListParentDataInMemory(
$this->listParentRelation,
$this->listParentRecordKey,
$parent
);
}
list($this->listParentRelation, $this->listParentRecordKey) = explode($separator, $parent, 2);
}
}
$this->storeActiveParentInSession();
$this->collectListParentHierarchy();
return $this;
} | Updates the active list parent if the request parameter is set.
@return $this | entailment |
protected function normalizeListParentParameter($parent)
{
$separator = $this->getListParentSeparator();
if (is_integer($parent) && $parent < 0 || is_string($parent) && preg_match('#-\d+#', $parent)) {
$parent = (int) $parent;
if ($parent < 0) {
// The the parent that conforms to the index in the parent chain
// This only works within the context of this model, so no cross-model logic is expected
$index = count($this->listParents) + $parent - 1;
if ($index >= 0 && isset($this->listParents[ $index ])) {
$parent = $this->listParents[ $index ]->relation . $separator . $this->listParents[ $index ]->key;
} else {
$parent = null;
}
} else {
$parent = null;
}
}
if (is_string($parent) && false === strpos($parent, $separator)) {
$parent = null;
}
return $parent;
} | Normalizes 'parent' query parameter for list parent update.
@param mixed $parent
@return int|null | entailment |
protected function updateActiveParents(array $parents)
{
$modelInfo = $this->getModelInformation();
$modelClass = $modelInfo->modelClass();
$model = new $modelClass;
$previousContext = null;
$previousParent = array_shift($parents);
$separator = $this->getListParentSeparator();
// Store top level parent as active
if ( ! $previousParent || is_string($previousParent) && false === strpos($previousParent, $separator)) {
$this->listParentRelation = $previousParent === false ? false : null;
$this->listParentRecordKey = null;
} else {
list($this->listParentRelation, $this->listParentRecordKey) = explode($separator, $previousParent, 2);
}
$count = 0;
// Add 'end' marker to force overwriting a previously longer chain link as a terminator
$parents[] = null;
// Loop through further parents, where $parent is what $previousParent refers back to
foreach ($parents as $parent) {
$count++;
// If we have no interpretable parent to use as sub-context, stop
if ( ! $previousParent || is_string($previousParent) && false === strpos($previousParent, $separator)) {
break;
}
// If we have no interpretable parent as target, clear the context, and stop
if ( ! $parent || is_string($parent) && false === strpos($parent, $separator)) {
$this->setListParentDataInMemory(null, null, $previousParent, $previousContext);
break;
}
list($relation, $key) = explode($separator, $parent, 2);
// Set new parent at this level
$this->setListParentDataInMemory($relation, $key, $previousParent, $previousContext);
// If this is the last parent, then there is no need to prepare for the next iteration
if ($count == count($parents)) {
break;
}
// If the context (model) changed, determine the new context and remember it for the next iteration
$listParentInfo = $this->getListParentInformation($model, $relation, $key, $modelInfo);
if ( ! count($listParentInfo)) {
break;
}
// Check and update the model class (for the memory context) if necessary.
// This is only relevant for list parent reference across models.
$listParentInfo = head($listParentInfo);
/** @var ListParentData $listParentInfo */
if ($modelClass !== get_class($listParentInfo->model)) {
$model = $listParentInfo->model;
$modelClass = get_class($model);
$previousContext = $this->getModelSessionKey($this->getModuleHelper()->modelSlug($model));
}
$previousParent = $parent;
}
} | Update a full list parent chain.
@param array $parents should be last-first ordered, strings with :-separated relaton:key | entailment |
protected function enrichListParents()
{
if (empty($this->listParents)) {
return;
}
// Mark for each list parents entry how the query params should be set up
$queries = [];
$previousModel = $this->getModelInformation()->modelClass();
/** @var ListParentData[] $reversed */
$reversed = array_reverse($this->listParents);
foreach ($reversed as $index => $parent) {
$nextParent = isset($reversed[ $index + 1 ]) ? $reversed[ $index + 1 ] : null;
if ($previousModel != get_class($parent->model)) {
$queries[] = null;
} else {
if ($nextParent) {
$queries[] = 'parent=' . $nextParent->relation . $this->getListParentSeparator() . $nextParent->key;
} else {
$queries[] = 'parents=';
}
}
$previousModel = get_class($parent->model);
}
$queries = array_values(array_reverse($queries));
foreach ($queries as $index => $query) {
$this->listParents[$index]->query = $query;
}
} | Enriches list parent data for view. | entailment |
protected function clearEntireListParentHierarchy()
{
$separator = $this->getListParentSeparator();
foreach ($this->listParents as $parent) {
if ( ! $parent || is_string($parent) && false === strpos($parent, $separator)) {
break;
}
// Unset parent at this level
$context = $this->getModelSessionKey(
$this->getModuleHelper()->modelSlug(get_class($parent->model))
);
$this->setListParentDataInMemory(null, null, $parent->relation . $separator . $parent->key, $context);
}
$this->setListParentDataInMemory(null, null, $this->globalSubContext());
$this->listParentRelation = null;
$this->listParentRecordKey = null;
$this->listParents = [];
} | Clears list parent chain as currently memorized. | entailment |
protected function retrieveActiveParentFromSession()
{
$parent = $this->getListParentDataFromMemory($this->globalSubContext());
if (false === $parent || null === $parent) {
$this->listParentRelation = $parent;
$this->listParentRecordKey = null;
return;
}
$this->listParentRelation = array_get($parent, 'relation');
$this->listParentRecordKey = array_get($parent, 'key');
} | Retrieves the currently set 'global' list parent from the session and stores it locally. | entailment |
protected function getListParentInformation(
Model $model,
$relation,
$key,
ModelInformationInterface $info,
$recurse = false
) {
// Don't attempt to load relation methods if the parent relation is not configured
if ( empty($info->list->parents)
|| ! count(
array_filter(
$info->list->parents,
function ($parent) use ($relation) { return $parent->relation == $relation; }
)
)
) {
return [];
}
/** @var Relation $relationInstance */
$relationInstance = $model->{$relation}();
// For MorphTo relations, we cannot know the related model from the relation
// instance, it being polymorphic. We have to trust the record 'key' to contain the model.
if ($relationInstance instanceof MorphTo) {
$separator = $this->getListParentMorphKeySeparator();
// If parent record indicator $key does not contain class/key separator symbol, ignore
if (false === strpos($key, $separator)) {
return [];
}
list($parentType, $parentKey) = explode($separator, $key, 2);
$parentModelClass = $this->getRelationMappedMorphClass($parentType);
if ( ! is_a($parentModelClass, Model::class, true)) {
// @codeCoverageIgnoreStart
throw new UnexpectedValueException(
"Parent record indicator {$key} does not refer to usable Eloquent model parent."
);
// @codeCoverageIgnoreEnd
}
$parentModel = new $parentModelClass;
$key = $parentKey;
} else {
$parentModel = $relationInstance->getRelated();
}
$parentModel = $this->getModelByKey($parentModel, $key);
if ( ! $parentModel) {
return [];
}
$parentInfo = $this->getModelInformationForModel($parentModel);
$list = [];
// Check for another link in the chain and recurse if there is
if ($recurse && ! empty($parentInfo->list->parents)) {
// When switching from one model to another, use the global subcontext,
// otherwise, use the subcontext that contains the next step
// Look up session data for list parent
$parentListParent = $this->getListParentDataFromMemory(
get_class($model) != get_class($parentModel) ? $this->globalSubContext() : $relation . ':' . $key,
$this->getModelSessionKey($this->getModuleHelper()->modelSlug($parentModel))
);
if (is_array($parentListParent)) {
$list = $this->getListParentInformation(
$parentModel,
array_get($parentListParent, 'relation'),
array_get($parentListParent, 'key'),
$parentInfo,
true
);
}
}
$module = $this->getModuleByModel($parentModel);
if ( ! $module) {
return [];
}
/** @var RouteHelperInterface $routeHelper */
$routeHelper = app(RouteHelperInterface::class);
$list[] = new ListParentData([
'relation' => $relation,
'key' => $key,
'model' => $parentModel,
'information' => $parentInfo,
'module_key' => $module->getKey(),
'route_prefix' => $routeHelper->getRouteNameForModelClass(get_class($parentModel), true),
'permission_prefix' => $routeHelper->getPermissionPrefixForModelSlug(
$this->getModuleHelper()->modelInformationKeyForModel($parentModel)
),
]);
return $list;
} | Returns information about a list parent, or all list parents in the chain.
Exceptions will be thrown if there are logical problems with the chain.
@param Model $model
@param string $relation
@param mixed $key
@param ModelInformationInterface|ModelInformation $info
@param bool $recurse if true, looks up entire chain
@return ListParentData[] | entailment |
protected function getModelByKey(Model $model, $key)
{
return $model::withoutGlobalScopes()
->where($model->getKeyName(), $key)
->first();
} | Returns model instance by key.
@param Model $model
@param mixed $key
@return Model|null | entailment |
protected function getModuleByModel(Model $model)
{
/** @var ModuleManagerInterface $modules */
$modules = app(ModuleManagerInterface::class);
return $modules->getByAssociatedClass(get_class($model));
} | Returns the module for a given model.
@param Model $model
@return ModuleInterface|false | entailment |
protected function isFieldValueBeDerivableFromListParent($field)
{
if ( ! $this->hasActiveListParent()) {
return false;
}
$listParentData = $this->getListParentDataForRelation($this->listParentRelation);
if ( ! $listParentData) {
return false;
}
return $field == $listParentData->field();
} | Returns whether the set list parent corresponds to a given field key.
@param string $field
@return bool | entailment |
protected function getListParentDataFromMemory($subContext, $context = null)
{
$memory = $this->getListMemory();
$oldContext = $memory->getContext();
$oldSubContext = $memory->getSubContext();
if (null !== $context) {
$memory->setContext($context);
}
$memory->setSubContext($subContext);
$listParent = $memory->getListParent();
if (null !== $context) {
$memory->setContext($oldContext);
}
$memory->setSubContext($oldSubContext);
return $listParent;
} | Retrieves list parent data from memory and resets memory context.
@param string|null $subContext
@param string|null $context
@return array|false|null | entailment |
protected function setListParentDataInMemory($relation, $key, $subContext, $context = null)
{
$memory = $this->getListMemory();
$oldContext = $memory->getContext();
$oldSubContext = $memory->getSubContext();
if (null !== $context) {
$memory->setContext($context);
}
$memory->setSubContext($subContext);
$memory->setListParent($relation, $key);
if (null !== $context) {
$memory->setContext($oldContext);
}
$memory->setSubContext($oldSubContext);
} | Stores list parent data in memory and resets memory context.
@param string|null|false $relation
@param mixed|null $key
@param string|null $subContext
@param string|null $context | entailment |
protected function getRelationMappedMorphType($class)
{
$map = Relation::morphMap();
if (empty($map)) {
return ltrim($class, '\\');
}
if ( false !== ($type = array_search($class, $map))
|| false !== ($type = array_search(ltrim($class, '\\'), $map))
) {
return $type;
}
return trim($class, '\\');
} | Returns morph relation type string for a model class, or returns class if not mapped.
@param string $class
@return string | entailment |
protected function getRelationMappedMorphClass($type)
{
$map = Relation::morphMap();
if (empty($map)) {
return $type;
}
return array_get($map, $type, ltrim($type, '\\'));
} | Returns morph relation class string for a morph relation type, or type if already a class.
@param string $type
@return string | entailment |
public function interpret($information)
{
$this->raw = $information;
$this->interpretReferenceData()
->interpretListData()
->interpretFormData()
->interpretShowData()
->interpretExportData();
return $this->createInformationInstance();
} | Interprets raw CMS model information as a model information object.
@param array $information
@return ModelInformationInterface|ModelInformation | entailment |
protected function normalizeScopeArray(array $scopes, $parentKey = 'list.scopes')
{
$scopes = $this->normalizeStandardArrayProperty(
$scopes,
'strategy',
ModelScopeData::class,
$parentKey
);
// Make sure that each scope entry has at least a method or a strategy
foreach ($scopes as $key => &$value) {
if ( ! $value['method'] && ! $value['strategy']) {
$value['method'] = $key;
}
}
unset($value);
return $scopes;
} | Normalizes an array with scope data.
@param array $scopes
@param string $parentKey
@return array | entailment |
protected function normalizeStandardArrayProperty(
array $source,
$standardProperty,
$objectClass = null,
$parentKey = null
) {
$normalized = [];
foreach ($source as $key => $value) {
// key may be present as values, when it is included just for order or presence,
// defaults need to be filled in
if (is_numeric($key) && ! is_array($value)) {
$key = $value;
$value = [];
}
// if the value is 'true', the main property is assume to be the same as the key
// (this is of limited use, but may make sense for export strategies)
if (true === $value) {
$value = $key;
}
// if value is just a string, it is the standard property
if (is_string($value)) {
$value = [
$standardProperty => $value,
];
}
if ($objectClass) {
if (empty($value)) {
$value = [];
}
$value = $this->makeClearedDataObject($objectClass, $value, $parentKey ? $parentKey . ".{$key}" : null);
}
$normalized[ $key ] = $value;
}
return $normalized;
} | Normalizes a standard array property.
This assumes sections such as list.columns, where keys are required designators.
@param array $source
@param string $standardProperty property to set for string values in normalized array
@param null|string $objectClass dataobject FQN to interpret as
@param null|string $parentKey
@return array | entailment |
protected function normalizeKeyLessArrayProperty(
array $source,
$standardProperty,
$objectClass = null,
$parentKey = null
) {
$normalized = [];
foreach ($source as $index => $value) {
// if value is just a string, it is the standard property
if (is_string($value)) {
$value = [
$standardProperty => $value,
];
}
if ($objectClass) {
$value = $this->makeClearedDataObject($objectClass, $value, $parentKey ? $parentKey . ".{$index}" : null);
}
$normalized[] = $value;
}
return $normalized;
} | Normalizes a standard array property for inassociative data.
This assumes sections such as list.columns, where values should appear without keys.
@param array $source
@param string $standardProperty property to set for string values in normalized array
@param null|string $objectClass dataobject FQN to interpret as
@param null|string $parentKey
@return array | entailment |
protected function makeClearedDataObject($objectClass, array $data, $parentKey = null)
{
/** @var AbstractDataObject $object */
$object = new $objectClass();
$object->clear();
try {
$object->setAttributes($data);
} catch (ModelConfigurationDataException $e) {
throw $e->setDotKey(
$parentKey . ($e->getDotKey() ? '.' . $e->getDotKey() : null)
);
}
return $object;
} | Makes a fresh dataobject with its defaults cleared before filling it with data.
@param string $objectClass
@param array $data
@param null|string $parentKey
@return AbstractDataObject
@throws ModelConfigurationDataException | entailment |
protected function performEnrichment()
{
$strategies = $this->info->export->strategies;
foreach ($strategies as $key => $strategyData) {
if (empty($strategyData['strategy'])) {
$strategies[ $key ]['strategy'] = $key;
}
}
$this->info->export->strategies = $strategies;
} | Performs enrichment. | entailment |
protected function getReference(Model $model)
{
$reference = $this->getReferenceValue($model);
return $this->wrapWithLink($reference, $this->getLinkForReferenceModel($model));
} | Returns a reference representation for a single model.
@param Model $model
@return string | entailment |
protected function getLinkForReferenceModel(Model $model)
{
$routeName = $this->getRouteHelper()->getRouteNameForModelClass(get_class($model), true);
$action = $this->determineRouteAction($model);
return route($routeName . '.' . $action, $model->getKey());
} | Returns action link for given model.
@param Model $model
@return string | entailment |
protected function determineRouteAction(Model $model)
{
$routeHelper = $this->getRouteHelper();
$permissionPrefix = $routeHelper->getPermissionPrefixForModelSlug(
$routeHelper->getRouteSlugForModelClass(get_class($model))
);
// Change the action to show if we don't have edit permissions
if ( ! cms_auth()->can($permissionPrefix . 'edit')) {
return 'show';
}
return 'edit';
} | Returns route action for given model.
The edit action is default, with a fallback to show if no permission is granted.
@param Model $model
@return string | entailment |
public function handle()
{
$this->line('');
$this->line('************************');
$this->line(' Welcome to Sco-Admin ');
$this->line('************************');
$this->publish();
$this->routes();
$this->info('Successfully Installed Sco-Admin!');
} | Execute the console command.
@return mixed | entailment |
protected function castValueAsJson($value)
{
$value = $this->asJson($value);
if ($value === false) {
throw new \RuntimeException(
sprintf(
"Unable to encode value [%s] for element [%s] to JSON: %s.",
$this->getName(),
get_class($this),
json_last_error_msg()
)
);
}
return $value;
} | Cast the given value to JSON.
@param mixed $value
@return string | entailment |
protected function castValue($value)
{
if (is_null($value)) {
return $value;
}
if ($this->isElementOfDate() && $this->isDateCastable()) {
return $this->fromDateTime($value);
}
switch ($this->getCast()) {
case 'int':
case 'integer':
return (int) $value;
case 'real':
case 'float':
case 'double':
return (float) $value;
case 'string':
return (string) $value;
case 'bool':
case 'boolean':
return (bool) $value;
case 'object':
return $this->fromJson($value, true);
case 'array':
case 'json':
return $this->fromJson($value);
case 'collection':
return new Collection($this->fromJson($value));
case 'comma':
return $this->fromCommaSeparated($value);
default:
return $value;
}
} | Cast a value to a native PHP type.
@param $value
@return array | entailment |
protected function getModelClassFromValue($value)
{
if (empty($value)) return null;
$parts = explode(static::CLASS_AND_KEY_SEPARATOR, $value, 2);
return $parts[0];
} | Returns the model class part of a morph model/key combination value.
@param string $value
@return string|null | entailment |
protected function getModelKeyFromValue($value)
{
if (empty($value)) return null;
$parts = explode(static::CLASS_AND_KEY_SEPARATOR, $value, 2);
if (count($parts) < 2) {
throw new UnexpectedValueException("Morph model value is not formatted as 'class:key'.");
}
return $parts[1];
} | Returns the model key part of a morph model/key combination value.
@param string $value
@return mixed|null | entailment |
protected function getValueFromRelationQuery($query)
{
// Prevent looking up connected model when foreign keys are NULL to prevent query errors.
/** @var MorphTo $query */
$typeName = $query->getMorphType();
$keyName = $query->getForeignKey();
if ( ! $this->model->{$typeName} || ! $this->model->{$keyName}) {
return null;
}
$query = $this->prepareRelationQuery($query);
return $this->getValueFromModel(
$query->first()
);
} | Returns the value per relation for a given relation query builder.
@param Builder|Relation $query
@return mixed|null | entailment |
protected function getValueFromModel($model)
{
if ( ! ($model instanceof Model)) {
return null;
}
return get_class($model)
. static::CLASS_AND_KEY_SEPARATOR
. $model->getKey();
} | Returns the value for a single related model.
@param Model|null $model
@return mixed|null | entailment |
protected function getModelByKey($model, $key)
{
if (is_string($model)) {
$model = new $model;
}
/** @var Model $model */
return $model->withoutGlobalScopes()->find($key);
} | Finds a (to be related) model by its key.
@param string|Model $model
@param string $key
@return Model|null | entailment |
protected function storeActiveTranslationLocale($request)
{
$locale = $request->input(DefaultModelController::ACTIVE_TRANSLATION_LOCALE_KEY);
if ( ! $locale) return;
/** @var TranslationLocaleHelperInterface $helper */
$helper = app(TranslationLocaleHelperInterface::class);
$helper->setActiveLocale($locale);
} | Stores active translation locale in session.
@param \Illuminate\Http\Request $request | entailment |
protected function decorateFieldData(array $data)
{
// Get the key-reference pairs required to fill the drop-down and group them by the model class.
// Also get displayable labels for each model class.
$modelClasses = $this->getMorphableModels();
$modelLabels = [];
$references = [];
foreach ($modelClasses as $modelClass) {
$modelLabels[ $modelClass ] = $this->getModelDisplayLabel($modelClass);
$referenceData = $this->getReferenceDataProvider()->getForModelClassByType(
get_class($this->model),
'form.field',
$this->field->key(),
$modelClass
);
$references[$modelClass] = [];
if ($referenceData) {
foreach (
$this->getReferenceRepository()->getReferencesForModelMetaReference($referenceData)->all()
as $referenceKey => $reference
) {
$references[$modelClass][ $modelClass . static::CLASS_AND_KEY_SEPARATOR . $referenceKey] = $reference;
}
}
}
$data['modelLabels'] = $modelLabels;
$data['dropdownOptions'] = $references;
return $data;
} | Enriches field data before passing it on to the view.
@param array $data
@return array | entailment |
protected function buildClass($name)
{
$replace = array_merge(
['DummyDisplayType' => $this->getDisplayType()],
$this->buildObserverReplacements(),
$this->buildModelReplacements()
);
return str_replace(
array_keys($replace),
array_values($replace),
parent::buildClass($name)
);
} | Build the class with the given name.
@param string $name
@return string | entailment |
protected function parseObserver($observer)
{
if (preg_match('([^A-Za-z0-9_/\\\\])', $observer)) {
throw new InvalidArgumentException('Observer name contains invalid characters.');
}
$observer = str_replace('/', '\\', $observer);
if (! Str::startsWith($observer, [
$rootNamespace = $this->laravel->getNamespace(),
'\\'
])) {
$observer = $rootNamespace . $this->getComponentNamespace()
. '\Observers\\'
. rtrim($observer, 'Observer') . 'Observer';
}
return $observer;
} | Get the fully-qualified observer class name.
@param string $observer
@return string | entailment |
public function render(Model $model, $source)
{
$source = $this->resolveModelSource($model, $source);
$date = $this->interpretAsDate($source);
if ( ! $date) {
return '';
}
return e($date->format($this->getFormat()));
} | 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 interpretAsDate($value)
{
if (null === $value || 0 === $value || '' === $value) {
return null;
}
if ($value instanceof DateTime) {
return $value;
}
if (is_string($value)) {
return new Carbon($value);
}
if (is_numeric($value)) {
return Carbon::createFromTimestamp($value);
}
throw new UnexpectedValueException("Expecting null or date");
} | Parses a source value as a boolean value.
@param mixed $value
@return DateTime|null | entailment |
protected function setCurrentModelClass()
{
if ( ! $this->router->isModelRoute()) {
$this->currentModelClass = null;
return $this;
}
$info = $this->repository->getByKey(
$this->router->getModuleKeyForCurrentRoute()
);
if ($info) {
$this->currentModelClass = $info->original_model ?: $info->model;
} else {
$this->currentModelClass = null;
}
$this->activeModelClass = $this->currentModelClass;
return $this;
} | Sets the active and current model class based on the current request. | entailment |
public function info()
{
if (empty($this->activeModelClass)) {
$info = false;
} else {
$info = $this->repository->getByModelClass($this->activeModelClass);
}
// Reset the active model class for future calls
$this->activeModelClass = $this->currentModelClass;
return $info;
} | Returns model information data object for active model.
@return ModelInformation|false | entailment |
protected function performEnrichment()
{
if ( ! count($this->info->list->columns)) {
$this->fillDataForEmpty();
} else {
$this->enrichCustomData();
}
} | Performs enrichment. | entailment |
protected function fillDataForEmpty()
{
// Fill list references if they are empty
$columns = [];
// Add columns for attributes
foreach ($this->info->attributes as $attribute) {
if ($attribute->hidden || ! $this->shouldAttributeBeDisplayedByDefault($attribute, $this->info)) {
continue;
}
$columns[ $attribute->name ] = $this->makeModelListColumnDataForAttributeData($attribute, $this->info);
}
// Add columns for relations?
// Perhaps, though it may be fine to leave this up to manual configuration.
// todo: consider
$this->info->list->columns = $columns;
} | Fills column data if no custom data is set. | entailment |
protected function enrichCustomData()
{
// Check filled columns and enrich them as required
// Note that these can be either attributes or relations
$columns = [];
foreach ($this->info->list->columns as $key => $column) {
try {
$this->enrichColumn($key, $column, $columns);
} catch (\Exception $e) {
// Wrap and decorate exceptions so it is easier to track the problem source
throw (new ModelInformationEnrichmentException(
"Issue with list column '{$key}' (list.columns.{$key}): \n{$e->getMessage()}",
(int) $e->getCode(),
$e
))
->setSection('list.columns')
->setKey($key);
}
}
$this->info->list->columns = $columns;
} | Enriches existing user configured data. | entailment |
protected function enrichColumn($key, ModelListColumnDataInterface $column, array &$columns)
{
$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 column data is fully set, no need to enrich
if ($this->isListColumnDataComplete($column)) {
$columns[ $key ] = $column;
return;
}
throw new UnexpectedValueException(
"Incomplete data for for list column key that does not match known model attribute or relation method. "
. "Requires at least 'source' and 'strategy' values."
);
}
if (isset($this->info->attributes[ $key ])) {
$attributeColumnInfo = $this->makeModelListColumnDataForAttributeData($this->info->attributes[ $key ], $this->info);
} else {
// Get from relation data
$attributeColumnInfo = $this->makeModelListColumnDataForRelationData(
$this->info->relations[ $normalizedRelationName ]
);
}
$attributeColumnInfo->merge($column);
$columns[ $key ] = $attributeColumnInfo;
} | Enriches a single list column and saves the data.
@param ModelListColumnDataInterface $column
@param string $key
@param array $columns by reference, data array to build, updated with enriched data | entailment |
protected function makeModelListColumnDataForAttributeData(ModelAttributeData $attribute, ModelInformationInterface $info)
{
$primaryIncrementing = $attribute->name === $this->model->getKeyName() && $info->incrementing;
$sortable = (
$attribute->isNumeric()
|| in_array($attribute->cast, [
AttributeCast::BOOLEAN,
AttributeCast::DATE,
AttributeCast::STRING,
])
&& ! in_array($attribute->type, [
'text', 'longtext', 'mediumtext',
'blob', 'longblob', 'mediumblob',
])
);
$sortDirection = 'asc';
if ( $primaryIncrementing
|| in_array($attribute->cast, [ AttributeCast::BOOLEAN, AttributeCast::DATE ])
) {
$sortDirection = 'desc';
}
return new ModelListColumnData([
'source' => $attribute->name,
'strategy' => $this->determineListDisplayStrategyForAttribute($attribute),
'style' => $primaryIncrementing ? 'primary-id' : null,
'editable' => $attribute->fillable,
'sortable' => $sortable,
'sort_strategy' => $attribute->translated ? 'translated' : null,
'sort_direction' => $sortDirection,
]);
} | Makes data set for list column given attribute data.
@param ModelAttributeData $attribute
@param ModelInformationInterface|ModelInformation $info
@return ModelListColumnData | entailment |
protected function makeModelListColumnDataForRelationData(ModelRelationData $relation)
{
return new ModelListColumnData([
'source' => $relation->method,
'strategy' => $this->determineListDisplayStrategyForRelation($relation),
'label' => ucfirst(str_replace('_', ' ', snake_case($relation->method))),
'sortable' => false,
]);
} | Makes data set for list column given relation data.
@param ModelRelationData $relation
@return ModelListColumnData | entailment |
protected function initializeForModelRoute()
{
$this->moduleKey = $this->routeHelper->getModuleKeyForCurrentRoute();
$this->modelSlug = $this->routeHelper->getModelSlugForCurrentRoute();
$this->permissionPrefix = $this->routeHelper->getPermissionPrefixForModelSlug($this->modelSlug);
if ( ! $this->moduleKey) {
// @codeCoverageIgnoreStart
throw new RuntimeException("Could not determine module key for route");
// @codeCoverageIgnoreEnd
}
$this->modelInformation = $this->infoRepository->getByKey($this->modelSlug);
if ( ! $this->modelInformation) {
// @codeCoverageIgnoreStart
throw new RuntimeException("Could not load information for model key '{$this->modelSlug}'");
// @codeCoverageIgnoreEnd
}
$this->routePrefix = $this->routeHelper->getRouteNameForModelClass(
$this->modelInformation->modelClass(),
true
);
return $this;
} | Initializes controller and checks context expecting a model route.
@return $this | entailment |
protected function initializeModelRepository()
{
/** @var ModelRepositoryFactoryInterface $factory */
$factory = app(ModelRepositoryFactoryInterface::class);
$this->modelRepository = $factory->make($this->modelInformation->modelClass());
$this->applyRepositoryContext();
return $this;
} | Sets up the model repository for the relevant model.
@return $this | entailment |
protected function getFormFieldStoreStrategyParametersForField(ModelFormFieldDataInterface $field)
{
$strategy = $field->store_strategy ?: '';
$pos = strpos($strategy, ':');
if (false === $pos) {
return [];
}
return array_map('trim', explode(',', substr($strategy, $pos + 1)));
} | Returns parameters that should be passed into the store strategy instance.
@param ModelFormFieldDataInterface|ModelFormFieldData $field
@return array | entailment |
public function render($key, $value)
{
if ('' === $value) {
$value = null;
}
if (null !== $value) {
$value = $value ? '1' : '0';
}
return view(
'cms-models::model.partials.filters.dropdown-boolean',
[
'label' => $this->filterData ? $this->filterData->label() : $key,
'key' => $key,
'selected' => $value,
'options' => [
'1' => $this->getTrueLabel(),
'0' => $this->getFalseLabel(),
],
]
);
} | Applies a strategy to render a filter field.
@param string $key
@param mixed $value
@return string|View | entailment |
public function render(Model $model, $source)
{
$value = $this->resolveModelSource($model, $source);
if (null === $value) {
return null;
}
if ($value) {
return cms_trans('common.boolean.true');
}
return cms_trans('common.boolean.false');
} | Renders a display value to print to the export.
@param Model $model
@param mixed $source source column, method name or value
@return string | entailment |
protected function performEnrichment()
{
if ( ! count($this->info->form->fields)) {
return;
}
$this->layoutFields = $this->info->form->getLayoutFormFieldKeys();
$this
->enrichCreateRules()
->enrichUpdateRules();
} | Performs enrichment of validation rules based on form field strategies.
@throws ModelInformationEnrichmentException | entailment |
protected function getCustomizedRuleKeysToExclude(array $customRules)
{
$keys = [];
foreach ($customRules as $key => $ruleParts) {
// If the set value for this key is false/null, the rule must be ignored entirely.
// This will disable enrichment using form field rules.
if (false === $ruleParts || empty($ruleParts)) {
$keys[] = $key;
}
}
return $keys;
} | Returns keys for rules that should not be included by custom configuration.
@param array $customRules
@return string[] | entailment |
protected function getCustomizedRuleKeysToKeepDefault(array $customRules)
{
$keys = [];
foreach ($customRules as $key => $ruleParts) {
// If the configured value is the name of a key (and so it is a non-associative
// part of the rules), it indicates that the default should be kept/copied over,
// for the key the value denotes.
if (is_string($ruleParts) && is_numeric($key)) {
$keys[] = $ruleParts;
}
}
return $keys;
} | Returns keys for rules that should be kept from the default generated rules,
even when in replace mode.
@param array $customRules
@return string[] | entailment |
protected function enrichRulesNew(
array $customRules,
array $generatedRules,
$replace,
array $excludeKeys,
array $keepDefaultKeys,
array $generatedRulesMap
) {
// so use them as a starting point.
// If custom rules are configured, they should not overwritten by form field rules,
$result = $customRules;
// Include any generated rules explicitly marked for inclusion.
foreach ($keepDefaultKeys as $key) {
if ( ! array_key_exists($key, $generatedRules)) {
continue;
}
$result[ $key ] = $generatedRules[ $key ];
}
// If the generated rules are explicitly replaced default rules, we don't have to merge them.
// Otherwise, append any form field defined rule that is
// not yet included and not marked for exclusion.
if ( ! $replace) {
foreach ($generatedRulesMap as $fieldKey => $ruleKeys) {
// The field key or any of its nested child rules keys may be disabled.
// If the field key itself is excluded, find the mapped keys for that
// field and exclude any of them.
// So skip any set of rules belonging to a field whose key has
// been excluded (as a rule key).
if (in_array($fieldKey, $excludeKeys)) {
continue;
}
foreach ($ruleKeys as $key) {
// Skip if ..
if (
// .. the key is already included, or marked for exclusion
in_array($key, $excludeKeys)
|| in_array($key, $keepDefaultKeys)
// .. the result array already has an entry for the key
|| array_key_exists($key, $result)
// .. no generated rule exists for the key (safeguard)
|| ! array_key_exists($key, $generatedRules)
) {
continue;
}
$result[ $key ] = $generatedRules[ $key ];
}
}
}
$result = $this->getRuleMerger()->convertRequiredForTranslatedFields($result);
return $this->castValidationRulesToArray($result);
} | Enriches rules and returns the enriched rules array.
@param array $customRules rules custom-defined in the configuration, normalized
@param array $generatedRules rules generated by the CMS, normalized
@param bool $replace whether to replace rules entirely (and not enricht non-present rules)
@param string[] $excludeKeys keys for rules that should be excluded
@param string[] $keepDefaultKeys keys for rules that should be kept as generated by default
@param array[] $generatedRulesMap the mapped rules per form field for generated rules
@return array | entailment |
protected function getFormFieldGeneratedRules($forCreate = true)
{
$this->generatedRulesMap = [];
$rules = [];
foreach ($this->info->form->fields as $field) {
try {
$this->getFormFieldGeneratedRule($field, $forCreate, $rules);
} catch (Exception $e) {
$section = 'form.validation.' . ($forCreate ? 'create' : 'update');
// Wrap and decorate exceptions so it is easier to track the problem source
throw (new ModelInformationEnrichmentException(
"Issue with validation rules for form field '{$field->key()}' ({$section}): \n{$e->getMessage()}",
$e->getCode(),
$e
))
->setSection($section)
->setKey($field->key());
}
}
return $rules;
} | Returns rules determined by form field strategies.
@param bool $forCreate
@return array
@throws ModelInformationEnrichmentException | entailment |
protected function getFormFieldGeneratedRule(ModelFormFieldDataInterface $field, $forCreate, array &$rules)
{
$this->generatedRulesMap[ $field->key() ] = [];
if ( ! $this->isFormFieldRelevant($field, $forCreate)) {
return;
}
// The rules returned by a strategy (specific), and those provided by the
// field type (attribute/relation), must first be combined --
// and in preparation for that be cast as uniform arrays of ValidationRuleData instances.
$fieldRules = $this->getAndMergeFormFieldRulesForStrategyAndBasedOnModelInformation($field, $forCreate);
// If the field is translated, mark the rules for it in preparation for further decoration
if ($field->translated()) {
array_map(function (ValidationRuleDataInterface $rule) {
$rule->setIsTranslated();
}, $fieldRules);
}
// The keys in the strategy or model information might have placeholders
// in its rules, to allow referring to other 'relative' validation keys
// for the field such as in required_with... rules.
// These placeholders need to be replaced.
$fieldRules = $this->replaceFieldKeyPlaceholderInValidationRules($field, $fieldRules);
// At this point we have a normalized array of data objects,
// which has dot-notation keys (for array-nested rules) that is offset
// for the field (so it leaves out the field key itself).
// Rules for the field key itself will thus have empty/null keys.
// The rules will also have been collapsed to one per key.
foreach ($fieldRules as $rule) {
if (empty($rule->key())) {
$rule->setKey($field->key());
$rules[ $field->key() ] = $rule;
$this->generatedRulesMap[ $field->key() ][] = $field->key();
continue;
}
$rule->prefixKey($field->key());
$rules[ $rule->key() ] = $rule;
$this->generatedRulesMap[ $field->key() ][] = $rule->key();
}
} | Updates collected rules array with rules based on form field data.
@param ModelFormFieldDataInterface|ModelFormFieldData $field
@param bool $forCreate
@param array $rules by reference | entailment |
protected function normalizeValidationRuleSourceDataFromConfig(array $rules)
{
// Remove entries to be ignored and excluded
$filteredRules = array_filter($rules, function ($rule, $key) {
return false !== $rule
&& ! empty($rule)
&& ! (is_string($rule) && is_numeric($key));
}, ARRAY_FILTER_USE_BOTH);
return $this->normalizeValidationRuleSourceData($filteredRules);
} | Normalizes custom configured rules data to include only specified rules.
This leaves out rules nullified to exclude them, as well as rules
marked to be included/kept as generated by default.
@param array $rules
@return ValidationRuleDataInterface[] | entailment |
protected function normalizeValidationRuleSourceData($rules)
{
if (false === $rules || empty($rules)) {
return [];
}
if (is_string($rules)) {
$rules = (array) $rules;
}
if ( ! is_array($rules)) {
throw new UnexpectedValueException("Form field base validation rules not array or arrayable");
}
// Loop through and cast anything not already a data object
$rules = array_map([$this, 'normalizeRulesProperty'], $rules, array_keys($rules));
// Make sure there is only one entry per rule key
$rules = $this->getRuleMerger()->collapseRulesForDuplicateKeys($rules);
// Key the array by the rule key
return array_combine(
array_map(function (ValidationRuleDataInterface $rule) {
return $rule->key() ?: '';
}, $rules),
$rules
);
} | Normalizes generated validation rule data to an array of data object instances.
The entries will be collapsed to one per key, and the array will be keyed by the key.
@param mixed $rules
@return ValidationRuleDataInterface[] | entailment |
protected function normalizeRulesProperty($rules, $key)
{
if ($rules instanceof ValidationRuleDataInterface) {
return $rules;
}
if (is_string($rules)) {
// Convert Laravel's pipe-syntax to array
$rules = explode('|', $rules);
}
if ( ! is_array($rules)) {
$rules = (array) $rules;
}
// If the array is marked up in a special format, it can reflect the
// contents of a validation rule dataobject directly.
if ($key === static::VALIDATION_RULE_DATA_KEY) {
return $this->makeValidationRuleDataFromSpecialArraySyntax($rules, '');
}
if (is_array(array_get($rules, static::VALIDATION_RULE_DATA_KEY))) {
return $this->makeValidationRuleDataFromSpecialArraySyntax($rules[static::VALIDATION_RULE_DATA_KEY], $key);
}
// If the array is associative (and the key is non-numeric), included
// it as a nested postfix for the field key, by including it in the data.
return new ValidationRuleData($rules, is_numeric($key) ? null : $key);
} | Normalizes rules data for a single validation rule key.
@param mixed $rules
@param int|string $key The source array key
@return ValidationRuleDataInterface | entailment |
protected function makeValidationRuleDataFromSpecialArraySyntax(array $rules, $key)
{
$data = new ValidationRuleData(
array_get($rules, 'rules', []),
array_get($rules, 'key', is_numeric($key) ? null : $key)
);
if (array_has($rules, 'translated')) {
$data->setIsTranslated((bool) $rules['translated']);
}
if (array_has($rules, 'locale_index')) {
// @codeCoverageIgnoreStart
if ((int) $rules['locale_index'] < 1) {
throw new UnexpectedValueException(
"Locale index for configured validation data cannot be less than 1 (key/index: {$key})"
);
}
// @codeCoverageIgnoreEnd
$data->setLocaleIndex((int) $rules['locale_index']);
}
return $data;
} | Makes a validation rule data object from a special configuration array.
@param array $rules
@param null|string $key
@return ValidationRuleData | entailment |
protected function getFormFieldModelInformationBasedRules(ModelFormFieldDataInterface $field)
{
$key = $field->key();
$modelInformation = $this->getModelInformation();
if (array_key_exists($key, $modelInformation->attributes)) {
return $this->getAttributeValidationResolver()->determineValidationRules(
$modelInformation->attributes[ $key ],
$field
);
}
if (array_key_exists($key, $modelInformation->relations)) {
return $this->getRelationValidationResolver()->determineValidationRules(
$modelInformation->relations[ $key ],
$field
);
}
return false;
} | Returns validation rules based on model information for a given form field.
@param ModelFormFieldDataInterface|ModelFormFieldData|null $field
@return array|false | entailment |
protected function replaceFieldKeyPlaceholderInValidationRules(ModelFormFieldDataInterface $field, array $rules)
{
foreach ($rules as $rule) {
// Prepare field prefix with locale placeholder if relevant
$fieldPrefix = $field->key();
if ($rule->isTranslated() && $rule->localeIndex() < 2) {
$fieldPrefix .= '.' . $this->getLocalePlaceholder();
}
// For each rule, if it is a string, replace the field placeholder with this prefix
$rule->setRules(
array_map(function ($rule) use ($fieldPrefix) {
if ( ! is_string($rule)) {
return $rule;
}
return str_replace(static::FIELD_KEY_PLACEHOLDER, $fieldPrefix, $rule);
}, $rule->rules())
);
}
return $rules;
} | Replaces placeholders for the field key (as prefix).
@param ModelFormFieldDataInterface $field
@param ValidationRuleDataInterface[] $rules
@return ValidationRuleDataInterface[] | entailment |
public function retrieve(Model $model, $source)
{
if ($this->isTranslated()) {
return $model->translations->pluck($source, config('translatable.locale_key', 'locale'))->toArray();
}
return $this->resolveModelSource($model, $source);
} | Retrieves current values from a model
@param Model $model
@param string $source
@return mixed | entailment |
public function store(Model $model, $source, $value)
{
if ( ! $this->isTranslated()) {
$this->performStore($model, $source, $value);
return;
}
/** @var Model|Translatable $model */
if ( ! is_array($value)) {
throw new UnexpectedValueException("Value should be in per-locale array format for translatable data");
}
foreach ($value as $locale => $singleValue) {
// Safeguard: use empty string if non-nullable translated field is null
if (null === $singleValue && ! $this->isNullable()) {
$singleValue = '';
}
$this->performStore($model->translateOrNew($locale), $source, $singleValue);
}
} | Stores a submitted value on a model
@param Model $model
@param string $source
@param mixed $value | entailment |
public function storeAfter(Model $model, $source, $value)
{
if ( ! $this->isTranslated()) {
$this->performStoreAfter($model, $source, $value);
return;
}
/** @var Model|Translatable $model */
if ( ! is_array($value)) {
throw new UnexpectedValueException("Value should be in per-locale array format for translatable data");
}
foreach ($value as $locale => $singleValue) {
$this->performStoreAfter($model->translateOrNew($locale), $source, $singleValue);
}
} | Stores a submitted value on a model, after it has been created (or saved).
@param Model $model
@param mixed $source
@param mixed $value | entailment |
public function validationRules(ModelInformationInterface $modelInformation = null, $create)
{
if ( ! ($field = $this->formFieldData)) {
return false;
}
return $this->getStrategySpecificRules($field);
} | Returns validation rules to use for submitted form data for this strategy.
If the return array is associative, rules are expected nested per key,
otherwise the rules will be added to the top level key.
@param ModelInformationInterface|ModelInformation|null $modelInformation
@param bool $create
@return array|false false if no validation should be performed. | entailment |
public function register()
{
$this->mergeConfigFrom(
$this->getBasePath() . '/config/admin.php',
'admin'
);
$this->registerMiddleware();
$this->registerFactory();
$this->app->instance('admin.instance', new Admin($this->app));
$this->app->bind(RepositoryInterface::class, Repository::class);
} | Register the application services.
@return void | entailment |
public function setTexts(string $active, string $inactive)
{
$this->texts = [$active, $inactive];
return $this;
} | @param string $active
@param string $inactive
@return ElSwitch | entailment |
public function setColors(string $active, string $inactive)
{
$this->colors = [$active, $inactive];
return $this;
} | @param string $active
@param string $inactive
@return ElSwitch | entailment |
public function setIconClasses(string $active, string $inactive)
{
$this->iconClasses = [$active, $inactive];
return $this;
} | @param string $active
@param string $inactive
@return $this | entailment |
protected function asDateTime($value)
{
if ($value instanceof Carbon) {
return $value->timezone($this->getTimezone());
}
if ($value instanceof \DateTimeInterface) {
return new Carbon(
$value->format('Y-m-d H:i:s.u'),
$value->getTimezone()
);
}
if (is_numeric($value)) {
return Carbon::createFromTimestamp($value)->timezone($this->getTimezone());
}
return Carbon::createFromFormat($this->getFormat(), $value);
} | Return a timestamp as DateTime object.
@param mixed $value
@return Carbon | entailment |
public function fromDateTime($value)
{
return empty($value) ? $value : $this->asDateTime($value)
->timezone($this->getTimezone())
->format($this->getFormat());
} | Convert a DateTime to a storable string.
@param \DateTime|int $value
@return string | entailment |
public function mapWebRoutes(Router $router)
{
$permissionPrefix = $this->routeHelper->getPermissionPrefixForModelSlug(
$this->getModelSlug()
);
$router->group(
[
'prefix' => $this->getRoutePrefix(),
'as' => $this->getRouteNamePrefix(),
'middleware' => [ cms_mw_permission("{$permissionPrefix}*") ],
],
function (Router $router) use ($permissionPrefix) {
$controller = $this->getModelWebController();
$router->get('/', [
'as' => 'index',
'uses' => $controller . '@index',
]);
$router->get('create', [
'as' => 'create',
'middleware' => [cms_mw_permission("{$permissionPrefix}create")],
'uses' => $controller . '@create',
]);
$router->post('/', [
'as' => 'store',
'middleware' => [
cms_mw_permission("{$permissionPrefix}create"),
StoreActiveFormContext::class,
],
'uses' => $controller . '@store',
]);
$router->post('filter', [
'as' => 'filter',
'uses' => $controller . '@filter',
]);
$router->get('export/{strategy}', [
'as' => 'export',
'middleware' => [cms_mw_permission("{$permissionPrefix}export")],
'uses' => $controller . '@export',
]);
$router->get('{key}', [
'as' => 'show',
'uses' => $controller . '@show',
]);
$router->get('{key}/edit', [
'as' => 'edit',
'middleware' => [cms_mw_permission("{$permissionPrefix}edit")],
'uses' => $controller . '@edit',
]);
$router->put('{key}/activate', [
'as' => 'activate',
'middleware' => [cms_mw_permission("{$permissionPrefix}edit")],
'uses' => $controller . '@activate',
]);
$router->put('{key}/position', [
'as' => 'position',
'middleware' => [cms_mw_permission("{$permissionPrefix}edit")],
'uses' => $controller . '@position',
]);
$router->get('{key}/deletable', [
'as' => 'deletable',
'middleware' => [cms_mw_permission("{$permissionPrefix}delete")],
'uses' => $controller . '@deletable',
]);
$router->put('{key}', [
'as' => 'update',
'middleware' => [
cms_mw_permission("{$permissionPrefix}edit"),
StoreActiveFormContext::class,
],
'uses' => $controller . '@update',
]);
$router->delete('{key}', [
'as' => 'destroy',
'middleware' => [cms_mw_permission("{$permissionPrefix}delete")],
'uses' => $controller . '@destroy',
]);
}
);
} | Generates web routes for the module given a contextual router instance.
Note that the module is responsible for ACL-checks, including route-based.
@param Router $router | entailment |
public function mapApiRoutes(Router $router)
{
$permissionPrefix = $this->routeHelper->getPermissionPrefixForModelSlug(
$this->getModelSlug()
);
$router->group(
[
'prefix' => $this->getRoutePrefix(),
'as' => $this->getRouteNamePrefix(),
'middleware' => [ cms_mw_permission("{$permissionPrefix}*") ],
],
function (Router $router) use ($permissionPrefix) {
$controller = $this->getModelApiController();
$router->get('/', [
'as' => 'index',
'uses' => $controller . '@index',
]);
$router->get('create', [
'as' => 'create',
'middleware' => [cms_mw_permission("{$permissionPrefix}create")],
'uses' => $controller . '@create',
]);
$router->post('/', [
'as' => 'store',
'middleware' => [cms_mw_permission("{$permissionPrefix}create")],
'uses' => $controller . '@store',
]);
$router->get('{key}', [
'as' => 'show',
'uses' => $controller . '@show',
]);
$router->get('{key}/edit', [
'as' => 'edit',
'middleware' => [cms_mw_permission("{$permissionPrefix}edit")],
'uses' => $controller . '@edit',
]);
$router->put('{key}', [
'as' => 'update',
'middleware' => [cms_mw_permission("{$permissionPrefix}edit")],
'uses' => $controller . '@update',
]);
$router->delete('{key}', [
'as' => 'destroy',
'middleware' => [cms_mw_permission("{$permissionPrefix}delete")],
'uses' => $controller . '@destroy',
]);
}
);
} | Generates API routes for the module given a contextual router instance.
Note that the module is responsible for ACL-checks, including route-based.
@param Router $router | entailment |
public function getMenuPresence()
{
return [
'id' => 'models.' . $this->getRouteSlug(),
'label' => ucfirst($this->getInformation()->labelPlural(false)),
'label_translated' => $this->getInformation()->labelPluralTranslationKey(),
'type' => MenuPresenceType::ACTION,
'action' => $this->routeHelper->getRouteNameForModelClass($this->class, true) . '.index',
'parameters' => [
'home' => true,
],
'permissions' => [
"models.{$this->getRouteSlug()}.*",
],
];
} | Returns data for CMS menu presence.
@return null|array|MenuPresenceInterface[]|MenuPresenceInterface[] | entailment |
public function render(Model $model, $source)
{
if (null === $this->resolveModelSource($model, $source)) {
return '';
}
return parent::render($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 |
public function handle(Request $request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if ($request->expectsJson()) {
return response()->json(Auth::user());
}
return redirect()->route('admin.dashboard');
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
protected function getFileValidationRules()
{
$rules = array_get($this->field->options, 'validation', []);
// If the 'image' rule is not set, make sure it is added.
if (is_string($rules)) {
if (empty($rules)) {
$rules = 'image';
} elseif ( ! preg_match('#(^|\|)image($|\|)#', $rules)) {
$rules .= '|image';
}
} elseif ( ! in_array('image', $rules)) {
array_unshift($rules, 'image');
}
return $rules;
} | Returns validation rules that should be applied to the uploaded file.
@return string|array | entailment |
public function setAutoSize($max, $min = 1)
{
$this->autoSize = [
'minRows' => intval($min),
'maxRows' => intval($max),
];
return $this;
} | @param int $max
@param int $min
@return $this | entailment |
public function determineValidationRules(ModelAttributeData $attribute, ModelFormFieldData $field)
{
$rules = [];
$required = $field->required();
switch ($attribute->cast) {
case AttributeCast::BOOLEAN:
$required = false;
break;
case AttributeCast::INTEGER:
$rules[] = 'integer';
break;
case AttributeCast::FLOAT:
$rules[] = 'numeric';
break;
case AttributeCast::STRING:
switch ($attribute->type) {
case 'enum':
$rules[] = 'in:' . implode(',', $attribute->values);
break;
case 'year':
$rules[] = 'digits:4';
break;
case 'varchar':
$rules[] = 'string';
if ($attribute->length) {
$rules[] = 'max:' . $attribute->length;
}
break;
case 'tinytext':
$rules[] = 'string';
$rules[] = 'max:255';
break;
case 'char':
$rules[] = 'string';
$rules[] = 'max:' . $attribute->length;
break;
case 'text':
case 'mediumtext':
case 'longtext':
case 'blob';
case 'mediumblob';
case 'longblob';
case 'binary';
case 'varbinary';
$rules[] = 'string';
break;
}
break;
case AttributeCast::DATE:
switch ($attribute->type) {
case 'date':
case 'datetime':
case 'timestamp':
$rules[] = 'date';
break;
case 'time':
$rules[] = 'regex:#^\d{1,2}:\d{1,2}(:\d{1,2})?$#';
break;
}
break;
case AttributeCast::JSON:
$rules[] = 'json';
break;
}
if ($required) {
// Special case for translated fields: required should be treated as required only if
// any other translated fields for that locale are entered.
// This should be handled by the class that requested the attribute validation rules.
/** @see AbstractFormFieldStoreStrategy */
$rules[] = 'required';
} else {
// Anything that is not required should by default be explicitly nullable
// since Laravel 5.4.
$rules[] = 'nullable';
}
return $rules;
} | Determines validation rules for given attribute data.
@param ModelAttributeData $attribute
@param ModelFormFieldData $field
@return array|false | entailment |
protected function getValueFromRelationQuery($query)
{
// Query must be a relation in this case, since we need the related model
if ( ! ($query instanceof Relation)) {
throw new UnexpectedValueException("Query must be Relation instance for " . get_class($this));
}
$relatedModel = $query->getRelated();
$keyName = $relatedModel->getKeyName();
$table = $relatedModel->getTable();
$query = $this->prepareRelationQuery($query);
return $query->pluck($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 Relation)) {
throw new UnexpectedValueException("{$source} did not resolve to relation");
}
// Any singular relations are unexpected
if ( $relation instanceof BelongsTo
|| $relation instanceof HasOne
|| $relation instanceof MorphOne
) {
throw new UnexpectedValueException("{$source} is a single relation, expecting plural");
}
if (null === $value) {
$value = [];
}
// Should not be used, since this is for singular relations..
if ($relation instanceof BelongsToMany) {
$relation->sync($value);
return;
}
// For *One and *Many relations, we need to handle detachment for currently related models.
if ( $relation instanceof HasOne
|| $relation instanceof HasMany
|| $relation instanceof MorphOne
|| $relation instanceof MorphMany
) {
// Detach only the models that shouldn't stay attached (ie. aren't in the new value array)
/** @var Collection|Model[] $currentlyRelated */
$currentlyRelated = $relation->get();
$currentlyRelated = $currentlyRelated->filter(function (Model $model) use ($value) {
return ! in_array($model->getKey(), $value);
});
$this->detachRelatedModelsForOneOrMany($currentlyRelated, $relation);
}
// For HasMany, the related models must be found,
// and then they should be saved on the relation.
$relatedModels = $this->getModelsByKey($relation->getRelated(), $value);
if ( ! count($relatedModels)) return;
if ( $relation instanceof HasOne
|| $relation instanceof HasMany
|| $relation instanceof MorphOne
|| $relation instanceof MorphMany
) {
foreach ($relatedModels as $relatedModel) {
$relation->save($relatedModel);
}
return;
}
throw new UnexpectedValueException(
'Unexpected relation class ' . get_class($relation) . " for {$source}"
);
} | Stores a submitted value on a model, after it has been created (or saved).
@param Model $model
@param mixed $source
@param mixed $value | entailment |
protected function getModelsByKey($model, $keys)
{
if (is_string($model)) {
$model = new $model;
}
/** @var Model $model */
return $model->withoutGlobalScopes()
->whereIn($model->getKeyName(), $keys)
->get()
->keyBy($model->getKeyName());
} | Finds (to be related) models by their keys.
@param string|Model $model
@param array|Arrayable $keys
@return Collection|Model[] | entailment |
public function from(string $designDoc, string $name): ViewQuery
{
return ViewQuery::from($designDoc, $name);
} | @param string $designDoc
@param string $name
@return ViewQuery | entailment |
public function fromSpatial(string $designDoc, string $name): SpatialViewQuery
{
return ViewQuery::fromSpatial($designDoc, $name);
} | @param string $designDoc
@param string $name
@return SpatialViewQuery | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.