Skip to content

Commit cb1170b

Browse files
author
Kirill Nesmeyanov
committed
Make value of type exception is final
1 parent 6a9d015 commit cb1170b

File tree

2 files changed

+42
-4
lines changed

2 files changed

+42
-4
lines changed

src/Exception/Mapping/InvalidValueOfTypeException.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
use TypeLang\Mapper\Runtime\Path\PathInterface;
99
use TypeLang\Parser\Node\Stmt\TypeStatement;
1010

11-
class InvalidValueOfTypeException extends ValueOfTypeException
11+
class InvalidValueOfTypeException extends ValueOfTypeException implements
12+
FinalExceptionInterface
1213
{
1314
public static function createFromPath(
1415
TypeStatement $expected,

src/Exception/Mapping/RuntimeException.php

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace TypeLang\Mapper\Exception\Mapping;
66

77
use TypeLang\Mapper\Exception\Template;
8+
use TypeLang\Mapper\Runtime\Context;
89
use TypeLang\Mapper\Runtime\Path\PathInterface;
910

1011
abstract class RuntimeException extends \RuntimeException
@@ -21,19 +22,55 @@ public function __construct(
2122
) {
2223
parent::__construct($template, $code, $previous);
2324

25+
$this->path = clone $path;
26+
$this->message = $this->template = self::createTemplate(
27+
template: $template,
28+
context: $this,
29+
path: $path,
30+
);
31+
}
32+
33+
private static function createTemplate(string $template, \Throwable $context, PathInterface $path): Template
34+
{
2435
$suffix = '';
2536

2637
if (!$path->isEmpty()) {
2738
$suffix = ' at {{path}}';
2839
}
2940

30-
$this->path = clone $path;
31-
$this->message = $this->template = new Template(
41+
return new Template(
3242
template: $template . $suffix,
33-
context: $this,
43+
context: $context,
3444
);
3545
}
3646

47+
/**
48+
* @template T of \Throwable
49+
* @param T $e
50+
* @return T
51+
*/
52+
public static function tryAdopt(\Throwable $e, Context $context): \Throwable
53+
{
54+
try {
55+
$property = new \ReflectionProperty($e, 'message');
56+
$message = $property->getValue($e);
57+
58+
if (!\is_string($message)) {
59+
return $e;
60+
}
61+
62+
$property->setValue($e, (string)self::createTemplate(
63+
template: $message,
64+
context: $e,
65+
path: clone $context->getPath(),
66+
));
67+
} catch (\Throwable) {
68+
return $e;
69+
}
70+
71+
return $e;
72+
}
73+
3774
public function getPath(): PathInterface
3875
{
3976
return $this->path;

0 commit comments

Comments
 (0)