GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Setup Failed
Push — master ( c5ade0...e039e4 )
by Gabriel
05:51
created

UrlGenerator   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 300
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 300
rs 9.2
c 1
b 0
f 1
wmc 34
lcom 1
cbo 4

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setRequest() 0 8 1
A full() 0 4 1
A current() 0 4 1
A to() 0 20 2
A isValidUrl() 0 7 2
A formatParameters() 0 10 2
B formatRoot() 0 11 5
B formatScheme() 0 10 5
A extractQueryString() 0 10 2
A format() 0 11 3
A previous() 0 12 4
A getPreviousUrlFromSession() 0 6 1
A asset() 0 11 2
A removeIndex() 0 5 2
1
<?php
2
3
namespace Nip\Router\Generator;
4
5
use Nip\Request;
6
use Nip\Router\RouteCollection;
7
use Nip\Utility\Arr;
8
use Nip\Utility\Str;
9
10
/**
11
 * Class UrlGenerator
12
 * @package Nip\Router\Generator
13
 */
14
class UrlGenerator
15
{
16
17
    /**
18
     * The route collection.
19
     *
20
     * @var RouteCollection
21
     */
22
    protected $routes;
23
24
    /**
25
     * The request instance.
26
     *
27
     * @var Request
28
     */
29
    protected $request;
30
31
    /**
32
     * A cached copy of the URL root for the current request.
33
     *
34
     * @var string|null
35
     */
36
    protected $cachedRoot;
37
38
    /**
39
     * A cached copy of the URL schema for the current request.
40
     *
41
     * @var string|null
42
     */
43
    protected $cachedSchema;
44
45
    /**
46
     * The forced URL root.
47
     *
48
     * @var string
49
     */
50
    protected $forcedRoot;
51
52
    /**
53
     * The forced schema for URLs.
54
     *
55
     * @var string
56
     */
57
    protected $forceScheme;
58
59
    /**
60
     * The callback to use to format hosts.
61
     *
62
     * @var \Closure
63
     */
64
    protected $formatHostUsing;
65
66
    /**
67
     * The callback to use to format paths.
68
     *
69
     * @var \Closure
70
     */
71
    protected $formatPathUsing;
72
73
    /**
74
     * Create a new URL Generator instance.
75
     *
76
     * @param  RouteCollection $routes
77
     * @param  Request $request
78
     */
79
    public function __construct(RouteCollection $routes, Request $request)
80
    {
81
        $this->routes = $routes;
82
        $this->setRequest($request);
83
    }
84
85
    /**
86
     * Set the current request instance.
87
     *
88
     * @param  Request $request
89
     * @return void
90
     */
91
    public function setRequest(Request $request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
92
    {
93
        $this->request = $request;
94
95
        $this->cachedRoot = null;
96
        $this->cachedSchema = null;
97
//        $this->routeGenerator = null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
98
    }
99
100
    /**
101
     * Get the full URL for the current request.
102
     *
103
     * @return string
104
     */
105
    public function full()
106
    {
107
        return $this->request->fullUrl();
108
    }
109
110
    /**
111
     * Get the current URL for the request.
112
     *
113
     * @return string
114
     */
115
    public function current()
116
    {
117
        return $this->to($this->request->getPathInfo());
118
    }
119
120
    /**
121
     * Generate an absolute URL to the given path.
122
     *
123
     * @param  string  $path
124
     * @param  mixed  $extra
125
     * @param  bool|null  $secure
126
     * @return string
127
     */
128
    public function to($path, $extra = [], $secure = null)
129
    {
130
        // First we will check if the URL is already a valid URL. If it is we will not
131
        // try to generate a new one but will simply return the URL as is, which is
132
        // convenient since developers do not always have to check if it's valid.
133
        if ($this->isValidUrl($path)) {
134
            return $path;
135
        }
136
        $tail = implode('/', array_map(
137
                'rawurlencode', (array) $this->formatParameters($extra))
138
        );
139
        // Once we have the scheme we will compile the "tail" by collapsing the values
140
        // into a single string delimited by slashes. This just makes it convenient
141
        // for passing the array of parameters to this URL as a list of segments.
142
        $root = $this->formatRoot($this->formatScheme($secure));
143
        list($path, $query) = $this->extractQueryString($path);
144
        return $this->format(
145
                $root, '/'.trim($path.'/'.$tail, '/')
146
            ).$query;
147
    }
148
149
    /**
150
     * Determine if the given path is a valid URL.
151
     *
152
     * @param  string $path
153
     * @return bool
154
     */
155
    public function isValidUrl($path)
156
    {
157
        if (!Str::startsWith($path, ['#', '//', 'mailto:', 'tel:', 'http://', 'https://'])) {
158
            return filter_var($path, FILTER_VALIDATE_URL) !== false;
159
        }
160
        return true;
161
    }
162
163
    /**
164
     * Format the array of URL parameters.
165
     *
166
     * @param  mixed|array  $parameters
167
     * @return array
168
     */
169
    public function formatParameters($parameters)
170
    {
171
        $parameters = Arr::wrap($parameters);
172
        foreach ($parameters as $key => $parameter) {
0 ignored issues
show
Unused Code introduced by
This foreach statement is empty and can be removed.

This check looks for foreach loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
173
//            if ($parameter instanceof UrlRoutable) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
174
//                $parameters[$key] = $parameter->getRouteKey();
175
//            }
176
        }
177
        return $parameters;
178
    }
179
180
    /**
181
     * Get the base URL for the request.
182
     *
183
     * @param  string $scheme
184
     * @param  string $root
185
     * @return string
186
     */
187
    public function formatRoot($scheme, $root = null)
188
    {
189
        if (is_null($root)) {
190
            if (is_null($this->cachedRoot)) {
191
                $this->cachedRoot = $this->forcedRoot ?: $this->request->root();
192
            }
193
            $root = $this->cachedRoot;
194
        }
195
        $start = Str::startsWith($root, 'http://') ? 'http://' : 'https://';
196
        return preg_replace('~' . $start . '~', $scheme, $root, 1);
197
    }
198
199
    /**
200
     * Get the default scheme for a raw URL.
201
     *
202
     * @param  bool|null $secure
203
     * @return string
204
     */
205
    public function formatScheme($secure)
206
    {
207
        if (!is_null($secure)) {
208
            return $secure ? 'https://' : 'http://';
209
        }
210
        if (is_null($this->cachedSchema)) {
211
            $this->cachedSchema = $this->forceScheme ?: $this->request->getScheme() . '://';
212
        }
213
        return $this->cachedSchema;
214
    }
215
216
    /**
217
     * Extract the query string from the given path.
218
     *
219
     * @param  string  $path
220
     * @return array
221
     */
222
    protected function extractQueryString($path)
223
    {
224
        if (($queryPosition = strpos($path, '?')) !== false) {
225
            return [
226
                substr($path, 0, $queryPosition),
227
                substr($path, $queryPosition),
228
            ];
229
        }
230
        return [$path, ''];
231
    }
232
233
    /**
234
     * Format the given URL segments into a single URL.
235
     *
236
     * @param  string $root
237
     * @param  string $path
238
     * @return string
239
     */
240
    public function format($root, $path)
241
    {
242
        $path = '/' . trim($path, '/');
243
        if ($this->formatHostUsing) {
244
            $root = call_user_func($this->formatHostUsing, $root);
245
        }
246
        if ($this->formatPathUsing) {
247
            $path = call_user_func($this->formatPathUsing, $path);
248
        }
249
        return trim($root . $path, '/');
250
    }
251
252
    /**
253
     * Get the URL for the previous request.
254
     *
255
     * @param  mixed $fallback
256
     * @return string
257
     */
258
    public function previous($fallback = false)
259
    {
260
        $referrer = $this->request->headers->get('referer');
261
        $url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession();
0 ignored issues
show
Bug introduced by
It seems like $referrer defined by $this->request->headers->get('referer') on line 260 can also be of type array; however, Nip\Router\Generator\UrlGenerator::to() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
262
        if ($url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url 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...
263
            return $url;
264
        } elseif ($fallback) {
265
            return $this->to($fallback);
266
        } else {
267
            return $this->to('/');
268
        }
269
    }
270
271
    /**
272
     * Get the previous URL from the session if possible.
273
     *
274
     * @return string|null
275
     */
276
    protected function getPreviousUrlFromSession()
277
    {
278
        return null;
279
//        $session = $this->getSession();
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
280
//        return $session ? $session->previousUrl() : null;
281
    }
282
283
    /**
284
     * Generate the URL to an application asset.
285
     *
286
     * @param  string $path
287
     * @param  bool|null $secure
288
     * @return string
289
     */
290
    public function asset($path, $secure = null)
291
    {
292
        if ($this->isValidUrl($path)) {
293
            return $path;
294
        }
295
        // Once we get the root URL, we will check to see if it contains an index.php
296
        // file in the paths. If it does, we will remove it since it is not needed
297
        // for asset paths, but only for routes to endpoints in the application.
298
        $root = $this->formatRoot($this->formatScheme($secure));
299
        return $this->removeIndex($root) . '/assets/' . trim($path, '/');
300
    }
301
302
    /**
303
     * Remove the index.php file from a path.
304
     *
305
     * @param  string $root
306
     * @return string
307
     */
308
    protected function removeIndex($root)
309
    {
310
        $i = 'index.php';
311
        return Str::contains($root, $i) ? str_replace('/' . $i, '', $root) : $root;
312
    }
313
}
314