Passed
Push — master ( f7c3db...316b3f )
by Kévin
02:59
created

ErrorFormatGuesser::guessErrorFormat()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 5
nop 2
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
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\Util;
15
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * Guesses the error format to use.
20
 *
21
 * @author Kévin Dunglas <[email protected]>
22
 */
23
final class ErrorFormatGuesser
24
{
25
    private function __construct()
26
    {
27
    }
28
29
    /**
30
     * Get the error format and its associated MIME type.
31
     *
32
     * @param Request $request
33
     * @param array   $errorFormats
34
     *
35
     * @return array
36
     */
37
    public static function guessErrorFormat(Request $request, array $errorFormats): array
38
    {
39
        $requestFormat = $request->getRequestFormat('');
40
41
        if ('' !== $requestFormat && isset($errorFormats[$requestFormat])) {
42
            return ['key' => $requestFormat, 'value' => $errorFormats[$requestFormat]];
43
        }
44
45
        $requestMimeTypes = Request::getMimeTypes($request->getRequestFormat());
46
        $defaultFormat = [];
47
48
        foreach ($errorFormats as $format => $errorMimeTypes) {
49
            if (array_intersect($requestMimeTypes, $errorMimeTypes)) {
50
                return ['key' => $format, 'value' => $errorMimeTypes];
51
            }
52
53
            if (!$defaultFormat) {
54
                $defaultFormat = ['key' => $format, 'value' => $errorMimeTypes];
55
            }
56
        }
57
58
        return $defaultFormat;
59
    }
60
}
61