Completed
Push — master ( c41372...e6a376 )
by Simon
04:10
created

ShortListController   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 198
Duplicated Lines 9.09 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 8
dl 18
loc 198
rs 8.6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 10 2
B index() 0 23 5
A Link() 0 11 2
C renderList() 0 27 7
C performAction() 18 55 12
B shortListCount() 0 14 6
A getSessionShortList() 0 7 1
A getShortListSession() 0 4 1
A getSecurityToken() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
use Jaybizzle\CrawlerDetect\CrawlerDetect;
3
4
class ShortListController extends Page_Controller
5
{
6
    private static $allowed_actions = array(
7
        'renderList',
8
        'performAction'
9
    );
10
11
    private static $url_handlers = array(
12
        'add'       => 'performAction',
13
        'remove'    => 'performAction',
14
        '$URL!'     => 'renderList',
15
    );
16
17
    private static $extensions = array(
18
        'ShortListPaginationExtension'
19
    );
20
21
    public function init()
22
    {
23
        parent::init();
24
25
        Session::start();
26
27
        if ($this->request->getVar('page')) {
28
            $this->currentPage = $this->request->getVar('page');
29
        }
30
    }
31
32
    /**
33
     * When landing on the homepage, if there is a shortlist for the current
34
     * user, redirect to the correct URL. Otherwise, 404.
35
     * */
36
    public function index($request)
37
    {
38
        if (($shortlist = $this->getSessionShortList())) {
39
            return $this->redirect(Config::inst()->get('ShortList', 'URLSegment') . $shortlist->URL);
40
        } else {
41
            $CrawlerDetect = new CrawlerDetect;
42
43
            // Check the user agent of the current 'visitor'
44
            if($CrawlerDetect->isCrawler()) {
45
                return $this->httpError(403);
46
            }
47
48
            $shortlist = $this->getSessionShortList();
49
50
            if (!$shortlist || !$shortlist->exists()) {
51
                $shortlist = new ShortList();
52
                $shortlist->write();
53
            }
54
        }
55
56
        // render with empty template.
57
        return $this->renderWith(array('Page', 'ShortList_empty'));
58
    }
59
60
    /**
61
     * Get the absolute URL of this controller.
62
     * */
63
    public function Link($action = null)
64
    {
65
        $shortlist = $this->getSessionShortList();
66
        $url = Config::inst()->get('ShortList', 'URLSegment');
67
68
        if ($shortlist) {
69
            $url .= $shortlist->URL;
70
        }
71
72
        return $url;
73
    }
74
75
    public function renderList($request)
76
    {
77
        $shortlist = DataObject::get_one('ShortList', $filter = array('URL' => $request->param('URL')));
78
79
        if (is_null(self::getSecurityToken()) ||
80
            !$request->param('URL') ||
81
            !$shortlist ||
82
            !$shortlist->exists()
83
        ) {
84
            return $this->httpError(404);
85
        }
86
87
        $link = false;
88
        $count = 0;
89
90
        if ($shortlist && $shortlist->exists()) {
91
            $link = $shortlist->Link();
92
            $count = $shortlist->ShortListItems()->Count();
93
        }
94
95
        return $this->customise(array(
96
            'ShortlistURL' => $link,
97
            'ShortlistCount' => $count
98
        ))->renderWith(
99
            array('ShortList', 'Page')
100
        );
101
    }
102
103
    public function performAction($request)
104
    {
105
        if (is_null(self::getSecurityToken()) ||
106
            !$request->getVar('id') ||
107
            !$request->getVar('type') ||
108
            !$request->getVar('s') ||
109
            $request->getVar('s') != self::getSecurityToken()
110
        ) {
111
            return $this->httpError(404);
112
        }
113
114
        $matches = array();
115
        preg_match('/remove|add/', $request->getURL(), $matches);
116
117
        switch ($matches[0]) {
118 View Code Duplication
            case 'add':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
                $action = new AddToshortlistAction();
120
                $status = $action->performAction(
121
                    $shortlist = $this->getSessionShortList(),
0 ignored issues
show
Documentation introduced by
$shortlist = $this->getSessionShortList() is of type object<DataObject>, but the function expects a object<ShortList>|null.

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...
122
                    $ID = $request->getVar('id'),
123
                    $type = $request->getVar('type'),
124
                    $session = $request->getVar('s')
125
                );
126
                break;
127 View Code Duplication
            case 'remove':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
                $action = new RemoveFromshortlistAction();
129
                $status = $action->performAction(
130
                    $shortlist = $this->getSessionShortList(),
0 ignored issues
show
Documentation introduced by
$shortlist = $this->getSessionShortList() is of type object<DataObject>, but the function expects a object<ShortList>|null.

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...
131
                    $ID = $request->getVar('id'),
132
                    $type = $request->getVar('type'),
133
                    $session = $request->getVar('s')
134
                );
135
                break;
136
        }
137
138
        if ($request->isAjax()) {
139
            $shortlist = $this->getSessionShortList();
140
            $url = false;
141
142
            if ($shortlist && $shortlist->exists()) {
143
                $url = $shortlist->Link();
144
            }
145
146
            return json_encode(array(
147
                'count' => $this->shortListCount($session),
0 ignored issues
show
Bug introduced by
The variable $session does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
148
                'url' => $url
149
            ));
150
        }
151
152
        if (array_key_exists('output', $request->getVars())) {
153
            return $status;
0 ignored issues
show
Bug introduced by
The variable $status does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
154
        }
155
156
        return $this->redirectBack();
157
    }
158
159
160
    /**
161
     * Get the number of items in the current short list.
162
     *
163
     * @param session The session to check & find a shortlist for.
164
     * @return mixed false if no session exists - else the number of items in the shortlist.
165
     * */
166
    public function shortListCount($session = false)
167
    {
168
        if (is_null(self::getSecurityToken()) || !$session || $session != self::getSecurityToken()) {
169
            return false;
170
        }
171
172
        $shortlist = $this->getSessionShortList();
173
174
        if (!$shortlist || !$shortlist->exists()) {
175
            return 0;
176
        }
177
178
        return $shortlist->Items()->count();
179
    }
180
181
    private function getSessionShortList()
182
    {
183
        return DataObject::get_one('ShortList',
184
            $filter = array('SessionID' => self::getSecurityToken()),
185
            $cache = false
186
        );
187
    }
188
189
    public static function getShortListSession()
190
    {
191
        return DataObject::get_one('ShortList', $filter = array('SessionID' => self::getSecurityToken()));
192
    }
193
194
    /**
195
     * Get the token to use to add/remove from shortlist.
196
     * */
197
    public static function getSecurityToken()
198
    {
199
        return Utilities::getSecurityToken();
200
    }
201
}
202