-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathValidatorVisitor.php
More file actions
93 lines (78 loc) · 2.68 KB
/
ValidatorVisitor.php
File metadata and controls
93 lines (78 loc) · 2.68 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace DesignPatterns\Behavioral\Visitor\Visitors;
use DesignPatterns\Behavioral\Visitor\FormFields\CheckboxesField;
use DesignPatterns\Behavioral\Visitor\FormFields\EmailField;
use DesignPatterns\Behavioral\Visitor\FormFields\IntegerField;
use DesignPatterns\Behavioral\Visitor\VisitorInterface;
/**
* Visitor that validates the view value of form fields.
*
* It corresponds to `ConcreteVisitor` in the Strategy pattern.
*
* @author Vlad Riabchenko <contact@vria.eu>
*/
class ValidatorVisitor implements VisitorInterface
{
/**
* Check that view value:
* - is not empty when it is required,
* - is a valid email address (empty value is ok when allowed).
*
* @param EmailField $emailField
*/
public function visitEmail(EmailField $emailField)
{
$viewValue = $emailField->getViewValue();
$empty = strlen($viewValue) === 0;
if ($emailField->isRequired() && $empty) {
$emailField->setError("Field is required.");
return;
}
if (!$empty && filter_var($viewValue, FILTER_VALIDATE_EMAIL) === false) {
$emailField->setError("Email is not valid.");
}
}
/**
* Check that view value:
* - is not empty when it is required,
* - is a valid integer (empty value is ok when allowed).
*
* @param IntegerField $integerField
*/
public function visitInteger(IntegerField $integerField)
{
$viewValue = $integerField->getViewValue();
$empty = strlen($viewValue) === 0;
if ($integerField->isRequired() && $empty) {
$integerField->setError("Field is required.");
return;
}
if (!$empty && filter_var($viewValue, FILTER_VALIDATE_INT) === false) {
$integerField->setError("Integer is not valid.");
}
}
/**
* Check that view value:
* - is not empty when it is required,
* - holds only allowed choices.
*
* @param CheckboxesField $checkboxesField
*/
public function visitCheckboxes(CheckboxesField $checkboxesField)
{
$viewValues = $checkboxesField->getViewValue();
$choices = array_keys($checkboxesField->getChoices());
// Verify that field is not empty
if ($checkboxesField->isRequired() && empty($viewValues)) {
$checkboxesField->setError("At least one choice is required.");
return;
}
// Verify that all checked values are in the list of allowed choices
foreach ($viewValues as $value) {
if (!in_array($value, $choices)) {
$checkboxesField->setError("Choice is not allowed.");
return;
}
}
}
}