Completed
Push — master ( 2a7201...61de25 )
by Jonathan
02:25
created

Auth::logout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
namespace Golem\Auth;
3
4
use Golem\Auth\Storage\StorageInterface;
5
6
class Auth implements AuthInterface
7
{
8
    /**
9
     * @var StorageInterface
10
     */
11
    private $storage;
12
13
    /**
14
     * @var string|int|null
15
     */
16
    private $id;
17
18
    /**
19
     * @var Authenticatable|null
20
     */
21
    private $user;
22
23
    /**
24
     * @var UserRepository
25
     */
26
    private $repository;
27
28
    /**
29
     * Auth constructor.
30
     * @param StorageInterface $storage
31
     * @param UserRepository $repository
32
     */
33 7
    public function __construct(StorageInterface $storage, UserRepository $repository)
34
    {
35 7
        $this->storage = $storage;
36 7
        $this->repository = $repository;
37 7
    }
38
39
    /**
40
     * @return bool
41
     */
42 7
    public function loggedIn()
43
    {
44 7
        if ($this->id === null) {
45 6
            $this->id = -1;
46 6
            if ($this->storage->exists()) {
47 3
                $this->id = $this->storage->read();
48
            }
49
        }
50 7
        return $this->id != -1;
51
    }
52
53
    /**
54
     * @return Authenticatable|null
55
     * @throws \RuntimeException
56
     */
57 3
    public function user()
58
    {
59 3
        if ($this->user === null && $this->loggedIn()) {
60 2
            $this->user = $this->repository->findUserById($this->id);
61
        }
62 2
        return $this->user;
63
    }
64
65
    /**
66
     * @return int|string|null
67
     */
68 2
    public function getUserId()
69
    {
70 2
        if (!$this->loggedIn()) {
71 1
            return null;
72
        }
73 1
        return $this->id;
74
    }
75
76
    /**
77
     * @param Authenticatable $user
78
     */
79 2
    public function login(Authenticatable $user)
80
    {
81 2
        $this->storage->store($user->getAuthId());
82 2
        $this->user = $user;
83 2
        $this->id = $user->getAuthId();
84 2
    }
85
86
    /**
87
     * Logs out user
88
     */
89 1
    public function logout()
90
    {
91 1
        $this->storage->clear();
92 1
        $this->user = null;
93 1
        $this->id = -1;
94 1
    }
95
}
96