Passed
Push — master ( a6375b...78beea )
by Anton
05:54
created

Auth::clearIdentity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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