FormatterFactory::parseFormatters()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * Copyright (c) 2020.
4
 * @author Paweł Antosiak <[email protected]>
5
 */
6
7
declare(strict_types=1);
8
9
namespace Gorynych\Http\Formatter;
10
11
use Gorynych\Http\Exception\NotAcceptableHttpException;
12
use Symfony\Component\Config\FileLocatorInterface;
13
use Symfony\Component\Yaml\Yaml;
14
15
final class FormatterFactory
16
{
17
    /** @var string[] */
18
    private array $formatters;
19
20 2
    public function __construct(FileLocatorInterface $fileLocator)
21
    {
22 2
        $this->formatters = $this->parseFormatters($fileLocator->locate('formatters.yaml'));
0 ignored issues
show
Bug introduced by
It seems like $fileLocator->locate('formatters.yaml') can also be of type array; however, parameter $file of Gorynych\Http\Formatter\...tory::parseFormatters() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

22
        $this->formatters = $this->parseFormatters(/** @scrutinizer ignore-type */ $fileLocator->locate('formatters.yaml'));
Loading history...
23 2
    }
24
25
    /**
26
     * Creates formatter for first acceptable format
27
     *
28
     * @param string ...$acceptableFormats
29
     * @return FormatterInterface
30
     * @throws NotAcceptableHttpException if proper formatter does not exist
31
     */
32 2
    public function create(string ...$acceptableFormats): FormatterInterface
33
    {
34 2
        foreach ($acceptableFormats as $format) {
35 2
            if (true === array_key_exists($format, $this->formatters)) {
36 1
                return new $this->formatters[$format];
37
            }
38
        }
39
40 1
        throw new NotAcceptableHttpException(
41
            sprintf(
42 1
                'Unable to provide an acceptable representation. Available alternatives: %s.',
43 1
                implode(', ', array_keys($this->formatters))
44
            )
45
        );
46
    }
47
48
    /**
49
     * @return string[]
50
     */
51 2
    private function parseFormatters(string $file): array
52
    {
53 2
        return Yaml::parseFile($file)['formatters'];
54
    }
55
}
56