CreatedResourceRenderer::updateHeaders()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 10
rs 10
ccs 2
cts 2
cp 1
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Provide\Representation;
6
7
use BEAR\Package\Exception\LocationHeaderRequestException;
8
use BEAR\Resource\RenderInterface;
9
use BEAR\Resource\ResourceInterface;
10
use BEAR\Resource\ResourceObject;
11
use BEAR\Sunday\Extension\Router\RouterInterface;
12
use Throwable;
13
14
use function is_string;
15
use function parse_str;
16
use function parse_url;
17
use function sprintf;
18
19
use const PHP_URL_HOST;
20
use const PHP_URL_PATH;
21
use const PHP_URL_QUERY;
22
use const PHP_URL_SCHEME;
23
24
/**
25
 * 201 CreatedResource renderer
26
 */
27
class CreatedResourceRenderer implements RenderInterface
28 7
{
29
    public function __construct(
30 7
        private RouterInterface $router,
31 7
        private ResourceInterface $resource,
32 7
    ) {
33
    }
34
35
    /**
36
     * {@inheritDoc}
37 4
     */
38
    public function render(ResourceObject $ro)
39 4
    {
40 4
        $urlSchema = (string) parse_url((string) $ro->uri, PHP_URL_SCHEME);
41
        $urlHost = (string) parse_url((string) $ro->uri, PHP_URL_HOST);
42 4
        $locationUri = sprintf('%s://%s%s', $urlSchema, $urlHost, $ro->headers['Location']);
43
        try {
44 1
            $locatedResource = $this->resource->uri($locationUri)();
45 1
        } catch (Throwable $e) {
46 1
            $ro->code = 500;
47
            $ro->view = '';
48 1
49
            throw new LocationHeaderRequestException($locationUri, 0, $e);
50 3
        }
51 3
52
        $this->updateHeaders($ro);
53 3
        $ro->view = $locatedResource->toString();
54
55
        return $ro->view;
56 3
    }
57
58 3
    private function getReverseMatchedLink(string $uri): string
59 3
    {
60 3
        $routeName = (string) parse_url($uri, PHP_URL_PATH);
61 3
        $urlQuery = (string) parse_url($uri, PHP_URL_QUERY);
62 1
        $urlQuery ? parse_str($urlQuery, $value) : $value = [];
63
        if ($value === []) {
64 2
            return $uri;
65 2
        }
66 1
67
        /** @var array<string, mixed> $value */
68
        $reverseUri = $this->router->generate($routeName, $value);
69 1
        if (is_string($reverseUri)) {
70
            return $reverseUri;
71
        }
72 3
73
        return $uri;
74 3
    }
75 3
76 3
    private function updateHeaders(ResourceObject $ro): void
77
    {
78 3
        $ro->headers['content-type'] = 'application/hal+json';
79
        if (! isset($ro->headers['Location'])) {
80
            // @codeCoverageIgnoreStart
81
            return;
82
            // @codeCoverageIgnoreEnd
83
        }
84
85
        $ro->headers['Location'] = $this->getReverseMatchedLink($ro->headers['Location']);
86
    }
87
}
88