Stratadox /
RestResource
| 1 | <?php declare(strict_types=1); |
||
| 2 | |||
| 3 | namespace Stratadox\RestResource; |
||
| 4 | |||
| 5 | use Throwable; |
||
| 6 | use function array_walk_recursive; |
||
| 7 | use function is_string; |
||
| 8 | use function json_encode; |
||
| 9 | use function json_last_error_msg; |
||
| 10 | |||
| 11 | final class DefaultJsonFormatter implements ResourceFormatter |
||
| 12 | { |
||
| 13 | use LinkRetrieval; |
||
| 14 | |||
| 15 | /** @var string */ |
||
| 16 | private $baseUri; |
||
| 17 | |||
| 18 | private function __construct(string $baseUri) |
||
| 19 | { |
||
| 20 | $this->baseUri = $baseUri; |
||
| 21 | } |
||
| 22 | |||
| 23 | public static function fromBaseUri(string $baseUri): ResourceFormatter |
||
| 24 | { |
||
| 25 | return new self($baseUri); |
||
| 26 | } |
||
| 27 | |||
| 28 | public function from(RestResource $resource): string |
||
| 29 | { |
||
| 30 | try { |
||
| 31 | $result = json_encode($this->prepare($resource)); |
||
| 32 | } catch (Throwable $exception) { |
||
| 33 | throw CannotFormatJson::because($resource, $exception); |
||
| 34 | } |
||
| 35 | if (!is_string($result)) { |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 36 | throw CannotFormatJson::jsonError($resource, json_last_error_msg()); |
||
| 37 | } |
||
| 38 | return $result; |
||
| 39 | } |
||
| 40 | |||
| 41 | private function prepare(RestResource $resource): array |
||
| 42 | { |
||
| 43 | return [$resource->name() => |
||
| 44 | $this->flatten($resource->body()) + |
||
| 45 | $this->linksOf($resource, $this->baseUri) |
||
| 46 | ]; |
||
| 47 | } |
||
| 48 | |||
| 49 | private function flatten(array $body): array |
||
| 50 | { |
||
| 51 | array_walk_recursive($body, function (&$data) { |
||
| 52 | if ($data instanceof RestResource) { |
||
| 53 | $data = $this->prepare($data); |
||
| 54 | } |
||
| 55 | }); |
||
| 56 | return $body; |
||
| 57 | } |
||
| 58 | } |
||
| 59 |