66use Middlewares \Utils \Factory ;
77use Middlewares \Utils \HttpErrorException ;
88use Psr \Http \Message \ResponseFactoryInterface ;
9+ use Psr \Http \Message \StreamFactoryInterface ;
910use Psr \Http \Message \ResponseInterface ;
1011use Psr \Http \Message \ServerRequestInterface ;
1112use Throwable ;
@@ -15,13 +16,18 @@ abstract class AbstractFormatter implements FormatterInterface
1516 /** @var ResponseFactoryInterface */
1617 protected $ responseFactory ;
1718
19+ /** @var StreamFactoryInterface */
20+ protected $ streamFactory ;
21+
1822 /** @var string[] */
1923 protected $ contentTypes = [];
2024
2125 public function __construct (
22- ResponseFactoryInterface $ responseFactory = null
26+ ResponseFactoryInterface $ responseFactory = null ,
27+ StreamFactoryInterface $ streamFactory = null
2328 ) {
2429 $ this ->responseFactory = $ responseFactory ?? Factory::getResponseFactory ();
30+ $ this ->streamFactory = $ streamFactory ?? Factory::getStreamFactory ();
2531 }
2632
2733 public function isValid (Throwable $ error , ServerRequestInterface $ request ): bool
@@ -34,21 +40,22 @@ abstract protected function format(Throwable $error): string;
3440 public function handle (Throwable $ error , ServerRequestInterface $ request ): ResponseInterface
3541 {
3642 $ response = $ this ->responseFactory ->createResponse ($ this ->errorStatus ($ error ));
37- $ response ->getBody ()->write ($ this ->format ($ error ));
43+ $ body = $ this ->streamFactory ->createStream ($ this ->format ($ error ));
44+ $ response = $ response ->withBody ($ body );
3845
3946 $ contentType = $ this ->getContentType ($ request );
4047
4148 return $ response ->withHeader ('Content-Type ' , $ contentType ? $ contentType : $ this ->contentTypes [0 ]);
4249 }
4350
44- protected function errorStatus (Throwable $ e ): int
51+ protected function errorStatus (Throwable $ error ): int
4552 {
46- if ($ e instanceof HttpErrorException) {
47- return $ e ->getCode ();
53+ if ($ error instanceof HttpErrorException) {
54+ return $ error ->getCode ();
4855 }
4956
50- if (method_exists ($ e , 'getStatusCode ' )) {
51- return $ e ->getStatusCode ();
57+ if (method_exists ($ error , 'getStatusCode ' )) {
58+ return $ error ->getStatusCode ();
5259 }
5360
5461 return 500 ;
0 commit comments