DatabaseTokensRepository.php 1.38 KB
Newer Older
Jacob Priddy's avatar
Jacob Priddy committed
1
2
3
4
5
6
7
<?php


namespace Source\Gateways\Tokens;


use App\User;
Jacob Priddy's avatar
Jacob Priddy committed
8
use Carbon\Carbon;
Jacob Priddy's avatar
Jacob Priddy committed
9
use Source\Entities\Token;
Jacob Priddy's avatar
Jacob Priddy committed
10
use Basho\Riak\Node\Builder;
Jacob Priddy's avatar
Jacob Priddy committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use Source\Exceptions\EntityNotFoundException;

class DatabaseTokensRepository implements TokensRepository {
    /**
     * @inheritDoc
     */
    public function create(Token $token): Token {
        $user = User::find($token->getUserId());

        if (!$user) {
            throw new EntityNotFoundException('Cannot create token for non existent user');
        }

        return $user->tokens()->create(
            [
Jacob Priddy's avatar
Jacob Priddy committed
26
27
                'name'       => $token->getName(),
                'api_token'  => $token->getTokenString(),
Jacob Priddy's avatar
Jacob Priddy committed
28
29
30
31
32
33
34
35
                'expires_at' => $token->getExpiresAt(),
            ]
        );
    }

    /**
     * @inheritDoc
     */
Jacob Priddy's avatar
Jacob Priddy committed
36
37
38
39
40
41
    public function findValidToken(string $token): ?Token {
        $found = \App\Token::where('api_token', $token)->andWhere('expired_at', '<', Carbon::now())->orWhere(
            static function (Builder $query) use ($token) {
                $query->where('api_token', $token)->andWhere('expired_at', null);
            }
        )->first();
Jacob Priddy's avatar
Jacob Priddy committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

        if (!$found) {
            return null;
        }

        return new Token(
            $found->id,
            $found->user_id,
            $found->name,
            $found->expires_at,
            $found->created_at,
            $found->updated_at
        );
    }
}