validate color (#2072)
This commit is contained in:
27
src/Validator/Constraints/HexColor.php
Normal file
27
src/Validator/Constraints/HexColor.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Kimai time-tracking app.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace App\Validator\Constraints;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
|
||||
/**
|
||||
* @Annotation
|
||||
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
|
||||
*/
|
||||
class HexColor extends Constraint
|
||||
{
|
||||
public const HEX_COLOR_ERROR = 'xd5hffg-dsfef3-426a-83d7-2g8jkfr56d84';
|
||||
|
||||
protected static $errorNames = [
|
||||
self::HEX_COLOR_ERROR => 'HEX_COLOR_ERROR',
|
||||
];
|
||||
|
||||
public $message = 'The given value is not a valid hexadecimal color.';
|
||||
}
|
||||
40
src/Validator/Constraints/HexColorValidator.php
Normal file
40
src/Validator/Constraints/HexColorValidator.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Kimai time-tracking app.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace App\Validator\Constraints;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidator;
|
||||
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
|
||||
|
||||
class HexColorValidator extends ConstraintValidator
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validate($value, Constraint $constraint)
|
||||
{
|
||||
if (!$constraint instanceof HexColor) {
|
||||
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\HexColor');
|
||||
}
|
||||
|
||||
$color = $value;
|
||||
|
||||
if ($color === null || (\is_string($color) && empty($color))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!\is_string($color) || 1 !== preg_match('/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/i', $color)) {
|
||||
$this->context->buildViolation($constraint->message)
|
||||
->setParameter('{{ value }}', $this->formatValue($color))
|
||||
->setCode(HexColor::HEX_COLOR_ERROR)
|
||||
->addViolation();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user