Skip to content

Commit

Permalink
deal with fields for which no constraints have been configured
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh authored and HypeMC committed Feb 7, 2024
1 parent fa7531f commit b341535
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/Symfony/Component/Validator/Constraints/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class Collection extends Composite
*/
public function __construct($fields = null, ?array $groups = null, $payload = null, ?bool $allowExtraFields = null, ?bool $allowMissingFields = null, ?string $extraFieldsMessage = null, ?string $missingFieldsMessage = null)
{
if (\is_array($fields) && ([] === $fields || ($firstField = reset($fields)) instanceof Constraint || ($firstField[0] ?? null) instanceof Constraint)) {
if (self::isFieldsOption($fields)) {
$fields = ['fields' => $fields];
}

Expand Down Expand Up @@ -87,4 +87,31 @@ protected function getCompositeOption()
{
return 'fields';
}

private static function isFieldsOption($options): bool
{
if (!\is_array($options)) {
return false;
}

if ([] === $options) {
return true;
}

foreach ($options as $optionOrField) {
if ($optionOrField instanceof Constraint) {
return true;
}

if (!\is_array($optionOrField)) {
return false;
}

if ([] !== $optionOrField && !($optionOrField[0] ?? null) instanceof Constraint) {
return false;
}
}

return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,41 @@ public function testEmptyFieldsInOptions()
'extraFieldsMessage' => 'foo bar baz',
]);

$this->assertSame([], $constraint->fields);
$this->assertTrue($constraint->allowExtraFields);
$this->assertSame('foo bar baz', $constraint->extraFieldsMessage);
}

public function testEmptyConstraintListFor()
{
$constraint = new Collection([
'foo' => [],
],
null,
null,
true,
null,
'foo bar baz'
);

$this->assertArrayHasKey('foo', $constraint->fields);
$this->assertInstanceOf(Required::class, $constraint->fields['foo']);
$this->assertTrue($constraint->allowExtraFields);
$this->assertSame('foo bar baz', $constraint->extraFieldsMessage);
}

public function testEmptyConstraintListForFieldInOptions()
{
$constraint = new Collection([
'fields' => [
'foo' => [],
],
'allowExtraFields' => true,
'extraFieldsMessage' => 'foo bar baz',
]);

$this->assertArrayHasKey('foo', $constraint->fields);
$this->assertInstanceOf(Required::class, $constraint->fields['foo']);
$this->assertTrue($constraint->allowExtraFields);
$this->assertSame('foo bar baz', $constraint->extraFieldsMessage);
}
Expand Down

0 comments on commit b341535

Please sign in to comment.