Issues (8)

Service/CanonicalUrlGenerator.php (1 issue)

Labels
Severity
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
    private $router;
12
    /** @var string */
13
    private $siteUrl;
14
    /** @var bool */
15
    private $trailingSlash;
16
17
    /**
18
     * CanonicalUrlService constructor.
19
     *
20
     * @param RouterInterface $router
21
     * @param array           $config
22
     */
23 10
    public function __construct(RouterInterface $router, array $config = [])
24
    {
25 10
        $this->router = $router;
26
27 10
        $this->siteUrl       = $config['site_url'];
28 10
        $this->trailingSlash = $config['trailing_slash'];
29 10
    }
30
31
    /**
32
     * Returns the canonical URL for a route.
33
     *
34
     * @param string       $route  Route to generate a URL for.
35
     * @param string|array $params String in 'key1=val1&key2=val2' format or array of query parameters.
36
     *
37
     * @return string
38
     */
39 8
    public function generate($route, $params = [])
40
    {
41 8
        if (!$route) {
42 1
            return '';
43
        }
44
45 7
        $params = $this->getParameters($params);
46
47 7
        $uri = $this->router->generate($route, $params, UrlGeneratorInterface::ABSOLUTE_PATH);
48 6
        $url = \rtrim($this->siteUrl, '/') . '/' . \ltrim($uri, '/');
49
50 6
        return $url;
51
    }
52
53
    /**
54
     * @param string|array $parameters
55
     *
56
     * @return array
57
     */
58 7
    private function getParameters($parameters = [])
59
    {
60 7
        if (\is_string($parameters)) {
61 1
            \parse_str($parameters, $parameters);
0 ignored issues
show
$parameters of type string is incompatible with the type array|null expected by parameter $arr of parse_str(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

61
            \parse_str($parameters, /** @scrutinizer ignore-type */ $parameters);
Loading history...
62
        }
63
64 7
        if (!$parameters) {
65 6
            $parameters = [];
66
        }
67
68 7
        return $parameters;
69
    }
70
}
71