1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Sulu. |
5
|
|
|
* |
6
|
|
|
* (c) MASSIVE ART WebServices GmbH |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the MIT license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sulu\Component\DocumentManager; |
13
|
|
|
|
14
|
|
|
use ProxyManager\Proxy\LazyLoadingInterface; |
15
|
|
|
use Sulu\Component\DocumentManager\Exception\DocumentManagerException; |
16
|
|
|
|
17
|
|
|
class DocumentAccessor |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var object |
21
|
|
|
*/ |
22
|
|
|
private $document; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var \ReflectionClass |
26
|
|
|
*/ |
27
|
|
|
private $reflection; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param $document |
31
|
|
|
*/ |
32
|
|
|
public function __construct($document) |
33
|
|
|
{ |
34
|
|
|
$this->document = $document; |
35
|
|
|
$documentClass = get_class($document); |
36
|
|
|
|
37
|
|
|
if ($document instanceof LazyLoadingInterface) { |
38
|
|
|
$documentClass = ClassNameInflector::getUserClassName($documentClass); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$this->reflection = new \ReflectionClass($documentClass); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $field |
46
|
|
|
* @param mixed $value |
47
|
|
|
* |
48
|
|
|
* @throws DocumentManagerException |
49
|
|
|
*/ |
50
|
|
|
public function set($field, $value) |
51
|
|
|
{ |
52
|
|
|
if (!$this->has($field)) { |
53
|
|
|
throw new DocumentManagerException(sprintf( |
54
|
|
|
'Document "%s" must have property "%s" (it is probably required by a behavior)', |
55
|
|
|
get_class($this->document), $field |
56
|
|
|
)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$property = $this->reflection->getProperty($field); |
60
|
|
|
$property->setAccessible(true); |
61
|
|
|
$property->setValue($this->document, $value); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function get($field) |
65
|
|
|
{ |
66
|
|
|
$property = $this->reflection->getProperty($field); |
67
|
|
|
// TODO: Can be cached? Makes a performance diff? |
68
|
|
|
$property->setAccessible(true); |
69
|
|
|
|
70
|
|
|
return $property->getValue($this->document); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @param $field |
75
|
|
|
* |
76
|
|
|
* @return bool |
77
|
|
|
*/ |
78
|
|
|
public function has($field) |
79
|
|
|
{ |
80
|
|
|
return $this->reflection->hasProperty($field); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|