|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Ivory Serializer package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Eric GELOEN <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please read the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Ivory\Serializer\Mutator; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @author GeLo <[email protected]> |
|
16
|
|
|
*/ |
|
17
|
|
|
class ReflectionMutator implements MutatorInterface |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* {@inheritdoc} |
|
21
|
|
|
*/ |
|
22
|
|
|
public function setValue($object, $property, $value) |
|
23
|
|
|
{ |
|
24
|
|
|
try { |
|
25
|
|
|
return $this->setPropertyValue($object, $property, $value); |
|
26
|
|
|
} catch (\ReflectionException $e) { |
|
27
|
|
|
$this->setMethodValue($object, $property, $value); |
|
28
|
|
|
} |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param object $object |
|
33
|
|
|
* @param string $property |
|
34
|
|
|
* @param mixed $value |
|
35
|
|
|
*/ |
|
36
|
|
|
private function setPropertyValue($object, $property, $value) |
|
37
|
|
|
{ |
|
38
|
|
|
$reflection = new \ReflectionProperty($object, $property); |
|
39
|
|
|
$reflection->setAccessible(true); |
|
40
|
|
|
$reflection->setValue($object, $value); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param object $object |
|
45
|
|
|
* @param string $property |
|
46
|
|
|
* @param mixed $value |
|
47
|
|
|
*/ |
|
48
|
|
View Code Duplication |
private function setMethodValue($object, $property, $value) |
|
|
|
|
|
|
49
|
|
|
{ |
|
50
|
|
|
$methods = []; |
|
51
|
|
|
$suffix = ucfirst($property); |
|
52
|
|
|
|
|
53
|
|
|
foreach (['get', 'has', 'is'] as $prefix) { |
|
54
|
|
|
try { |
|
55
|
|
|
$reflection = new \ReflectionMethod($object, $methods[] = $prefix.$suffix); |
|
56
|
|
|
$reflection->setAccessible(true); |
|
57
|
|
|
$reflection->invoke($object, $value); |
|
58
|
|
|
|
|
59
|
|
|
return; |
|
60
|
|
|
} catch (\ReflectionException $e) { |
|
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
throw new \InvalidArgumentException(sprintf( |
|
65
|
|
|
'The property "%s" or methods %s don\'t exist.', |
|
66
|
|
|
$property, |
|
67
|
|
|
'"'.implode('", "', $methods).'"' |
|
68
|
|
|
)); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
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.