|
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 ReflectionProperty; |
|
15
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
|
16
|
|
|
use Respect\Validation\Rule; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Validates an object attribute. |
|
20
|
|
|
* |
|
21
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
|
22
|
|
|
* @author Henrique Moody <[email protected]> |
|
23
|
|
|
* |
|
24
|
|
|
* @since 0.3.9 |
|
25
|
|
|
*/ |
|
26
|
|
|
final class Attribute extends AbstractRelated |
|
27
|
|
|
{ |
|
28
|
|
|
/** |
|
29
|
|
|
* Initializes the rule. |
|
30
|
|
|
* |
|
31
|
|
|
* @param string $attributeName |
|
32
|
|
|
* @param Rule $rule |
|
33
|
|
|
* @param bool $mandatory |
|
34
|
|
|
*/ |
|
35
|
1 |
|
public function __construct(string $attributeName, Rule $rule = null, bool $mandatory = true) |
|
36
|
|
|
{ |
|
37
|
1 |
|
if ('' === $attributeName) { |
|
38
|
1 |
|
throw new ComponentException('Attribute name cannot be empty'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
parent::__construct($attributeName, $rule, $mandatory); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Get the value of attribute in the object object even when the attribute is private. |
|
46
|
|
|
* |
|
47
|
|
|
* @param object $object |
|
48
|
|
|
* @param string $attributeName |
|
49
|
|
|
* |
|
50
|
|
|
* @return mixed |
|
51
|
|
|
*/ |
|
52
|
28 |
|
public function getReferenceValue($object, $attributeName) |
|
53
|
|
|
{ |
|
54
|
28 |
|
$attributeMirror = new ReflectionProperty($object, $attributeName); |
|
55
|
28 |
|
$attributeMirror->setAccessible(true); |
|
56
|
|
|
|
|
57
|
28 |
|
return $attributeMirror->getValue($object); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Verifies if the input is an object and if it has the attribute. |
|
62
|
|
|
* |
|
63
|
|
|
* @param object $object |
|
64
|
|
|
* @param string $attributeName |
|
65
|
|
|
* |
|
66
|
|
|
* @return bool |
|
67
|
|
|
*/ |
|
68
|
64 |
|
public function hasReference($object, $attributeName): bool |
|
69
|
|
|
{ |
|
70
|
64 |
|
return is_object($object) && property_exists($object, $attributeName); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|