55namespace TypeLang \Mapper \Exception \Mapping ;
66
77use TypeLang \Mapper \Exception \Template ;
8+ use TypeLang \Mapper \Runtime \Context ;
89use TypeLang \Mapper \Runtime \Path \PathInterface ;
910
1011abstract 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