zend-blog-3-backend

Форк
0
551 строка · 10.4 Кб
1
<?php
2

3
namespace App\Entity;
4

5
use App\Utils\HashId;
6
use DateTime;
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\Common\Collections\Collection;
9
use Doctrine\ORM\Mapping as ORM;
10
use Serializable;
11
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
12
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
13
use Symfony\Component\Security\Core\User\UserInterface;
14
use Symfony\Component\Validator\Constraints as Assert;
15

16
/**
17
 * @ORM\Table(name="users")
18
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
19
 * @DoctrineAssert\UniqueEntity(
20
 *   fields={"username"},
21
 *   message="This username is already used"
22
 * )
23
 * @DoctrineAssert\UniqueEntity(
24
 *   fields={"email"},
25
 *   message="This email is already used"
26
 * )
27
 */
28
class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface, Serializable
29
{
30
    public const ROLE_USER = 'ROLE_USER';
31
    public const ROLE_ADMIN = 'ROLE_ADMIN';
32

33
    public const TYPE_GUEST = 'guest';
34
    public const TYPE_ADMIN = 'admin';
35

36
    public const MALE = 1;
37
    public const FEMALE = 2;
38

39
    /**
40
     * @var int
41
     *
42
     * @ORM\Id
43
     * @ORM\Column(type="integer")
44
     * @ORM\GeneratedValue(strategy="AUTO")
45
     */
46
    protected $id;
47

48
    /**
49
     * @var string
50
     *
51
     * @ORM\Column(name="username", type="string", length=128, unique=true)
52
     */
53
    protected $username;
54

55
    /**
56
     * @var string
57
     *
58
     * @ORM\Column(name="mail", type="string", length=64, unique=true)
59
     * @Assert\Email()
60
     */
61
    protected $email;
62

63
    /**
64
     * @var string
65
     *
66
     * @ORM\Column(name="password", type="string", length=96)
67
     */
68
    protected $password;
69

70
    /**
71
     * @var string
72
     *
73
     * @ORM\Column(name="password_salt", type="string", length=32)
74
     */
75
    protected $salt;
76

77
    /**
78
     * @var string
79
     *
80
     * @ORM\Column(type="string", length=24)
81
     */
82
    protected $wsseKey;
83

84
    /**
85
     * @var string
86
     *
87
     * @ORM\Column(name="user_type", type="string", length=16)
88
     */
89
    protected $userType;
90

91
    /**
92
     * @var DateTime
93
     *
94
     * @ORM\Column(name="time_created", type="milliseconds_dt")
95
     */
96
    protected $timeCreated;
97

98
    /**
99
     * @var DateTime
100
     *
101
     * @ORM\Column(name="last_login", type="milliseconds_dt", nullable=true)
102
     */
103
    protected $lastLogin;
104

105
    /**
106
     * @var int
107
     *
108
     * @ORM\Column(type="integer")
109
     */
110
    protected $loginCount = 0;
111

112
    /**
113
     * @var string
114
     *
115
     * @ORM\Column(name="ip_last", type="string", length=15, nullable=true)
116
     */
117
    protected $ipAddressLast;
118

119
    /**
120
     * @var Collection
121
     *
122
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="user")
123
     */
124
    protected $comments;
125

126
    /**
127
     * @var string|null
128
     *
129
     * @ORM\Column(type="string", length=64, nullable=true)
130
     */
131
    private $displayName;
132

133
    /**
134
     * @var int
135
     *
136
     * @ORM\Column(type="smallint", options={"default": 1, "comment":"1: male, 2: female"})
137
     */
138
    private $gender = self::MALE;
139

140
    /**
141
     * @var int
142
     *
143
     * @ORM\Column(type="smallint", options={"default": 0, "unsigned": true})
144
     */
145
    private $avatarVariant = 0;
146

147
    public function __construct()
148
    {
149
        $this->comments = new ArrayCollection();
150

151
        $this->setRandomSalt();
152
        $this->setRandomWsseKey();
153

154
        $this->timeCreated = new DateTime();
155
        $this->userType = self::TYPE_GUEST;
156
    }
157

158
    public function getUserIdentifier(): string
159
    {
160
        return $this->username;
161
    }
162

163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function serialize()
167
    {
168
        return serialize([
169
            $this->id,
170
            $this->username,
171
            $this->password,
172
            $this->salt,
173
        ]);
174
    }
175

176
    /**
177
     * {@inheritdoc}
178
     */
179
    public function unserialize($serialized)
180
    {
181
        list(
182
            $this->id,
183
            $this->username,
184
            $this->password,
185
            $this->salt
186
            ) = unserialize($serialized, ['allowed_classes' => false]);
187
    }
188

189
    /**
190
     * {@inheritdoc}
191
     */
192
    public function getRoles()
193
    {
194
        $roles = [self::ROLE_USER];
195
        if ($this->userType === self::TYPE_ADMIN) {
196
            $roles = [self::ROLE_ADMIN];
197
        }
198

199
        return $roles;
200
    }
201

202
    /**
203
     * @return string
204
     */
205
    public function getAvatarHash(): string
206
    {
207
        $genderOption = ($this->getGender() === self::MALE) ? HashId::MALE : HashId::FEMALE;
208

209
        $options = HashId::TYPE_USER | $genderOption;
210
        $options += $this->getAvatarVariant() << 4;
211

212
        return HashId::hash($this->getId(), $options);
213
    }
214

215
    /**
216
     * {@inheritdoc}
217
     */
218
    public function eraseCredentials()
219
    {
220
    }
221

222
    public function setRandomSalt(): void
223
    {
224
        try {
225
            $randomBytes = random_bytes(16);
226
        } catch (\Exception $e) {
227
            $randomBytes = openssl_random_pseudo_bytes(16, $isSourceStrong);
228
            if ($isSourceStrong === false || $randomBytes === false) {
229
                throw new \RuntimeException('IV generation failed');
230
            }
231
        }
232

233
        $this->salt = bin2hex($randomBytes);
234
    }
235

236
    public function setRandomWsseKey(): void
237
    {
238
        try {
239
            $randomBytes = random_bytes(18);
240
        } catch (\Exception $e) {
241
            $randomBytes = openssl_random_pseudo_bytes(18, $isSourceStrong);
242
            if ($isSourceStrong === false || $randomBytes === false) {
243
                throw new \RuntimeException('IV generation failed');
244
            }
245
        }
246

247
        $this->wsseKey = strtr(base64_encode($randomBytes), '+/', '-_');
248
    }
249

250
    /**
251
     * Get id
252
     *
253
     * @return int|null
254
     */
255
    public function getId(): ?int
256
    {
257
        return $this->id;
258
    }
259

260
    /**
261
     * Set username
262
     *
263
     * @param string $username
264
     *
265
     * @return User
266
     */
267
    public function setUsername(string $username): self
268
    {
269
        $this->username = $username;
270

271
        return $this;
272
    }
273

274
    /**
275
     * Get username
276
     *
277
     * @return string
278
     */
279
    public function getUsername(): string
280
    {
281
        return $this->username;
282
    }
283

284
    /**
285
     * Set email
286
     *
287
     * @param string $email
288
     *
289
     * @return User
290
     */
291
    public function setEmail(string $email): self
292
    {
293
        $this->email = $email;
294

295
        return $this;
296
    }
297

298
    /**
299
     * Get mail
300
     *
301
     * @return string
302
     */
303
    public function getEmail(): string
304
    {
305
        return $this->email;
306
    }
307

308
    /**
309
     * Set password
310
     *
311
     * @param string $password
312
     *
313
     * @return User
314
     */
315
    public function setPassword(string $password): self
316
    {
317
        $this->password = $password;
318

319
        return $this;
320
    }
321

322
    /**
323
     * Get password
324
     *
325
     * @return string
326
     */
327
    public function getPassword(): ?string
328
    {
329
        return $this->password;
330
    }
331

332
    /**
333
     * Get salt
334
     *
335
     * @return string
336
     */
337
    public function getSalt(): ?string
338
    {
339
        return $this->salt;
340
    }
341

342
    /**
343
     * @return string
344
     */
345
    public function getWsseKey(): string
346
    {
347
        return $this->wsseKey;
348
    }
349

350
    /**
351
     * @param string $wsseKey
352
     *
353
     * @return $this
354
     */
355
    public function setWsseKey(string $wsseKey): self
356
    {
357
        $this->wsseKey = $wsseKey;
358

359
        return $this;
360
    }
361

362
    /**
363
     * Set userType
364
     *
365
     * @param string $userType
366
     *
367
     * @return User
368
     */
369
    public function setUserType(string $userType): self
370
    {
371
        $this->userType = $userType;
372

373
        return $this;
374
    }
375

376
    /**
377
     * Get userType
378
     *
379
     * @return string
380
     */
381
    public function getUserType(): string
382
    {
383
        return $this->userType;
384
    }
385

386
    /**
387
     * Set timeCreated
388
     *
389
     * @param DateTime $timeCreated
390
     *
391
     * @return User
392
     */
393
    public function setTimeCreated(DateTime $timeCreated): self
394
    {
395
        $this->timeCreated = $timeCreated;
396

397
        return $this;
398
    }
399

400
    /**
401
     * Get timeCreated
402
     *
403
     * @return DateTime
404
     */
405
    public function getTimeCreated(): DateTime
406
    {
407
        return $this->timeCreated;
408
    }
409

410
    /**
411
     * Set lastLogin
412
     *
413
     * @param DateTime $lastLogin
414
     *
415
     * @return User
416
     */
417
    public function setLastLogin(DateTime $lastLogin): self
418
    {
419
        $this->lastLogin = $lastLogin;
420

421
        return $this;
422
    }
423

424
    /**
425
     * Get lastLogin
426
     *
427
     * @return DateTime
428
     */
429
    public function getLastLogin(): DateTime
430
    {
431
        return $this->lastLogin;
432
    }
433

434
    /**
435
     * Set ipAddressLast
436
     *
437
     * @param string|null $ip
438
     *
439
     * @return User
440
     */
441
    public function setIpAddressLast(string $ip = null): self
442
    {
443
        $this->ipAddressLast = $ip;
444

445
        return $this;
446
    }
447

448
    /**
449
     * Get ipAddressLast
450
     *
451
     * @return string|null
452
     */
453
    public function getIpAddressLast(): ?string
454
    {
455
        return $this->ipAddressLast;
456
    }
457

458
    /**
459
     * Add comments
460
     *
461
     * @param Comment $comments
462
     *
463
     * @return User
464
     */
465
    public function addComment(Comment $comments): self
466
    {
467
        $this->comments[] = $comments;
468

469
        return $this;
470
    }
471

472
    /**
473
     * Remove comments
474
     *
475
     * @param Comment $comments
476
     */
477
    public function removeComment(Comment $comments): void
478
    {
479
        $this->comments->removeElement($comments);
480
    }
481

482
    /**
483
     * Get comments
484
     *
485
     * @return Collection
486
     */
487
    public function getComments()
488
    {
489
        return $this->comments;
490
    }
491

492
    /**
493
     * Set loginCount
494
     *
495
     * @param int $loginCount
496
     *
497
     * @return User
498
     */
499
    public function setLoginCount(int $loginCount): self
500
    {
501
        $this->loginCount = $loginCount;
502

503
        return $this;
504
    }
505

506
    /**
507
     * Get loginCount
508
     *
509
     * @return int
510
     */
511
    public function getLoginCount(): int
512
    {
513
        return $this->loginCount;
514
    }
515

516
    public function getDisplayName(): ?string
517
    {
518
        return $this->displayName;
519
    }
520

521
    public function setDisplayName(string $displayName = null): self
522
    {
523
        $this->displayName = $displayName;
524

525
        return $this;
526
    }
527

528
    public function getGender(): int
529
    {
530
        return $this->gender;
531
    }
532

533
    public function setGender(int $gender): self
534
    {
535
        $this->gender = $gender;
536

537
        return $this;
538
    }
539

540
    public function getAvatarVariant(): int
541
    {
542
        return $this->avatarVariant;
543
    }
544

545
    public function setAvatarVariant(int $avatarVariant): self
546
    {
547
        $this->avatarVariant = $avatarVariant;
548

549
        return $this;
550
    }
551
}
552

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.