-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
MappingRule.php
98 lines (86 loc) · 2.67 KB
/
MappingRule.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Extension\Validator\ViolationMapper;
use Symfony\Component\Form\Exception\ErrorMappingException;
use Symfony\Component\Form\FormInterface;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class MappingRule
{
private $origin;
private $propertyPath;
private $targetPath;
/**
* @param FormInterface $origin
* @param string $propertyPath
* @param string $targetPath
*/
public function __construct(FormInterface $origin, $propertyPath, $targetPath)
{
$this->origin = $origin;
$this->propertyPath = $propertyPath;
$this->targetPath = $targetPath;
}
/**
* @return FormInterface
*/
public function getOrigin()
{
return $this->origin;
}
/**
* Matches a property path against the rule path.
*
* If the rule matches, the form mapped by the rule is returned.
* Otherwise this method returns false.
*
* @param string $propertyPath The property path to match against the rule
*
* @return FormInterface|null The mapped form or null
*/
public function match($propertyPath)
{
if ($propertyPath === $this->propertyPath) {
return $this->getTarget();
}
}
/**
* Matches a property path against a prefix of the rule path.
*
* @param string $propertyPath The property path to match against the rule
*
* @return bool Whether the property path is a prefix of the rule or not
*/
public function isPrefix($propertyPath)
{
$length = \strlen($propertyPath);
$prefix = substr($this->propertyPath, 0, $length);
$next = isset($this->propertyPath[$length]) ? $this->propertyPath[$length] : null;
return $prefix === $propertyPath && ('[' === $next || '.' === $next);
}
/**
* @return FormInterface
*
* @throws ErrorMappingException
*/
public function getTarget()
{
$childNames = explode('.', $this->targetPath);
$target = $this->origin;
foreach ($childNames as $childName) {
if (!$target->has($childName)) {
throw new ErrorMappingException(sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName()));
}
$target = $target->get($childName);
}
return $target;
}
}