Test Failed
Push — master ( da5def...342071 )
by Christian
04:54
created

FromArray::setMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

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 4
cts 5
cp 0.8
crap 2.032
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 3
    public static function fromArray(array $array): self
17
    {
18 3
        $self = new static();
19
20 3
        foreach ($array as $property => $value) {
21 3
            $method = $self->setMethod($property);
22
            $self->$method($value);
23
        }
24
25
        return $self;
26
    }
27
28
    /**
29
     * @param string $property
30
     *
31
     * @throws MethodDoesNotExistsException
32
     *
33
     * @return string
34
     */
35 3
    private function setMethod(string $property): string
36
    {
37 3
        $method = $this->snakeCaseToCamelCase('set'.$property);
38
39 3
        if (! method_exists($this, $method)) {
40 3
            throw new MethodDoesNotExistsException("Method {$method} does not exists.");
41
        }
42
43
        return $method;
44
    }
45
46
    /**
47
     * @param string $string
48
     *
49
     * @return string
50
     */
51 3
    private function snakeCaseToCamelCase(string $string): string
52
    {
53 3
        return str_replace('_', '', lcfirst(ucwords($string, '_')));
54
    }
55
}
56