RouteAssembler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 64
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C assembleUrl() 0 29 7
A getCurrentRouteResult() 0 4 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Acelaya\Website\Service;
5
6
use Psr\Http\Message\ServerRequestInterface;
7
use Zend\Expressive\Router\RouteResult;
8
use Zend\Expressive\Router\RouterInterface;
9
10
class RouteAssembler implements RouteAssemblerInterface
11
{
12
    /**
13
     * @var RouterInterface
14
     */
15
    protected $router;
16
    /**
17
     * @var ServerRequestInterface
18
     */
19
    protected $request;
20
21
    public function __construct(RouterInterface $router, ServerRequestInterface $request)
22
    {
23
        $this->router = $router;
24
        $this->request = $request;
25
    }
26
27 5
    /**
28
     * Assembles a route with given name using given information
29 5
     *
30 5
     * @param string|null $name
31 5
     * @param array|bool $routeParams
32
     * @param array|bool $queryParams
33
     * @param bool $inherit Tells if route and query params should be inherited from current route
34
     * @return string
35
     */
36
    public function assembleUrl(
37
        string $name = null,
38
        $routeParams = [],
39
        $queryParams = [],
40
        bool $inherit = false
41
    ): string {
42 5
        $routeResult = $this->getCurrentRouteResult();
43
        if ($name === null) {
44
            $name = $routeResult->isSuccess() ? $routeResult->getMatchedRouteName() : 'home';
45
        }
46
47
        if (is_bool($routeParams)) {
48 5
            $inherit = $routeParams;
49 5
            $routeParams = [];
50
        }
51 5
52 1
        if (is_bool($queryParams)) {
53 1
            $inherit = $queryParams;
54
            $queryParams = [];
55
        }
56 5
57 1
        if ($inherit) {
58 1
            $routeParams = array_merge($routeResult->getMatchedParams(), $routeParams);
59
            $queryParams = array_merge($this->request->getQueryParams(), $queryParams);
60
        }
61 5
62 2
        $queryString = empty($queryParams) ? '' : sprintf('?%s', http_build_query($queryParams));
63 2
        return $this->router->generateUri($name, $routeParams) . $queryString;
64
    }
65
66 5
    /**
67 5
     * @return RouteResult
68
     */
69
    public function getCurrentRouteResult(): RouteResult
70
    {
71
        return $this->router->match($this->request);
72
    }
73
}
74