Passed
Push — develop ( 1795b3...a8232e )
by BENARD
02:40
created

User::setLastLogin()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 1
1
<?php
2
3
namespace ProjetNormandie\UserBundle\Entity;
4
5
use DateTime;
6
use Doctrine\Common\Collections\Collection;
7
use Doctrine\ORM\Mapping as ORM;
8
use Knp\DoctrineBehaviors\Contract\Entity\TimestampableInterface;
9
use Knp\DoctrineBehaviors\Model\Timestampable\TimestampableTrait;
10
use Knp\DoctrineBehaviors\Contract\Entity\SluggableInterface;
11
use Knp\DoctrineBehaviors\Model\Sluggable\SluggableTrait;
12
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
13
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
14
use Symfony\Component\Security\Core\User\UserInterface;
15
use ApiPlatform\Core\Annotation\ApiResource;
16
use ApiPlatform\Core\Annotation\ApiFilter;
17
use ApiPlatform\Core\Serializer\Filter\GroupFilter;
18
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\DateFilter;
19
20
/**
21
 * User
22
 *
23
 * @ORM\Table(name="user")
24
 * @ORM\Entity(repositoryClass="ProjetNormandie\UserBundle\Repository\UserRepository")
25
 * @ORM\EntityListeners({"ProjetNormandie\UserBundle\EventListener\Entity\UserListener"})
26
 * @DoctrineAssert\UniqueEntity(fields={"email"})
27
 * @DoctrineAssert\UniqueEntity(fields={"username"})
28
 * @ApiResource(attributes={"order"={"username": "ASC"}})
29
 * @ApiFilter(DateFilter::class, properties={"lastLogin": DateFilter::EXCLUDE_NULL})
30
 * @ApiFilter(
31
 *     GroupFilter::class,
32
 *     arguments={
33
 *          "parameterName": "groups",
34
 *          "overrideDefaultGroups": true,
35
 *          "whitelist": {"user.read.mini"}
36
 *     }
37
 * )
38
 */
39
class User implements UserInterface, TimestampableInterface, SluggableInterface, PasswordAuthenticatedUserInterface
40
{
41
    use TimestampableTrait;
42
    use SluggableTrait;
43
44
    const ROLE_DEFAULT = 'ROLE_USER';
45
    const ROLE_ADMIN = 'ROLE_ADMIN';
46
    const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN';
47
48
    /**
49
     * @ORM\Id
50
     * @ORM\Column(type="integer")
51
     * @ORM\GeneratedValue(strategy="AUTO")
52
     */
53
    protected ?int $id = null;
54
55
    /**
56
     * @ORM\Column(type="string", length=50, unique=true)
57
     */
58
    protected string $username = '';
59
60
    /**
61
     * @ORM\Column(type="string", length=180, unique=true)
62
     */
63
    private string $email = '';
64
65
    /**
66
     * @ORM\Column(type="boolean")
67
     */
68
    protected bool $enabled = false;
69
70
    /**
71
     * @ORM\Column(type="array")
72
     */
73
    private array $roles = [];
74
75
    /**
76
     * @ORM\Column(name="password", type="string")
77
     */
78
    private ?string $password;
79
80
    /**
81
     * Plain password. Used for model validation. Must not be persisted.
82
     */
83
    protected string $plainPassword = '';
84
85
    /**
86
     * @ORM\Column(name="last_login",type="datetime", nullable=true)
87
     */
88
    protected ?DateTime $lastLogin = null;
89
90
    /**
91
     * @ORM\Column(name="confirmation_token",type="string", length=180, nullable=true, unique=true)
92
     */
93
    protected ?string $confirmationToken = null;
94
95
    /**
96
     * @ORM\Column(name="password_requested_at",type="datetime", nullable=true)
97
     */
98
    protected ?DateTime $passwordRequestedAt = null;
99
100
    /**
101
     * @ORM\Column(name="nbConnexion", type="integer", nullable=false)
102
     */
103
    protected int $nbConnexion = 0;
104
105
    /**
106
     * @ORM\Column(name="nbForumMessage", type="integer", nullable=false)
107
     */
108
    protected int $nbForumMessage = 0;
109
110
    /**
111
     * @ORM\Column(name="avatar", type="string", length=100, nullable=false)
112
     */
113
    protected string $avatar = 'default.png';
114
115
    /**
116
     * @ORM\Column(name="comment", type="text", length=100, nullable=true)
117
     */
118
    protected ?string $comment = null;
119
120
    /**
121
     * @ORM\Column(name="locale", type="string", length=2, nullable=true)
122
     */
123
    protected string $locale = 'en';
124
125
    /**
126
     * @ORM\Column(name="rules_accepted", type="boolean", nullable=false)
127
     */
128
    protected bool $rules_accepted = true;
129
130
    /**
131
     * @ORM\ManyToMany(targetEntity="ProjetNormandie\UserBundle\Entity\Group")
132
     * @ORM\JoinTable(name="user_group",
133
     *      joinColumns={@ORM\JoinColumn(name="userId", referencedColumnName="id")},
134
     *      inverseJoinColumns={@ORM\JoinColumn(name="groupId", referencedColumnName="id")}
135
     * )
136
     * @var Collection
137
     */
138
    protected $groups;
139
140
    /**
141
     * @ORM\OneToMany(targetEntity="ProjetNormandie\UserBundle\Entity\UserIp", mappedBy="user")
142
     */
143
    private $userIp;
144
145
    /**
146
     * @ORM\ManyToOne(targetEntity="ProjetNormandie\UserBundle\Entity\Status")
147
     * @ORM\JoinColumns({
148
     *   @ORM\JoinColumn(name="idStatus", referencedColumnName="id", nullable=false)
149
     * })
150
     */
151
    private $status;
152
153
    /**
154
     * @return int|null
155
     */
156
    public function getId(): ?int
157
    {
158
        return $this->id;
159
    }
160
161
    /**
162
     * @return string
163
     */
164
    public function getUsername(): string
165
    {
166
        return $this->username;
167
    }
168
169
    /**
170
     * @param $username
171
     * @return User
172
     */
173
    public function setUsername($username): User
174
    {
175
        $this->username = $username;
176
        return $this;
177
    }
178
179
    /**
180
     * @return string|null
181
     */
182
    public function getEmail(): ?string
183
    {
184
        return $this->email;
185
    }
186
187
    /**
188
     * @param string $email
189
     * @return User
190
     */
191
    public function setEmail(string $email): User
192
    {
193
        $this->email = $email;
194
195
        return $this;
196
    }
197
198
    /**
199
     * @param $boolean
200
     * @return User
201
     */
202
    public function setEnabled($boolean): User
203
    {
204
        $this->enabled = (bool) $boolean;
205
206
        return $this;
207
    }
208
209
    /**
210
     * @return bool
211
     */
212
    public function isEnabled(): bool
213
    {
214
        return $this->enabled;
215
    }
216
217
    /**
218
     * @return array|string[]
219
     */
220
    public function getRoles(): array
221
    {
222
        $roles = $this->roles;
223
224
        foreach ($this->getGroups() as $group) {
225
            $roles = array_merge($roles, $group->getRoles());
226
        }
227
228
        // we need to make sure to have at least one role
229
        $roles[] = 'ROLE_USER';
230
231
        return array_values(array_unique($roles));
232
    }
233
234
    /**
235
     * @param array $roles
236
     * @return User
237
     */
238
    public function setRoles(array $roles): User
239
    {
240
        $this->roles = $roles;
241
242
        return $this;
243
    }
244
245
    /**
246
     * @return string
247
     */
248
    public function getPassword(): ?string
249
    {
250
        return $this->password;
251
    }
252
253
    /**
254
     * @param string $password
255
     * @return User
256
     */
257
    public function setPassword(string $password): User
258
    {
259
        $this->password = $password;
260
261
        return $this;
262
    }
263
264
    /**
265
     * Returning a salt is only needed, if you are not using a modern
266
     * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
267
     */
268
    public function getSalt(): ?string
269
    {
270
        return null;
271
    }
272
273
    /**
274
     * @return string
275
     */
276
    public function getPlainPassword(): ?string
277
    {
278
        return $this->plainPassword;
279
    }
280
281
282
    /**
283
     * @param $role
284
     * @return bool
285
     */
286
    public function hasRole($role): bool
287
    {
288
        return in_array(strtoupper($role), $this->getRoles(), true);
289
    }
290
291
    /**
292
     *
293
     */
294
    public function eraseCredentials()
295
    {
296
        // If you store any temporary, sensitive data on the user, clear it here
297
        // $this->plainPassword = null;
298
    }
299
300
    /**
301
     * @return DateTime|null
302
     */
303
    public function getLastLogin(): ?DateTime
304
    {
305
        return $this->lastLogin;
306
    }
307
308
    /**
309
     * @param DateTime|null $time
310
     * @return User
311
     */
312
    public function setLastLogin(DateTime $time = null) : User
313
    {
314
        $lastLogin = $this->getLastLogin();
315
        if (($lastLogin === null) || ($lastLogin->format('Y-m-d') != $time->format('Y-m-d'))) {
0 ignored issues
show
Bug introduced by
The method format() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

315
        if (($lastLogin === null) || ($lastLogin->format('Y-m-d') != $time->/** @scrutinizer ignore-call */ format('Y-m-d'))) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
316
            ++$this->nbConnexion;
317
        }
318
        $this->lastLogin = $time;
319
        return $this;
320
    }
321
322
    /**
323
     * @param $confirmationToken
324
     * @return User
325
     */
326
    public function setConfirmationToken($confirmationToken): User
327
    {
328
        $this->confirmationToken = $confirmationToken;
329
        return $this;
330
    }
331
332
    /**
333
     * @return string
334
     */
335
    public function getConfirmationToken(): ?string
336
    {
337
        return $this->confirmationToken;
338
    }
339
340
    /**
341
     * @param DateTime|null $date
342
     * @return User
343
     */
344
    public function setPasswordRequestedAt(DateTime $date = null): User
345
    {
346
        $this->passwordRequestedAt = $date;
347
        return $this;
348
    }
349
350
    /**
351
     * Gets the timestamp that the user requested a password reset.
352
     * @return null|DateTime
353
     */
354
    public function getPasswordRequestedAt(): ?DateTime
355
    {
356
        return $this->passwordRequestedAt;
357
    }
358
359
    /**
360
     * @param $ttl
361
     * @return bool
362
     */
363
    public function isPasswordRequestNonExpired($ttl): bool
364
    {
365
        return $this->getPasswordRequestedAt() instanceof DateTime &&
366
               $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
367
    }
368
369
    /**
370
     * @return string
371
     */
372
    public function getLocale(): string
373
    {
374
        return $this->locale;
375
    }
376
377
    /**
378
     * @param string $locale
379
     * @return User
380
     */
381
    public function setLocale(string $locale): User
382
    {
383
        $this->locale = $locale;
384
        return $this;
385
    }
386
387
    /**
388
     * @return int
389
     */
390
    public function getNbConnexion(): int
391
    {
392
        return $this->nbConnexion;
393
    }
394
395
    /**
396
     * @param int $nbConnexion
397
     * @return User
398
     */
399
    public function setNbConnexion(int $nbConnexion): User
400
    {
401
        $this->nbConnexion = $nbConnexion;
402
        return $this;
403
    }
404
405
    /**
406
     * @return int
407
     */
408
    public function getNbForumMessage(): int
409
    {
410
        return $this->nbForumMessage;
411
    }
412
413
    /**
414
     * @param int $nbForumMessage
415
     * @return User
416
     */
417
    public function setNbForumMessage(int $nbForumMessage): User
418
    {
419
        $this->nbForumMessage = $nbForumMessage;
420
        return $this;
421
    }
422
423
    /**
424
     * @return string
425
     */
426
    public function getAvatar(): string
427
    {
428
        return $this->avatar;
429
    }
430
431
    /**
432
     * @param string $avatar
433
     * @return User
434
     */
435
    public function setAvatar(string $avatar): User
436
    {
437
        $this->avatar = $avatar;
438
        return $this;
439
    }
440
441
    /**
442
     * @return string
443
     */
444
    public function getComment(): ?string
445
    {
446
        return $this->comment;
447
    }
448
449
    /**
450
     * @param string|null $comment
451
     * @return User
452
     */
453
    public function setComment(string $comment = null) : User
454
    {
455
        $this->comment = $comment;
456
        return $this;
457
    }
458
459
460
    /**
461
     * @return mixed
462
     */
463
    public function getUserIp()
464
    {
465
        return $this->userIp;
466
    }
467
468
    /**
469
     * Set status
470
     * @param Status|object|null $status
471
     * @return User
472
     */
473
    public function setStatus(Status $status = null): User
474
    {
475
        $this->status = $status;
476
        return $this;
477
    }
478
479
    /**
480
     * Get status
481
     * @return Status
482
     */
483
    public function getStatus(): Status
484
    {
485
        return $this->status;
486
    }
487
488
    /**
489
     * Set rules_accepted
490
     * @param bool $rules_accepted
491
     * @return User
492
     */
493
    public function setRulesAccepted(bool $rules_accepted): User
494
    {
495
        $this->rules_accepted = $rules_accepted;
496
        return $this;
497
    }
498
499
    /**
500
     * Get rules_accepted
501
     * @return bool
502
     */
503
    public function getRulesAccepted(): bool
504
    {
505
        return $this->rules_accepted;
506
    }
507
508
    /**
509
     * @param $groups
510
     * @return User
511
     */
512
    public function setGroups($groups): User
513
    {
514
        $this->groups = $groups;
515
        return $this;
516
    }
517
518
    /**
519
     * @return Collection
520
     */
521
    public function getGroups(): Collection
522
    {
523
        return $this->groups;
524
    }
525
526
    /**
527
     * @param $password
528
     * @return User
529
     */
530
    public function setPlainPassword($password): User
531
    {
532
        $this->plainPassword = $password;
533
        return $this;
534
    }
535
536
    /**
537
     * @param $group
538
     * @return User
539
     */
540
    public function addGroup($group): User
541
    {
542
        $this->groups[] = $group;
543
        return $this;
544
    }
545
546
     /**
547
     * @param Group $group
548
     */
549
    public function removeGroup(Group $group)
550
    {
551
        $this->groups->removeElement($group);
552
    }
553
554
555
    /**
556
     * @return string
557
     */
558
    public function __toString()
559
    {
560
        return sprintf('%s [%d]', $this->getUsername(), $this->getId());
561
    }
562
563
    /**
564
     * @param $role
565
     * @return User
566
     */
567
    public function addRole($role): User
568
    {
569
        $role = strtoupper($role);
570
        if ($role === static::ROLE_DEFAULT) {
571
            return $this;
572
        }
573
        if (!in_array($role, $this->roles, true)) {
574
            $this->roles[] = $role;
575
        }
576
        return $this;
577
    }
578
579
    /**
580
     * @param $role
581
     * @return User
582
     */
583
    public function removeRole($role): User
584
    {
585
        if (false !== $key = array_search(strtoupper($role), $this->roles, true)) {
586
            unset($this->roles[$key]);
587
            $this->roles = array_values($this->roles);
588
        }
589
        return $this;
590
    }
591
592
593
    /**
594
     * Returns an array of the fields used to generate the slug.
595
     * @return string[]
596
     */
597
    public function getSluggableFields(): array
598
    {
599
        return ['username'];
600
    }
601
}
602