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

PaginateRoute::renderPageList()   F

Complexity

Conditions 25
Paths 6144

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 0
c 0
b 0
f 0
cc 25
nc 6144
nop 4

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 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($paginator, $nextPage, false);
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
     * @param LengthAwarePaginator $paginator
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(LengthAwarePaginator $paginator, $full = false): ?string
160
    {
161
        $previousPage = $this->previousPage();
162
163
        if ($previousPage === null) {
164
            return null;
165
        }
166
167
        return $this->pageUrl($paginator, $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($paginator, $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>";
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
    /**
308
     * Render html link tags for SEO indication of previous and next page.
309
     *
310
     * @param LengthAwarePaginator $paginator
311
     * @param bool $full Return the full version of the URL in for the first page
312
     *                                                                          Ex. /users/page/1 instead of /users
313
     *
314
     * @return string
315
     */
316
    public function renderRelLinks(LengthAwarePaginator $paginator, $full = false): string
317
    {
318
        $urls = $this->allUrls($paginator, $full);
319
320
        $linkItems = '';
321
322
        foreach ($urls as $i => $url) {
323
            $pageNum = $i + 1;
324
325
            switch ($pageNum - $this->currentPage()) {
326
                case -1:
327
                    $linkItems .= "<link rel=\"prev\" href=\"{$url}\" />";
328
                    break;
329
                case 1:
330
                    $linkItems .= "<link rel=\"next\" href=\"{$url}\" />";
331
                    break;
332
            }
333
        }
334
335
        return $linkItems;
336
    }
337
338
    /**
339
     * @param LengthAwarePaginator $paginator
340
     * @param bool $full Return the full version of the URL in for the first page
341
     *                                                                         Ex. /users/page/1 instead of /users
342
     *
343
     * @return string
344
     * @deprecated in favor of renderPageList.
345
     */
346
    public function renderHtml(LengthAwarePaginator $paginator, $full = false): string
347
    {
348
        return $this->renderPageList($paginator, $full);
349
    }
350
351
    /**
352
     * Generate a page URL, based on custom path or the request's current URL.
353
     *
354
     * @param LengthAwarePaginator $paginator
355
     * @param int $page
356
     * @param bool $full Return the full version of the URL in for the first page
357
     *                   Ex. /users/page/1 instead of /users
358
     *
359
     * @return string|null
360
     */
361
    public function pageUrl(LengthAwarePaginator $paginator, $page, $full = false): string
362
    {
363
        $currentPageUrl = $paginator->path() ? $paginator->path() : $this->router->getCurrentRoute()->uri();
364
365
        $url = $this->addPageQuery(str_replace('{pageQuery?}', '', $currentPageUrl), $page, $full);
366
367
        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...
368
            $url = str_replace(['{' . $parameterName . '}', '{' . $parameterName . '?}'], $parameterValue, $url);
369
        }
370
371
        $query = Request::getQueryString();
372
373
        $query = $query
374
            ? '?' . $query
375
            : '';
376
377
        return $this->urlGenerator->to($url) . $query;
378
    }
379
380
    /**
381
     * Append the page query to a URL.
382
     *
383
     * @param string $url
384
     * @param int $page
385
     * @param bool $full Return the full version of the URL in for the first page
386
     *                     Ex. /users/page/1 instead of /users
387
     *
388
     * @return string
389
     */
390
    public function addPageQuery($url, $page, $full = false): string
391
    {
392
        // If the first page's URL is requested and $full is set to false, there's nothing to be added.
393
        if ($page === 1 && !$full) {
394
            return $url;
395
        }
396
397
        return trim($url, '/') . "/{$this->pageKeyword}/{$page}";
398
    }
399
400
    /**
401
     * Register the Route::paginate macro.
402
     */
403
    public function registerMacros(): void
404
    {
405
        $pageKeyword = $this->pageKeyword;
406
        $router = $this->router;
407
408
        $router->macro('paginate', function ($uri, $action) use ($pageKeyword, $router) {
409
            $route = null;
410
411
            $router->group(
412
                ['middleware' => 'Vipertecpro\PaginateRoute\SetPageMiddleware'],
413
                function () use ($pageKeyword, $router, $uri, $action, &$route) {
414
                    $route = $router->get($uri . '/{pageQuery?}', $action)->where('pageQuery', $pageKeyword . '/[0-9]+');
415
                });
416
417
            return $route;
418
        });
419
    }
420
}
421