allow to pre-define colors to choose from (#2481)

This commit is contained in:
Kevin Papst
2021-04-06 00:45:54 +02:00
committed by GitHub
parent f4dbdbb427
commit 68bb01d064
28 changed files with 574 additions and 21 deletions

View File

@@ -0,0 +1,26 @@
<?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;
class ColorChoices extends Constraint
{
public const COLOR_CHOICES_ERROR = 'ui5hffg-dsfef3-1234-5678-2g8jkfr56d84';
public const COLOR_CHOICES_NAME_ERROR = 'ui5hffg-dsfef3-1234-5679-2g8jkfr56d84';
protected static $errorNames = [
self::COLOR_CHOICES_ERROR => 'COLOR_CHOICES_ERROR',
self::COLOR_CHOICES_NAME_ERROR => 'COLOR_CHOICES_NAME_ERROR',
];
public $message = 'The given value {{ value }} is not a valid hexadecimal color.';
public $invalidNameMessage = 'The given value {{ name }} is not a valid color name for {{ color }}. Allowed are {{ max }} characters, given {{ count }}.';
}

View File

@@ -0,0 +1,71 @@
<?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 ColorChoicesValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ColorChoices) {
throw new UnexpectedTypeException($constraint, ColorChoices::class);
}
$color = $value;
if ($color === null || (\is_string($color) && empty(trim($color)))) {
return;
}
$colors = explode(',', $color);
foreach ($colors as $color) {
$color = explode('|', $color);
$name = $color[0];
$code = $color[0];
if (\count($color) > 1) {
$code = $color[1];
}
if (empty($name)) {
$name = $code;
}
if (!\is_string($code) || 1 !== preg_match('/^#[0-9a-fA-F]{6}$/i', $code)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($code))
->setCode(ColorChoices::COLOR_CHOICES_ERROR)
->addViolation();
return;
}
if ($name === $code) {
return;
}
if (!\is_string($name) || 1 !== preg_match('/^[0-9a-zA-Z]{1,10}$/i', $name)) {
$this->context->buildViolation($constraint->invalidNameMessage)
->setParameter('{{ name }}', $this->formatValue($name))
->setParameter('{{ color }}', $this->formatValue($code))
->setParameter('{{ max }}', $this->formatValue(10))
->setParameter('{{ count }}', $this->formatValue(\strlen($name)))
->setCode(ColorChoices::COLOR_CHOICES_NAME_ERROR)
->addViolation();
}
}
}
}