Completed
Pull Request — master (#7)
by
unknown
01:29
created

PaginateRoute   F

Complexity

Total Complexity 65

Size/Duplication

Total Lines 407
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 65
lcom 1
cbo 6
dl 0
loc 407
rs 3.2
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A currentPage() 0 12 3
A isCurrentPage() 0 4 1
A nextPage() 0 8 2
A hasNextPage() 0 4 1
A nextPageUrl() 0 10 2
A previousPage() 0 8 2
A hasPreviousPage() 0 4 1
A previousPageUrl() 0 10 2
A allUrls() 0 15 3
A getLeftPoint() 0 16 5
A getRightPoint() 0 15 5
F renderPageList() 0 54 25
A renderRelLinks() 0 21 4
A renderHtml() 0 4 1
A pageUrl() 0 18 3
A addPageQuery() 0 9 3
A registerMacros() 0 17 1

How to fix   Complexity   

Complex Class

Complex classes like PaginateRoute often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PaginateRoute, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Vipertecpro\PaginateRoute;
4
5
use Illuminate\Pagination\LengthAwarePaginator;
6
use Illuminate\Contracts\Routing\UrlGenerator;
7
use Illuminate\Routing\RouteParameterBinder;
8
use Illuminate\Routing\Router;
9
use Illuminate\Support\Facades\Request;
10
use Illuminate\Translation\Translator;
11
12
class PaginateRoute
13
{
14
    /**
15
     * @var Translator
16
     */
17
    protected $translator;
18
19
    /**
20
     * @var Router
21
     */
22
    protected $router;
23
24
    /**
25
     * @var UrlGenerator
26
     */
27
    protected $urlGenerator;
28
29
    /**
30
     * @var string|array
31
     */
32
    protected $pageKeyword;
33
34
    /**
35
     * @param Translator $translator
36
     * @param Router $router
37
     * @param UrlGenerator $urlGenerator
38
     */
39
    public function __construct(Translator $translator, Router $router, UrlGenerator $urlGenerator)
40
    {
41
        $this->translator = $translator;
42
        $this->router = $router;
43
        $this->urlGenerator = $urlGenerator;
44
45
        // Unfortunately we can't do this in the service provider since routes are booted first
46
        $this->translator->addNamespace('paginateroute', __DIR__.'/../resources/lang');
47
48
        $this->pageKeyword = $this->translator->get('paginateroute::paginateroute.page');
49
    }
50
51
    /**
52
     * Return the current page.
53
     *
54
     * @return int
55
     */
56
    public function currentPage()
57
    {
58
        $currentRoute = $this->router->getCurrentRoute();
59
60
        if (! $currentRoute) {
61
            return 1;
62
        }
63
64
        $query = $currentRoute->parameter('pageQuery');
65
66
        return (int) str_replace($this->pageKeyword.'/', '', $query) ?: 1;
67
    }
68
69
    /**
70
     * Check if the given page is the current page.
71
     *
72
     * @param int $page
73
     *
74
     * @return bool
75
     */
76
    public function isCurrentPage($page): bool
77
    {
78
        return $this->currentPage() === $page;
79
    }
80
81
    /**
82
     * Get the next page number.
83
     *
84
     * @param LengthAwarePaginator $paginator
85
     *
86
     * @return int|void
87
     */
88
    public function nextPage(LengthAwarePaginator $paginator)
89
    {
90
        if (! $paginator->hasMorePages()) {
91
            return null;
92
        }
93
94
        return $this->currentPage() + 1;
95
    }
96
97
    /**
98
     * Determine weather there is a next page.
99
     *
100
     * @param LengthAwarePaginator $paginator
101
     *
102
     * @return bool
103
     */
104
    public function hasNextPage(LengthAwarePaginator $paginator): bool
105
    {
106
        return $this->nextPage($paginator) !== null;
107
    }
108
109
    /**
110
     * Get the next page URL.
111
     *
112
     * @param LengthAwarePaginator $paginator
113
     *
114
     * @return string|void
115
     */
116
    public function nextPageUrl(LengthAwarePaginator $paginator)
117
    {
118
        $nextPage = $this->nextPage($paginator);
119
120
        if ($nextPage === null) {
121
            return null;
122
        }
123
124
        return $this->pageUrl($nextPage);
125
    }
126
127
    /**
128
     * Get the previous page number.
129
     *
130
     * @return int|void|null
131
     */
132
    public function previousPage()
133
    {
134
        if ($this->currentPage() <= 1) {
135
            return null;
136
        }
137
138
        return $this->currentPage() - 1;
139
    }
140
141
    /**
142
     * Determine wether there is a previous page.
143
     *
144
     * @return bool
145
     */
146
    public function hasPreviousPage(): bool
147
    {
148
        return $this->previousPage() !== null;
149
    }
150
151
    /**
152
     * Get the previous page URL.
153
     *
154
     * @param bool $full Return the full version of the URL in for the first page
155
     *                   Ex. /users/page/1 instead of /users
156
     *
157
     * @return string|void|null
158
     */
159
    public function previousPageUrl($full = false): ?string
160
    {
161
        $previousPage = $this->previousPage();
162
163
        if ($previousPage === null) {
164
            return null;
165
        }
166
167
        return $this->pageUrl($previousPage, $full);
168
    }
169
170
    /**
171
     * Get all urls in an array.
172
     *
173
     * @param LengthAwarePaginator $paginator
174
     * @param bool                                                  $full      Return the full version of the URL in for the first page
175
     *                                                                         Ex. /users/page/1 instead of /users
176
     *
177
     * @return array
178
     */
179
    public function allUrls(LengthAwarePaginator $paginator, $full = false): array
180
    {
181
        if (! $paginator->hasPages()) {
182
            return [];
183
        }
184
185
        $urls = [];
186
        $left = $this->getLeftPoint($paginator);
187
        $right = $this->getRightPoint($paginator);
188
        for ($page = $left; $page <= $right; $page++) {
189
            $urls[$page] = $this->pageUrl($page, $full);
190
        }
191
192
        return $urls;
193
    }
194
195
    /**
196
     * Get the left most point in the pagination element.
197
     *
198
     * @param LengthAwarePaginator $paginator
199
     * @return int
200
     */
201
    public function getLeftPoint(LengthAwarePaginator $paginator): int
202
    {
203
        $side = $paginator->onEachSide;
204
        $current = $paginator->currentPage();
205
        $last = $paginator->lastPage();
206
207
        if (! empty($side)) {
208
            $x = $current + $side;
209
            $offset = $x >= $last ? $x - $last : 0;
210
            $left = $current - $side - $offset;
211
        }
212
        if(!isset($left) || $left < 1){
213
            return 1;
214
        }
215
        return $left;
216
    }
217
218
    /**
219
     * Get the right or last point of the pagination element.
220
     *
221
     * @param LengthAwarePaginator $paginator
222
     * @return int
223
     */
224
    public function getRightPoint(LengthAwarePaginator $paginator): int
225
    {
226
        $side = $paginator->onEachSide;
227
        $current = $paginator->currentPage();
228
        $last = $paginator->lastPage();
229
230
        if (! empty($side)) {
231
            $offset = $current <= $side ? $side - $current + 1 : 0;
232
            $right = $current + $side + $offset;
233
        }
234
        if(!isset($right) || $right > $last){
235
            return $last;
236
        }
237
        return $right;
238
    }
239
240
    /**
241
     * Render a plain html list with previous, next and all urls. The current page gets a current class on the list item.
242
     *
243
     * @param LengthAwarePaginator $paginator
244
     * @param bool $full Return the full version of the URL in for the first page
245
     *                                                                                 Ex. /users/page/1 instead of /users
246
     * @param string $styles Include $styles on pagination list
247
     * @param bool $additionalLinks Include prev and next links on pagination list
248
     *
249
     * @return string
250
     */
251
252
    public function renderPageList(LengthAwarePaginator $paginator, $full = false, $styles = null, $additionalLinks = false): string
253
    {
254
        $urls = $this->allUrls($paginator, $full);
255
        $ul_class = '';
256
        if ($styles !== null  && isset($styles['ul'])) {
257
            $ul_class = " class=\"{$styles['ul']}\"";
258
        }
259
        $li_class = 'page-item';
260
        $a = $previous_a = $next_a = 'page-link';
261
        $active_a = false;
262
        $previous_label = "&laquo;";
263
        $next_label = "&raquo;";
264
        if ($styles !== null  && isset($styles['li'])) {
265
            $li_class = $styles['li'];
266
        }
267
        if ($styles !== null  && isset($styles['a'])) {
268
            $a = $styles['a'];
269
        }
270
        if ($styles !== null  && isset($styles['previous_a'])) {
271
            $previous_a = $styles['previous_a'];
272
        }
273
        if ($styles !== null  && isset($styles['next_a'])) {
274
            $next_a = $styles['next_a'];
275
        }
276
        if ($styles !== null  && isset($styles['active_a'])) {
277
            $active_a = $styles['active_a'];
278
        }
279
        if ($styles !== null  && isset($styles['previous_label'])) {
280
            $previous_label = $styles['previous_label'];
281
        }
282
        if ($styles !== null  && isset($styles['next_label'])) {
283
            $next_label = $styles['next_label'];
284
        }
285
        $listItems = "<ul{$ul_class}>";
286
        if ($this->hasPreviousPage() && $additionalLinks) {
287
            $listItems .= "<li class='$li_class'> <a class='$previous_a' href=\"{$this->previousPageUrl($paginator)}\">$previous_label</a></li>";
0 ignored issues
show
Documentation introduced by
$paginator is of type object<Illuminate\Pagina...n\LengthAwarePaginator>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
288
        }
289
        foreach ($urls as $i => $url) {
290
            $pageNum = $i;
291
            $li_active = '';
292
            $link = "<a class='$a' href=\"{$url}\">{$pageNum}</a>";
293
            if ($pageNum === $this->currentPage()) {
294
                $li_active = $active_a ? '' : 'active';
295
                $a_active = $active_a ? $active_a : '';
296
                $link = "<a class='$a $a_active' href=\"{$url}\">{$pageNum}</a>";
297
            }
298
            $listItems .= "<li class='$li_class $li_active'>$link</li>";
299
        }
300
        if ($this->hasNextPage($paginator) && $additionalLinks) {
301
            $listItems .= "<li class='$li_class'> <a class='$next_a' href=\"{$this->nextPageUrl($paginator)}\">$next_label</a></li>";
302
        }
303
        $listItems .= '</ul>';
304
        return $listItems;
305
    }
306
    /**
307
     * Render html link tags for SEO indication of previous and next page.
308
     *
309
     * @param LengthAwarePaginator $paginator
310
     * @param bool                                                  $full       Return the full version of the URL in for the first page
311
     *                                                                          Ex. /users/page/1 instead of /users
312
     *
313
     * @return string
314
     */
315
    public function renderRelLinks(LengthAwarePaginator $paginator, $full = false): string
316
    {
317
        $urls = $this->allUrls($paginator, $full);
318
319
        $linkItems = '';
320
321
        foreach ($urls as $i => $url) {
322
            $pageNum = $i + 1;
323
324
            switch ($pageNum - $this->currentPage()) {
325
                case -1:
326
                    $linkItems .= "<link rel=\"prev\" href=\"{$url}\" />";
327
                    break;
328
                case 1:
329
                    $linkItems .= "<link rel=\"next\" href=\"{$url}\" />";
330
                    break;
331
            }
332
        }
333
334
        return $linkItems;
335
    }
336
337
    /**
338
     * @param LengthAwarePaginator $paginator
339
     * @param bool $full Return the full version of the URL in for the first page
340
     *                                                                         Ex. /users/page/1 instead of /users
341
     *
342
     * @return string
343
     * @deprecated in favor of renderPageList.
344
     */
345
    public function renderHtml(LengthAwarePaginator $paginator, $full = false): string
346
    {
347
        return $this->renderPageList($paginator, $full);
348
    }
349
350
    /**
351
     * Generate a page URL, based on the request's current URL.
352
     *
353
     * @param int  $page
354
     * @param bool $full Return the full version of the URL in for the first page
355
     *                   Ex. /users/page/1 instead of /users
356
     *
357
     * @return string|null
358
     */
359
    public function pageUrl($page, $full = false): string
360
    {
361
        $currentPageUrl = $this->router->getCurrentRoute()->uri();
362
363
        $url = $this->addPageQuery(str_replace('{pageQuery?}', '', $currentPageUrl), $page, $full);
364
365
        foreach ((new RouteParameterBinder($this->router->getCurrentRoute()))->parameters(app('request')) as $parameterName => $parameterValue) {
0 ignored issues
show
Bug introduced by
It seems like $this->router->getCurrentRoute() can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
366
            $url = str_replace(['{'.$parameterName.'}', '{'.$parameterName.'?}'], $parameterValue, $url);
367
        }
368
369
        $query = Request::getQueryString();
370
371
        $query = $query
372
            ? '?'.$query
373
            : '';
374
375
        return $this->urlGenerator->to($url).$query;
376
    }
377
378
    /**
379
     * Append the page query to a URL.
380
     *
381
     * @param string $url
382
     * @param int    $page
383
     * @param bool   $full Return the full version of the URL in for the first page
384
     *                     Ex. /users/page/1 instead of /users
385
     *
386
     * @return string
387
     */
388
    public function addPageQuery($url, $page, $full = false): string
389
    {
390
        // If the first page's URL is requested and $full is set to false, there's nothing to be added.
391
        if ($page === 1 && ! $full) {
392
            return $url;
393
        }
394
395
        return trim($url, '/')."/{$this->pageKeyword}/{$page}";
396
    }
397
398
    /**
399
     * Register the Route::paginate macro.
400
     */
401
    public function registerMacros(): void
402
    {
403
        $pageKeyword = $this->pageKeyword;
404
        $router = $this->router;
405
406
        $router->macro('paginate', function ($uri, $action) use ($pageKeyword, $router) {
407
            $route = null;
408
409
            $router->group(
410
                ['middleware' => 'Vipertecpro\PaginateRoute\SetPageMiddleware'],
411
                function () use ($pageKeyword, $router, $uri, $action, &$route) {
412
                    $route = $router->get($uri.'/{pageQuery?}', $action)->where('pageQuery', $pageKeyword.'/[0-9]+');
413
                });
414
415
            return $route;
416
        });
417
    }
418
}
419