Completed
Push — master ( b63f4d...9f7372 )
by Jesse
01:49
created

DefaultJsonFormatter::prepare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
    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)) {
0 ignored issues
show
introduced by
The condition is_string($result) is always true.
Loading history...
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
45
    {
46
        array_walk_recursive($body, function (&$data) {
47
            if ($data instanceof RestResource) {
48
                $data = $this->prepare($data);
49
            }
50
        });
51
        return $body;
52
    }
53
}
54