respect-validation/library/Exceptions/ValidationException.php
Henrique Moody 75a9b8e94f
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.
2024-12-18 19:49:09 +01:00

41 lines
1,022 B
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Exceptions;
use InvalidArgumentException;
use function realpath;
final class ValidationException extends InvalidArgumentException implements Exception
{
/** @param array<string, mixed> $messages */
public function __construct(
string $message,
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);
}
public function getFullMessage(): string
{
return $this->fullMessage;
}
/** @return array<string, mixed> */
public function getMessages(): array
{
return $this->messages;
}
}