ChainableFormatRetriever::getFormat()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
4
namespace W2w\Lib\Apie\Core\Encodings;
5
6
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
7
use W2w\Lib\Apie\Interfaces\FormatRetrieverInterface;
8
9
/**
10
 * Combines multiple Format Retrievers into one.
11
 */
12
class ChainableFormatRetriever implements FormatRetrieverInterface
13
{
14
    /**
15
     * @var FormatRetrieverInterface[]
16
     */
17
    private $formatRetrievers;
18
19
    /**
20
     * @param FormatRetrieverInterface[]
21
     */
22
    public function __construct(array $formatRetrievers)
23
    {
24
        $this->formatRetrievers = $formatRetrievers;
25
    }
26
27
    /**
28
     * @param string $contentType
29
     * @return string|null
30
     */
31
    public function getFormat(string $contentType): ?string
32
    {
33
        $contentTypes = explode(',', $contentType);
34
        foreach ($contentTypes as $individualContentType) {
35
            if (strpos($individualContentType, ';') !== false) {
36
                $individualContentType = strstr($individualContentType, ';', true);
37
            }
38
            $res = $this->findOne('getFormat', $individualContentType);
39
            if (!is_null($res)) {
40
                return $res;
41
            }
42
        }
43
        throw new NotAcceptableHttpException('"' . $contentType . '" is not accepted');
44
    }
45
46
    /**
47
     * @param string $format
48
     * @return string|null
49
     */
50
    public function getContentType(string $format): ?string
51
    {
52
        $res = $this->findOne('getContentType', $format);
53
        if (!is_null($res)) {
54
            return $res;
55
        }
56
        throw new NotAcceptableHttpException('"' . $format . '" is not accepted');
57
    }
58
59
    /**
60
     * Helper method or getFormat and getContentType.
61
     *
62
     * @param string $method
63
     * @param string $input
64
     * @return string|null
65
     */
66
    private function findOne(string $method, string $input): ?string
67
    {
68
        foreach ($this->formatRetrievers as $formatRetriever) {
69
            $res = $formatRetriever->$method($input);
70
            if (!is_null($res)) {
71
                return $res;
72
            }
73
        }
74
        return null;
75
    }
76
}
77