SplitItemOperation   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 55
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A processData() 0 18 4
A __construct() 0 4 1
A createItem() 0 16 4
1
<?php
2
3
namespace Oliverde8\Component\PhpEtl\ChainOperation\Transformer;
4
5
use oliverde8\AssociativeArraySimplified\AssociativeArray;
6
use Oliverde8\Component\PhpEtl\ChainOperation\AbstractChainOperation;
7
use Oliverde8\Component\PhpEtl\ChainOperation\DataChainOperationInterface;
8
use Oliverde8\Component\PhpEtl\Exception\ChainOperationException;
9
use Oliverde8\Component\PhpEtl\Item\ChainBreakItem;
10
use Oliverde8\Component\PhpEtl\Item\DataItem;
11
use Oliverde8\Component\PhpEtl\Item\DataItemInterface;
12
use Oliverde8\Component\PhpEtl\Item\ItemInterface;
13
use Oliverde8\Component\PhpEtl\Item\MixItem;
14
use Oliverde8\Component\PhpEtl\Model\ExecutionContext;
15
16
class SplitItemOperation extends AbstractChainOperation implements DataChainOperationInterface
17
{
18
    protected bool $singleElement;
19
20
    protected array $keys;
21
22
    /**
23
     * @param bool $singleElement
24
     * @param array $keys
25
     */
26
    public function __construct(bool $singleElement, array $keys)
27
    {
28
        $this->singleElement = $singleElement;
29
        $this->keys = $keys;
30
    }
31
32
    /**
33
     * @throws ChainOperationException
34
     */
35
    public function processData(DataItemInterface $item, ExecutionContext $context): ItemInterface
36
    {
37
        if ($this->singleElement) {
38
            $data = AssociativeArray::getFromKey($item->getData(), $this->keys[0], new ChainBreakItem());
39
40
            if ($data instanceof ItemInterface) {
41
                return $data;
42
            }
43
44
            return $this->createItem($data);
45
        }
46
47
        $newItemData = [];
48
        foreach ($this->keys as $key) {
49
            $newItemData[] = AssociativeArray::getFromKey($item->getData(), $key, []);
50
        }
51
52
        return $this->createItem($newItemData);
53
    }
54
55
    protected function createItem($data): ItemInterface
56
    {
57
        if (!is_array($data)) {
58
            throw new ChainOperationException(sprintf('Split operation expects an array to split; "%s', gettype($data)));
59
        }
60
61
        $items = [];
62
        foreach ($data as $datum) {
63
            if ($datum instanceof ItemInterface) {
64
                $items[] = $datum;
65
            } else {
66
                $items[] = new DataItem($datum);
67
            }
68
        }
69
70
        return new MixItem($items);
71
    }
72
}