1
|
|
|
<?php |
2
|
|
|
namespace Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping; |
3
|
|
|
|
4
|
|
|
use Boekkooi\Bundle\JqueryValidationBundle\Exception\LogicException; |
5
|
|
|
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\ConstraintRule; |
6
|
|
|
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\ConstraintMapperInterface; |
7
|
|
|
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleCollection; |
8
|
|
|
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleMessage; |
9
|
|
|
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; |
10
|
|
|
use Symfony\Component\Form\FormInterface; |
11
|
|
|
use Symfony\Component\Validator\Constraint; |
12
|
|
|
use Symfony\Component\Validator\Constraints\IsFalse; |
13
|
|
|
use Symfony\Component\Validator\Constraints\IsTrue; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* A Rule mapper for IsTrue and IsFalse. |
17
|
|
|
* |
18
|
|
|
* @author Warnar Boekkooi <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class IsBooleanRule implements ConstraintMapperInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var bool |
24
|
|
|
*/ |
25
|
|
|
private $useAdditional; |
26
|
|
|
|
27
|
|
|
public function __construct($useAdditional) |
28
|
|
|
{ |
29
|
|
|
$this->useAdditional = $useAdditional; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* {@inheritdoc} |
34
|
|
|
*/ |
35
|
|
|
public function resolve(Constraint $constraint, FormInterface $form, RuleCollection $collection) |
36
|
|
|
{ |
37
|
|
|
if (!$this->supports($constraint, $form)) { |
38
|
|
|
throw new LogicException(); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$boolType = $constraint instanceof IsTrue; |
42
|
|
|
|
43
|
|
|
// If the isTrue is applied and it is a checkbox then just make it required |
44
|
|
|
if ($boolType && $form->getConfig()->getType()->getInnerType() instanceof CheckboxType) { |
45
|
|
|
$collection->set( |
46
|
|
|
RequiredRule::RULE_NAME, |
47
|
|
|
new ConstraintRule( |
48
|
|
|
RequiredRule::RULE_NAME, |
49
|
|
|
true, |
50
|
|
|
new RuleMessage($constraint->message), |
51
|
|
|
$constraint->groups |
52
|
|
|
) |
53
|
|
|
); |
54
|
|
|
|
55
|
|
|
return; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// A additional method is used to skip if not found |
59
|
|
|
if (!$this->useAdditional) { |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** @var IsTrue|IsFalse $constraint */ |
64
|
|
|
$collection->set( |
65
|
|
|
'equals', |
66
|
|
|
new ConstraintRule( |
67
|
|
|
'equals', |
68
|
|
|
$boolType ? '1' : '0', |
69
|
|
|
new RuleMessage($constraint->message), |
70
|
|
|
$constraint->groups |
71
|
|
|
) |
72
|
|
|
); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function supports(Constraint $constraint, FormInterface $form) |
76
|
|
|
{ |
77
|
|
|
return in_array( |
78
|
|
|
get_class($constraint), |
79
|
|
|
array( |
80
|
|
|
IsTrue::class, |
81
|
|
|
IsFalse::class, |
82
|
|
|
), |
83
|
|
|
true |
84
|
|
|
); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|