Skip to content

Commit

Permalink
Add error path to exception details (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
NanoSector authored Jan 26, 2024
1 parent 61db218 commit 8207642
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/OpenApiValidator.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
<?php

declare(strict_types=1);

namespace Gertjuhh\SymfonyOpenapiValidator;

use League\OpenAPIValidation\PSR7\Exception\ValidationFailed;
use League\OpenAPIValidation\PSR7\ValidatorBuilder;
use League\OpenAPIValidation\Schema\Exception\SchemaMismatch;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\AssertionFailedError;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
Expand All @@ -13,6 +15,7 @@
trait OpenApiValidator
{
private static PsrHttpFactory | null $psrHttpFactory = null;

/** @var array<string, ValidatorBuilder> */
private static array $validatorBuilder = [];

Expand Down Expand Up @@ -59,15 +62,23 @@ private static function getValidatorBuilder(string $schema): ValidatorBuilder
private static function wrapValidationException(\Throwable $exception, string $scope): AssertionFailedError
{
$message = [$exception->getMessage()];
$at = null;

while (null !== ($exception = $exception->getPrevious())) {
$message[] = $exception->getMessage();

if (!$at && $exception instanceof SchemaMismatch && $breadcrumb = $exception->dataBreadCrumb()) {
$at = \implode('.', $breadcrumb->buildChain());
}
}

return new AssertionFailedError(
\sprintf(
'OpenAPI %s error:%s%s',
'OpenAPI %s error%s:%s%s',
$scope,
$at !== null
? sprintf(' at %s', $at)
: '',
"\n",
\implode("\n", $message),
),
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/OpenApiValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function testValidatorThrowsErrorWhenResponseIsInvalid(): void
new AssertionFailedError(
\sprintf(
'%s%s%s%s%s',
'OpenAPI response error:',
'OpenAPI response error at hello:',
"\n",
'Body does not match schema for content-type "application/json" for Response [get /hello-world 200]',
"\n",
Expand Down

0 comments on commit 8207642

Please sign in to comment.