OverwriteRules
This commit is contained in:
parent
3a26a2e0c2
commit
709201547c
8 changed files with 252 additions and 19 deletions
|
|
@ -7,6 +7,7 @@ namespace Icefox\DTO;
|
|||
use Icefox\DTO\Attributes\FromInput;
|
||||
use Icefox\DTO\Attributes\CastWith;
|
||||
use Icefox\DTO\Attributes\FromRouteParameter;
|
||||
use Icefox\DTO\Attributes\OverwriteRules;
|
||||
use Icefox\DTO\Support\RuleFactory;
|
||||
use Icefox\DTO\Support\ValueFactory;
|
||||
use Illuminate\Http\Request;
|
||||
|
|
@ -66,7 +67,8 @@ trait DataObject
|
|||
}
|
||||
}
|
||||
|
||||
$rules = RuleFactory::buildRules($parameters, '');
|
||||
$rules = static::getRules();
|
||||
|
||||
$validator = static::withValidator($input, $rules);
|
||||
|
||||
if ($validator->fails()) {
|
||||
|
|
@ -101,6 +103,42 @@ trait DataObject
|
|||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,array<int, string|Rule>>
|
||||
*/
|
||||
public static function getRules(): array
|
||||
{
|
||||
$parameters = RuleFactory::getParametersMeta(static::class);
|
||||
$customRules = static::rules();
|
||||
$classReflection = new ReflectionClass(static::class);
|
||||
$rulesMethod = $classReflection->getMethod('rules');
|
||||
|
||||
if (!empty($rulesMethod->getAttributes(OverwriteRules::class))) {
|
||||
return $customRules;
|
||||
}
|
||||
|
||||
$inferredRules = RuleFactory::infer($parameters, '');
|
||||
return self::mergeRules($inferredRules, $customRules);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,array<int, string|Rule>> $inferredRules
|
||||
* @param array<string,array<int, string|Rule>> $customRules
|
||||
* @return array<string,array<int, string|Rule>>
|
||||
*/
|
||||
protected static function mergeRules(array $inferredRules, array $customRules): array
|
||||
{
|
||||
$merged = $inferredRules;
|
||||
foreach ($customRules as $key => $rules) {
|
||||
if (isset($merged[$key])) {
|
||||
$merged[$key] = array_values(array_unique(array_merge($merged[$key], $rules)));
|
||||
} else {
|
||||
$merged[$key] = $rules;
|
||||
}
|
||||
}
|
||||
return $merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $data
|
||||
* @param array<string,array<int, string|Rule>> $rules
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue