From c89dde38f8746c8b4de5222bedaf078178075190 Mon Sep 17 00:00:00 2001 From: Bentley O'Kane-Chase Date: Sat, 3 Dec 2022 12:20:12 +1000 Subject: [PATCH] Reduce code duplication --- .../DataPropertyValidationRulesResolver.php | 36 ++++++++----------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/Resolvers/DataPropertyValidationRulesResolver.php b/src/Resolvers/DataPropertyValidationRulesResolver.php index b9c97561..700471b3 100644 --- a/src/Resolvers/DataPropertyValidationRulesResolver.php +++ b/src/Resolvers/DataPropertyValidationRulesResolver.php @@ -69,27 +69,19 @@ protected function getNestedRules( $inferrer->handle($property, $toplevelRules); } - if (! $this->dataConfig->usesRelativeRuleGeneration()) { - $prefix = match (true) { - $property->type->isDataObject => "{$propertyName}", - $property->type->isDataCollectable => "{$propertyName}.*", - }; - - return $this->dataValidationRulesResolver - ->execute( - $property->type->dataClass, - $payload, - $this->isNestedDataNullable($nullable, $property) - ) - ->mapWithKeys(fn (array $rules, string $name) => [ - "{$prefix}.{$name}" => $rules, - ]) - ->prepend($toplevelRules->normalize(), $propertyName); + $relativeRuleGeneration = $this->dataConfig->usesRelativeRuleGeneration(); + if ($relativeRuleGeneration) { + $payload = $payload[$propertyName] ?? []; } - if ($property->type->isDataCollectable) { - return collect($payload[$propertyName] ?? []) - ->flatMap(function ($item, $key) use ($nullable, $property, $propertyName) { + $prefix = match (true) { + $property->type->isDataObject || $relativeRuleGeneration => "{$propertyName}.", + $property->type->isDataCollectable => "{$propertyName}.*.", + }; + + if ($relativeRuleGeneration && $property->type->isDataCollectable) { + return collect($payload) + ->flatMap(function ($item, $key) use ($prefix, $nullable, $property) { return $this->dataValidationRulesResolver ->execute( $property->type->dataClass, @@ -97,7 +89,7 @@ protected function getNestedRules( $this->isNestedDataNullable($nullable, $property) ) ->mapWithKeys(fn (array $rules, string $name) => [ - "{$propertyName}.{$key}.{$name}" => $rules, + "{$prefix}{$key}.{$name}" => $rules, ]); }) ->prepend($toplevelRules->normalize(), $propertyName); @@ -106,11 +98,11 @@ protected function getNestedRules( return $this->dataValidationRulesResolver ->execute( $property->type->dataClass, - $payload[$propertyName] ?? [], + $payload, $this->isNestedDataNullable($nullable, $property) ) ->mapWithKeys(fn (array $rules, string $name) => [ - "{$propertyName}.{$name}" => $rules, + "{$prefix}{$name}" => $rules, ]) ->prepend($toplevelRules->normalize(), $propertyName); }