Skip to content

[Validator] use constructor property promotion in Charset and MacAddress constraints #53444

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions src/Symfony/Component/Validator/Constraints/Charset.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,13 @@ final class Charset extends Constraint
self::BAD_ENCODING_ERROR => 'BAD_ENCODING_ERROR',
];

public array|string $encodings = [];
public string $message = 'The detected character encoding is invalid ({{ detected }}). Allowed encodings are {{ encodings }}.';

public function __construct(array|string $encodings = null, string $message = null, array $groups = null, mixed $payload = null, array $options = null)
{
parent::__construct($options, $groups, $payload);

$this->message = $message ?? $this->message;
$this->encodings = (array) ($encodings ?? $this->encodings);
public function __construct(
public array|string $encodings = [],
public string $message = 'The detected character encoding is invalid ({{ detected }}). Allowed encodings are {{ encodings }}.',
array $groups = null,
mixed $payload = null,
) {
parent::__construct(null, $groups, $payload);

if ([] === $this->encodings) {
throw new ConstraintDefinitionException(sprintf('The "%s" constraint requires at least one encoding.', static::class));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function validate(mixed $value, Constraint $constraint): void
throw new UnexpectedValueException($value, 'string');
}

if (!\in_array($detected = mb_detect_encoding($value, $constraint->encodings, true), $constraint->encodings, true)) {
if (!\in_array($detected = mb_detect_encoding($value, $constraint->encodings, true), (array) $constraint->encodings, true)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ detected }}', $detected)
->setParameter('{{ encodings }}', implode(', ', $constraint->encodings))
Expand Down
18 changes: 4 additions & 14 deletions src/Symfony/Component/Validator/Constraints/MacAddress.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
* Validates that a value is a valid MAC address.
Expand All @@ -28,25 +27,16 @@ class MacAddress extends Constraint
self::INVALID_MAC_ERROR => 'INVALID_MAC_ERROR',
];

public string $message = 'This is not a valid MAC address.';

/** @var callable|null */
public $normalizer;
public ?\Closure $normalizer;

public function __construct(
array $options = null,
string $message = null,
public string $message = 'This value is not a valid MAC address.',
callable $normalizer = null,
array $groups = null,
mixed $payload = null,
) {
parent::__construct($options, $groups, $payload);

$this->message = $message ?? $this->message;
$this->normalizer = $normalizer ?? $this->normalizer;
parent::__construct(null, $groups, $payload);

if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', get_debug_type($this->normalizer)));
}
$this->normalizer = null !== $normalizer ? $normalizer(...) : null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function testSingleEncodingCanBeSet()
{
$encoding = new Charset('UTF-8');

$this->assertSame(['UTF-8'], $encoding->encodings);
$this->assertSame('UTF-8', $encoding->encodings);
}

public function testMultipleEncodingCanBeSet()
Expand All @@ -48,7 +48,7 @@ public function testAttributes()
$this->assertTrue($loader->loadClassMetadata($metadata));

[$aConstraint] = $metadata->properties['a']->getConstraints();
$this->assertSame(['UTF-8'], $aConstraint->encodings);
$this->assertSame('UTF-8', $aConstraint->encodings);

[$bConstraint] = $metadata->properties['b']->getConstraints();
$this->assertSame(['ASCII', 'UTF-8'], $bConstraint->encodings);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected function createValidator(): CharsetValidator
/**
* @dataProvider provideValidValues
*/
public function testEncodingIsValid(string|\Stringable $value, array $encodings)
public function testEncodingIsValid(string|\Stringable $value, array|string $encodings)
{
$this->validator->validate($value, new Charset(encodings: $encodings));

Expand Down Expand Up @@ -63,6 +63,7 @@ public static function provideValidValues()
{
yield ['my ascii string', ['ASCII']];
yield ['my ascii string', ['UTF-8']];
yield ['my ascii string', 'UTF-8'];
yield ['my ascii string', ['ASCII', 'UTF-8']];
yield ['my ûtf 8', ['ASCII', 'UTF-8']];
yield ['my ûtf 8', ['UTF-8']];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\MacAddress;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

Expand All @@ -24,23 +23,9 @@ class MacAddressTest extends TestCase
{
public function testNormalizerCanBeSet()
{
$mac = new MacAddress(['normalizer' => 'trim']);
$mac = new MacAddress(normalizer: 'trim');

$this->assertEquals('trim', $mac->normalizer);
}

public function testInvalidNormalizerThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).');
new MacAddress(['normalizer' => 'Unknown Callable']);
}

public function testInvalidNormalizerObjectThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).');
new MacAddress(['normalizer' => new \stdClass()]);
$this->assertEquals(trim(...), $mac->normalizer);
}

public function testAttributes()
Expand All @@ -51,7 +36,7 @@ public function testAttributes()

[$aConstraint] = $metadata->properties['a']->getConstraints();
self::assertSame('myMessage', $aConstraint->message);
self::assertSame('trim', $aConstraint->normalizer);
self::assertEquals(trim(...), $aConstraint->normalizer);
self::assertSame(['Default', 'MacAddressDummy'], $aConstraint->groups);

[$bConstraint] = $metadata->properties['b']->getConstraints();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ public static function getValidMacs(): array
*/
public function testValidMacsWithWhitespaces($mac)
{
$this->validator->validate($mac, new MacAddress([
'normalizer' => 'trim',
]));
$this->validator->validate($mac, new MacAddress(normalizer: 'trim'));

$this->assertNoViolation();
}
Expand All @@ -97,9 +95,7 @@ public static function getValidMacsWithWhitespaces(): array
*/
public function testInvalidMacs($mac)
{
$constraint = new MacAddress([
'message' => 'myMessage',
]);
$constraint = new MacAddress('myMessage');

$this->validator->validate($mac, $constraint);

Expand Down