Completed
Push — master ( 41ae82...437c90 )
by Dave
13s queued 11s
created

OutputFormatterRegistry::getIdentifiers()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * Static Analysis Results Baseliner (sarb).
5
 *
6
 * (c) Dave Liddament
7
 *
8
 * For the full copyright and licence information please view the LICENSE file distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace DaveLiddament\StaticAnalysisResultsBaseliner\Framework\Container;
14
15
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\OutputFormatter\InvalidOutputFormatterException;
16
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\OutputFormatter\OutputFormatter;
17
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\OutputFormatter\OutputFormatterLookupService;
18
use Webmozart\Assert\Assert;
19
20
class OutputFormatterRegistry implements OutputFormatterLookupService
21
{
22
    /**
23
     * @var OutputFormatter[]
24
     * @psalm-var array<string, OutputFormatter>
25
     */
26
    private $outputFormatters;
27
28
    /**
29
     * OutputFormatterRegistry constructor.
30
     *
31
     * @param OutputFormatter[] $outputFormatters
32
     */
33
    public function __construct(array $outputFormatters)
34
    {
35
        $this->outputFormatters = [];
36
        foreach ($outputFormatters as $outputFormatter) {
37
            $this->addOutputFormatter($outputFormatter);
38
        }
39
    }
40
41
    /**
42
     * Returns a list of all OutputFormatter identifiers.
43
     *
44
     * These are used to identify which OutputFormatter to use.
45
     *
46
     * @return string[]
47
     */
48
    public function getIdentifiers(): array
49
    {
50
        return array_keys($this->outputFormatters);
51
    }
52
53
    public function getOutputFormatter(string $identifier): OutputFormatter
54
    {
55
        if (!array_key_exists($identifier, $this->outputFormatters)) {
56
            throw new InvalidOutputFormatterException($identifier);
57
        }
58
59
        return $this->outputFormatters[$identifier];
60
    }
61
62
    private function addOutputFormatter(OutputFormatter $outputFormatter): void
63
    {
64
        $identifier = $outputFormatter->getIdentifier();
65
        Assert::keyNotExists($this->outputFormatters, $identifier,
66
            "Multiple OutputFormatters configured with the identifer [$identifier]"
67
        );
68
69
        $this->outputFormatters[$identifier] = $outputFormatter;
70
    }
71
}
72