FromArray::setMethod()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Omatech\Mage\Core\Domains\Shared\Traits;
4
5
use Omatech\Mage\Core\Domains\Shared\Exceptions\MethodDoesNotExistsException;
6
7
trait FromArray
8
{
9
    /**
10
     * @param array $array
11
     * @return self
12
     * @throws MethodDoesNotExistsException
13
     */
14 17
    public static function fromArray(array $array)
15
    {
16 17
        $self = new static();
17
18 17
        foreach ($array as $property => $value) {
19 17
            $method = $self->setMethod($property);
20 14
            $self->$method($value);
21
        }
22
23 14
        return $self;
24
    }
25
26
    /**
27
     * @param string $property
28
     * @return string
29
     * @throws MethodDoesNotExistsException
30
     */
31 17
    private function setMethod(string $property): string
32
    {
33 17
        $method = $this->snakeCaseToCamelCase('set'.$property);
34
35 17
        if (! method_exists($this, $method)) {
36 3
            throw new MethodDoesNotExistsException("Method {$method} does not exists.");
37
        }
38
39 14
        return $method;
40
    }
41
42
    /**
43
     * @param string $string
44
     * @return string
45
     */
46 17
    private function snakeCaseToCamelCase(string $string): string
47
    {
48 17
        return str_replace('_', '', lcfirst(ucwords($string, '_')));
49
    }
50
}
51