Passed
Pull Request — master (#1620)
by Tarmo
63:23
created

ApiKey::getRoles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 0
dl 0
loc 14
ccs 9
cts 9
cp 1
crap 1
rs 9.9
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Entity/ApiKey.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Entity;
10
11
use App\Entity\Interfaces\EntityInterface;
12
use App\Entity\Interfaces\UserGroupAwareInterface;
13
use App\Entity\Traits\Blameable;
14
use App\Entity\Traits\Timestampable;
15
use App\Entity\Traits\Uuid;
16
use App\Enum\Role;
17
use Doctrine\Common\Collections\ArrayCollection;
18
use Doctrine\Common\Collections\Collection;
19
use Doctrine\DBAL\Types\Types;
20
use Doctrine\ORM\Mapping as ORM;
21
use OpenApi\Annotations as OA;
22
use Ramsey\Uuid\Doctrine\UuidBinaryOrderedTimeType;
23
use Ramsey\Uuid\UuidInterface;
24
use Symfony\Bridge\Doctrine\Validator\Constraints as AssertCollection;
25
use Symfony\Component\Serializer\Annotation\Groups;
26
use Symfony\Component\String\ByteString;
27
use Symfony\Component\Validator\Constraints as Assert;
28
use Throwable;
29
use function array_map;
30
use function array_merge;
31
use function array_unique;
32
use function array_values;
33
34
/**
35
 * Class ApiKey
36
 *
37
 * @package App\Entity
38
 * @author TLe, Tarmo Leppänen <[email protected]>
39
 */
40
#[ORM\Entity]
41
#[ORM\Table(
42
    name: 'api_key',
43
)]
44
#[ORM\UniqueConstraint(
45
    name: 'uq_token',
46
    columns: [
47
        'token',
48
    ],
49
)]
50
#[ORM\ChangeTrackingPolicy('DEFERRED_EXPLICIT')]
51
#[AssertCollection\UniqueEntity('token')]
52
class ApiKey implements EntityInterface, UserGroupAwareInterface
53
{
54
    use Blameable;
55
    use Timestampable;
56
    use Uuid;
57
58
    /**
59
     * @OA\Property(type="string", format="uuid")
60
     */
61
    #[ORM\Id]
62
    #[ORM\Column(
63
        name: 'id',
64
        type: UuidBinaryOrderedTimeType::NAME,
65
        unique: true,
66
    )]
67
    #[Groups([
68
        'ApiKey',
69
        'ApiKey.id',
70
71
        'LogRequest.apiKey',
72
    ])]
73
    private UuidInterface $id;
74
75
    #[ORM\Column(
76
        name: 'token',
77
        type: Types::STRING,
78
        length: 40,
79
        options: [
80
            'comment' => 'Generated API key string for authentication',
81
        ],
82
    )]
83
    #[Groups([
84
        'ApiKey',
85
        'ApiKey.token',
86
    ])]
87
    #[Assert\NotBlank]
88
    #[Assert\NotNull]
89
    #[Assert\Length(
90
        exactly: 40,
91
    )]
92
    private string $token = '';
93
94
    #[ORM\Column(
95
        name: 'description',
96
        type: Types::TEXT,
97
    )]
98
    #[Groups([
99
        'ApiKey',
100
        'ApiKey.description',
101
    ])]
102
    #[Assert\NotNull]
103
    private string $description = '';
104
105
    /**
106
     * @var Collection<int, UserGroup>|ArrayCollection<int, UserGroup>
107
     */
108
    #[ORM\JoinTable(
109
        name: 'api_key_has_user_group',
110
    )]
111
    #[ORM\ManyToMany(
112
        targetEntity: UserGroup::class,
113
        inversedBy: 'apiKeys',
114
    )]
115
    #[Groups([
116
        'ApiKey.userGroups',
117
    ])]
118
    private Collection | ArrayCollection $userGroups;
119
120
    /**
121
     * @var Collection<int, LogRequest>|ArrayCollection<int, LogRequest>
122
     */
123
    #[ORM\OneToMany(
124
        mappedBy: 'apiKey',
125
        targetEntity: LogRequest::class,
126
    )]
127
    #[Groups([
128
        'ApiKey.logsRequest',
129
    ])]
130
    private Collection | ArrayCollection $logsRequest;
131
132
    /**
133
     * ApiKey constructor.
134
     *
135
     * @throws Throwable
136
     */
137 87
    public function __construct()
138
    {
139 87
        $this->id = $this->createUuid();
140 87
        $this->userGroups = new ArrayCollection();
141 87
        $this->logsRequest = new ArrayCollection();
142
143 87
        $this->generateToken();
144
    }
145
146 30
    public function getId(): string
147
    {
148 30
        return $this->id->toString();
149
    }
150
151 27
    public function getToken(): string
152
    {
153 27
        return $this->token;
154
    }
155
156 86
    public function setToken(string $token): self
157
    {
158 86
        $this->token = $token;
159
160 86
        return $this;
161
    }
162
163
    /**
164
     * @throws Throwable
165
     */
166 86
    public function generateToken(): self
167
    {
168 86
        return $this->setToken(ByteString::fromRandom(40)->toString());
169
    }
170
171 6
    public function getDescription(): string
172
    {
173 6
        return $this->description;
174
    }
175
176 17
    public function setDescription(string $description): self
177
    {
178 17
        $this->description = $description;
179
180 17
        return $this;
181
    }
182
183
    /**
184
     * Getter method for user groups collection.
185
     *
186
     * @return Collection<int, UserGroup>|ArrayCollection<int, UserGroup>
187
     */
188 7
    public function getUserGroups(): Collection | ArrayCollection
189
    {
190 7
        return $this->userGroups;
191
    }
192
193
    /**
194
     * Getter method for user request log collection.
195
     *
196
     * @return Collection<int, LogRequest>|ArrayCollection<int, LogRequest>
197
     */
198 2
    public function getLogsRequest(): Collection | ArrayCollection
199
    {
200 2
        return $this->logsRequest;
201
    }
202
203
    /**
204
     * Getter for roles.
205
     *
206
     * @return array<int, string>
207
     */
208 22
    #[Groups([
209
        'ApiKey.roles',
210
    ])]
211
    public function getRoles(): array
212
    {
213 22
        return array_values(
214 22
            array_map(
215
                '\strval',
216 22
                array_unique(
217 22
                    array_merge(
218 22
                        [Role::ROLE_API->value],
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ']' on line 218 at column 39
Loading history...
219 22
                        $this->userGroups
220 22
                            ->map(static fn (UserGroup $userGroup): string => $userGroup->getRole()->getId())
221 22
                            ->toArray(),
222
                    ),
223
                ),
224
            ),
225
        );
226
    }
227
228 18
    public function addUserGroup(UserGroup $userGroup): self
229
    {
230 18
        if ($this->userGroups->contains($userGroup) === false) {
231 18
            $this->userGroups->add($userGroup);
232 18
            $userGroup->addApiKey($this);
233
        }
234
235 18
        return $this;
236
    }
237
238 3
    public function removeUserGroup(UserGroup $userGroup): self
239
    {
240 3
        if ($this->userGroups->removeElement($userGroup)) {
241 2
            $userGroup->removeApiKey($this);
242
        }
243
244 3
        return $this;
245
    }
246
247 3
    public function clearUserGroups(): self
248
    {
249 3
        $this->userGroups->clear();
250
251 3
        return $this;
252
    }
253
}
254