Passed
Push — master ( d7e703...d0dd1b )
by Patrick
09:55
created

ShiftAPI::signup()   C

Complexity

Conditions 15
Paths 18

Size

Total Lines 64
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 44
c 0
b 0
f 0
nc 18
nop 3
dl 0
loc 64
rs 5.9166

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
class ShiftAPI extends VolunteerAPI
3
{
4
    use Processor;
0 ignored issues
show
introduced by
The trait Processor requires some properties which are not provided by ShiftAPI: $startTime, $certs, $endTime, $mail, $uid, $title
Loading history...
5
6
    public function __construct()
7
    {
8
        parent::__construct('shifts');
9
    }
10
11
    public function setup($app)
12
    {
13
        parent::setup($app);
14
        $app->post('/Actions/CreateGroup', array($this, 'createGroup'));
15
        $app->post('/Actions/NewGroup', array($this, 'newGroup'));
16
        $app->post('/Actions/DeleteGroup', array($this, 'deleteGroup'));
17
        $app->post('/{shift}/Actions/Signup[/]', array($this, 'signup'));
18
        $app->post('/{shift}/Actions/Abandon[/]', array($this, 'abandon'));
19
        $app->post('/{shift}/Actions/Approve[/]', array($this, 'approvePending'));
20
        $app->post('/{shift}/Actions/Disapprove[/]', array($this, 'disapprovePending')); 
21
        $app->post('/{shift}/Actions/StartGroupSignup', array($this, 'startGroupSignup'));
22
        $app->post('/{shift}/Actions/GenerateGroupLink', array($this, 'generateGroupLink'));
23
        $app->post('/{shift}/Actions/EmptyShift[/]', array($this, 'emptyShift'));
24
        $app->post('/{shift}/Actions/ForceShiftEmpty[/]', array($this, 'forceEmpty'));
25
    }
26
27
    protected function canCreate($request)
28
    {
29
        //Check is handled by validateCreate...
30
        return true;
31
    }
32
33
    protected function canUpdate($request, $entity)
34
    {
35
        if($this->isVolunteerAdmin($request))
36
        {
37
            return true;
38
        }
39
        return $this->isUserDepartmentLead($entity['departmentID'], $this->user);
40
    }
41
42
    protected function canDelete($request, $entity)
43
    {
44
        return $this->canUpdate($request, $entity);
45
    }
46
47
    protected function validateCreate(&$obj, $request)
48
    {
49
        if($this->isVolunteerAdmin($request))
50
        {
51
            return true;
52
        }
53
        if(!isset($obj['departmentID']))
54
        {
55
             return false;
56
        }
57
        if(isset($obj['unbounded']) && $obj['unbounded'])
58
        {
59
            if(!isset($obj['minShifts']) || $obj['minShifts'] === 0 || $obj['minShifts'] === '')
60
            {
61
                 $obj['minShifts'] = '1';
62
            }
63
        }
64
        return $this->isUserDepartmentLead($obj['departmentID'], $this->user);
65
    }
66
67
    protected function processEntry($entry, $request)
68
    {
69
        return $this->processShift($entry, $request);
70
    }
71
72
    protected function postUpdateAction($newObj, $request, $oldObj)
73
    {
74
        $oldShift = new \VolunteerShift(false, $oldObj);
75
        if($oldShift->isFilled() && ($oldObj['startTime'] != $newObj['startTime'] || $oldObj['endTime'] != $newObj['endTime']))
76
        {
77
            $email = new \Emails\ShiftEmail($oldShift, 'shiftChangedSource');
78
            $emailProvider = \EmailProvider::getInstance();
79
            if($emailProvider->sendEmail($email) === false)
80
            {
81
                throw new \Exception('Unable to send email!');
82
            }
83
        }
84
        return true;
85
    }
86
87
    protected function postDeleteAction($entry)
88
    {
89
        if(empty($entry))
90
        {
91
            return true;
92
        }
93
        $shift = new \VolunteerShift(false, $entry[0]);
94
        if($shift->isFilled())
95
        {
96
            $email = new \Emails\ShiftEmail($shift, 'shiftCanceledSource');
97
            $emailProvider = \EmailProvider::getInstance();
98
            if($emailProvider->sendEmail($email) === false)
99
            {
100
                throw new \Exception('Unable to send email!');
101
            } 
102
        }
103
        return true;
104
    }
105
106
    protected function genUUID()
107
    {
108
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
109
            // 32 bits for "time_low"
110
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
111
112
            // 16 bits for "time_mid"
113
            mt_rand(0, 0xffff),
114
115
            // 16 bits for "time_hi_and_version",
116
            // four most significant bits holds version number 4
117
            mt_rand(0, 0x0fff) | 0x4000,
118
119
            // 16 bits, 8 bits for "clk_seq_hi_res",
120
            // 8 bits for "clk_seq_low",
121
            // two most significant bits holds zero and one for variant DCE1.1
122
            mt_rand(0, 0x3fff) | 0x8000,
123
124
            // 48 bits for "node"
125
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
126
        );
127
    }
128
129
    public function createGroup($request, $response)
130
    {
131
        $array = $request->getParsedBody();
132
        $count = count($array);
133
        $entArray = array();
134
        $uuid = $this->genUUID();
135
        $dataTable = $this->getDataTable();
136
        //User must be able to edit all shifts
137
        for($i = 0; $i < $count; $i++)
138
        {
139
            $filter = $this->getFilterForPrimaryKey($array[$i]);
140
            $entity = $dataTable->read($filter);
141
            if($entity === false || !isset($entity[0]))
142
            {
143
                return $response->withStatus(404);
144
            }
145
            $entity = $entity[0];
146
            if(!$this->canUpdate($request, $entity))
147
            {
148
                return $response->withStatus(401);
149
            }
150
            $entity['groupID'] = $uuid;
151
            array_push($entArray, $entity);
152
        }
153
        //If we got here we can update them all
154
        $myRet = true;
155
        $errors = array();
156
        for($i = 0; $i < $count; $i++)
157
        {
158
            $filter = $this->getFilterForPrimaryKey($array[$i]);
159
            $ret = $dataTable->update($filter, $entArray[$i]);
160
            if($ret === false)
161
            {
162
               $myRet = false;
163
               array_push($errors, $array[$i]);
164
            }
165
        }
166
        if($myRet)
0 ignored issues
show
introduced by
The condition $myRet is always true.
Loading history...
167
        {
168
            return $response->withJson($myRet);
169
        }
170
        else
171
        {
172
            return $response->withJson(array('res'=>$myRet, 'errors'=>$errors));
173
        }
174
    }
175
176
    public function newGroup($request, $response)
177
    {
178
        if(!$this->canCreate($request))
179
        {
180
            return $response->withStatus(401);
181
        }
182
        $data = $request->getParsedBody();
183
        $shift = array();
184
        $shift['groupID'] = $this->genUUID();
185
        $shift['departmentID'] = $data['groupDepartmentID'];
186
        $shift['earlyLate'] = $data['groupEarlyLate'];
187
        $shift['enabled'] = $data['groupEnabled'];
188
        $shift['endTime'] = $data['groupEndTime'];
189
        $shift['eventID'] = $data['groupEvent'];
190
        $shift['name'] = $data['groupName'];
191
        $shift['startTime'] = $data['groupStartTime'];
192
        $dataTable = $this->getDataTable();
193
        $ret = true;
194
        foreach($data['roles'] as $role=>$count)
195
        {
196
            $count = intval($count);
197
            for($i = 0; $i < $count; $i++)
198
            {
199
                $shift['roleID'] = $role;
200
                if($dataTable->create($shift) === false)
201
                {
202
                    $ret = false;
203
                }
204
            }
205
        }
206
        return $response->withJSON($ret);
207
    }
208
209
    public function deleteGroup($request, $response)
210
    {
211
        $data = $request->getParsedBody();
212
        $dataTable = $this->getDataTable();
213
        $filter = new \Data\Filter('groupID eq '.$data['groupID']);
214
        $entities = $dataTable->read($filter);
215
        if(empty($entities))
216
        {
217
            return $response->withStatus(404);
218
        }
219
        if(!$this->canUpdate($request, $entities[0]))
220
        {
221
            return $response->withStatus(401);
222
        }
223
        $res = $dataTable->delete($filter);
224
        if($res)
225
        {
226
            return $response->withJSON($res);
227
        }
228
        return $response->withJSON($res, 500);
229
    }
230
231
    protected function doSignup($uid, $status, $entity, $filter, $dataTable)
232
    {
233
        if(isset($entity['earlyLate']) && $entity['earlyLate'] !== '-1')
234
        {
235
            $event = new \VolunteerEvent($entity['eventID']);
236
            if(!$event->hasVolOnEEList($uid, intval($entity['earlyLate'])))
237
            {
238
                $status = 'pending';
239
                $entity['needEEApproval'] = true;
240
                $event->addToEEList($uid, intval($entity['earlyLate']));
241
            }
242
        }
243
        $entity['participant'] = $uid;
244
        $entity['status'] = $status;
245
        return $dataTable->update($filter, $entity);
246
    }
247
248
    public function signup($request, $response, $args)
249
    {
250
        $this->validateLoggedIn($request);
251
        $shiftId = $args['shift'];
252
        $dataTable = $this->getDataTable();
253
        $filter = $this->getFilterForPrimaryKey($shiftId);
254
        $entity = $dataTable->read($filter);
255
        if(empty($entity))
256
        {
257
            return $response->withStatus(404);
258
        }
259
        $entity = $entity[0];
260
        if(isset($entity['participant']) && strlen($entity['participant']) > 0)
261
        {
262
            return $response->withStatus(401);
263
        }
264
        $shift = new \VolunteerShift($shiftId, $entity);
265
        $entity = $this->processShift($entity, $request);
266
        if(isset($entity['minShifts']) && $entity['minShifts'] > 0)
267
        {
268
          $shift->makeCopy($dataTable);
269
        }
270
        if(isset($entity['overlap']) && $entity['overlap'])
271
        {
272
            $overlaps = $shift->findOverlaps($this->user->uid);
273
            $count = count($overlaps);
0 ignored issues
show
Bug introduced by
It seems like $overlaps can also be of type true; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

273
            $count = count(/** @scrutinizer ignore-type */ $overlaps);
Loading history...
274
            $leads = array();
275
            for($i = 0; $i < $count; $i++)
276
            {
277
                $dept = new \VolunteerDepartment($overlaps[$i]->departmentID);
278
                $leads = array_merge($leads, $dept->getLeadEmails());
279
                $overlaps[$i]->status = 'pending';
280
                $tmp = new \Data\Filter('_id eq '.$overlaps[$i]->{'_id'});
281
                $res = $dataTable->update($tmp, $overlaps[$i]);
282
                if($res === false)
283
                {
284
                    return $response->withJSON(array('err'=>'Unable to update overlap with id '.$overlaps[$i]->{'_id'}));
285
                }
286
            }
287
            $dept = new \VolunteerDepartment($entity['departmentID']);
288
            $leads = array_merge($leads, $dept->getLeadEmails());
289
            $leads = array_unique($leads);
290
            $ret = $this->doSignup($this->user->uid, 'pending', $entity, $filter, $dataTable);
291
            $profile = new \VolunteerProfile($this->user->uid);
292
            $email = new \Emails\TwoShiftsAtOnceEmail($profile);
293
            $email->addLeads($leads);
294
            $emailProvider = \EmailProvider::getInstance();
295
            if($emailProvider->sendEmail($email) === false)
296
            {
297
                throw new \Exception('Unable to send duplicate email!');
298
            }
299
            return $response->withJSON($ret);
300
        }
301
        if(isset($entity['available']) && $entity['available'])
302
        {
303
            $ret = $this->doSignup($this->user->uid, 'filled', $entity, $filter, $dataTable);
304
            return $response->withJSON($ret);
305
        }
306
        if(isset($entity['status']) && $entity['status'] === 'groupPending')
307
        {
308
            $ret = $this->doSignup($this->user->uid, 'filled', $entity, $filter, $dataTable);
309
            return $response->withJSON($ret);
310
        }
311
        print_r($entity); die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
312
    }
313
314
    public function abandon($request, $response, $args)
315
    {
316
        $this->validateLoggedIn($request);
317
        $shiftId = $args['shift'];
318
        $dataTable = $this->getDataTable();
319
        $filter = $this->getFilterForPrimaryKey($shiftId);
320
        $entity = $dataTable->read($filter);
321
        if(empty($entity))
322
        {
323
            return $response->withStatus(404);
324
        }
325
        $entity = $entity[0];
326
        if(!isset($entity['participant']) || $entity['participant'] !== $this->user->uid)
327
        {
328
            return $response->withStatus(401);
329
        }
330
        $entity['participant'] = '';
331
        $entity['status'] = 'unfilled';
332
        if(isset($entity['needEEApproval']))
333
        {
334
          unset($entity['needEEApproval']);
335
        }
336
        return $response->withJSON($dataTable->update($filter, $entity));
337
    }
338
339
    public function approvePending($request, $response, $args)
340
    {
341
        if(!$this->canCreate($request))
342
        {
343
            return $response->withStatus(401);
344
        }
345
        $shiftId = $args['shift'];
346
        $dataTable = $this->getDataTable();
347
        $filter = $this->getFilterForPrimaryKey($shiftId);
348
        $entity = $dataTable->read($filter);
349
        if(empty($entity))
350
        {
351
            return $response->withStatus(404);
352
        }
353
        $entity = $entity[0];
354
        $entity['status'] = 'filled';
355
        return $response->withJSON($dataTable->update($filter, $entity));
356
    }
357
358
    public function disapprovePending($request, $response, $args)
359
    {
360
        if(!$this->canCreate($request))
361
        {
362
            return $response->withStatus(401);
363
        }
364
        $shiftId = $args['shift'];
365
        $dataTable = $this->getDataTable();
366
        $filter = $this->getFilterForPrimaryKey($shiftId);
367
        $entity = $dataTable->read($filter);
368
        if(empty($entity))
369
        {
370
            return $response->withStatus(404);
371
        }
372
        $entity['participant'] = '';
373
        $entity['status'] = 'unfilled';
374
        $profile = new \VolunteerProfile($this->user->uid);
375
        $email = new \Emails\PendingRejectedEmail($profile);
376
        $email->setShift($entity);
377
        $emailProvider = \EmailProvider::getInstance();
378
        if($emailProvider->sendEmail($email) === false)
379
        {
380
            throw new \Exception('Unable to send duplicate email!');
381
        }
382
        return $response->withJSON($dataTable->update($filter, $entity));
383
    }
384
385
    public function startGroupSignup($request, $response, $args)
386
    {
387
        $this->validateLoggedIn($request);
388
        $shiftId = $args['shift'];
389
        $dataTable = $this->getDataTable();
390
        $filter = $this->getFilterForPrimaryKey($shiftId);
391
        $entity = $dataTable->read($filter);
392
        if(empty($entity))
393
        {
394
            return $response->withStatus(404);
395
        }
396
        $entity = $entity[0];
397
        if(isset($entity['participant']) && strlen($entity['participant']) > 0)
398
        {
399
            return $response->withStatus(401);
400
        }
401
        $filter = new \Data\Filter('groupID eq '.$entity['groupID'].' and enabled eq true');
402
        $entities = $dataTable->read($filter);
403
        $count = count($entities);
0 ignored issues
show
Bug introduced by
It seems like $entities can also be of type boolean; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

403
        $count = count(/** @scrutinizer ignore-type */ $entities);
Loading history...
404
        $dept = new \VolunteerDepartment($entity['departmentID']);
405
        $res = array();
406
        $res['department'] = $dept->departmentName;
0 ignored issues
show
Bug Best Practice introduced by
The property departmentName does not exist on VolunteerDepartment. Since you implemented __get, consider adding a @property annotation.
Loading history...
407
        $res['earlyLate'] = $entity['earlyLate'];
408
        $res['endTime'] = $entity['endTime'];
409
        $res['eventID'] = $entity['eventID'];
410
        $res['name'] = $entity['name'];
411
        $res['startTime'] = $entity['startTime'];
412
        $res['groupID'] = $entity['groupID'];
413
        $res['shifts'] = array();
414
        $roles = array();
415
        for($i = 0; $i < $count; $i++)
416
        {
417
            if(isset($entities[$i]['status']) && ($entities[$i]['status'] === 'filled' || $entities[$i]['status'] === 'pending'))
418
            {
419
                continue;
420
            }
421
            if(!isset($roles[$entities[$i]['roleID']]))
422
            {
423
                $roles[$entities[$i]['roleID']] = new \VolunteerRole($entities[$i]['roleID']);
424
            }
425
            $role = $roles[$entities[$i]['roleID']];
426
            $entities[$i]['role'] = $role->display_name;
427
            array_push($res['shifts'], $entities[$i]);
428
        }
429
        return $response->withJSON($res);
430
    }
431
432
    public function generateGroupLink($request, $response, $args)
433
    {
434
        $this->validateLoggedIn($request);
435
        $shiftId = $args['shift'];
436
        $dataTable = $this->getDataTable();
437
        $filter = $this->getFilterForPrimaryKey($shiftId);
438
        $entity = $dataTable->read($filter);
439
        if(empty($entity))
440
        {
441
            return $response->withStatus(404);
442
        }
443
        $entity = $entity[0];
444
        if(isset($entity['participant']) && strlen($entity['participant']) > 0)
445
        {
446
            return $response->withStatus(401);
447
        }
448
        $data = $request->getParsedBody();
449
        $myShift = $data['myshift'];
450
        $roles = array();
451
        foreach($data as $key => $value)
452
        {
453
            if(substr($key, 0, 6) === "roles.")
454
            {
455
                $roles[substr($key, 6)] = $value;
456
            }
457
        }
458
        $filter = new \Data\Filter('groupID eq '.$entity['groupID'].' and enabled eq true');
459
        $entities = $dataTable->read($filter);
460
        $count = count($entities);
0 ignored issues
show
Bug introduced by
It seems like $entities can also be of type boolean; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

460
        $count = count(/** @scrutinizer ignore-type */ $entities);
Loading history...
461
        $uuid = $this->genUUID();
462
        for($i = 0; $i < $count; $i++)
463
        {
464
            if(isset($entities[$i]['status']) && ($entities[$i]['status'] === 'filled' || $entities[$i]['status'] === 'pending'))
465
            {
466
                $entities[$i] = false;
467
                continue;
468
            }
469
            if((string)$entities[$i]['_id'] === (string)new \MongoDB\BSON\ObjectId($myShift))
470
            {
471
                $entities[$i]['participant'] = $this->user->uid;
472
                $entities[$i]['status'] = 'filled';
473
                $entities[$i]['signupLink'] = $uuid;
474
            }
475
            else if(isset($roles[$entities[$i]['roleID']]))
476
            {
477
                $entities[$i]['status'] = 'groupPending';
478
                $entities[$i]['signupLink'] = $uuid;
479
                $roles[$entities[$i]['roleID']]--;
480
                if($roles[$entities[$i]['roleID']] === 0)
481
                {
482
                    unset($roles[$entities[$i]['roleID']]);
483
                }
484
            }
485
            else
486
            {
487
                $entities[$i] = false;
488
            }
489
        }
490
        if(count($roles) !== 0)
491
        {
492
            throw new \Exception('Not enough shifts to fullfill requests');
493
        }
494
        for($i = 0; $i < $count; $i++)
495
        {
496
            if($entities[$i] === false)
497
            {
498
                continue;
499
            }
500
            $filter = new \Data\Filter('_id eq '.$entities[$i]['_id']);
501
            $res = $dataTable->update($filter, $entities[$i]);
502
            if($res === false)
503
            {
504
                throw new \Exception('Not able to save shift '.$entities[$i]['_id']);
505
            }
506
        }
507
        return $response->withJSON(array('uuid' => $uuid));
508
    }
509
510
    function emptyShift($request, $response, $args)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
511
    {
512
        $this->validateLoggedIn($request);
513
        $shiftId = $args['shift'];
514
        $dataTable = $this->getDataTable();
515
        $filter = $this->getFilterForPrimaryKey($shiftId);
516
        $entity = $dataTable->read($filter);
517
        if(empty($entity))
518
        {
519
            return $response->withStatus(404);
520
        }
521
        $entity = $entity[0];
522
        if(!$this->canUpdate($request, $entity))
523
        {
524
            return $response->withStatus(401);
525
        }
526
        $shift = new \VolunteerShift(false, $entity);
527
        $entity['participant'] = '';
528
        $entity['status'] = 'unfilled';
529
        if(isset($entity['needEEApproval']))
530
        {
531
          unset($entity['needEEApproval']);
532
        }
533
        $ret = $dataTable->update($filter, $entity);
534
        if($ret)
535
        {
536
            $email = new \Emails\ShiftEmail($shift, 'shiftEmptiedSource');
537
            $emailProvider = \EmailProvider::getInstance();
538
            if($emailProvider->sendEmail($email) === false)
539
            {
540
                throw new \Exception('Unable to send email!');
541
            }
542
        }
543
        return $response->withJSON($ret);
544
    }
545
546
    function forceEmpty($request, $response, $args)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
547
    {
548
        $this->validateLoggedIn($request);
549
        $shiftId = $args['shift'];
550
        $dataTable = $this->getDataTable();
551
        $filter = $this->getFilterForPrimaryKey($shiftId);
552
        $entity = $dataTable->read($filter);
553
        if(empty($entity))
554
        {
555
            return $response->withStatus(404);
556
        }
557
        $entity = $entity[0];
558
        if(!$this->canUpdate($request, $entity))
559
        {
560
            return $response->withStatus(401);
561
        }
562
        $entity['participant'] = '';
563
        $entity['status'] = 'unfilled';
564
        if(isset($entity['needEEApproval']))
565
        {
566
          unset($entity['needEEApproval']);
567
        }
568
        return $response->withJSON($dataTable->update($filter, $entity));
569
    }
570
}
571
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
572