1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Respect\Validation\Rules; |
13
|
|
|
|
14
|
|
|
use ArrayAccess; |
15
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
16
|
|
|
|
17
|
|
|
class KeyNested extends AbstractRelated |
18
|
|
|
{ |
19
|
16 |
|
public function hasReference($input) |
20
|
|
|
{ |
21
|
|
|
try { |
22
|
16 |
|
$this->getReferenceValue($input); |
23
|
7 |
|
} catch (ComponentException $cex) { |
24
|
7 |
|
return false; |
25
|
|
|
} |
26
|
|
|
|
27
|
10 |
|
return true; |
28
|
|
|
} |
29
|
|
|
|
30
|
12 |
|
private function getReferencePieces() |
31
|
|
|
{ |
32
|
12 |
|
return explode('.', rtrim($this->reference, '.')); |
33
|
|
|
} |
34
|
|
|
|
35
|
10 |
|
private function getValueFromArray($array, $key) |
36
|
|
|
{ |
37
|
10 |
|
if (!array_key_exists($key, $array)) { |
38
|
2 |
|
$message = sprintf('Cannot select the key %s from the given array', $this->reference); |
39
|
2 |
|
throw new ComponentException($message); |
40
|
|
|
} |
41
|
|
|
|
42
|
9 |
|
return $array[$key]; |
43
|
|
|
} |
44
|
|
|
|
45
|
4 |
|
private function getValueFromObject($object, $property) |
46
|
|
|
{ |
47
|
4 |
|
if (empty($property) || !property_exists($object, $property)) { |
48
|
1 |
|
$message = sprintf('Cannot select the property %s from the given object', $this->reference); |
49
|
1 |
|
throw new ComponentException($message); |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
return $object->{$property}; |
53
|
|
|
} |
54
|
|
|
|
55
|
12 |
|
private function getValue($value, $key) |
56
|
|
|
{ |
57
|
12 |
|
if (is_array($value) || $value instanceof ArrayAccess) { |
58
|
10 |
|
return $this->getValueFromArray($value, $key); |
59
|
|
|
} |
60
|
|
|
|
61
|
4 |
|
if (is_object($value)) { |
62
|
4 |
|
return $this->getValueFromObject($value, $key); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
$message = sprintf('Cannot select the property %s from the given data', $this->reference); |
66
|
1 |
|
throw new ComponentException($message); |
67
|
|
|
} |
68
|
|
|
|
69
|
16 |
|
public function getReferenceValue($input) |
70
|
|
|
{ |
71
|
16 |
|
if (is_scalar($input)) { |
72
|
4 |
|
$message = sprintf('Cannot select the %s in the given data', $this->reference); |
73
|
4 |
|
throw new ComponentException($message); |
74
|
|
|
} |
75
|
|
|
|
76
|
12 |
|
$keys = $this->getReferencePieces(); |
77
|
12 |
|
$value = $input; |
78
|
12 |
|
while (!is_null($key = array_shift($keys))) { |
79
|
12 |
|
$value = $this->getValue($value, $key); |
80
|
|
|
} |
81
|
|
|
|
82
|
10 |
|
return $value; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|