HasPrevNextUtils   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
eloc 34
c 3
b 2
f 0
dl 0
loc 55
rs 10
wmc 8

1 Method

Rating   Name   Duplication   Size   Complexity  
B addPrevNextUtils() 0 49 8
1
<?php
2
3
namespace LeKoala\CmsActions;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\Forms\FieldList;
7
8
/**
9
 * Add prev next in utils
10
 * Simply call `addPrevNextUtils` method in your getCMSUtils
11
 * This is not so useful anymore since silverstripe provides this by default now
12
 * but can help if you use custom prev/next logic
13
 */
14
trait HasPrevNextUtils
15
{
16
    /**
17
     * @param FieldList $utils
18
     * @return FieldList
19
     */
20
    public function addPrevNextUtils(FieldList $utils)
21
    {
22
        $controller = Controller::curr();
23
        $request = $controller->getRequest();
24
        $url = rtrim($request->getURL(), '/') . '/';
25
26
        $query = $_GET;
27
        if (!empty($query)) {
28
            $url .= '?' . http_build_query($query);
29
        }
30
31
        $routeParams = $request->routeParams();
32
        $recordClass = get_class($this);
33
        $getPreviousRecordID = $routeParams['cmsactions'][$recordClass]['PreviousRecordID'] ?? $request->param('PreviousRecordID');
34
        $getNextRecordID = $routeParams['cmsactions'][$recordClass]['NextRecordID'] ?? $request->param('NextRecordID');
35
36
        $search = sprintf('/%d/', $this->ID);
37
        $replaceStr = '/%d/';
38
        $PrevRecordLink = $routeParams['cmsactions'][$recordClass]['PrevRecordLink'] ?? null;
39
        $NextRecordLink = $routeParams['cmsactions'][$recordClass]['NextRecordLink'] ?? null;
40
        if (!$PrevRecordLink) {
41
            $PrevRecordLink = str_replace($search, sprintf($replaceStr, $getPreviousRecordID), $url);
42
        }
43
        if (!$NextRecordLink) {
44
            $NextRecordLink = str_replace($search, sprintf($replaceStr, $getNextRecordID), $url);
45
        }
46
47
        if ($this->ID && $getNextRecordID) {
48
            $utils->unshift(
49
                $NextBtnLink = new CmsInlineFormAction(
50
                    'NextBtnLink',
51
                    _t('HasPrevNextUtils.Next', 'Next') . ' >',
52
                    'btn-secondary'
53
                )
54
            );
55
            $NextBtnLink->setLink($NextRecordLink);
56
        }
57
        if ($this->ID && $getPreviousRecordID) {
58
            $utils->unshift(
59
                $PrevBtnLink = new CmsInlineFormAction(
60
                    'PrevBtnLink',
61
                    '< ' . _t('HasPrevNextUtils.Previous', 'Previous'),
62
                    'btn-secondary'
63
                )
64
            );
65
            $PrevBtnLink->setLink($PrevRecordLink);
66
        }
67
68
        return $utils;
69
    }
70
}
71