Passed
Pull Request — master (#190)
by Arman
03:14
created

NativeSessionAdapter::initializeSession()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 20
rs 9.2222
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.5
13
 */
14
15
namespace Quantum\Libraries\Session\Adapters\Native;
16
17
use Quantum\Libraries\Session\Contracts\SessionStorageInterface;
18
use Quantum\Libraries\Session\Exceptions\SessionException;
19
use Quantum\Libraries\Session\Traits\SessionTrait;
20
21
/**
22
 * Class Session
23
 * @package Quantum\Libraries\Session
24
 */
25
class NativeSessionAdapter implements SessionStorageInterface
26
{
27
28
    use SessionTrait;
29
30
    /**
31
     * Session default timeout
32
     */
33
    const SESSION_TIMEOUT = 30 * 60;
34
35
    /**
36
     * Session params
37
     * @var array
38
     */
39
    private static $params = [];
40
41
    /**
42
     * Session storage
43
     * @var array $storage
44
     */
45
    private static $storage = [];
46
47
    /**
48
     * @param array|null $params
49
     * @throws SessionException
50
     */
51
    public function __construct(?array $params = null)
52
    {
53
        $this->initializeSession($params);
54
    }
55
56
    /**
57
     * @param array|null $params
58
     * @return void
59
     * @throws SessionException
60
     */
61
    protected function initializeSession(?array $params = null): void
62
    {
63
        $timeout = $params['timeout'] ?? self::SESSION_TIMEOUT;
64
65
        if (session_status() !== PHP_SESSION_ACTIVE) {
66
            if (@session_start() === false) {
67
                throw SessionException::sessionNotStarted();
68
            }
69
        }
70
71
        if (isset($_SESSION['LAST_ACTIVITY']) && time() - $_SESSION['LAST_ACTIVITY'] > $timeout) {
72
            if (@session_destroy() === false) {
73
                throw SessionException::sessionNotDestroyed();
74
            }
75
        }
76
77
        $_SESSION['LAST_ACTIVITY'] = time();
78
79
        self::$params = $params;
80
        self::$storage = &$_SESSION;
81
    }
82
}