/
ObjectWalker.php
102 lines (88 loc) · 2.34 KB
/
ObjectWalker.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
99
100
101
102
<?php
namespace DMS\Filter;
/**
* Walks over the properties of an object applying the filters
* that were defined for them
*
* @package DMS
* @subpackage Filter
*/
class ObjectWalker
{
/**
* @var object
*/
protected $object;
/**
* @var ReflectionClass
*/
protected $reflClass;
/**
* Constructor
*
* @param object $object
*/
public function __construct( $object )
{
$this->object = $object;
$this->reflClass = new \ReflectionClass($object);
}
/**
* Applies the selected rules to a property in the object
*
* @param string $property
* @param array $filterRules
*/
public function applyFilterRules($property, $filterRules = array())
{
foreach($filterRules as $rule ) {
$this->applyFilterRule($property, $rule);
}
}
/**
* Applies a Filtering Rule to a property
*
* @param string $property
* @param Rules\Rule $filterRule
*/
public function applyFilterRule($property, Rules\Rule $filterRule)
{
$value = $this->getPropertyValue($property);
$filteredValue = $filterRule->applyFilter($value);
$this->setPropertyValue($property, $filteredValue);
}
/**
* Retrieves the value of the property, overcoming visibility problems
*
* @param string $property
* @return mixed
*/
private function getPropertyValue($propertyName)
{
return $this->getAccessibleReflectionProperty($propertyName)
->getValue($this->object);
}
/**
* Overrides the value of a property, overcoming visibility problems
*
* @param string $property
* @param mixed $value
*/
private function setPropertyValue($propertyName, $value)
{
$this->getAccessibleReflectionProperty($propertyName)
->setValue($this->object, $value);
}
/**
* Retrieves a property from the object and makes it visible
*
* @param string $propertyName
* @return ReflectionProperty
*/
private function getAccessibleReflectionProperty($propertyName)
{
$property = $this->reflClass->getProperty($propertyName);
$property->setAccessible(true);
return $property;
}
}