Passed
Push — master ( cc4f3c...e533d6 )
by Kévin
05:08 queued 01:54
created

FormatMatcher::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Api;
15
16
/**
17
 * Matches a mime type to a format.
18
 *
19
 * @internal
20
 */
21
final class FormatMatcher
22
{
23
    private $formats;
24
25
    public function __construct(array $formats)
26
    {
27
        $normalizedFormats = [];
28
        foreach ($formats as $format => $mimeTypes) {
29
            $normalizedFormats[$format] = (array) $mimeTypes;
30
        }
31
        $this->formats = $normalizedFormats;
32
    }
33
34
    /**
35
     * Gets the format associated with the mime type.
36
     *
37
     * Adapted from {@see \Symfony\Component\HttpFoundation\Request::getFormat}.
38
     */
39
    public function getFormat(string $mimeType): ?string
40
    {
41
        $canonicalMimeType = null;
42
        $pos = strpos($mimeType, ';');
43
        if (false !== $pos) {
44
            $canonicalMimeType = trim(substr($mimeType, 0, $pos));
45
        }
46
47
        foreach ($this->formats as $format => $mimeTypes) {
48
            if (\in_array($mimeType, $mimeTypes, true)) {
49
                return $format;
50
            }
51
            if (null !== $canonicalMimeType && \in_array($canonicalMimeType, $mimeTypes, true)) {
52
                return $format;
53
            }
54
        }
55
56
        return null;
57
    }
58
}
59