1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Zlikavac32\SymfonyEnum\Validator\Constraints; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use LogicException; |
9
|
|
|
use Symfony\Component\Validator\Constraints\Choice; |
10
|
|
|
use Symfony\Component\Validator\Constraints\ChoiceValidator; |
11
|
|
|
use function Zlikavac32\Enum\assertFqnIsEnumClass; |
12
|
|
|
use Zlikavac32\Enum\Enum; |
13
|
|
|
|
14
|
|
|
abstract class AbstractEnumConstraint extends Choice |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var string|Enum Although this will contain string, Zlikavac32\Enum\Enum is hinted so that static calls to |
18
|
|
|
* this property can also be statically resolved |
19
|
|
|
*/ |
20
|
|
|
public ?string $enumClass = null; |
21
|
|
|
|
22
|
|
|
public function __construct(Closure $callback, $options = null) |
23
|
|
|
{ |
24
|
|
|
if (false === is_array($options)) { |
25
|
|
|
$options = ['enumClass' => $options]; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$this->assertThatOverriddenKeysAreNotSet($options); |
29
|
|
|
|
30
|
|
|
parent::__construct(['strict' => true, 'callback' => $callback] + $options); |
31
|
|
|
|
32
|
|
|
$this->assertEnumClassIsValid($this->enumClass); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function validatedBy() |
36
|
|
|
{ |
37
|
|
|
return ChoiceValidator::class; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
private function assertThatOverriddenKeysAreNotSet(array $options): void |
41
|
|
|
{ |
42
|
|
|
foreach (['choices', 'callback', 'strict'] as $key) { |
43
|
|
|
if (array_key_exists($key, $options)) { |
44
|
|
|
throw new LogicException( |
45
|
|
|
sprintf('Key %s is overridden internally so it should not be set from the outside', $key) |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function assertEnumClassIsValid(?string $enumClass): void |
52
|
|
|
{ |
53
|
|
|
if (null === $enumClass) { |
54
|
|
|
throw new LogicException('Enum class can not be null'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
assertFqnIsEnumClass($enumClass); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritdoc} |
62
|
|
|
*/ |
63
|
|
|
public function getDefaultOption() |
64
|
|
|
{ |
65
|
|
|
return 'enumClass'; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* {@inheritdoc} |
70
|
|
|
*/ |
71
|
|
|
public function getRequiredOptions() |
72
|
|
|
{ |
73
|
|
|
return ['enumClass']; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|