Skip to content

Commit 75a9b8e

Browse files
committed
Overwrite file and line in ValidationException
Because of how PHP works, when we instantiate an Exception object, the `file` and `line` properties are the file and line where we created the object. That's a desirable behaviour, but there's no value for a user to know that we created an instance of `ValidationException` in the `Validator` class. This commit will overwrite the file and line in the `ValidationException` to where the method `assert()` was called. Note that when running `check()` it will still point to `Validator`, but I decided not to change it, as the method `check()` got deprecated.
1 parent aa293de commit 75a9b8e

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

library/Exceptions/ValidationException.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
use InvalidArgumentException;
1313

14+
use function realpath;
15+
1416
final class ValidationException extends InvalidArgumentException implements Exception
1517
{
1618
/** @param array<string, mixed> $messages */
@@ -19,6 +21,10 @@ public function __construct(
1921
private readonly string $fullMessage,
2022
private readonly array $messages,
2123
) {
24+
if (realpath($this->file) === realpath(__DIR__ . '/../Validator.php')) {
25+
$this->file = $this->getTrace()[0]['file'] ?? $this->file;
26+
$this->line = $this->getTrace()[0]['line'] ?? $this->line;
27+
}
2228
parent::__construct($message);
2329
}
2430

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
/*
4+
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
5+
* SPDX-License-Identifier: MIT
6+
*/
7+
8+
declare(strict_types=1);
9+
10+
use Respect\Validation\Exceptions\ValidationException;
11+
12+
test('Should overwrite stack trace when in Validator', function (): void {
13+
try {
14+
v::intType()->assert('string');
15+
} catch (ValidationException $e) {
16+
expect($e->getFile())->toBe(__FILE__);
17+
expect($e->getLine())->toBe(__LINE__ - 3);
18+
}
19+
});
20+
21+
test('Should not overwrite stack trace when created manually', function (): void {
22+
try {
23+
throw new ValidationException('message', 'fullMessage', ['id' => 'message']);
24+
} catch (ValidationException $e) {
25+
expect($e->getFile())->toBe(__FILE__);
26+
expect($e->getLine())->toBe(__LINE__ - 3);
27+
}
28+
});

0 commit comments

Comments
 (0)