validate color (#2072)

This commit is contained in:
Kevin Papst
2020-10-28 20:01:08 +01:00
committed by GitHub
parent 82e1d6b917
commit 1444593bbd
8 changed files with 189 additions and 14 deletions

View 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.';
}

View 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();
}
}
}