LocalizedRouteDetector::getLocalizedName()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 15
rs 9.2222
c 0
b 0
f 0
ccs 9
cts 9
cp 1
cc 6
nc 6
nop 2
crap 6
1
<?php
2
3
/*
4
 *
5
 * (c) Yaroslav Honcharuk <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Yarhon\RouteGuardBundle\Routing;
12
13
use Symfony\Component\Routing\RouterInterface;
14
use Symfony\Component\Routing\RouteCollection;
15
use Symfony\Component\Routing\RequestContext;
16
17
/**
18
 * @author Yaroslav Honcharuk <[email protected]>
19
 */
20
class LocalizedRouteDetector
21
{
22
    /**
23
     * @var RouteCollection
24
     */
25
    private $routeCollection;
26
27
    /**
28
     * @var RequestContext
29
     */
30
    private $context;
31
32
    /**
33
     * @param RouterInterface $router
34
     */
35 21
    public function __construct(RouterInterface $router)
36
    {
37 21
        $this->routeCollection = $router->getRouteCollection();
38 21
        $this->context = $router->getContext();
39 21
    }
40
41
    /**
42
     * @see \Symfony\Component\Routing\Generator\UrlGenerator::generate
43
     * Note: UrlGenerator uses $defaultLocale parameter when determining locale for url generation, but
44
     * a) it's never passed to UrlGenerator constructor - see \Symfony\Component\Routing\Router::getGenerator
45
     * b) we have no way to retrieve it
46
     *
47
     * @param string $name
48
     * @param array  $parameters
49
     *
50
     * @return string|null
51
     */
52 21
    public function getLocalizedName($name, array $parameters = [])
53
    {
54 21
        $defaultLocale = null;
55 21
        $contextLocale = $this->context->getParameter('_locale');
56
57 21
        $locale = isset($parameters['_locale']) ? $parameters['_locale'] : $contextLocale ?: $defaultLocale;
58
59 21
        if (null !== $locale) {
60 21
            $localizedName = $name.'.'.$locale;
61 21
            if (null !== ($route = $this->routeCollection->get($localizedName)) && $route->getDefault('_canonical_route') === $name) {
62 2
                return $localizedName;
63
            }
64
        }
65
66 19
        return null;
67
    }
68
}
69