Completed
Pull Request — 2.3 (#1140)
by
unknown
20:56 queued 16:36
created

RoutingExtension::getPath()   C

Complexity

Conditions 11
Paths 42

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 42
nop 3
dl 0
loc 52
rs 6.9006
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Victoire\Bundle\CoreBundle\Twig\Extension;
4
5
use Doctrine\ORM\EntityRepository;
6
use Psr\Log\LoggerInterface;
7
use Symfony\Bridge\Twig\Extension\RoutingExtension as BaseRoutingExtension;
8
use Symfony\Component\HttpFoundation\RequestStack;
9
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
10
use Victoire\Bundle\I18nBundle\Resolver\LocaleResolver;
11
use Victoire\Bundle\PageBundle\Helper\PageHelper;
12
use Victoire\Bundle\ViewReferenceBundle\Exception\ViewReferenceNotFoundException;
13
14
/**
15
 * class RoutingExtension.
16
 */
17
class RoutingExtension extends BaseRoutingExtension
18
{
19
    private $pageHelper;
20
    private $generator;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
21
    private $localeResolver;
22
    private $logger;
23
    private $errorPageRepository;
24
    private $locale;
25
26
    /**
27
     * @param PageHelper            $pageHelper
28
     * @param UrlGeneratorInterface $generator
29
     * @param LocaleResolver        $localeResolver
30
     * @param RequestStack          $requestStack
31
     * @param LoggerInterface       $logger
32
     * @param EntityRepository      $errorPageRepository
33
     * @param                       $locale
34
     */
35
    public function __construct(
36
        PageHelper $pageHelper,
37
        UrlGeneratorInterface $generator,
38
        LocaleResolver $localeResolver,
39
        RequestStack $requestStack,
40
        LoggerInterface $logger,
41
        EntityRepository $errorPageRepository,
42
        $locale
43
    ) {
44
        $this->pageHelper = $pageHelper;
45
        $this->generator = $generator;
46
        $this->localeResolver = $localeResolver;
47
        $this->request = $requestStack->getCurrentRequest();
0 ignored issues
show
Bug introduced by
The property request does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
48
        $this->logger = $logger;
49
        $this->errorPageRepository = $errorPageRepository;
50
        parent::__construct($generator);
51
        $this->locale = $locale;
52
    }
53
54
    public function getPath($name, $parameters = [], $relative = false)
55
    {
56
        $requestLocale = $this->request ? $this->request->getLocale() : $this->locale;
57
        if ($name == 'victoire_core_page_show_by_id') {
58
            $params = [
59
                'viewId' => $parameters['viewId'],
60
                'locale' => $requestLocale,
61
            ];
62
            unset($parameters['viewId']);
63
            if (!empty($parameters['entityId'])) {
64
                $params['entityId'] = $parameters['entityId'];
65
                unset($parameters['entityId']);
66
            }
67
68
            try {
69
                $page = $this->pageHelper->findPageByParameters($params);
70
                $parameters['url'] = $page->getReference($requestLocale)->getUrl();
71
            } catch (ViewReferenceNotFoundException $e) {
72
                $this->logger->error($e->getMessage(), [
73
                    'params' => $params,
74
                ]);
75
                $errorPage = $this->errorPageRepository->findOneByCode(404);
76
                $parameters['url'] = $this->generator->generate(
77
                    'victoire_core_page_show',
78
                    array_merge(
79
                        [
80
                            '_locale' => $requestLocale,
81
                            'url'     => $errorPage ? $errorPage->getSlug() : '',
82
                        ],
83
                        $parameters
84
                    )
85
                );
86
            }
87
88
            $name = 'victoire_core_page_show';
89
        }
90
91
        $prefix = '';
92
        //if locale is passed (and different) and i18n strategy is "domain"
93
        if (!empty($parameters['_locale'])
94
            && $parameters['_locale'] != $requestLocale
95
            && $this->localeResolver->localePattern === LocaleResolver::PATTERN_DOMAIN
96
        ) {
97
            $prefix = $this->getPrefix($parameters['_locale']);
98
            //if we set a prefix, we don't want an absolute path
99
            if ($prefix) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $prefix of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
100
                $relative = true;
101
            }
102
        }
103
104
        return $prefix.$this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::ABSOLUTE_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
105
    }
106
107
    /**
108
     * If victoire_i18n.locale_pattern == domain, then we force the url rewrite with a valid host.
109
     *
110
     * @param $locale
111
     *
112
     * @return null
113
     */
114
    protected function getPrefix($locale)
115
    {
116
        foreach ($this->localeResolver->getDomainConfig() as $_domain => $_locale) {
117
            if ($_locale === $locale) {
118
                $urlPrefix = sprintf('%s://%s', $this->request ? $this->request->getScheme() : 'http', $_domain);
119
                if ($this->request && $this->request->getPort()) {
120
                    $urlPrefix .= ':'.$this->request->getPort();
121
                }
122
123
                return $urlPrefix;
124
            }
125
        }
126
    }
127
}
128