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
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use ArrayAccess; |
17
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
18
|
|
|
|
19
|
|
|
class KeyNested extends AbstractRelated |
20
|
|
|
{ |
21
|
12 |
|
public function hasReference($input) |
22
|
|
|
{ |
23
|
|
|
try { |
24
|
12 |
|
$this->getReferenceValue($input); |
25
|
6 |
|
} catch (ComponentException $cex) { |
26
|
6 |
|
return false; |
27
|
|
|
} |
28
|
|
|
|
29
|
6 |
|
return true; |
30
|
|
|
} |
31
|
|
|
|
32
|
8 |
|
private function getReferencePieces() |
33
|
|
|
{ |
34
|
8 |
|
return explode('.', rtrim((string) $this->reference, '.')); |
35
|
|
|
} |
36
|
|
|
|
37
|
6 |
|
private function getValueFromArray($array, $key) |
38
|
|
|
{ |
39
|
6 |
|
if (!array_key_exists($key, $array)) { |
40
|
1 |
|
$message = sprintf('Cannot select the key %s from the given array', $this->reference); |
41
|
1 |
|
throw new ComponentException($message); |
42
|
|
|
} |
43
|
|
|
|
44
|
5 |
|
return $array[$key]; |
45
|
|
|
} |
46
|
|
|
|
47
|
2 |
|
private function getValueFromObject($object, $property) |
48
|
|
|
{ |
49
|
2 |
|
if (empty($property) || !property_exists($object, $property)) { |
50
|
1 |
|
$message = sprintf('Cannot select the property %s from the given object', $this->reference); |
51
|
1 |
|
throw new ComponentException($message); |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
return $object->{$property}; |
55
|
|
|
} |
56
|
|
|
|
57
|
8 |
|
private function getValue($value, $key) |
58
|
|
|
{ |
59
|
8 |
|
if (is_array($value) || $value instanceof ArrayAccess) { |
60
|
6 |
|
return $this->getValueFromArray($value, $key); |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
if (is_object($value)) { |
64
|
2 |
|
return $this->getValueFromObject($value, $key); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$message = sprintf('Cannot select the property %s from the given data', $this->reference); |
68
|
|
|
throw new ComponentException($message); |
69
|
|
|
} |
70
|
|
|
|
71
|
12 |
|
public function getReferenceValue($input) |
72
|
|
|
{ |
73
|
12 |
|
if (is_scalar($input)) { |
74
|
4 |
|
$message = sprintf('Cannot select the %s in the given data', $this->reference); |
75
|
4 |
|
throw new ComponentException($message); |
76
|
|
|
} |
77
|
|
|
|
78
|
8 |
|
$keys = $this->getReferencePieces(); |
79
|
8 |
|
$value = $input; |
80
|
8 |
|
while (!is_null($key = array_shift($keys))) { |
81
|
8 |
|
$value = $this->getValue($value, $key); |
82
|
|
|
} |
83
|
|
|
|
84
|
6 |
|
return $value; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|