Completed
Push — master ( 4bdd95...d41ddb )
by Simon
02:07
created

ShortListController::addToShortList()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 35
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 35
rs 8.439
cc 6
eloc 14
nc 3
nop 3
1
<?php
2
3
class ShortListController extends Page_Controller
1 ignored issue
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
{
5
    private static $allowed_actions = array(
6
        'renderList',
7
        'addOrRemove'
8
    );
9
10
    private static $url_handlers = array(
11
        'add'       => 'addOrRemove',
12
        'remove'    => 'addOrRemove',
13
        '$URL!'     => 'renderList',
14
    );
15
16
    public function init()
17
    {
18
        parent::init();
19
20
        Session::start();
21
22
        if ($this->request->getVar('page')) {
23
            $this->currentPage = $this->request->getVar('page');
24
        }
25
    }
26
27
    /**
28
     * When landing on the homepage, if there is a shortlist for the current
29
     * user, redirect to the correct URL. Otherwise, 404.
30
     * */
31
    public function index($request)
32
    {
33
34
        if (($shortlist = $this->getSessionShortList())) {
35
            return $this->redirect(Config::inst()->get('ShortList', 'URLSegment') . $shortlist->URL);
36
        } else {
37
            $this->initList();
38
        }
39
40
        // render with empty template.
41
        return $this->renderWith(array('Page', 'ShortList_empty'));
42
    }
43
44
    /**
45
     * Get the absolute URL of this controller.
46
     * */
47
    public function Link($action = null)
48
    {
49
        $shortlist = $this->getSessionShortList();
50
        $url = Config::inst()->get('ShortList', 'URLSegment');
51
52
        if ($shortlist) {
53
            $url .= $shortlist->URL;
54
        }
55
56
        return $url;
57
    }
58
59
    /**
60
     * Create a new list if necessary. If a bot, do nothing!
61
     * */
62
    public function initList()
63
    {
64
        if (!ShortList::isBrowser()) {
65
            return $this->httpError(404);
66
        }
67
68
        $shortlist = $this->getSessionShortList();
69
70
        if (!$shortlist || !$shortlist->exists()) {
71
            $shortlist = new ShortList();
72
            $shortlist->write();
73
        }
74
    }
75
76
    public function renderList($request)
77
    {
78
        $shortlist = DataObject::get_one('ShortList', $filter = array('URL' => $request->param('URL')));
79
80
        if (is_null(session_id()) ||
81
            !$request->param('URL') ||
82
            !$shortlist ||
83
            !$shortlist->exists() ||
84
            !ShortList::isBrowser()
85
        ) {
86
            return $this->httpError(404);
87
        }
88
89
        return $this->customise(array(
90
            'ShortlistURL' => $shortlist && $shortlist->exists() ? $shortlist->Link() : false,
91
            'ShortlistCount' => $shortlist && $shortlist->exists() ? $shortlist->ShortListItems()->Count() : 0
92
        ))->renderWith(
93
            array('ShortList', 'Page')
94
        );
95
    }
96
97
    /**
98
     * Add an item to the shortlist.
99
     *
100
     * @param ID id of the object to add.
101
     * @param type classname of the item to remove
102
     * @param session session id.
103
     *
104
     * */
105
    public function addToShortList($ID = false, $type = null, $session = false)
106
    {
107
        if (!$ID || is_null($type) || !$session) {
108
            return false;
109
        }
110
111
        $shortlist = $this->getSessionShortList();
112
113
        if (!$shortlist || !$shortlist->exists()) {
114
            $shortlist = new ShortList();
115
            $shortlist->write();
116
        }
117
118
        // check whether the itme is already in the list
119
        // before attempting to add it.
120
        /*
1 ignored issue
show
Unused Code Comprehensibility introduced by
58% 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...
121
$existing = $shortlist->ShortListItems()->filterAny(
122
            array('ItemID' => $ID, 'ItemType' => $type)
123
        );
124
125
        if ($existing->count() == 1) {
126
            return true;
127
        }
128
*/
129
130
        $shortlistItem = new ShortListItem();
131
        $shortlistItem->ShortListID = $shortlist->ID;
132
        $shortlistItem->ItemID = $ID;
133
        $shortlistItem->ItemType = $type;
134
135
        $shortlist->ShortListItems()->add($shortlistItem);
136
        $shortlist->write();
137
138
        return true;
139
    }
140
141
    public function addOrRemove($request)
142
    {
143
        if (is_null(session_id()) ||
144
            !$request->getVar('id') ||
145
            !$request->getVar('type') ||
146
            !$request->getVar('s') ||
147
            $request->getVar('s') != session_id() ||
148
            !ShortList::isBrowser()
149
        ) {
150
            return $this->httpError(404);
151
        }
152
153
        if (strpos($request->getURL(), 'remove') !== false) {
154
            $status = $this->removeFromShortList(
155
                $ID = $request->getVar('id'),
156
                $type = $request->getVar('type'),
157
                $session = $request->getVar('s')
158
            );
159
        } else {
160
            $status = $this->addToShortList(
161
                $ID = $request->getVar('id'),
162
                $type = $request->getVar('type'),
163
                $session = $request->getVar('s')
164
            );
165
        }
166
167
168
        if ($request->isAjax()) {
169
            $shortlist = $this->getSessionShortList();
170
            $url = false;
171
172
            if ($shortlist && $shortlist->exists()) {
173
                $url = $shortlist->Link();
174
            }
175
176
            return json_encode(array(
177
                'status' => $status,
178
                'count' => $this->shortListCount($session),
179
                'url' => $url
180
            ));
181
        }
182
183
        return $this->redirectBack();
184
    }
185
186
    /**
187
     * Remove an item from the shortlist.
188
     *
189
     * @param ID id of the object to remove.
190
     * @param type classname of the item to remove
191
     * @param session session id.
192
     *
193
     * */
194
    private function removeFromShortList($ID = false, $type = null, $session = false)
195
    {
196
        $shortlist = $this->getSessionShortList();
197
198
        if (!$shortlist || !$shortlist->exists()) {
199
            return true;
200
        }
201
202
        $item = DataObject::get_one('ShortListItem', $filter = "ItemType = '" . $type . "' AND ItemID = " . $ID);
203
204
        if ($item && $item->exists()) {
205
            $item->delete();
206
        } else {
207
	        return false;
208
        }
209
210
        return true;
211
    }
212
213
    /**
214
     * Get the number of items in the current short list.
215
     *
216
     * @param session The session to check & find a shortlist for.
217
     * @return mixed false if no session exists - else the number of items in the shortlist.
218
     * */
219
    public function shortListCount($session = false)
220
    {
221
        if (is_null(session_id()) || !$session || $session != session_id() || !ShortList::isBrowser()) {
222
            return false;
223
        }
224
225
        $shortlist = $this->getSessionShortList();
226
227
        if (!$shortlist || !$shortlist->exists()) {
228
            return 0;
229
        }
230
231
        return $shortlist->Items()->count();
232
    }
233
234
235
	/**
236
	 * Get a paginated list of the shortlist items.
237
	 *
238
	 * @return mixed the paginated list of items, or false if the list cannot be found.
239
	 * */
240
    public function paginatedItems()
241
    {
242
        if (!$this->getRequest()->param('URL') || !ShortList::isBrowser()) {
243
            return false;
244
        }
245
246
        $items = false;
247
        $list = DataObject::get_one('ShortList', $filter = array('URL' => $this->getRequest()->param('URL')));
248
249
        if ($list) {
250
            $items = $list->ShortListItems();
251
        }
252
253
        $this->list = new PaginatedList($items, $this->getRequest());
254
        $this->list->setPageLength(Config::inst()->get('ShortList', 'PaginationCount'));
255
        $this->list->setPaginationGetVar('page');
256
257
        if ($this->currentPage) {
258
            $this->list->setCurrentPage($this->currentPage);
259
        }
260
261
        return $this->list;
262
    }
263
264
    public function nextPage()
265
    {
266
        if ($this->list->CurrentPage() < $this->list->TotalPages()) {
267
            return '?page=' . ($this->list->CurrentPage() + 1);
268
        }
269
270
        return false;
271
    }
272
273
    public function prevPage()
274
    {
275
        if ($this->list->CurrentPage() > 1) {
276
            return '?page=' . ($this->list->CurrentPage() - 1);
277
        }
278
279
        return false;
280
    }
281
282
283
    private function getSessionShortList()
284
    {
285
        return DataObject::get_one('ShortList', $filter = array('SessionID' => session_id()));
286
    }
287
}
288