Passed
Push — master ( bb924a...090072 )
by Vasyl
01:56
created

UrlAliasMiddleware::makeNewRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 19
rs 9.8666
1
<?php
2
3
namespace Fomvasss\UrlAliases\Middleware;
4
5
use Closure;
6
use Fomvasss\UrlAliases\UrlAliasLocalization;
7
use Illuminate\Http\Request;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
class UrlAliasMiddleware
10
{
11
12
    const ALIAS_REQUEST_URI_KEY = 'ALIAS_REQUEST_URI';
13
14
    /**
15
     * @var
16
     */
17
    protected $config;
18
19
    /**
20
     * @var bool
21
     */
22
    protected $useLocalization = false;
23
24
    /**
25
     * Handle an incoming request.
26
     *
27
     * @param  \Illuminate\Http\Request  $request
28
     * @param  \Closure  $next
29
     * @return mixed
30
     */
31
    public function handle($request, Closure $next)
32
    {
33
        $this->app = app();
0 ignored issues
show
Bug introduced by
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

33
        $this->app = /** @scrutinizer ignore-call */ app();
Loading history...
Bug Best Practice introduced by
The property app does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
34
        $this->config = $this->app['config'];
35
36
        if ($this->isAvailableMethod($request) && $this->isAvailableCheckPath($request)) {
37
38
            $path = $request->path();
39
40
            // Check lovalization support
41
            if ($this->useLocalization = $this->config->get('url-aliases.use_localization') && $this->isAvailableLocalizationPath($request)) {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $this->useLocalization =...lizationPath($request)), Probably Intended Meaning: ($this->useLocalization ...alizationPath($request)
Loading history...
42
                $localization = $this->app->make(UrlAliasLocalization::class);
43
44
                $localizationResult = $localization->prepareLocalizePath($request->path());
45
46
                if (isset($localizationResult['redirect'])) {
47
                    $params = count($request->all()) ? '?' . http_build_query($request->all()) : '';
48
                    return redirect()->to($localizationResult['redirect'] . $params, 301); // hide default locale in URL
0 ignored issues
show
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

48
                    return /** @scrutinizer ignore-call */ redirect()->to($localizationResult['redirect'] . $params, 301); // hide default locale in URL
Loading history...
49
                } elseif (isset($localizationResult['path'])) {
50
                    $path = $localizationResult['path'];
51
                }
52
            }
53
54
            $urlModels = $this->getByPath($path);
55
56
            // If visited source - system path
57
            if ($urlModel = $urlModels->where('source', $path)->where('locale', $this->app->getLocale())->first()/* && $path != 'de'*/) {
58
59
                $redirectStatus = $this->config->get('url-aliases.redirect_for_system_path', 301) == 301 ? 301 : 302;
60
61
                // Redirect to alias path
62
                $params = count($request->all()) ? '?' . http_build_query($request->all()) : '';
63
64
                if ($this->useLocalization) {
65
                    return redirect()->to(url($urlModel->localeAlias) . '/' . $params, $redirectStatus);
0 ignored issues
show
Bug introduced by
The function url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

65
                    return redirect()->to(/** @scrutinizer ignore-call */ url($urlModel->localeAlias) . '/' . $params, $redirectStatus);
Loading history...
66
                }
67
68
                return redirect()->to(url($urlModel->alias) . '/' . $params, $redirectStatus);
69
70
                // If visited alias
71
            } elseif ($urlModel = $urlModels->where('alias', $path)->where('locale', $this->app->getLocale())->first()) {
72
73
                // Redirect to source
74
                if ($redirect = $this->isTypeRedirect($urlModel)) {
75
                    return $redirect;
76
                }
77
78
                // Make new request
79
                $newRequest = $this->makeNewRequest($request, $urlModel);
80
                
81
                return $next($newRequest);
82
                
83
            // Check if isset facet in current url and find aliased path without facet
84
            } elseif ($customReturn = $this->customize($request, $next)) {
85
86
                return $customReturn;
87
            }
88
        }
89
        
90
        return $next($request);
91
    }
92
93
    /**
94
     * Remake request
95
     * @param Request $request
96
     * @param $urlModel
97
     * @return Request
98
     */
99
    protected function makeNewRequest(Request $request, $urlModel, $getParams = [])
100
    {
101
        $newRequest = $request;
102
        $newRequest->server->set('REQUEST_URI', $urlModel->source);
103
        $newRequest->initialize(
104
            $request->query->all(),
105
            $request->request->all(),
106
            $request->attributes->all(),
107
            $request->cookies->all(),
108
            $request->files->all(),
109
            $newRequest->server->all() + [static::ALIAS_REQUEST_URI_KEY => $request->path()],
110
            $request->getContent()
111
        );
112
113
//          $request = \Request::create($systemPath, 'GET');
114
//          return $response = \Route::dispatch($request);
115
        $newRequest->merge($getParams);
116
117
        return $newRequest;
118
    }
119
120
    public function customize($request, Closure $next)
121
    {
122
       //...
123
        return $next($request);
124
    }
125
126
    /**
127
     * If type redirect - redirect.
128
     * @param $urlModel
129
     * @return bool|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\RedirectResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type Illuminate\Routing\Redirector was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
130
     */
131
    protected function isTypeRedirect($urlModel)
132
    {
133
        if (in_array($urlModel->type, [301, 302])) {
134
            if ($this->useLocalization) {
135
                return redirect(url($urlModel->localeSource), $urlModel->type);
0 ignored issues
show
Bug introduced by
The function url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

135
                return redirect(/** @scrutinizer ignore-call */ url($urlModel->localeSource), $urlModel->type);
Loading history...
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

135
                return /** @scrutinizer ignore-call */ redirect(url($urlModel->localeSource), $urlModel->type);
Loading history...
136
            }
137
138
            return redirect()->to(url($urlModel->source), $urlModel->type);
139
        }
140
141
        return false;
142
    }
143
144
    /**
145
     * @param Request $request
146
     * @return bool
147
     */
148
    protected function isAvailableCheckPath(Request $request)
149
    {
150
        if ($request->is(...$this->config->get('url-aliases.ignored_paths', []))) {
151
            return false;
152
        }
153
        
154
        return true;
155
    }
156
157
    protected function isAvailableLocalizationPath(Request $request)
158
    {
159
        if ($request->is(...$this->config->get('url-aliases-laravellocalization.urlsIgnored', []))) {
160
            return false;
161
        }
162
163
        return true;
164
    }
165
166
    /**
167
     * @param Request $request
168
     * @return bool
169
     */
170
    protected function isAvailableMethod(Request $request)
171
    {
172
        if (in_array($request->getMethod(), $this->config->get('url-aliases.available_methods', [])) || empty($this->config->get('url-aliases.available_methods', []))) {
173
            return true;
174
        }
175
        
176
        return false;
177
    }
178
179
    /**
180
     * @param $path
181
     * @return mixed
182
     */
183
    protected function getByPath($path)
184
    {
185
        $model = $this->config->get('url-aliases.model', \Fomvasss\UrlAliases\Models\UrlAlias::class);
186
        
187
        return $model::byPath($path)->get();
188
    }
189
}
190