Total Complexity | 8 |
Total Lines | 46 |
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 | private function __construct(string $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)) { |
||
|
|||
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 |
||
57 | } |
||
58 | } |
||
59 |