DefineObject   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 40
ccs 15
cts 15
cp 1
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 12 4
A assignValueWithSetterMethod() 0 14 3
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