refactor rules out of DataObject
This commit is contained in:
parent
77d1aebc0a
commit
74f151df07
5 changed files with 115 additions and 93 deletions
|
|
@ -46,7 +46,7 @@ trait DataObject
|
|||
public static function fromArray(array $input): ?static
|
||||
{
|
||||
$logger = new Log();
|
||||
$parameters = RuleFactory::getParametersMeta(static::class);
|
||||
$parameters = ReflectionHelper::getParametersMeta(static::class);
|
||||
foreach ($parameters as $parameter) {
|
||||
$parameterName = $parameter->reflection->getName();
|
||||
|
||||
|
|
@ -69,8 +69,7 @@ trait DataObject
|
|||
}
|
||||
$logger->inputRaw($input);
|
||||
|
||||
$rules = static::getRules();
|
||||
$logger->rules($rules);
|
||||
$rules = (new RuleFactory($logger))->make(static::class);
|
||||
|
||||
$validator = static::withValidator($input, $rules);
|
||||
|
||||
|
|
@ -102,52 +101,11 @@ trait DataObject
|
|||
return App::make(static::class, $mappedInput);
|
||||
}
|
||||
|
||||
public static function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public static function fails(Validator $validator): ?static
|
||||
{
|
||||
throw new ValidationException($validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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