Total Complexity | 7 |
Total Lines | 41 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php declare(strict_types=1); |
||
11 | final class DefaultJsonFormatter implements ResourceFormatter |
||
12 | { |
||
13 | use LinkRetrieval; |
||
14 | |||
15 | /** @var string */ |
||
16 | private $baseUri; |
||
17 | |||
18 | public function __construct(string $baseUri) |
||
19 | { |
||
20 | $this->baseUri = $baseUri; |
||
21 | } |
||
22 | |||
23 | public function from(RestResource $resource): string |
||
24 | { |
||
25 | try { |
||
26 | $result = json_encode($this->prepare($resource)); |
||
27 | } catch (Throwable $exception) { |
||
28 | throw CannotFormatJson::because($resource, $exception); |
||
29 | } |
||
30 | if (!is_string($result)) { |
||
|
|||
31 | throw CannotFormatJson::jsonError($resource, json_last_error_msg()); |
||
32 | } |
||
33 | return $result; |
||
34 | } |
||
35 | |||
36 | private function prepare(RestResource $resource): array |
||
37 | { |
||
38 | return [$resource->name() => |
||
39 | $this->flatten($resource->body()) + |
||
40 | $this->linksOf($resource, $this->baseUri) |
||
41 | ]; |
||
42 | } |
||
43 | |||
44 | private function flatten(array $body): array |
||
52 | } |
||
53 | } |
||
54 |