GlobalSession::resume()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 13
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\SSO\Server;
6
7
/**
8
 * Interact with the global session using PHP's session_* functions.
9
 *
10
 * @codeCoverageIgnore
11
 */
12
class GlobalSession implements SessionInterface
13
{
14
    /**
15
     * Options passed to session_start().
16
     * @var array<string,mixed>
17
     */
18
    protected $options;
19
20
    /**
21
     * Class constructor.
22
     *
23
     * @param array<string,mixed> $options  Options passed to session_start().
24
     */
25
    public function __construct(array $options = [])
26
    {
27
        $this->options = $options + ['cookie_samesite' => 'None', 'cookie_secure' => true];
28
    }
29
30
    /**
31
     * @inheritDoc
32
     */
33
    public function getId(): string
34
    {
35
        return session_id();
0 ignored issues
show
introduced by
Method Jasny\SSO\Server\GlobalSession::getId() should return string but returns string|false.
Loading history...
36
    }
37
38
    /**
39
     * @inheritDoc
40
     */
41
    public function start(): void
42
    {
43
        $started = session_status() !== PHP_SESSION_ACTIVE
44
            ? session_start($this->options)
45
            : true;
46
47
        if (!$started) {
48
            $err = error_get_last() ?? ['message' => 'Failed to start session'];
49
            throw new ServerException($err['message'], 500);
50
        }
51
52
        // Session shouldn't be empty when resumed.
53
        $_SESSION['_sso_init'] = 1;
54
    }
55
56
    /**
57
     * @inheritDoc
58
     */
59
    public function resume(string $id): void
60
    {
61
        session_id($id);
62
        $started = session_start($this->options);
63
64
        if (!$started) {
65
            $err = error_get_last() ?? ['message' => 'Failed to start session'];
66
            throw new ServerException($err['message'], 500);
67
        }
68
69
        if ($_SESSION === []) {
70
            session_abort();
71
            throw new BrokerException("Session has expired. Client must attach with new token.", 401);
72
        }
73
    }
74
75
    /**
76
     * @inheritDoc
77
     */
78
    public function isActive(): bool
79
    {
80
        return session_status() === PHP_SESSION_ACTIVE;
81
    }
82
}
83