Completed
Push — master ( e47c19...3aaaf2 )
by Anton
15s queued 13s
created

Auth   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 94.12%

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 58
ccs 16
cts 17
cp 0.9412
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setIdentity() 0 12 2
A clearIdentity() 0 5 1
A getIdentity() 0 11 3
1
<?php
2
3
/**
4
 * Bluz Framework Component
5
 *
6
 * @copyright Bluz PHP Team
7
 * @link      https://github.com/bluzphp/framework
8
 */
9
10
declare(strict_types=1);
11
12
namespace Bluz\Auth;
13
14
use Bluz\Common\Options;
15
use Bluz\Proxy\Request;
16
use Bluz\Proxy\Session;
17
18
/**
19
 * Auth class
20
 *
21
 * @package  Bluz\Auth
22
 * @author   Anton Shevchuk
23
 * @link     https://github.com/bluzphp/framework/wiki/Auth
24
 */
25
class Auth
26
{
27
    use Options;
28
29
    /**
30
     * @var IdentityInterface Instance of EntityInterface
31
     */
32
    protected $identity;
33
34
    /**
35
     * Setup identity
36
     *
37
     * @param  IdentityInterface $identity
38
     *
39
     * @return void
40
     */
41 3
    public function setIdentity(IdentityInterface $identity): void
42
    {
43
        // save identity to Auth
44 3
        $this->identity = $identity;
45
        // regenerate session
46 3
        if (PHP_SAPI !== 'cli') {
47
            Session::regenerateId();
48
        }
49
        // save identity to session
50 3
        Session::set('auth:identity', $identity);
51
        // save user agent to session
52 3
        Session::set('auth:agent', Request::getServer('HTTP_USER_AGENT'));
53 3
    }
54
55
    /**
56
     * Return identity if user agent is correct
57
     *
58
     * @return IdentityInterface|null
59
     */
60 9
    public function getIdentity(): ?IdentityInterface
61
    {
62 9
        if (!$this->identity) {
63
            // check user agent
64 6
            if (Session::get('auth:agent') === Request::getServer('HTTP_USER_AGENT')) {
65 5
                $this->identity = Session::get('auth:identity');
66
            } else {
67 1
                $this->clearIdentity();
68
            }
69
        }
70 9
        return $this->identity;
71
    }
72
73
    /**
74
     * Clear identity and user agent information
75
     *
76
     * @return void
77
     */
78 2
    public function clearIdentity(): void
79
    {
80 2
        $this->identity = null;
81 2
        Session::delete('auth:identity');
82 2
        Session::delete('auth:agent');
83 2
    }
84
}
85