44
55namespace Yiisoft \ErrorHandler ;
66
7+ use Psr \EventDispatcher \EventDispatcherInterface ;
78use Psr \Http \Message \ServerRequestInterface ;
89use Psr \Log \LoggerInterface ;
910use Throwable ;
11+ use Yiisoft \ErrorHandler \Event \ApplicationError ;
1012use Yiisoft \ErrorHandler \Exception \ErrorException ;
1113use Yiisoft \ErrorHandler \Renderer \PlainTextRenderer ;
1214use Yiisoft \Http \Status ;
@@ -37,14 +39,20 @@ final class ErrorHandler
3739 private int $ memoryReserveSize = 262_144 ;
3840 private string $ memoryReserve = '' ;
3941 private bool $ debug = false ;
42+ private ?string $ workingDirectory = null ;
4043
4144 private LoggerInterface $ logger ;
4245 private ThrowableRendererInterface $ defaultRenderer ;
46+ private ?EventDispatcherInterface $ eventDispatcher ;
4347
44- public function __construct (LoggerInterface $ logger , ThrowableRendererInterface $ defaultRenderer )
45- {
48+ public function __construct (
49+ LoggerInterface $ logger ,
50+ ThrowableRendererInterface $ defaultRenderer ,
51+ EventDispatcherInterface $ eventDispatcher = null
52+ ) {
4653 $ this ->logger = $ logger ;
4754 $ this ->defaultRenderer = $ defaultRenderer ;
55+ $ this ->eventDispatcher = $ eventDispatcher ;
4856 }
4957
5058 /**
@@ -136,6 +144,10 @@ public function register(): void
136144 $ this ->renderThrowableAndTerminate ($ error );
137145 }
138146 });
147+
148+ if (!(PHP_SAPI === 'cli ' || PHP_SAPI === 'phpdbg ' )) {
149+ $ this ->workingDirectory = getcwd ();
150+ }
139151 }
140152
141153 /**
@@ -154,12 +166,18 @@ public function unregister(): void
154166 */
155167 private function renderThrowableAndTerminate (Throwable $ t ): void
156168 {
169+ if (!empty ($ this ->workingDirectory )) {
170+ chdir ($ this ->workingDirectory );
171+ }
157172 // disable error capturing to avoid recursive errors while handling exceptions
158173 $ this ->unregister ();
159174 // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
160175 http_response_code (Status::INTERNAL_SERVER_ERROR );
161176
162177 echo $ this ->handle ($ t );
178+ if ($ this ->eventDispatcher !== null ) {
179+ $ this ->eventDispatcher ->dispatch (new ApplicationError ($ t ));
180+ }
163181 register_shutdown_function (static function (): void {
164182 exit (1 );
165183 });
0 commit comments