OverrideCreate.php 2.22 KB
Newer Older
1
2
3
4
5
6
7
<?php

namespace Source\UseCases\Overrides\OverrideCreate;

use Carbon\Carbon;
use Source\Sanitize\CastsTo;
use InvalidArgumentException;
Jacob Priddy's avatar
Jacob Priddy committed
8
use Source\Entities\Override;
9
use Source\Gateways\Doors\DoorsRepository;
Jacob Priddy's avatar
Jacob Priddy committed
10
use Source\Gateways\Users\UsersRepository;
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use Source\Gateways\Overrides\OverridesRepository;

class OverrideCreate implements OverrideCreateUseCase
{
    use CastsTo;

    /**
     * @var \Source\Gateways\Overrides\OverridesRepository
     */
    protected OverridesRepository $overrides;

    /**
     * @var \Source\Gateways\Users\UsersRepository
     */
    protected UsersRepository $users;

    /**
     * @var \Source\Gateways\Doors\DoorsRepository
     */
    protected DoorsRepository $doors;

    public function __construct(OverridesRepository $overrides, UsersRepository $users, DoorsRepository $doors)
    {
        $this->overrides = $overrides;
        $this->users = $users;
        $this->doors = $doors;
    }

    /**
     * @inheritDoc
     */
    public function create(array $attributes, Presenter $presenter): void
    {
        $response = new ResponseModel();
45
46
        $userId = self::castToInt($attributes['user_id']);
        $doorId = self::castToInt($attributes['door_id']);
47
48
49
50
51
52
53
54
55

        if (!$this->users->get($userId)) {
            $response->addError('User does not exist!');
        }

        if (!$this->doors->get($doorId)) {
            $response->addError('Door does not exist!');
        }

Jacob Priddy's avatar
Jacob Priddy committed
56
57
58
59
60
61
62
63
64
65
66
67
68
        if (!$response->hasError()) {
            try {
                $override = $this->overrides->addOverride(
                    new Override(
                        0,
                        $attributes['reason'],
                        $userId,
                        $doorId,
                        $attributes['type'],
                        new Carbon($attributes['start']),
                        new Carbon($attributes['end'])
                    )
                );
69

Jacob Priddy's avatar
Jacob Priddy committed
70
                $response->setOverride($override);
Jacob Priddy's avatar
Jacob Priddy committed
71
72
            } catch (InvalidArgumentException $e) {
                $response->addError($e->getMessage());
73
74
75
76
77
78
79
80
81
82
            }
        }

        if ($response->hasError()) {
            $presenter->presentError($response);
        } else {
            $presenter->present($response);
        }
    }
}