Skip to content

Commit 316b3f3

Browse files
natepagedunglas
authored andcommitted
Update ErrorFormatGuesser to handle custom formats and improve guess… (#1656)
* Updated ErrorFormatGuesser to handle custom formats and improve guessing from request * Use isset instead of array_key_exists and use Request::getMimeTypes instead of private function. * Fix comments
1 parent f7c3dbc commit 316b3f3

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/Util/ErrorFormatGuesser.php

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,24 @@ private function __construct()
3737
public static function guessErrorFormat(Request $request, array $errorFormats): array
3838
{
3939
$requestFormat = $request->getRequestFormat('');
40+
4041
if ('' !== $requestFormat && isset($errorFormats[$requestFormat])) {
4142
return ['key' => $requestFormat, 'value' => $errorFormats[$requestFormat]];
4243
}
4344

44-
foreach ($errorFormats as $key => $value) {
45-
return ['key' => $key, 'value' => $value];
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+
}
4656
}
4757

48-
return [];
58+
return $defaultFormat;
4959
}
5060
}

tests/Util/ErrorFormatGuesserTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,14 @@ public function testFallbackWhenNotSupported()
4848
$this->assertEquals('xml', $format['key']);
4949
$this->assertEquals('text/xml', $format['value'][0]);
5050
}
51+
52+
public function testGuessCustomErrorFormat()
53+
{
54+
$request = new Request();
55+
$request->setRequestFormat('custom_json_format');
56+
57+
$format = ErrorFormatGuesser::guessErrorFormat($request, ['xml' => ['text/xml'], 'custom_json_format' => ['application/json']]);
58+
$this->assertEquals('custom_json_format', $format['key']);
59+
$this->assertEquals('application/json', $format['value'][0]);
60+
}
5161
}

0 commit comments

Comments
 (0)