1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
namespace Innmind\Reflection\ExtractionStrategy; |
4
|
|
|
use Innmind\Reflection\Exception\LogicException; |
5
|
|
|
class ReflectionStrategy implements ExtractionStrategyInterface |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* {@inheritdoc} |
9
|
|
|
*/ |
10
|
18 |
|
public function supports($object, string $property): bool |
11
|
|
|
{ |
12
|
|
|
try { |
13
|
18 |
|
$this->property($object, $property); |
14
|
|
|
|
15
|
14 |
|
return true; |
16
|
6 |
|
} catch (\Exception $e) { |
17
|
6 |
|
return false; |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* {@inheritdoc} |
23
|
|
|
*/ |
24
|
12 |
View Code Duplication |
public function extract($object, string $property) |
|
|
|
|
25
|
|
|
{ |
26
|
12 |
|
if (!$this->supports($object, $property)) { |
27
|
2 |
|
throw new LogicException; |
28
|
|
|
} |
29
|
|
|
|
30
|
10 |
|
$refl = $this->property($object, $property); |
31
|
|
|
|
32
|
10 |
|
if (!$refl->isPublic()) { |
33
|
6 |
|
$refl->setAccessible(true); |
34
|
|
|
} |
35
|
|
|
|
36
|
10 |
|
$value = $refl->getValue($object); |
37
|
|
|
|
38
|
10 |
|
if (!$refl->isPublic()) { |
39
|
6 |
|
$refl->setAccessible(false); |
40
|
|
|
} |
41
|
|
|
|
42
|
10 |
|
return $value; |
43
|
|
|
} |
44
|
|
|
|
45
|
18 |
|
private function property($object, string $property): \ReflectionProperty |
46
|
|
|
{ |
47
|
|
|
try { |
48
|
18 |
|
return $this->objectProperty($object, $property); |
49
|
6 |
|
} catch (\Exception $e) { |
50
|
6 |
|
return $this->classProperty(get_class($object), $property); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
18 |
|
private function objectProperty($object, string $property): \ReflectionProperty |
55
|
|
|
{ |
56
|
18 |
|
$refl = new \ReflectionObject($object); |
57
|
|
|
|
58
|
18 |
|
if ($refl->hasProperty($property)) { |
59
|
14 |
|
return $refl->getProperty($property); |
60
|
|
|
} |
61
|
|
|
|
62
|
6 |
|
throw new \Exception; |
63
|
|
|
} |
64
|
|
|
|
65
|
6 |
|
private function classProperty(string $class, string $property): \ReflectionProperty |
66
|
|
|
{ |
67
|
6 |
|
$refl = new \ReflectionClass($class); |
68
|
|
|
|
69
|
6 |
|
if ($refl->hasProperty($property)) { |
70
|
|
|
return $refl->getProperty($property); |
71
|
|
|
} |
72
|
|
|
|
73
|
6 |
|
if ($refl->getParentClass()) { |
74
|
|
|
return $this->property($refl->getParentClass()->getName(), $property); |
75
|
|
|
} |
76
|
|
|
|
77
|
6 |
|
throw new \Exception; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.