OutputFormatterRegistry::getOutputFormatter()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
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
final class OutputFormatterRegistry implements OutputFormatterLookupService
21
{
22
    /**
23
     * @var OutputFormatter[]
24
     *
25
     * @psalm-var array<string, OutputFormatter>
26
     */
27
    private $outputFormatters;
28
29
    /**
30
     * OutputFormatterRegistry constructor.
31
     *
32
     * @param OutputFormatter[] $outputFormatters
33
     */
34
    public function __construct(array $outputFormatters)
35
    {
36
        $this->outputFormatters = [];
37
        foreach ($outputFormatters as $outputFormatter) {
38
            $this->addOutputFormatter($outputFormatter);
39
        }
40
    }
41
42
    /**
43
     * Returns a list of all OutputFormatter identifiers.
44
     *
45
     * These are used to identify which OutputFormatter to use.
46
     *
47
     * @return string[]
48
     */
49
    public function getIdentifiers(): array
50
    {
51
        return array_keys($this->outputFormatters);
52
    }
53
54
    public function getOutputFormatter(string $identifier): OutputFormatter
55
    {
56
        if (!array_key_exists($identifier, $this->outputFormatters)) {
57
            throw new InvalidOutputFormatterException($identifier);
58
        }
59
60
        return $this->outputFormatters[$identifier];
61
    }
62
63
    private function addOutputFormatter(OutputFormatter $outputFormatter): void
64
    {
65
        $identifier = $outputFormatter->getIdentifier();
66
        Assert::keyNotExists($this->outputFormatters, $identifier,
67
            "Multiple OutputFormatters configured with the identifier [$identifier]",
68
        );
69
70
        $this->outputFormatters[$identifier] = $outputFormatter;
71
    }
72
}
73