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