|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the sauls/helpers package. |
|
4
|
|
|
* |
|
5
|
|
|
* @author Saulius Vaičeliūnas <[email protected]> |
|
6
|
|
|
* @link http://saulius.vaiceliunas.lt |
|
7
|
|
|
* @copyright 2018 |
|
8
|
|
|
* |
|
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
10
|
|
|
* file that was distributed with this source code. |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace Sauls\Component\Helper\Operation\ObjectOperation; |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
use Sauls\Component\Helper\Exception\PropertyNotAccessibleException; |
|
17
|
|
|
|
|
18
|
|
|
class DefineObject extends AbstractOperation implements DefineObjectInterface |
|
19
|
|
|
{ |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param object $object |
|
23
|
|
|
* @param array $properties |
|
24
|
|
|
* @param array $methodPrefixes |
|
25
|
|
|
* |
|
26
|
|
|
* @return object |
|
27
|
|
|
* @throws PropertyNotAccessibleException |
|
28
|
|
|
*/ |
|
29
|
5 |
|
public function execute(object $object, array $properties, array $methodPrefixes = ['set', 'add']): object |
|
30
|
|
|
{ |
|
31
|
|
|
try { |
|
32
|
5 |
|
foreach ($properties as $property => $value) { |
|
33
|
5 |
|
if (false === $this->assignValueWithSetterMethod($object, [$property, $value], $methodPrefixes)) { |
|
34
|
5 |
|
$object->$property = $value; |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
4 |
|
return $object; |
|
39
|
1 |
|
} catch (\Throwable $t) { |
|
40
|
1 |
|
throw new PropertyNotAccessibleException($t->getMessage()); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
5 |
|
private function assignValueWithSetterMethod(object $object, array $parameters, array $methodPrefixes): bool |
|
45
|
|
|
{ |
|
46
|
5 |
|
[$property, $value] = $parameters; |
|
47
|
5 |
|
foreach ($methodPrefixes as $setterMethodPrefix) { |
|
48
|
|
|
|
|
49
|
5 |
|
$setterMethod = $this->createPropertyMethodName($setterMethodPrefix, $property); |
|
50
|
|
|
|
|
51
|
5 |
|
if (\method_exists($object, $setterMethod)) { |
|
52
|
4 |
|
$object->$setterMethod($value); |
|
53
|
4 |
|
return true; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
5 |
|
return false; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|