-
Notifications
You must be signed in to change notification settings - Fork 1
/
PropertyAccessor.php
54 lines (42 loc) · 1.33 KB
/
PropertyAccessor.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
<?php
declare(strict_types=1);
namespace Chubbyphp\Validation\Accessor;
use Chubbyphp\Validation\ValidatorLogicException;
use Doctrine\Persistence\Proxy;
final class PropertyAccessor implements AccessorInterface
{
private string $property;
public function __construct(string $property)
{
$this->property = $property;
}
/**
* @return mixed
*/
public function getValue(object $object)
{
$class = $this->getClass($object);
if (!property_exists($class, $this->property)) {
throw ValidatorLogicException::createMissingProperty($class, $this->property);
}
$getter = \Closure::bind(
fn ($property) => $this->{$property},
$object,
$class
);
return $getter($this->property);
}
private function getClass(object $object): string
{
if (interface_exists('Doctrine\Persistence\Proxy') && $object instanceof Proxy) {
if (!$object->__isInitialized()) {
$object->__load();
}
$reflectionParentClass = (new \ReflectionObject($object))->getParentClass();
if ($reflectionParentClass instanceof \ReflectionClass) {
return $reflectionParentClass->getName();
}
}
return \get_class($object);
}
}