forked from boekkooi/JqueryValidationBundle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathValidConstraintPass.php
81 lines (70 loc) · 2.6 KB
/
ValidConstraintPass.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Processor;
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleContextBuilder;
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleProcessorContext;
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleProcessorInterface;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\ConstraintRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Util\FormViewRecursiveIterator;
use Boekkooi\Bundle\JqueryValidationBundle\Validator\ConstraintCollection;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Validator\Constraints\Valid;
/**
* @author Warnar Boekkooi <[email protected]>
*/
class ValidConstraintPass implements FormRuleProcessorInterface
{
public function process(FormRuleProcessorContext $processContext, FormRuleContextBuilder $formRuleContext)
{
$form = $processContext->getForm();
if (!$this->requiresValidConstraint($form) || $this->hasValidConstraint($processContext->getConstraints())) {
return;
}
$view = $processContext->getView();
$it = new \RecursiveIteratorIterator(
new FormViewRecursiveIterator($view->getIterator()),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $childView) {
if (isset($childView->vars['required'])) {
$childView->vars['required'] = false;
}
$this->cleanChildRules($childView, $formRuleContext);
}
}
private function requiresValidConstraint(FormInterface $form)
{
$formConfig = $form->getConfig();
return !$form->isRoot() &&
$formConfig->getCompound() &&
$formConfig->getMapped() &&
$formConfig->getDataClass() !== null
;
}
private function hasValidConstraint(ConstraintCollection $constraints)
{
foreach ($constraints as $constraint) {
if (get_class($constraint) === Valid::class) {
return true;
}
}
return false;
}
private function cleanChildRules(FormView $childView, FormRuleContextBuilder $formRuleContext)
{
$rules = $formRuleContext->get($childView);
if ($rules === null) {
return;
}
// Don't remove transformer rules!
foreach ($rules as $name => $rule) {
if (!$rule instanceof ConstraintRule) {
continue;
}
$rules->remove($name);
}
if (empty($rules)) {
$formRuleContext->remove($childView);
}
}
}