Passed
Push — master ( 8bd912...d93388 )
by Alan
06:58 queued 02:20
created

src/Util/ErrorFormatGuesser.php (1 issue)

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
    public static function guessErrorFormat(Request $request, array $errorFormats): array
33
    {
34
        $requestFormat = $request->getRequestFormat('');
35
36
        if ('' !== $requestFormat && isset($errorFormats[$requestFormat])) {
37
            return ['key' => $requestFormat, 'value' => $errorFormats[$requestFormat]];
38
        }
39
40
        $requestMimeTypes = Request::getMimeTypes($request->getRequestFormat());
41
        $defaultFormat = [];
42
43
        foreach ($errorFormats as $format => $errorMimeTypes) {
44
            if (array_intersect($requestMimeTypes, $errorMimeTypes)) {
45
                return ['key' => $format, 'value' => $errorMimeTypes];
46
            }
47
48
            if (!$defaultFormat) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $defaultFormat of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
49
                $defaultFormat = ['key' => $format, 'value' => $errorMimeTypes];
50
            }
51
        }
52
53
        return $defaultFormat;
54
    }
55
}
56