From cffaf3c28575ca5928542192933061de6503a94d Mon Sep 17 00:00:00 2001 From: Elwyn Van der Borght Date: Mon, 14 Sep 2026 18:41:45 +0200 Subject: [PATCH] feat: allow a custom status code on ValidationApiProblem Validation failures are not always a 400; 422 is just as common. The status code is now an optional constructor argument, defaulting to 400. No range check on the value, since HttpApiProblem itself accepts any status code and guarding only this subclass would be inconsistent. --- README.md | 6 ++++++ spec/Http/ValidationApiProblemSpec.php | 6 ++++++ src/Http/ValidationApiProblem.php | 4 ++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3c9388b..8b5f1ff 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,12 @@ new ValidationApiProblem(new ConstraintViolationList([ } ```` +The status code defaults to 400 and can be overridden: + +```php +new ValidationApiProblem($violationList, 422); +``` + #### BadRequestProblem ```php diff --git a/spec/Http/ValidationApiProblemSpec.php b/spec/Http/ValidationApiProblemSpec.php index d0f52c2..bfc1417 100644 --- a/spec/Http/ValidationApiProblemSpec.php +++ b/spec/Http/ValidationApiProblemSpec.php @@ -30,6 +30,12 @@ public function it_is_an_http_api_problem(): void $this->shouldHaveType(HttpApiProblem::class); } + public function it_can_be_constructed_with_a_custom_status_code(): void + { + $this->beConstructedWith(new ConstraintViolationList([]), 422); + $this->toArray()->shouldHaveKeyWithValue('status', 422); + } + public function it_can_parse_to_array(): void { $this->toArray()->shouldBe([ diff --git a/src/Http/ValidationApiProblem.php b/src/Http/ValidationApiProblem.php index 0b24b42..3c2b4c5 100644 --- a/src/Http/ValidationApiProblem.php +++ b/src/Http/ValidationApiProblem.php @@ -10,10 +10,10 @@ class ValidationApiProblem extends HttpApiProblem { public const TYPE_SYMFONY_VIOLATIONS = 'https://symfony.com/errors/validation'; - public function __construct(ConstraintViolationListInterface $violationList) + public function __construct(ConstraintViolationListInterface $violationList, int $statusCode = 400) { parent::__construct( - 400, + $statusCode, [ 'type' => self::TYPE_SYMFONY_VIOLATIONS, 'title' => 'Validation Failed',