AttributesBagMethods   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 15
c 0
b 0
f 0
dl 0
loc 57
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A withAttributes() 0 11 3
A hasAttribute() 0 3 1
A attribute() 0 7 2
A attributes() 0 3 1
A withAttribute() 0 4 1
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\Common;
13
14
use Slick\WebStack\Domain\Security\Exception\MissingAttributeException;
15
use Traversable;
16
17
/**
18
 * AttributesBagMethods
19
 *
20
 * @package Slick\WebStack\Domain\Security\Common
21
 */
22
trait AttributesBagMethods
23
{
24
25
    /** @var array<string, mixed>  */
26
    protected array $attributes = [];
27
28
    /**
29
     * @inheritDoc
30
     */
31
    public function attributes(): iterable
32
    {
33
        return $this->attributes;
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    public function withAttributes(iterable $attributes): static
40
    {
41
        if ($attributes instanceof Traversable) {
42
            foreach ($attributes as $name => $value) {
43
                $this->withAttribute($name, $value);
44
            }
45
            return $this;
46
        }
47
48
        $this->attributes = (array) $attributes;
49
        return $this;
50
    }
51
52
    /**
53
     * @inheritDoc
54
     */
55
    public function hasAttribute(string $name): bool
56
    {
57
        return array_key_exists($name, $this->attributes);
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function attribute(string $name): mixed
64
    {
65
        if (!$this->hasAttribute($name)) {
66
            throw new MissingAttributeException("There are no attribute '$name' in class ".__CLASS__);
67
        }
68
69
        return $this->attributes[$name];
70
    }
71
72
    /**
73
     * @inheritDoc
74
     */
75
    public function withAttribute(string $name, mixed $value): self
76
    {
77
        $this->attributes[$name] = $value;
78
        return $this;
79
    }
80
}
81