Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit98f4fa1

Browse files
[HttpKernel] AddHttpException::fromStatusCode()
1 parentc221681 commit98f4fa1

File tree

5 files changed

+66
-11
lines changed

5 files changed

+66
-11
lines changed

‎src/Symfony/Component/HttpKernel/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Add method`isKernelTerminating()` to`ExceptionEvent` that allows to check if an exception was thrown while the kernel is being terminated
8+
* Add`HttpException::fromStatusCode()`
89

910
7.0
1011
---

‎src/Symfony/Component/HttpKernel/Controller/ArgumentResolver/RequestPayloadValueResolver.php‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,14 @@
1313

1414
useSymfony\Component\EventDispatcher\EventSubscriberInterface;
1515
useSymfony\Component\HttpFoundation\Request;
16-
useSymfony\Component\HttpFoundation\Response;
1716
useSymfony\Component\HttpKernel\Attribute\MapQueryString;
1817
useSymfony\Component\HttpKernel\Attribute\MapRequestPayload;
1918
useSymfony\Component\HttpKernel\Controller\ValueResolverInterface;
2019
useSymfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
2120
useSymfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
21+
useSymfony\Component\HttpKernel\Exception\BadRequestHttpException;
2222
useSymfony\Component\HttpKernel\Exception\HttpException;
23+
useSymfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
2324
useSymfony\Component\HttpKernel\KernelEvents;
2425
useSymfony\Component\Serializer\Exception\NotEncodableValueException;
2526
useSymfony\Component\Serializer\Exception\PartialDenormalizationException;
@@ -124,21 +125,21 @@ public function onKernelControllerArguments(ControllerArgumentsEvent $event): vo
124125
}
125126

126127
if (\count($violations)) {
127-
thrownewHttpException($validationFailedCode,implode("\n",array_map(staticfn ($e) =>$e->getMessage(),iterator_to_array($violations))),newValidationFailedException($payload,$violations));
128+
throw HttpException::fromStatusCode($validationFailedCode,implode("\n",array_map(staticfn ($e) =>$e->getMessage(),iterator_to_array($violations))),newValidationFailedException($payload,$violations));
128129
}
129130
}else {
130131
try {
131132
$payload =$this->$payloadMapper($request,$type,$argument);
132133
}catch (PartialDenormalizationException$e) {
133-
thrownewHttpException($validationFailedCode,implode("\n",array_map(staticfn ($e) =>$e->getMessage(),$e->getErrors())),$e);
134+
throw HttpException::fromStatusCode($validationFailedCode,implode("\n",array_map(staticfn ($e) =>$e->getMessage(),$e->getErrors())),$e);
134135
}
135136
}
136137

137138
if (null ===$payload) {
138139
$payload =match (true) {
139140
$argument->metadata->hasDefaultValue() =>$argument->metadata->getDefaultValue(),
140141
$argument->metadata->isNullable() =>null,
141-
default =>thrownewHttpException($validationFailedCode)
142+
default =>throw HttpException::fromStatusCode($validationFailedCode)
142143
};
143144
}
144145

@@ -167,11 +168,11 @@ private function mapQueryString(Request $request, string $type, MapQueryString $
167168
privatefunctionmapRequestPayload(Request$request,string$type,MapRequestPayload$attribute): ?object
168169
{
169170
if (null ===$format =$request->getContentTypeFormat()) {
170-
thrownewHttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE,'Unsupported format.');
171+
thrownewUnsupportedMediaTypeHttpException('Unsupported format.');
171172
}
172173

173174
if ($attribute->acceptFormat && !\in_array($format, (array)$attribute->acceptFormat,true)) {
174-
thrownewHttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE,sprintf('Unsupported format, expects "%s", but "%s" given.',implode('", "', (array)$attribute->acceptFormat),$format));
175+
thrownewUnsupportedMediaTypeHttpException(sprintf('Unsupported format, expects "%s", but "%s" given.',implode('", "', (array)$attribute->acceptFormat),$format));
175176
}
176177

177178
if ($data =$request->request->all()) {
@@ -183,15 +184,15 @@ private function mapRequestPayload(Request $request, string $type, MapRequestPay
183184
}
184185

185186
if ('form' ===$format) {
186-
thrownewHttpException(Response::HTTP_BAD_REQUEST,'Request payload contains invalid "form" data.');
187+
thrownewBadRequestHttpException('Request payload contains invalid "form" data.');
187188
}
188189

189190
try {
190191
return$this->serializer->deserialize($data,$type,$format,self::CONTEXT_DESERIALIZE +$attribute->serializationContext);
191192
}catch (UnsupportedFormatException$e) {
192-
thrownewHttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE,sprintf('Unsupported format: "%s".',$format),$e);
193+
thrownewUnsupportedMediaTypeHttpException(sprintf('Unsupported format: "%s".',$format),$e);
193194
}catch (NotEncodableValueException$e) {
194-
thrownewHttpException(Response::HTTP_BAD_REQUEST,sprintf('Request payload contains invalid "%s" data.',$format),$e);
195+
thrownewBadRequestHttpException(sprintf('Request payload contains invalid "%s" data.',$format),$e);
195196
}
196197
}
197198
}

‎src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public function logKernelException(ExceptionEvent $event): void
6363
}
6464
if (!$throwableinstanceof HttpExceptionInterface ||$throwable->getStatusCode() !==$config['status_code']) {
6565
$headers =$throwableinstanceof HttpExceptionInterface ?$throwable->getHeaders() : [];
66-
$throwable =newHttpException($config['status_code'],$throwable->getMessage(),$throwable,$headers);
66+
$throwable = HttpException::fromStatusCode($config['status_code'],$throwable->getMessage(),$throwable,$headers);
6767
$event->setThrowable($throwable);
6868
}
6969
break;
@@ -78,7 +78,7 @@ public function logKernelException(ExceptionEvent $event): void
7878
/** @var WithHttpStatus $instance */
7979
$instance =$attributes[0]->newInstance();
8080

81-
$throwable =newHttpException($instance->statusCode,$throwable->getMessage(),$throwable,$instance->headers);
81+
$throwable = HttpException::fromStatusCode($instance->statusCode,$throwable->getMessage(),$throwable,$instance->headers);
8282
$event->setThrowable($throwable);
8383
break;
8484
}

‎src/Symfony/Component/HttpKernel/Exception/HttpException.php‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,27 @@ public function __construct(int $statusCode, string $message = '', \Throwable $p
2929
parent::__construct($message,$code,$previous);
3030
}
3131

32+
publicstaticfunctionfromStatusCode(int$statusCode,string$message ='',\Throwable$previous =null,array$headers = [],int$code =0):self
33+
{
34+
returnmatch ($statusCode) {
35+
400 =>newBadRequestHttpException($message,$previous,$code,$headers),
36+
403 =>newAccessDeniedHttpException($message,$previous,$code,$headers),
37+
404 =>newNotFoundHttpException($message,$previous,$code,$headers),
38+
406 =>newNotAcceptableHttpException($message,$previous,$code,$headers),
39+
409 =>newConflictHttpException($message,$previous,$code,$headers),
40+
410 =>newGoneHttpException($message,$previous,$code,$headers),
41+
411 =>newLengthRequiredHttpException($message,$previous,$code,$headers),
42+
412 =>newPreconditionFailedHttpException($message,$previous,$code,$headers),
43+
423 =>newLockedHttpException($message,$previous,$code,$headers),
44+
415 =>newUnsupportedMediaTypeHttpException($message,$previous,$code,$headers),
45+
422 =>newUnprocessableEntityHttpException($message,$previous,$code,$headers),
46+
428 =>newPreconditionRequiredHttpException($message,$previous,$code,$headers),
47+
429 =>newTooManyRequestsHttpException(null,$message,$previous,$code,$headers),
48+
503 =>newServiceUnavailableHttpException(null,$message,$previous,$code,$headers),
49+
default =>newstatic($statusCode,$message,$previous,$headers,$code),
50+
};
51+
}
52+
3253
publicfunctiongetStatusCode():int
3354
{
3455
return$this->statusCode;

‎src/Symfony/Component/HttpKernel/Tests/Exception/HttpExceptionTest.php‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,38 @@ public function testThrowableIsAllowedForPrevious()
6363
$this->assertSame($previous,$exception->getPrevious());
6464
}
6565

66+
/**
67+
* @dataProvider provideStatusCode
68+
*/
69+
publicfunctiontestFromStatusCode(int$statusCode)
70+
{
71+
$exception = HttpException::fromStatusCode($statusCode);
72+
$this->assertInstanceOf(HttpException::class,$exception);
73+
$this->assertSame($statusCode,$exception->getStatusCode());
74+
}
75+
76+
publicstaticfunctionprovideStatusCode()
77+
{
78+
return [
79+
[400],
80+
[401],
81+
[403],
82+
[404],
83+
[406],
84+
[409],
85+
[410],
86+
[411],
87+
[412],
88+
[418],
89+
[423],
90+
[415],
91+
[422],
92+
[428],
93+
[429],
94+
[503],
95+
];
96+
}
97+
6698
protectedfunctioncreateException(string$message ='',\Throwable$previous =null,int$code =0,array$headers = []):HttpException
6799
{
68100
returnnewHttpException(200,$message,$previous,$headers,$code);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp