-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathViewToModelTransformerVisitor.php
More file actions
67 lines (57 loc) · 2 KB
/
ViewToModelTransformerVisitor.php
File metadata and controls
67 lines (57 loc) · 2 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
<?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 transforms view value to model value. When the field is not valid then the model value is null.
*
* It corresponds to `ConcreteVisitor` in the Strategy pattern.
*
* @author Vlad Riabchenko <contact@vria.eu>
*/
class ViewToModelTransformerVisitor implements VisitorInterface
{
/**
* @param EmailField $emailField
*/
public function visitEmail(EmailField $emailField)
{
$value = null;
if (!$emailField->getError()) {
// Set the email model value only when there is no validation error.
$value = $emailField->getViewValue();
}
$emailField->setValue($value);
}
/**
* @param IntegerField $integerField
*/
public function visitInteger(IntegerField $integerField)
{
$value = null;
if (!$integerField->getError()) {
// Set the integer model value only when there is no validation error.
$value = intval($integerField->getViewValue());
}
$integerField->setValue($value);
}
/**
* @param CheckboxesField $checkboxesField
*/
public function visitCheckboxes(CheckboxesField $checkboxesField)
{
$values = null;
if (!$checkboxesField->getError()) {
// Set the checkboxes model value only when there is no validation error.
$values = [];
$choices = $checkboxesField->getChoices();
// For each view value find a corresponding model value and add it to the array of view values.
foreach ($checkboxesField->getViewValue() as $viewValue) {
$values[] = $choices[$viewValue];
}
}
$checkboxesField->setValue($values);
}
}