59 lines
2.2 KiB
PHP
59 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Rules;
|
|
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
/**
|
|
* Check if the max count of children element is reached.
|
|
*
|
|
* @package App\Rules
|
|
*/
|
|
class IsMaxChildrenReached implements ValidationRule
|
|
{
|
|
/**
|
|
* Construct method.
|
|
*
|
|
* @param Model $parentModel The parent Model.
|
|
* @param string $relationName The name of the relation (used in whereRelation()).
|
|
* @param integer $max The max count of children allowed.
|
|
* @param integer|null $idToIgnore The id of the children model to ignore.
|
|
* @return void
|
|
*/
|
|
public function __construct(
|
|
private Model $parentModel,
|
|
private string $relationName,
|
|
private int $max,
|
|
private int|null $idToIgnore = null
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* Run the validation rule.
|
|
*
|
|
* @param string $attribute
|
|
* @param mixed $value
|
|
* @param \Closure(string):\Illuminate\Translation\PotentiallyTranslatedString $fail
|
|
* @return void
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
|
|
*/
|
|
public function validate(string $attribute, mixed $value, \Closure $fail): void
|
|
{
|
|
$children = $this->parentModel->where('id', $value)->first()->{$this->relationName};
|
|
if (!is_null($this->idToIgnore)) {
|
|
$children = $children->where('id', '!==', $this->idToIgnore);
|
|
}
|
|
if ($children->count() >= $this->max) {
|
|
$parentName = str($this->parentModel->getTable())->singular();
|
|
$childrenName = str($this->parentModel->{$this->relationName}()->getModel()->getTable())->singular();
|
|
|
|
$fail(trans('crud.messages.rule_max_reached', [
|
|
'parent' => str(trans_choice('models.classes.' . $parentName, 1))->title(),
|
|
'max' => $this->max,
|
|
'children' => str(trans_choice('models.classes.' . $childrenName, 1))->title()->plural()
|
|
]));
|
|
}
|
|
}
|
|
}
|