UpdateToken.php 1.39 KB
Newer Older
1
2
3
4
<?php

namespace Source\UseCases\Tokens\UpdateToken;

5
use Carbon\Carbon;
6
7
8
9
10
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
use Source\Entities\Token;
use Source\Sanitize\CastsTo;
use Source\Gateways\Tokens\TokensRepository;
use Source\Exceptions\EntityNotFoundException;

class UpdateToken implements UpdateTokenUseCase
{
    use CastsTo;

    /**
     * @var \Source\Gateways\Tokens\TokensRepository
     */
    protected TokensRepository $tokens;

    public function __construct(TokensRepository $tokens)
    {
        $this->tokens = $tokens;
    }

    /**
     * @inheritDoc
     */
    public function update(string $tokenId, array $attributes, Presenter $presenter): void
    {
        $token = $this->tokens->get($tokenId);

        if (!$token) {
            throw new EntityNotFoundException();
        }

36
37
38
39
40
        $expiresAt = $attributes['expires_at'] ?? null;
        if ($expiresAt) {
            $expiresAt = new Carbon($expiresAt);
        } else {
            $expiresAt = $token->getExpiresAt();
41
42
        }

43
44
45
46
47
        $token = new Token(
            $token->getId(),
            $token->getUserId(),
            $token->getTokenString(),
            $attributes['name'] ?? $token->getName(),
48
            $expiresAt,
49
50
51
52
53
54
55
56
57
58
            $token->getCreatedAt(),
            $token->getUpdatedAt()
        );

        $token = $this->tokens->update($token->getId(), $token);

        $response = new ResponseModel($token);
        $presenter->present($response);
    }
}