Allow user to override default options when extending the Choice Constraint

Co-authored-by: Maxime Steinhausser <maxime.steinhausser@gmail.com>
This commit is contained in:
Benjamin Lévêque 2020-11-05 15:26:06 +01:00 committed by Maxime Steinhausser
parent dc0d45d31a
commit d553750054
3 changed files with 60 additions and 1 deletions

View File

@ -69,7 +69,7 @@ class Choice extends Constraint
if (\is_array($choices) && \is_string(key($choices))) {
$options = array_merge($choices, $options);
} elseif (null !== $choices) {
$options['choices'] = $choices;
$options['value'] = $choices;
}
parent::__construct($options, $groups, $payload);

View File

@ -0,0 +1,25 @@
<?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 PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintChoiceWithPreset;
class ChoiceTest extends TestCase
{
public function testSetDefaultPropertyChoice()
{
$constraint = new ConstraintChoiceWithPreset('A');
self::assertEquals(['A', 'B', 'C'], $constraint->choices);
}
}

View File

@ -0,0 +1,34 @@
<?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\Fixtures;
use Symfony\Component\Validator\Constraints\Choice;
class ConstraintChoiceWithPreset extends Choice
{
public $type;
public function __construct(string $type) {
parent::__construct($type);
if ($this->type === 'A') {
$this->choices = ['A', 'B', 'C'];
} else {
$this->choices = ['D', 'E', 'F'];
}
}
public function getDefaultOption(): ?string
{
return 'type';
}
}