Passed
Push — master ( fff9a6...600230 )
by Andy
02:12
created

CanonicalUrlGenerator::getParameters()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 1
crap 3
1
<?php
2
3
namespace Palmtree\CanonicalUrlBundle\Service;
4
5
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
6
use Symfony\Component\Routing\RouterInterface;
7
8
class CanonicalUrlGenerator
9
{
10
    /** @var RouterInterface */
11
    protected $router;
12
    /** @var string */
13
    protected $siteUrl;
14
    /** @var bool */
15
    protected $trailingSlash;
16
17
    /**
18
     * CanonicalUrlService constructor.
19
     * @param RouterInterface $router
20
     * @param array           $config
21
     */
22 14
    public function __construct(RouterInterface $router, array $config = [])
23
    {
24 14
        $this->router = $router;
25
26 14
        $this->siteUrl       = $config['site_url'];
27 14
        $this->trailingSlash = $config['trailing_slash'];
28 14
    }
29
30
    /**
31
     * Returns the canonical URL for a route.
32
     *
33
     * @param string       $route      Route to generate a URL for.
34
     * @param string|array $parameters String in 'key1=val1&key2=val2' format or array of query parameters.
35
     *
36
     * @return string
37
     */
38 8
    public function generate($route, $parameters = [])
39
    {
40 8
        if (!$route) {
41 1
            return '';
42
        }
43
44 7
        $parameters = $this->getParameters($parameters);
45
46 7
        $uri = $this->router->generate($route, $parameters, UrlGeneratorInterface::ABSOLUTE_PATH);
47 6
        $url = rtrim($this->siteUrl, '/') . '/' . ltrim($uri, '/');
48
49 6
        return $url;
50
    }
51
52
    /**
53
     * @param string|array $parameters
54
     * @return array
55
     */
56 7
    protected function getParameters($parameters = [])
57
    {
58 7
        if (is_string($parameters)) {
59 1
            parse_str($parameters, $parameters);
60
        }
61
62 7
        if (!$parameters) {
63 6
            $parameters = [];
64
        }
65
66 7
        return $parameters;
67
    }
68
}
69