Passed
Push — master ( 342071...ce1cac )
by Christian
04:33
created

FromArray::setMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
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
     *
12
     * @throws MethodDoesNotExistsException
13
     *
14
     * @return static
15
     */
16 16
    public static function fromArray(array $array): self
17
    {
18 16
        $self = new static();
19
20 16
        foreach ($array as $property => $value) {
21 16
            $method = $self->setMethod($property);
22 13
            $self->$method($value);
23
        }
24
25 13
        return $self;
26
    }
27
28
    /**
29
     * @param string $property
30
     *
31
     * @throws MethodDoesNotExistsException
32
     *
33
     * @return string
34
     */
35 16
    private function setMethod(string $property): string
36
    {
37 16
        $method = $this->snakeCaseToCamelCase('set'.$property);
38
39 16
        if (! method_exists($this, $method)) {
40 3
            throw new MethodDoesNotExistsException("Method {$method} does not exists.");
41
        }
42
43 13
        return $method;
44
    }
45
46
    /**
47
     * @param string $string
48
     *
49
     * @return string
50
     */
51 16
    private function snakeCaseToCamelCase(string $string): string
52
    {
53 16
        return str_replace('_', '', lcfirst(ucwords($string, '_')));
54
    }
55
}
56