Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions library/Exceptions/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

use InvalidArgumentException;

use function realpath;

final class ValidationException extends InvalidArgumentException implements Exception
{
/** @param array<string, mixed> $messages */
Expand All @@ -19,6 +21,10 @@ public function __construct(
private readonly string $fullMessage,
private readonly array $messages,
) {
if (realpath($this->file) === realpath(__DIR__ . '/../Validator.php')) {
$this->file = $this->getTrace()[0]['file'] ?? $this->file;
$this->line = $this->getTrace()[0]['line'] ?? $this->line;
}
parent::__construct($message);
}

Expand Down
28 changes: 28 additions & 0 deletions tests/feature/ValidationExceptionStackTraceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* Copyright (c) Alexandre Gomes Gaigalas <[email protected]>
* SPDX-License-Identifier: MIT
*/

declare(strict_types=1);

use Respect\Validation\Exceptions\ValidationException;

test('Should overwrite stack trace when in Validator', function (): void {
try {
v::intType()->assert('string');
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});

test('Should not overwrite stack trace when created manually', function (): void {
try {
throw new ValidationException('message', 'fullMessage', ['id' => 'message']);
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});
Loading