|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Form\Choice; |
|
4
|
|
|
|
|
5
|
|
|
use Bdf\Form\ElementBuilderInterface; |
|
6
|
|
|
use Symfony\Component\Validator\Constraints\Choice as ChoiceConstraint; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Trait for configure choices on an element |
|
10
|
|
|
*/ |
|
11
|
|
|
trait ChoiceBuilderTrait |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var ChoiceInterface|null |
|
15
|
|
|
*/ |
|
16
|
|
|
private $choices; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Define choices for the element |
|
20
|
|
|
* |
|
21
|
|
|
* Note: a constraint will be added, so this method should not be called multiple times |
|
22
|
|
|
* |
|
23
|
|
|
* Usage: |
|
24
|
|
|
* <code> |
|
25
|
|
|
* $builder->choices(['foo', 'bar']); // Simple choice, without defined label |
|
26
|
|
|
* // With label as key |
|
27
|
|
|
* $builder->choices([ |
|
28
|
|
|
* 'First choice' => 'foo', |
|
29
|
|
|
* 'Second choice' => 'bar', |
|
30
|
|
|
* ]); |
|
31
|
|
|
* |
|
32
|
|
|
* // Using lazy loading |
|
33
|
|
|
* // Return value must follow array choices syntax |
|
34
|
|
|
* $builder->choices(function () { |
|
35
|
|
|
* return $this->repository->loadChoices(); |
|
36
|
|
|
* }); |
|
37
|
|
|
* |
|
38
|
|
|
* $builder->choices(['foo', 'bar'], 'my error'); // With message |
|
39
|
|
|
* $builder->choices(['foo', 'bar'], ['min' => 2, 'max' => 6]); // With options array |
|
40
|
|
|
* </code> |
|
41
|
|
|
* |
|
42
|
|
|
* @param ChoiceInterface|array|callable $choices The allowed values in PHP form. |
|
43
|
|
|
* @param null|string|array $options If options is a string it will be considered as constraint message |
|
44
|
|
|
* |
|
45
|
|
|
* @return $this |
|
46
|
|
|
* @see ChoiceConstraint |
|
47
|
|
|
*/ |
|
48
|
15 |
|
final public function choices($choices, $options = null): self |
|
49
|
|
|
{ |
|
50
|
15 |
|
if (!$choices instanceof ChoiceInterface) { |
|
51
|
15 |
|
$choices = is_array($choices) ? new ArrayChoice($choices) : new LazyChoice($choices); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
15 |
|
if (is_string($options)) { |
|
55
|
4 |
|
$options = ['message' => $options, 'multipleMessage' => $options]; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
15 |
|
$options['callback'] = [$choices, 'values']; |
|
59
|
|
|
|
|
60
|
15 |
|
$this->choices = $choices; |
|
61
|
|
|
|
|
62
|
15 |
|
return $this->satisfy(new ChoiceConstraint($options)); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Get the built choices |
|
67
|
|
|
* |
|
68
|
|
|
* @return ChoiceInterface|null |
|
69
|
|
|
* @internal |
|
70
|
|
|
*/ |
|
71
|
332 |
|
final protected function getChoices(): ?ChoiceInterface |
|
72
|
|
|
{ |
|
73
|
332 |
|
return $this->choices; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* {@inheritdoc} |
|
78
|
|
|
* |
|
79
|
|
|
* @see ElementBuilderInterface::satisfy() |
|
80
|
|
|
*/ |
|
81
|
|
|
abstract public function satisfy($constraint, $options = null, bool $append = true); |
|
82
|
|
|
} |
|
83
|
|
|
|