Skip to content

[Validator] Add the HexColor constraint and validator #35626

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

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* added option `alpha3` to `Country` constraint
* allow to define a reusable set of constraints by extending the `Compound` constraint
* added `Sequentially` constraint, to sequentially validate a set of constraints (any violation raised will prevent further validation of the nested constraints)
* added the `HexColor` constraint and validator

5.0.0
-----
Expand Down
38 changes: 38 additions & 0 deletions src/Symfony/Component/Validator/Constraints/HexColor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*/
final class HexColor extends Constraint
{
public const INVALID_FORMAT_ERROR = 'e8c5955b-9ee3-451e-9c12-4d18240805db';

/**
* @see https://www.w3.org/TR/html52/sec-forms.html#color-state-typecolor
*/
public $html5 = true;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: add $errorNames

public $message = 'This value is not a valid hexadecimal color.';

/**
* {@inheritdoc}
*/
public function getDefaultOption()
{
return 'html5';
}
}
50 changes: 50 additions & 0 deletions src/Symfony/Component/Validator/Constraints/HexColorValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

final class HexColorValidator extends ConstraintValidator
{
private const PATTERN_HTML5 = '/^#[0-9a-f]{6}$/i';
private const PATTERN = '/^#[0-9a-f]{3}(?:[0-9a-f](?:[0-9a-f]{2}(?:[0-9a-f]{2})?)?)?$/i';

/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof HexColor) {
throw new UnexpectedTypeException($constraint, HexColor::class);
}

if (null === $value || '' === $value) {
return;
}

if (!\is_string($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedValueException($value, 'string');
}

$value = (string) $value;

if (!preg_match($constraint->html5 ? self::PATTERN_HTML5 : self::PATTERN, $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(HexColor::INVALID_FORMAT_ERROR)
->addViolation();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,10 @@
<source>This value is not a valid hostname.</source>
<target>This value is not a valid hostname.</target>
</trans-unit>
<trans-unit id="96">
<source>This value is not a valid hexadecimal color.</source>
<target>This value is not a valid hexadecimal color.</target>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,10 @@
<source>This value is not a valid hostname.</source>
<target>Cette valeur n'est pas un nom d'hôte valide.</target>
</trans-unit>
<trans-unit id="96">
<source>This value is not a valid hexadecimal color.</source>
<target>Cette valeur n'est pas une couleur hexadécimale valide.</target>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\HexColor;
use Symfony\Component\Validator\Constraints\HexColorValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

final class HexColorValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return new HexColorValidator();
}

public function testUnexpectedType()
{
$this->expectException(UnexpectedTypeException::class);
$this->expectExceptionMessage('Expected argument of type "Symfony\Component\Validator\Constraints\HexColor", "Symfony\Component\Validator\Constraints\Email" given');

$this->validator->validate(null, new Email());
}

public function testUnexpectedValue()
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Expected argument of type "string", "stdClass" given');

$this->validator->validate(new \stdClass(), new HexColor());
}

public function testNullIsValid()
{
$this->validator->validate(null, new HexColor());

$this->assertNoViolation();
}

public function testEmptyStringIsValid()
{
$this->validator->validate('', new HexColor());

$this->assertNoViolation();
}

/**
* @dataProvider getValidHexColors
*/
public function testValidHexColors($hexColor, bool $html5 = true)
{
$this->validator->validate($hexColor, new HexColor($html5));

$this->assertNoViolation();
}

public function getValidHexColors()
{
// Valid for both patterns
foreach ([
'#000000',
'#abcabc',
'#BbBbBb',
new class() {
public function __toString(): string
{
return '#1Ee54d';
}
},
] as $hexColor) {
yield [$hexColor, true];
yield [$hexColor, false];
}

// Only valid with the generic pattern
foreach ([
'#abc',
'#A000',
'#1e98ccCC',
] as $hexColor) {
yield [$hexColor, false];
}
}

/**
* @dataProvider getHexColorsWithInvalidFormat
*/
public function testHexColorsWithInvalidFormat($hexColor, bool $html5 = true)
{
$this->validator->validate($hexColor, new HexColor([
'html5' => $html5,
'message' => 'foo',
]));

$this->buildViolation('foo')
->setParameter('{{ value }}', '"'.(string) $hexColor.'"')
->setCode(HexColor::INVALID_FORMAT_ERROR)
->assertRaised();
}

public function getHexColorsWithInvalidFormat()
{
// Invalid for both patterns
foreach ([
'#',
'#A',
'#A1',
'000000',
'#abcabg',
' #ffffff',
'#12345',
new class() {
public function __toString(): string
{
return '#010101 ';
}
},
'#1e98ccCC9',
] as $hexColor) {
yield [$hexColor, true];
yield [$hexColor, false];
}

// Only invalid with the html5 pattern
foreach ([
'#abc',
'#A000',
'#1e98ccCC',
] as $hexColor) {
yield [$hexColor, true];
}
}
}