CreateUser.php 1.42 KB
Newer Older
Jacob Priddy's avatar
Jacob Priddy committed
1
2
3
4
<?php

namespace Source\UseCases\Users\CreateUser;

Jacob Priddy's avatar
Jacob Priddy committed
5
use Exception;
Jacob Priddy's avatar
Jacob Priddy committed
6
7
8
9
10
use Carbon\Carbon;
use Source\Entities\User;
use Source\Gateways\Users\UsersRepository;
use Source\Exceptions\EntityExistsException;

Jacob Priddy's avatar
Jacob Priddy committed
11
12
class CreateUser implements CreateUserUseCase
{
Jacob Priddy's avatar
Jacob Priddy committed
13
14
15
16
17
    /**
     * @var UsersRepository
     */
    protected UsersRepository $usersRepository;

Jacob Priddy's avatar
Jacob Priddy committed
18
19
    public function __construct(UsersRepository $usersRepository)
    {
Jacob Priddy's avatar
Jacob Priddy committed
20
21
22
23
24
        $this->usersRepository = $usersRepository;
    }

    /**
     * @inheritDoc
Jacob Priddy's avatar
Jacob Priddy committed
25
     * @throws Exception
Jacob Priddy's avatar
Jacob Priddy committed
26
     */
Jacob Priddy's avatar
Jacob Priddy committed
27
28
    public function create(array $attributes, Presenter $presenter): void
    {
Jacob Priddy's avatar
Jacob Priddy committed
29
        $expires = $attributes['expires_at'] ?? null;
Jacob Priddy's avatar
Jacob Priddy committed
30

Jacob Priddy's avatar
Jacob Priddy committed
31
32
33
34
35
        $expires = $expires ? new Carbon($expires) : null;

        $emplid = $attributes['emplid'] ?? null;

        $password = $attributes['password'] ?? '';
Jacob Priddy's avatar
Jacob Priddy committed
36
37
38
39
40
41
42

        // ID, createdAt, and updatedAt will get overwritten
        $user = new User(
            0,
            $attributes['first_name'],
            $attributes['last_name'],
            $attributes['display_name'],
Jacob Priddy's avatar
Jacob Priddy committed
43
            $emplid,
Jacob Priddy's avatar
Jacob Priddy committed
44
            $attributes['email'],
Jacob Priddy's avatar
Jacob Priddy committed
45
            $password,
Jacob Priddy's avatar
Jacob Priddy committed
46
47
48
49
50
51
52
            $attributes['doorcode'],
            $expires,
            null,
            null,
        );


Jacob Priddy's avatar
Jacob Priddy committed
53
        if (!($user = $this->usersRepository->create($user))) {
Jacob Priddy's avatar
Jacob Priddy committed
54
55
56
            throw new EntityExistsException();
        }

Jacob Priddy's avatar
Jacob Priddy committed
57
58
        $response = new ResponseModel($user);

Jacob Priddy's avatar
Jacob Priddy committed
59
60
61
        $presenter->present($response);
    }
}