Test Failed
Push — dev ( fdf488...077c6d )
by Janko
14:47
created

SessionDestruction::destroySession()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 10
nop 2
dl 0
loc 18
rs 9.6111
1
<?php
2
3
namespace Stu\Lib\Session;
4
5
use RuntimeException;
6
use Stu\Orm\Entity\UserInterface;
7
use Stu\Orm\Repository\SessionStringRepositoryInterface;
8
9
final class SessionDestruction implements SessionDestructionInterface
10
{
11
    public function __construct(
12
        private SessionStringRepositoryInterface $sessionStringRepository
13
    ) {}
14
15
    public function destroySession(SessionInterface $session, ?UserInterface $user = null): void
16
    {
17
        $userToTruncate = $user ?? $session->getUser();
18
        if ($userToTruncate !== null) {
19
            $this->sessionStringRepository->truncate($userToTruncate);
20
        }
21
22
        if ($user === null) {
23
            $this->destroyLoginCookies();
24
            $sessionName = session_name();
25
            if ($sessionName) {
26
                setcookie($sessionName, '', ['expires' => time() - 42000]);
27
            }
28
            if (@session_destroy() === false) {
29
                throw new RuntimeException('The session could not be destroyed');
30
            }
31
32
            $session->setUser(null);
33
        }
34
    }
35
36
    private function destroyLoginCookies(): void
37
    {
38
        setcookie('sstr');
39
    }
40
}
41