Completed
Push — master ( 616f83...c8d577 )
by Gilles
13s
created

RewritingRouterOverride   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 104
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
lcom 0
cbo 0
dl 0
loc 104
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
F matchRequest() 0 84 14
A fetchRewritingRedirectTypeFromUrl() 0 9 1
1
<?php
2
3
namespace RewriteUrl\Service;
4
5
use RewriteUrl\Model\RewritingRedirectType;
6
use RewriteUrl\Model\RewritingRedirectTypeQuery;
7
use Thelia\Core\Routing\RewritingRouter;
8
use Propel\Runtime\ActiveQuery\Criteria;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
11
use Thelia\Core\HttpFoundation\Request as TheliaRequest;
12
use Thelia\Exception\UrlRewritingException;
13
use Thelia\Model\ConfigQuery;
14
use Thelia\Model\LangQuery;
15
use Thelia\Model\RewritingUrlQuery;
16
use Thelia\Tools\URL;
17
18
/**
19
 * This class RewritingRouterOverride is overriding the base class RewritingRouter use by Thelia.
20
 * It provides a way of choosing the type of redirection (301 ou 302) rather than the hard-coded 301 redirection of Thelia.
21
 */
22
class RewritingRouterOverride extends RewritingRouter
23
{
24
    /**
25
     * @inheritdoc
26
     */
27
    public function matchRequest(Request $request)
28
    {
29
        if (ConfigQuery::isRewritingEnable()) {
30
            $urlTool = URL::getInstance();
31
32
            $pathInfo = $request instanceof TheliaRequest ? $request->getRealPathInfo() : $request->getPathInfo();
0 ignored issues
show
Bug introduced by
The class Thelia\Core\HttpFoundation\Request does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
33
34
            try {
35
                $rewrittenUrlData = $urlTool->resolve($pathInfo);
36
            } catch (UrlRewritingException $e) {
0 ignored issues
show
Bug introduced by
The class Thelia\Exception\UrlRewritingException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
37
                switch ($e->getCode()) {
38
                    case UrlRewritingException::URL_NOT_FOUND:
39
                        throw new ResourceNotFoundException();
40
                        break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
41
                    default:
42
                        throw $e;
43
                }
44
            }
45
46
            // If we have a "lang" parameter, whe have to check if the found URL has the proper locale
47
            // If it's not the case, find the rewritten URL with the requested locale, and redirect to it.
48
            if (null ==! $requestedLocale = $request->get('lang')) {
49
                if (null !== $requestedLang = LangQuery::create()->findOneByLocale($requestedLocale)) {
50
                    if ($requestedLang->getLocale() != $rewrittenUrlData->locale) {
51
                        $localizedUrl = $urlTool->retrieve(
52
                            $rewrittenUrlData->view,
53
                            $rewrittenUrlData->viewId,
54
                            $requestedLang->getLocale()
55
                        )->toString();
56
57
                        $this->redirect($urlTool->absoluteUrl($localizedUrl), 301);
58
                    }
59
                }
60
            }
61
62
            /* is the URL redirected ? */
63
            if (null !== $rewrittenUrlData->redirectedToUrl) {
64
                $redirect = RewritingUrlQuery::create()
65
                    ->filterByView($rewrittenUrlData->view)
66
                    ->filterByViewId($rewrittenUrlData->viewId)
67
                    ->filterByViewLocale($rewrittenUrlData->locale)
68
                    ->filterByRedirected(null, Criteria::ISNULL)
69
                    ->findOne()
70
                ;
71
72
                // Differences with the base class for handling 301 or 302 redirection
73
                $redirectType = $this->fetchRewritingRedirectTypeFromUrl($rewrittenUrlData->rewrittenUrl);
74
75
                if ($redirectType == null) {
76
                    $httpRedirectCode = RewritingRedirectType::DEFAULT_REDIRECT_TYPE;
77
                } else {
78
                    $httpRedirectCode = $redirectType->getHttpcode();
79
                }
80
                // End of differences
81
82
                $this->redirect($urlTool->absoluteUrl($redirect->getUrl()), $httpRedirectCode);
83
            }
84
85
            /* define GET arguments in request */
86
87
            if (null !== $rewrittenUrlData->view) {
88
                $request->attributes->set('_view', $rewrittenUrlData->view);
89
                if (null !== $rewrittenUrlData->viewId) {
90
                    $request->query->set($rewrittenUrlData->view . '_id', $rewrittenUrlData->viewId);
91
                }
92
            }
93
94
            if (null !== $rewrittenUrlData->locale) {
95
                $this->manageLocale($rewrittenUrlData, $request);
96
            }
97
98
99
            foreach ($rewrittenUrlData->otherParameters as $parameter => $value) {
100
                $request->query->set($parameter, $value);
101
            }
102
103
            return array(
104
                '_controller' => 'Thelia\\Controller\\Front\\DefaultController::noAction',
105
                '_route' => 'rewrite',
106
                '_rewritten' => true,
107
            );
108
        }
109
        throw new ResourceNotFoundException();
110
    }
111
112
    /**
113
     * @param $url
114
     * @return RewritingRedirectType
115
     */
116
    public function fetchRewritingRedirectTypeFromUrl($url)
117
    {
118
        return RewritingRedirectTypeQuery::create()
119
            ->joinRewritingUrl()
120
            ->useRewritingUrlQuery()
121
            ->filterByUrl($url)
122
            ->endUse()
123
            ->findOne();
124
    }
125
}