ImporterRepository::find()   B
last analyzed

Complexity

Conditions 6
Paths 14

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 11
cp 0
rs 8.9457
c 0
b 0
f 0
cc 6
nc 14
nop 1
crap 42
1
<?php
2
3
namespace Mathielen\ImportEngine\Importer;
4
5
use Mathielen\ImportEngine\Storage\StorageInterface;
6
use Psr\Log\LoggerInterface;
7
8
class ImporterRepository
9
{
10
    /**
11
     * @var Importer[]
12
     */
13
    private $importers = array();
14
15
    /**
16
     * @var ImporterPrecondition[]
17
     */
18
    private $preconditions = array();
19
20
    /**
21
     * @var LoggerInterface
22
     */
23
    private $logger;
24
25 1
    public function __construct(LoggerInterface $logger = null)
26
    {
27 1
        $this->logger = $logger;
28 1
    }
29
30 1
    public function register($id, Importer $importer, ImporterPrecondition $precondition = null)
31
    {
32 1
        $this->importers[$id] = $importer;
33
34 1
        if ($precondition) {
35
            $this->preconditions[$id] = $precondition;
36
        }
37 1
    }
38
39
    public function getIds()
40
    {
41
        return array_keys($this->importers);
42
    }
43
44
    public function hasPrecondition($id)
45
    {
46
        return isset($this->preconditions[$id]);
47
    }
48
49
    /**
50
     * @return Importer
51
     */
52 1
    public function get($id)
53
    {
54 1
        if (!isset($this->importers[$id])) {
55
            throw new \InvalidArgumentException("Unknown importer: $id. Register first.");
56
        }
57
58 1
        return $this->importers[$id];
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    public function find(StorageInterface $storage)
65
    {
66
        if ($this->logger) {
67
            $this->logger->debug('Searching for importer for storage');
68
        }
69
70
        foreach ($this->preconditions as $importerId => $precondition) {
71
            if ($this->logger) {
72
                $this->logger->debug("Checking preconditions for importer: '".$importerId."'");
73
            }
74
75
            if ($precondition->isSatisfiedBy($storage, $this->logger)) {
76
                if ($this->logger) {
77
                    $this->logger->debug("Preconditions matched for importer: '".$importerId."'. Using this import.");
78
                }
79
80
                return $importerId;
81
            }
82
        }
83
84
        return;
85
    }
86
}
87