Passed
Push — master ( 5b5a8e...384cd4 )
by Tomasz
02:33
created

CommandFactory::shouldBeCreated()   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 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace WriteModel;
5
6
class CommandFactory
7
{
8
    /** @var string[] */
9
    private $fields;
10
11
    /** @var callable */
12
    private $factoryMethod;
13
14 5
    public function __construct(string ...$fields)
15
    {
16 5
        $this->fields = $fields;
17 5
    }
18
19 4
    public function createBy(callable $factoryMethod): void
20
    {
21 4
        $this->factoryMethod = $factoryMethod;
22 4
    }
23
24 3
    public function shouldBeCreated(array $data): bool
25
    {
26 3
        if (empty($this->fields)) {
27 1
            return true;
28
        }
29
30
        // command should be created if there is data for at least one command's field
31 2
        $intersection = array_intersect(array_keys($data), $this->fields);
32 2
        return count($intersection) > 0;
33
    }
34
35 5
    public function create(array $data)
36
    {
37 5
        if (!is_callable($this->factoryMethod)) {
38 1
            throw LogicException::factoryMethodIsNotProvided($this->fields);
39
        }
40
41 4
        $values = $this->resolveValues($data);
42 4
        $command = call_user_func($this->factoryMethod, $values);
43
44 4
        if (!is_object($command)) {
45 1
            throw LogicException::commandIsNotAnObject();
46
        }
47
48 3
        return $command;
49
    }
50
51 4
    private function resolveValues(array $data): array
52
    {
53 4
        if (empty($this->fields)) {
54 1
            return $data;
55
        }
56
57
        // use only data indicated in $fields array
58 3
        $data = array_filter($data, function ($key) {
59 2
            return in_array($key, $this->fields);
60 3
        }, ARRAY_FILTER_USE_KEY);
61
62
        // flip $fields to have it's value as keys in $defaults array and reset all values to null
63 3
        $defaults = array_map(function () {
64 3
            return null;
65 3
        }, array_flip($this->fields));
66
67 3
        return array_merge($defaults, $data);
68
    }
69
}
70