Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 15 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
| JsonRenderer | |
0.00% |
0 / 15 |
|
0.00% |
0 / 4 |
56 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| handle | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
20 | |||
| response | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
2 | |||
| replace | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray; |
| 6 | |
| 7 | use Celema\Core\Factory\Factory; |
| 8 | use Celema\Core\Response; |
| 9 | use Celema\Router\After; |
| 10 | use Override; |
| 11 | use Psr\Http\Message\ResponseInterface as PsrResponse; |
| 12 | use Traversable; |
| 13 | |
| 14 | class JsonRenderer implements AfterRenderer |
| 15 | { |
| 16 | public function __construct( |
| 17 | protected Factory $factory, |
| 18 | ) {} |
| 19 | |
| 20 | #[Override] |
| 21 | public function handle(mixed $data): PsrResponse |
| 22 | { |
| 23 | if ($data instanceof PsrResponse) { |
| 24 | return $data; |
| 25 | } |
| 26 | |
| 27 | if ($data instanceof Response) { |
| 28 | return $data->unwrap(); |
| 29 | } |
| 30 | |
| 31 | $flags = JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR; |
| 32 | |
| 33 | if ($data instanceof Traversable) { |
| 34 | return $this->response(json_encode(iterator_to_array($data), $flags)); |
| 35 | } |
| 36 | |
| 37 | return $this->response(json_encode($data, $flags)); |
| 38 | } |
| 39 | |
| 40 | public function response(string $json): PsrResponse |
| 41 | { |
| 42 | $response = $this->factory |
| 43 | ->response() |
| 44 | ->withHeader('Content-Type', 'application/json'); |
| 45 | $response->getBody()->write($json); |
| 46 | |
| 47 | return $response; |
| 48 | } |
| 49 | |
| 50 | #[Override] |
| 51 | public function replace(After $handler): bool |
| 52 | { |
| 53 | return is_a($handler, Renderer::class); |
| 54 | } |
| 55 | } |