ChainableFormatRetriever   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 63
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getFormat() 0 13 4
A __construct() 0 3 1
A getContentType() 0 7 2
A findOne() 0 9 3
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