CreateShift::__invoke()   B
last analyzed

Complexity

Conditions 6
Paths 10

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 8.6737
c 0
b 0
f 0
cc 6
nc 10
nop 4
1
<?php
2
3
namespace Scheduler\Application\Service;
4
5
use DateTime;
6
use Aura\Payload\Payload;
7
use Scheduler\Domain\Model\Shift\Shift;
8
use Scheduler\Domain\Model\Shift\ShiftMapper;
9
use Scheduler\Domain\Model\User\NullUser;
10
11
class CreateShift
12
{
13
    const INVALID_DATE_MESSAGE = "must be a valid string representation of a date";
14
15
    private $payload;
16
    private $shiftMapper;
17
18
    public function __construct(ShiftMapper $shiftMapper)
19
    {
20
        $this->payload = new Payload();
21
        $this->shiftMapper = $shiftMapper;
22
    }
23
24
    public function __invoke($currentUser, $start, $end, $break)
25
    {
26
        if (! $currentUser->isAuthenticated()) {
27
            return $this->payload->setStatus(Payload::NOT_AUTHENTICATED);
28
        }
29
30
        if ($currentUser->getRole() !== "manager") {
31
            return $this->payload->setStatus(Payload::NOT_AUTHORIZED);
32
        }
33
34
        $invalid = [];
35
        try {
36
            $start = new DateTime($start);
37
        } catch (\Exception $e) {
38
            $invalid["start"] = self::INVALID_DATE_MESSAGE;
39
        }
40
41
        try {
42
            $end = new DateTime($end);
43
        } catch (\Exception $e) {
44
            $invalid["end"] = self::INVALID_DATE_MESSAGE;
45
        }
46
47
        if (count($invalid)) {
48
            return $this->payload->setStatus(Payload::NOT_VALID)
49
                                 ->setMessages($invalid);
50
        }
51
52
        $employee = new NullUser();
53
        $break = (float) $break;
54
55
        $shift = new Shift(null, $currentUser, $employee, $break, $start, $end);
56
        $this->shiftMapper->insert($shift);
57
58
        $this->payload->setStatus(Payload::CREATED);
59
        $this->payload->setOutput($shift);
60
61
        return $this->payload;
62
    }
63
}
64