Skip to content

Commit

Permalink
Always normalize values to optional strings to simplify validation logic
Browse files Browse the repository at this point in the history
  • Loading branch information
keichinger committed Oct 30, 2023
1 parent 9c48669 commit fa4a4dc
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions src/Field/Definition/ChoiceField.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Torr\Storyblok\Field\Definition;

use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\AtLeastOneOf;
use Symfony\Component\Validator\Constraints\Count;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
Expand Down Expand Up @@ -95,31 +94,30 @@ public function validateData (ComponentContext $context, array $contentPath, mix

private function validateSingleSelect (ComponentContext $context, array $contentPath, mixed $data) : void
{
$data = $context->normalizeOptionalString($data);

if (null === $data)
{
return;
}

\assert(\is_string($data));

$context->ensureDataIsValid(
$contentPath,
$this,
$data,
[
new AtLeastOneOf([
new Type("string"),
new Type("int"),
]),
new Type("string"),
$this->required
? new NotBlank()
: null,
],
);

\assert(\is_int($data) || \is_string($data));

if (\is_string($data))
{
$data = $context->normalizeOptionalString($data);
}

$choicesConstraints = $this->choices->getValidationConstraints(false);

if (null !== $data && !empty($choicesConstraints))
if (!empty($choicesConstraints))
{
$context->ensureDataIsValid(
$contentPath,
Expand All @@ -138,6 +136,13 @@ private function validateMultiSelect (ComponentContext $context, array $contentP
return;
}

\assert(\is_array($data));

$data = \array_map(
$context->normalizeOptionalString(...),
$data,
);

$context->ensureDataIsValid(
$contentPath,
$this,
Expand All @@ -146,16 +151,11 @@ private function validateMultiSelect (ComponentContext $context, array $contentP
new Type("array"),
new All([
new NotNull(),
new AtLeastOneOf([
new Type("string"),
new Type("int"),
]),
new Type("string"),
]),
],
);

\assert(\is_array($data));

if ($this->required || null !== $this->minimumNumberOfOptions || null !== $this->maximumNumberOfOptions)
{
$context->ensureDataIsValid(
Expand Down

0 comments on commit fa4a4dc

Please sign in to comment.