RouterReverseLink::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 4
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Provide\Representation;
6
7
use BEAR\Resource\ReverseLinkInterface;
8
use BEAR\Sunday\Extension\Router\RouterInterface;
9
10
use function is_string;
11
use function parse_str;
12
use function parse_url;
13
14
use const PHP_URL_PATH;
15
use const PHP_URL_QUERY;
16
17
final class RouterReverseLink implements ReverseLinkInterface
18
{
19
    /** @var RouterInterface */
20
    private $router;
21
22
    public function __construct(RouterInterface $router)
23
    {
24
        $this->router = $router;
25
    }
26
27
    public function __invoke(string $uri): string
28
    {
29
        $routeName = (string) parse_url($uri, PHP_URL_PATH);
30
        $urlQuery = parse_url($uri, PHP_URL_QUERY);
31
        $urlQuery ? parse_str($urlQuery, $value) : $value = [];
32
        if ($value === []) {
33
            return $uri;
34
        }
35
36
        /** @var array<string, mixed> $value */
37
        $reverseUri = $this->router->generate($routeName, $value);
38
        if (is_string($reverseUri)) {
39
            return $reverseUri;
40
        }
41
42
        return $uri;
43
    }
44
}
45