Completed
Push — master ( 9f7372...9a51f5 )
by Jesse
01:39
created

DefaultJsonFormatter::from()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 11
rs 10
c 1
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
    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
The condition is_string($result) is always true.
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