Passed
Pull Request — master (#3)
by De Cramer
02:07
created

ChainBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 0
cts 2
cp 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Oliverde8\Component\PhpEtl;
6
7
use Oliverde8\Component\PhpEtl\Builder\Factories\AbstractFactory;
8
use Oliverde8\Component\PhpEtl\ChainOperation\ChainOperationInterface;
9
use Oliverde8\Component\PhpEtl\Exception\UnknownOperationException;
10
11
/**
12
 * Class ChainBuilder
13
 *
14
 * @author    de Cramer Oliver<[email protected]>
15
 * @copyright 2018 Oliverde8
16
 * @package Oliverde8\Component\PhpEtl
17
 */
18
class ChainBuilder
19
{
20
    /** @var AbstractFactory[] */
21
    protected array $operationFactories;
22
23
    protected ExecutionContextFactoryInterface $contextFactory;
24
25
    /**
26
     * @param ExecutionContextFactoryInterface $contextFactory
27
     */
28
    public function __construct(ExecutionContextFactoryInterface $contextFactory)
29
    {
30
        $this->contextFactory = $contextFactory;
31
    }
32
33
34
    /**
35
     * Register an operation factory.
36
     *
37
     * @param AbstractFactory $factory
38
     */
39
    public function registerFactory(AbstractFactory $factory)
40
    {
41
        $this->operationFactories[] = $factory;
42
    }
43
44
    /**
45
     * Get chain processor from configs.
46
     *
47
     * @throws Exception\ChainBuilderValidationException
48
     * @throws UnknownOperationException
49
     */
50
    public function buildChainProcessor(array $configs): ChainProcessorInterface
51
    {
52
        $chainOperations = [];
53
        foreach ($configs as $id => $operation) {
54
            $chainOperations[$id] = $this->getOperationFromConfig($operation);
55
        }
56
57
        return new ChainProcessor($chainOperations, $this->contextFactory);
58
    }
59
60
    /**
61
     * Get chain operation instance from config.
62
     *
63
     * @throws Exception\ChainBuilderValidationException
64
     * @throws UnknownOperationException
65
     */
66
    protected function getOperationFromConfig(array $config): ChainOperationInterface
67
    {
68
        foreach ($this->operationFactories as $factory) {
69
            if (is_null($config['options'])) {
70
                $config['options'] = [];
71
            }
72
73
            if ($factory->supports($config['operation'], $config['options'])) {
74
                return $factory->getOperation($config['operation'], $config['options']);
75
            }
76
        }
77
78
       throw new UnknownOperationException("No compatible factories were found for operation '{$config['operation']}'");
79
    }
80
}
81