Passed
Branch master (d8a671)
by Tomasz
02:11
created

CommandFactory::create()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 1
nop 1
crap 3
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 4
    public function __construct(string ...$fields)
15
    {
16 4
        $this->fields = $fields;
17 4
    }
18
19 3
    public function createBy(callable $factoryMethod): void
20
    {
21 3
        $this->factoryMethod = $factoryMethod;
22 3
    }
23
24 2
    public function shouldBeCreated(array $data): bool
25
    {
26
        // command should be created if there is data for at least one command's field
27 2
        $intersection = array_intersect(array_keys($data), $this->fields);
28 2
        return count($intersection) > 0;
29
    }
30
31 4
    public function create(array $data)
32
    {
33 4
        if (!is_callable($this->factoryMethod)) {
34 1
            throw LogicException::factoryMethodIsNotProvided($this->fields);
35
        }
36
37
        // use only data indicated in $fields array
38
        $data = array_filter($data, function ($key) { return in_array($key, $this->fields); }, ARRAY_FILTER_USE_KEY);
39
40
        // flip $fields to have it's value as keys in $defaults array and reset all values to null
41
        $defaults = array_map(function () { return null; }, array_flip($this->fields));
42
        $command = call_user_func($this->factoryMethod, array_merge($defaults, $data));
43
44
        if (!is_object($command)) {
45
            throw LogicException::commandIsNotAnObject();
46
        }
47
48
        return $command;
49
    }
50
}
51