HttpException.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Exception;
  11. /**
  12. * HttpException.
  13. *
  14. * @author Kris Wallsmith <kris@symfony.com>
  15. */
  16. class HttpException extends \RuntimeException implements HttpExceptionInterface
  17. {
  18. public function __construct(
  19. private int $statusCode,
  20. string $message = '',
  21. ?\Throwable $previous = null,
  22. private array $headers = [],
  23. int $code = 0,
  24. ) {
  25. parent::__construct($message, $code, $previous);
  26. }
  27. public static function fromStatusCode(int $statusCode, string $message = '', ?\Throwable $previous = null, array $headers = [], int $code = 0): self
  28. {
  29. return match ($statusCode) {
  30. 400 => new BadRequestHttpException($message, $previous, $code, $headers),
  31. 403 => new AccessDeniedHttpException($message, $previous, $code, $headers),
  32. 404 => new NotFoundHttpException($message, $previous, $code, $headers),
  33. 406 => new NotAcceptableHttpException($message, $previous, $code, $headers),
  34. 409 => new ConflictHttpException($message, $previous, $code, $headers),
  35. 410 => new GoneHttpException($message, $previous, $code, $headers),
  36. 411 => new LengthRequiredHttpException($message, $previous, $code, $headers),
  37. 412 => new PreconditionFailedHttpException($message, $previous, $code, $headers),
  38. 423 => new LockedHttpException($message, $previous, $code, $headers),
  39. 415 => new UnsupportedMediaTypeHttpException($message, $previous, $code, $headers),
  40. 422 => new UnprocessableEntityHttpException($message, $previous, $code, $headers),
  41. 428 => new PreconditionRequiredHttpException($message, $previous, $code, $headers),
  42. 429 => new TooManyRequestsHttpException(null, $message, $previous, $code, $headers),
  43. 503 => new ServiceUnavailableHttpException(null, $message, $previous, $code, $headers),
  44. default => new static($statusCode, $message, $previous, $headers, $code),
  45. };
  46. }
  47. public function getStatusCode(): int
  48. {
  49. return $this->statusCode;
  50. }
  51. public function getHeaders(): array
  52. {
  53. return $this->headers;
  54. }
  55. public function setHeaders(array $headers): void
  56. {
  57. $this->headers = $headers;
  58. }
  59. }