AbstractToken::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * This file is part of web-stack
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Slick\WebStack\Domain\Security\Authentication\Token;
13
14
use Slick\WebStack\Domain\Security\Authentication\TokenInterface;
15
use Slick\WebStack\Domain\Security\Common\AttributesBagMethods;
16
use Slick\WebStack\Domain\Security\UserInterface;
17
18
/**
19
 * AbstractToken
20
 *
21
 * @package Slick\WebStack\Domain\Security\Authentication\Token
22
 * @implements TokenInterface<UserInterface>
23
 */
24
abstract class AbstractToken implements TokenInterface
25
{
26
    use AttributesBagMethods;
27
28
    /** @var array<string> */
29
    protected array $roleNames = [];
30
31
    /** @phpstan-var UserInterface|null  */
32
    protected ?UserInterface $user = null;
33
34
    /**
35
     * Creates an AbstractToken
36
     *
37
     * @param array<string|\Stringable> $roles
38
     */
39
    public function __construct(array $roles = [])
40
    {
41
        foreach ($roles as $role) {
42
            $this->roleNames[] = (string) $role;
43
        }
44
    }
45
46
    /**
47
     * @inheritDoc
48
     */
49
    public function __toString(): string
50
    {
51
        $class = static::class;
52
        $class = substr($class, strrpos($class, '\\') + 1);
53
        return sprintf(
54
            '%s(user="%s", roles="%s")',
55
            $class,
56
            $this->userIdentifier(),
57
            implode(', ', $this->roleNames)
58
        );
59
    }
60
61
    /**
62
     * @inheritDoc
63
     */
64
    public function userIdentifier(): string
65
    {
66
        return $this->user ? $this->user->userIdentifier() : '';
67
    }
68
69
    /**
70
     * @inheritDoc
71
     */
72
    public function roleNames(): array
73
    {
74
        return $this->roleNames;
75
    }
76
77
    /**
78
     * @inheritDoc
79
     */
80
    public function user(): ?UserInterface
81
    {
82
        return $this->user;
83
    }
84
85
    /**
86
     * @inheritDoc
87
     */
88
    public function __serialize(): array
89
    {
90
        return [
91
            "user" => $this->user,
92
            "roleNames" => $this->roleNames,
93
            "attributes" => $this->attributes
94
        ];
95
    }
96
97
    /**
98
     * @inheritDoc
99
     * @param array<string, mixed> $data
100
     */
101
    public function __unserialize(array $data): void
102
    {
103
        $this->user = $data["user"];
104
        $this->roleNames = $data["roleNames"];
105
        $this->attributes = $data["attributes"];
106
    }
107
}
108