Passed
Pull Request — master (#5728)
by
unknown
08:45
created

Session::getStatusList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Entity;
8
9
use ApiPlatform\Core\Serializer\Filter\GroupFilter;
10
use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
11
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
12
use ApiPlatform\Metadata\ApiFilter;
13
use ApiPlatform\Metadata\ApiResource;
14
use ApiPlatform\Metadata\Delete;
15
use ApiPlatform\Metadata\Get;
16
use ApiPlatform\Metadata\GetCollection;
17
use ApiPlatform\Metadata\Link;
18
use ApiPlatform\Metadata\Post;
19
use ApiPlatform\Metadata\Put;
20
use ApiPlatform\Serializer\Filter\PropertyFilter;
21
use Chamilo\CoreBundle\Entity\Listener\SessionListener;
22
use Chamilo\CoreBundle\Repository\SessionRepository;
23
use Chamilo\CoreBundle\State\UserSessionSubscriptionsStateProvider;
24
use DateTime;
25
use Doctrine\Common\Collections\ArrayCollection;
26
use Doctrine\Common\Collections\Collection;
27
use Doctrine\Common\Collections\Criteria;
28
use Doctrine\Common\Collections\ReadableCollection;
29
use Doctrine\ORM\Mapping as ORM;
30
use LogicException;
31
use Stringable;
32
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
33
use Symfony\Component\Serializer\Annotation\Groups;
34
use Symfony\Component\Validator\Constraints as Assert;
35
36
#[ApiResource(
37
    operations: [
38
        new Get(
39
            uriTemplate: '/sessions/{id}',
40
            normalizationContext: [
41
                'groups' => ['session:basic'],
42
            ],
43
            security: "is_granted('ROLE_ADMIN') or is_granted('VIEW', object)"
44
        ),
45
        new Put(security: "is_granted('ROLE_ADMIN')"),
46
        new GetCollection(security: "is_granted('ROLE_ADMIN')"),
47
        new GetCollection(
48
            uriTemplate: '/users/{id}/session_subscriptions/past.{_format}',
49
            uriVariables: [
50
                'id' => new Link(
51
                    fromClass: User::class,
52
                ),
53
            ],
54
            paginationEnabled: false,
55
            normalizationContext: [
56
                'groups' => [
57
                    'user_subscriptions:sessions',
58
                ],
59
            ],
60
            security: "is_granted('ROLE_USER')",
61
            name: 'user_session_subscriptions_past',
62
            provider: UserSessionSubscriptionsStateProvider::class,
63
        ),
64
        new GetCollection(
65
            uriTemplate: '/users/{id}/session_subscriptions/current.{_format}',
66
            uriVariables: [
67
                'id' => new Link(
68
                    fromClass: User::class,
69
                ),
70
            ],
71
            paginationEnabled: false,
72
            normalizationContext: [
73
                'groups' => [
74
                    'user_subscriptions:sessions',
75
                ],
76
            ],
77
            security: "is_granted('ROLE_USER')",
78
            name: 'user_session_subscriptions_current',
79
            provider: UserSessionSubscriptionsStateProvider::class,
80
        ),
81
        new GetCollection(
82
            uriTemplate: '/users/{id}/session_subscriptions/upcoming.{_format}',
83
            uriVariables: [
84
                'id' => new Link(
85
                    fromClass: User::class,
86
                ),
87
            ],
88
            paginationEnabled: false,
89
            normalizationContext: [
90
                'groups' => [
91
                    'user_subscriptions:sessions',
92
                ],
93
            ],
94
            security: "is_granted('ROLE_USER')",
95
            name: 'user_session_subscriptions_upcoming',
96
            provider: UserSessionSubscriptionsStateProvider::class,
97
        ),
98
        new Post(security: "is_granted('ROLE_ADMIN')"),
99
        new Delete(security: "is_granted('DELETE', object)"),
100
    ],
101
    normalizationContext: ['groups' => ['session:basic']],
102
    denormalizationContext: ['groups' => ['session:write']],
103
    security: "is_granted('ROLE_ADMIN')"
104
)]
105
#[ORM\Table(name: 'session')]
106
#[ORM\UniqueConstraint(name: 'title', columns: ['title'])]
107
#[ORM\EntityListeners([SessionListener::class])]
108
#[ORM\Entity(repositoryClass: SessionRepository::class)]
109
#[UniqueEntity('title')]
110
#[ApiFilter(SearchFilter::class, properties: ['title' => 'partial'])]
111
#[ApiFilter(PropertyFilter::class)]
112
#[ApiFilter(OrderFilter::class, properties: ['id', 'title'])]
113
#[ApiFilter(GroupFilter::class, arguments: ['parameterName' => 'groups'])]
114
class Session implements ResourceWithAccessUrlInterface, Stringable
115
{
116
    public const READ_ONLY = 1;
117
    public const VISIBLE = 2;
118
    public const INVISIBLE = 3;
119
    public const AVAILABLE = 4;
120
    public const LIST_ONLY = 5;
121
122
    public const STUDENT = 0;
123
    public const DRH = 1;
124
    public const COURSE_COACH = 2;
125
    public const GENERAL_COACH = 3;
126
    public const SESSION_ADMIN = 4;
127
128
    #[Groups([
129
        'session:basic',
130
        'session:read',
131
        'session_rel_user:read',
132
        'session_rel_course_rel_user:read',
133
        'course:read',
134
        'track_e_exercise:read',
135
        'user_subscriptions:sessions',
136
    ])]
137
    #[ORM\Column(name: 'id', type: 'integer')]
138
    #[ORM\Id]
139
    #[ORM\GeneratedValue]
140
    protected ?int $id = null;
141
142
    /**
143
     * @var Collection<int, SessionRelCourse>
144
     */
145
    #[Groups([
146
        'session:read',
147
        'session_rel_user:read',
148
        'session_rel_course_rel_user:read',
149
        'user_subscriptions:sessions',
150
    ])]
151
    #[ORM\OrderBy(['position' => 'ASC'])]
152
    #[ORM\OneToMany(
153
        mappedBy: 'session',
154
        targetEntity: SessionRelCourse::class,
155
        cascade: ['persist'],
156
        fetch: 'EXTRA_LAZY',
157
        orphanRemoval: true
158
    )]
159
    protected Collection $courses;
160
161
    /**
162
     * @var Collection<int, SessionRelUser>
163
     */
164
    #[Groups([
165
        'session:read',
166
    ])]
167
    #[ORM\OneToMany(
168
        mappedBy: 'session',
169
        targetEntity: SessionRelUser::class,
170
        cascade: ['persist', 'remove'],
171
        fetch: 'EXTRA_LAZY',
172
        orphanRemoval: true
173
    )]
174
    protected Collection $users;
175
176
    /**
177
     * @var Collection<int, SessionRelCourseRelUser>
178
     */
179
    #[Groups([
180
        'session:read',
181
        'session_rel_course_rel_user:read',
182
    ])]
183
    #[ORM\OneToMany(
184
        mappedBy: 'session',
185
        targetEntity: SessionRelCourseRelUser::class,
186
        cascade: ['persist'],
187
        orphanRemoval: true
188
    )]
189
    protected Collection $sessionRelCourseRelUsers;
190
191
    /**
192
     * @var Collection<int, SkillRelCourse>
193
     */
194
    #[ORM\OneToMany(
195
        mappedBy: 'session',
196
        targetEntity: SkillRelCourse::class,
197
        cascade: ['persist', 'remove']
198
    )]
199
    protected Collection $skills;
200
201
    /**
202
     * @var Collection<int, SkillRelUser>
203
     */
204
    #[ORM\OneToMany(mappedBy: 'session', targetEntity: SkillRelUser::class, cascade: ['persist'])]
205
    protected Collection $issuedSkills;
206
207
    /**
208
     * @var Collection<int, EntityAccessUrlInterface>
209
     */
210
    #[ORM\OneToMany(
211
        mappedBy: 'session',
212
        targetEntity: AccessUrlRelSession::class,
213
        cascade: ['persist'],
214
        orphanRemoval: true
215
    )]
216
    protected Collection $urls;
217
218
    /**
219
     * @var Collection<int, ResourceLink>
220
     */
221
    #[ORM\OneToMany(mappedBy: 'session', targetEntity: ResourceLink::class, cascade: ['remove'], orphanRemoval: true)]
222
    protected Collection $resourceLinks;
223
224
    protected AccessUrl $currentUrl;
225
226
    protected ?Course $currentCourse = null;
227
228
    #[Assert\NotBlank]
229
    #[Groups([
230
        'session:basic',
231
        'session:read',
232
        'session:write',
233
        'session_rel_course_rel_user:read',
234
        'document:read',
235
        'session_rel_user:read',
236
        'course:read',
237
        'track_e_exercise:read',
238
        'calendar_event:read',
239
        'user_subscriptions:sessions',
240
    ])]
241
    #[ORM\Column(name: 'title', type: 'string', length: 150)]
242
    protected string $title;
243
244
    #[Groups([
245
        'session:basic',
246
        'session:read',
247
        'session:write',
248
    ])]
249
    #[ORM\Column(name: 'description', type: 'text', unique: false, nullable: true)]
250
    protected ?string $description;
251
252
    #[Groups([
253
        'session:read',
254
        'session:write',
255
    ])]
256
    #[ORM\Column(name: 'show_description', type: 'boolean', nullable: true)]
257
    protected ?bool $showDescription;
258
259
    #[Groups(['session:read', 'session:write', 'user_subscriptions:sessions'])]
260
    #[ORM\Column(name: 'duration', type: 'integer', nullable: true)]
261
    protected ?int $duration = null;
262
263
    #[Groups(['session:basic', 'session:read'])]
264
    #[ORM\Column(name: 'nbr_courses', type: 'integer', unique: false, nullable: false)]
265
    protected int $nbrCourses;
266
267
    #[Groups(['session:basic', 'session:read'])]
268
    #[ORM\Column(name: 'nbr_users', type: 'integer', unique: false, nullable: false)]
269
    protected int $nbrUsers;
270
271
    #[Groups(['session:read'])]
272
    #[ORM\Column(name: 'nbr_classes', type: 'integer', unique: false, nullable: false)]
273
    protected int $nbrClasses;
274
275
    #[Groups([
276
        'session:basic',
277
        'session:read',
278
        'session:write',
279
    ])]
280
    #[ORM\Column(name: 'visibility', type: 'integer')]
281
    protected int $visibility;
282
283
    #[ORM\ManyToOne(targetEntity: Promotion::class, cascade: ['persist'], inversedBy: 'sessions')]
284
    #[ORM\JoinColumn(name: 'promotion_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
285
    protected ?Promotion $promotion = null;
286
287
    #[Groups([
288
        'session:read',
289
        'session:write',
290
        'session_rel_user:read',
291
        'session_rel_course_rel_user:read',
292
        'user_subscriptions:sessions',
293
    ])]
294
    #[ORM\Column(name: 'display_start_date', type: 'datetime', unique: false, nullable: true)]
295
    protected ?DateTime $displayStartDate;
296
297
    #[Groups([
298
        'session:read',
299
        'session:write',
300
        'session_rel_user:read',
301
        'session_rel_course_rel_user:read',
302
        'user_subscriptions:sessions',
303
    ])]
304
    #[ORM\Column(name: 'display_end_date', type: 'datetime', unique: false, nullable: true)]
305
    protected ?DateTime $displayEndDate;
306
307
    #[Groups([
308
        'session:read',
309
        'session:write',
310
        'session_rel_user:read',
311
        'session_rel_course_rel_user:read',
312
    ])]
313
    #[ORM\Column(name: 'access_start_date', type: 'datetime', unique: false, nullable: true)]
314
    protected ?DateTime $accessStartDate;
315
316
    #[Groups([
317
        'session:read',
318
        'session:write',
319
        'session_rel_user:read',
320
        'session_rel_course_rel_user:read',
321
    ])]
322
    #[ORM\Column(name: 'access_end_date', type: 'datetime', unique: false, nullable: true)]
323
    protected ?DateTime $accessEndDate;
324
325
    #[Groups([
326
        'session:read',
327
        'session:write',
328
        'session_rel_user:read',
329
        'session_rel_course_rel_user:read',
330
    ])]
331
    #[ORM\Column(name: 'coach_access_start_date', type: 'datetime', unique: false, nullable: true)]
332
    protected ?DateTime $coachAccessStartDate;
333
334
    #[Groups([
335
        'session:read',
336
        'session:write',
337
        'session_rel_user:read',
338
        'session_rel_course_rel_user:read',
339
    ])]
340
    #[ORM\Column(name: 'coach_access_end_date', type: 'datetime', unique: false, nullable: true)]
341
    protected ?DateTime $coachAccessEndDate;
342
343
    #[ORM\Column(name: 'position', type: 'integer', nullable: false, options: ['default' => 0])]
344
    protected int $position;
345
346
    #[Groups(['session:read'])]
347
    #[ORM\Column(name: 'status', type: 'integer', nullable: false)]
348
    protected int $status;
349
350
    #[Groups(['session:read', 'session:write', 'session_rel_user:read', 'user_subscriptions:sessions'])]
351
    #[ORM\ManyToOne(targetEntity: SessionCategory::class, inversedBy: 'sessions')]
352
    #[ORM\JoinColumn(name: 'session_category_id', referencedColumnName: 'id')]
353
    protected ?SessionCategory $category = null;
354
355
    #[ORM\Column(
356
        name: 'send_subscription_notification',
357
        type: 'boolean',
358
        nullable: false,
359
        options: ['default' => false]
360
    )]
361
    protected bool $sendSubscriptionNotification;
362
363
    /**
364
     * Image illustrating the session (was extra field 'image' in 1.11).
365
     */
366
    #[Groups(['user_subscriptions:sessions'])]
367
    #[ORM\ManyToOne(targetEntity: Asset::class, cascade: ['remove'])]
368
    #[ORM\JoinColumn(name: 'image_id', referencedColumnName: 'id', onDelete: 'SET NULL')]
369
    protected ?Asset $image = null;
370
371
    #[Groups(['user_subscriptions:sessions', 'session:read', 'session:item:read', 'session:basic'])]
372
    private ?string $imageUrl = null;
373
374
    #[Groups(['user_subscriptions:sessions', 'session:read', 'session:item:read'])]
375
    private int $accessVisibility = 0;
376
377
    public function __construct()
378
    {
379
        $this->skills = new ArrayCollection();
380
        $this->issuedSkills = new ArrayCollection();
381
        $this->resourceLinks = new ArrayCollection();
382
        $this->courses = new ArrayCollection();
383
        $this->users = new ArrayCollection();
384
        $this->sessionRelCourseRelUsers = new ArrayCollection();
385
        $this->urls = new ArrayCollection();
386
        $this->duration = 0;
387
        $this->description = '';
388
        $this->nbrClasses = 0;
389
        $this->nbrUsers = 0;
390
        $this->nbrCourses = 0;
391
        $this->sendSubscriptionNotification = false;
392
        $now = new DateTime();
393
        $this->displayStartDate = $now;
394
        $this->displayEndDate = $now;
395
        $this->accessStartDate = $now;
396
        $this->accessEndDate = $now;
397
        $this->coachAccessStartDate = $now;
398
        $this->coachAccessEndDate = $now;
399
        $this->visibility = 1;
400
        $this->showDescription = false;
401
        $this->category = null;
402
        $this->status = 0;
403
        $this->position = 0;
404
    }
405
406
    public function __toString(): string
407
    {
408
        return $this->getTitle();
409
    }
410
411
    public static function getRelationTypeList(): array
412
    {
413
        return [self::STUDENT, self::DRH, self::COURSE_COACH, self::GENERAL_COACH, self::SESSION_ADMIN];
414
    }
415
416
    public static function getStatusList(): array
417
    {
418
        return [
419
            self::READ_ONLY => 'status_read_only',
420
            self::VISIBLE => 'status_visible',
421
            self::INVISIBLE => 'status_invisible',
422
            self::AVAILABLE => 'status_available',
423
        ];
424
    }
425
426
    public function getDuration(): ?int
427
    {
428
        return $this->duration;
429
    }
430
431
    public function setDuration(int $duration): self
432
    {
433
        $this->duration = $duration;
434
435
        return $this;
436
    }
437
438
    public function getShowDescription(): bool
439
    {
440
        return $this->showDescription;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->showDescription could return the type null which is incompatible with the type-hinted return boolean. Consider adding an additional type-check to rule them out.
Loading history...
441
    }
442
443
    public function setShowDescription(bool $showDescription): self
444
    {
445
        $this->showDescription = $showDescription;
446
447
        return $this;
448
    }
449
450
    /**
451
     * @return Collection<int, SessionRelUser>
452
     */
453
    public function getUsers(): Collection
454
    {
455
        return $this->users;
456
    }
457
458
    public function setUsers(Collection $users): self
459
    {
460
        $this->users = new ArrayCollection();
461
        foreach ($users as $user) {
462
            $this->addUserSubscription($user);
463
        }
464
465
        return $this;
466
    }
467
468
    public function addUserSubscription(SessionRelUser $subscription): void
469
    {
470
        $subscription->setSession($this);
471
        if (!$this->hasUser($subscription)) {
472
            $this->users->add($subscription);
473
            $this->nbrUsers++;
474
        }
475
    }
476
477
    public function hasUser(SessionRelUser $subscription): bool
478
    {
479
        if (0 !== $this->getUsers()->count()) {
480
            $criteria = Criteria::create()
481
                ->where(
482
                    Criteria::expr()->eq('user', $subscription->getUser())
483
                )
484
                ->andWhere(
485
                    Criteria::expr()->eq('session', $subscription->getSession())
486
                )
487
                ->andWhere(
488
                    Criteria::expr()->eq('relationType', $subscription->getRelationType())
489
                )
490
            ;
491
            $relation = $this->getUsers()->matching($criteria);
492
493
            return $relation->count() > 0;
494
        }
495
496
        return false;
497
    }
498
499
    public function hasCourse(Course $course): bool
500
    {
501
        if (0 !== $this->getCourses()->count()) {
502
            $criteria = Criteria::create()->where(Criteria::expr()->eq('course', $course));
503
            $relation = $this->getCourses()->matching($criteria);
504
505
            return $relation->count() > 0;
506
        }
507
508
        return false;
509
    }
510
511
    /**
512
     * @return Collection<int, SessionRelCourse>
513
     */
514
    public function getCourses(): Collection
515
    {
516
        return $this->courses;
517
    }
518
519
    public function setCourses(ArrayCollection $courses): void
520
    {
521
        $this->courses = new ArrayCollection();
522
        foreach ($courses as $course) {
523
            $this->addCourses($course);
524
        }
525
    }
526
527
    public function addCourses(SessionRelCourse $course): void
528
    {
529
        $course->setSession($this);
530
        $this->courses->add($course);
531
    }
532
533
    public function removeCourses(SessionRelCourse $course): void
534
    {
535
        foreach ($this->courses as $key => $value) {
536
            if ($value->getId() === $course->getId()) {
537
                unset($this->courses[$key]);
538
            }
539
        }
540
    }
541
542
    public function getId(): ?int
543
    {
544
        return $this->id;
545
    }
546
547
    /**
548
     * Remove course subscription for a user.
549
     * If user status in session is student, then decrease number of course users.
550
     */
551
    public function removeUserCourseSubscription(User $user, Course $course): void
552
    {
553
        foreach ($this->sessionRelCourseRelUsers as $i => $sessionRelUser) {
554
            if ($sessionRelUser->getCourse()->getId() === $course->getId()
555
                && $sessionRelUser->getUser()->getId() === $user->getId()
556
            ) {
557
                if (self::STUDENT === $this->sessionRelCourseRelUsers[$i]->getStatus()) {
558
                    $sessionCourse = $this->getCourseSubscription($course);
559
                    $sessionCourse->setNbrUsers($sessionCourse->getNbrUsers() - 1);
560
                }
561
562
                unset($this->sessionRelCourseRelUsers[$i]);
563
            }
564
        }
565
    }
566
567
    public function getStatus(): int
568
    {
569
        return $this->status;
570
    }
571
572
    public function setStatus(int $status): self
573
    {
574
        $this->status = $status;
575
576
        return $this;
577
    }
578
579
    public function setTitle(string $title): self
580
    {
581
        $this->title = $title;
582
583
        return $this;
584
    }
585
586
    public function getCourseSubscription(Course $course): ?SessionRelCourse
587
    {
588
        $criteria = Criteria::create()->where(Criteria::expr()->eq('course', $course));
589
590
        return $this->courses->matching($criteria)->current();
591
    }
592
593
    public function getTitle(): string
594
    {
595
        return $this->title;
596
    }
597
598
    public function getNbrUsers(): int
599
    {
600
        return $this->nbrUsers;
601
    }
602
603
    public function setNbrUsers(int $nbrUsers): self
604
    {
605
        $this->nbrUsers = $nbrUsers;
606
607
        return $this;
608
    }
609
610
    /**
611
     * @return Collection<int, SessionRelCourseRelUser>
612
     */
613
    public function getAllUsersFromCourse(int $status): Collection
614
    {
615
        $criteria = Criteria::create()->where(Criteria::expr()->eq('status', $status));
616
617
        return $this->getSessionRelCourseRelUsers()->matching($criteria);
618
    }
619
620
    public function getSessionRelCourseRelUsers(): Collection
621
    {
622
        return $this->sessionRelCourseRelUsers;
623
    }
624
625
    public function setSessionRelCourseRelUsers(Collection $sessionRelCourseRelUsers): self
626
    {
627
        $this->sessionRelCourseRelUsers = new ArrayCollection();
628
        foreach ($sessionRelCourseRelUsers as $item) {
629
            $this->addSessionRelCourseRelUser($item);
630
        }
631
632
        return $this;
633
    }
634
635
    public function addSessionRelCourseRelUser(SessionRelCourseRelUser $sessionRelCourseRelUser): void
636
    {
637
        $sessionRelCourseRelUser->setSession($this);
638
        if (!$this->hasUserCourseSubscription($sessionRelCourseRelUser)) {
639
            $this->sessionRelCourseRelUsers->add($sessionRelCourseRelUser);
640
        }
641
    }
642
643
    public function hasUserCourseSubscription(SessionRelCourseRelUser $subscription): bool
644
    {
645
        if (0 !== $this->getSessionRelCourseRelUsers()->count()) {
646
            $criteria = Criteria::create()
647
                ->where(
648
                    Criteria::expr()->eq('user', $subscription->getUser())
649
                )
650
                ->andWhere(
651
                    Criteria::expr()->eq('course', $subscription->getCourse())
652
                )
653
                ->andWhere(
654
                    Criteria::expr()->eq('session', $subscription->getSession())
655
                )
656
            ;
657
            $relation = $this->getSessionRelCourseRelUsers()->matching($criteria);
658
659
            return $relation->count() > 0;
660
        }
661
662
        return false;
663
    }
664
665
    /**
666
     * @return Collection<int, SessionRelCourseRelUser>
667
     */
668
    public function getSessionRelCourseByUser(User $user, ?int $status = null): Collection
669
    {
670
        $criteria = Criteria::create()->where(Criteria::expr()->eq('user', $user));
671
        if (null !== $status) {
672
            $criteria->andWhere(Criteria::expr()->eq('status', $status));
673
        }
674
675
        return $this->sessionRelCourseRelUsers->matching($criteria);
676
    }
677
678
    public function getDescription(): ?string
679
    {
680
        return $this->description;
681
    }
682
683
    public function setDescription(string $description): self
684
    {
685
        $this->description = $description;
686
687
        return $this;
688
    }
689
690
    public function getNbrCourses(): int
691
    {
692
        return $this->nbrCourses;
693
    }
694
695
    public function setNbrCourses(int $nbrCourses): self
696
    {
697
        $this->nbrCourses = $nbrCourses;
698
699
        return $this;
700
    }
701
702
    public function getNbrClasses(): int
703
    {
704
        return $this->nbrClasses;
705
    }
706
707
    public function setNbrClasses(int $nbrClasses): self
708
    {
709
        $this->nbrClasses = $nbrClasses;
710
711
        return $this;
712
    }
713
714
    public function getVisibility(): int
715
    {
716
        return $this->visibility;
717
    }
718
719
    public function setVisibility(int $visibility): self
720
    {
721
        $this->visibility = $visibility;
722
723
        return $this;
724
    }
725
726
    public function getPromotion(): ?Promotion
727
    {
728
        return $this->promotion;
729
    }
730
731
    public function setPromotion(?Promotion $promotion): self
732
    {
733
        $this->promotion = $promotion;
734
735
        return $this;
736
    }
737
738
    public function getDisplayStartDate(): ?DateTime
739
    {
740
        return $this->displayStartDate;
741
    }
742
743
    public function setDisplayStartDate(?DateTime $displayStartDate): self
744
    {
745
        $this->displayStartDate = $displayStartDate;
746
747
        return $this;
748
    }
749
750
    public function getDisplayEndDate(): ?DateTime
751
    {
752
        return $this->displayEndDate;
753
    }
754
755
    public function setDisplayEndDate(?DateTime $displayEndDate): self
756
    {
757
        $this->displayEndDate = $displayEndDate;
758
759
        return $this;
760
    }
761
762
    public function getGeneralCoaches(): ReadableCollection
763
    {
764
        return $this->getGeneralCoachesSubscriptions()
765
            ->map(fn (SessionRelUser $subscription) => $subscription->getUser())
766
        ;
767
    }
768
769
    #[Groups(['user_subscriptions:sessions'])]
770
    public function getGeneralCoachesSubscriptions(): Collection
771
    {
772
        $criteria = Criteria::create()->where(Criteria::expr()->eq('relationType', self::GENERAL_COACH));
773
774
        return $this->users->matching($criteria);
775
    }
776
777
    public function hasUserAsGeneralCoach(User $user): bool
778
    {
779
        $criteria = Criteria::create()
780
            ->where(
781
                Criteria::expr()->eq('relationType', self::GENERAL_COACH)
782
            )
783
            ->andWhere(
784
                Criteria::expr()->eq('user', $user)
785
            )
786
        ;
787
788
        return $this->users->matching($criteria)->count() > 0;
789
    }
790
791
    public function addGeneralCoach(User $coach): self
792
    {
793
        return $this->addUserInSession(self::GENERAL_COACH, $coach);
794
    }
795
796
    public function addUserInSession(int $relationType, User $user): self
797
    {
798
        $sessionRelUser = (new SessionRelUser())->setUser($user)->setRelationType($relationType);
799
        $this->addUserSubscription($sessionRelUser);
800
801
        return $this;
802
    }
803
804
    public function removeGeneralCoach(User $user): self
805
    {
806
        $this->removeUserInSession(self::GENERAL_COACH, $user);
807
808
        return $this;
809
    }
810
811
    public function removeUserInSession(int $relationType, User $user): self
812
    {
813
        $criteria = Criteria::create()
814
            ->where(
815
                Criteria::expr()->eq('relationType', $relationType)
816
            )
817
            ->andWhere(
818
                Criteria::expr()->eq('user', $user)
819
            )
820
        ;
821
        $subscriptions = $this->users->matching($criteria);
822
823
        foreach ($subscriptions as $subscription) {
824
            $this->removeUserSubscription($subscription);
825
        }
826
827
        return $this;
828
    }
829
830
    public function removeUserSubscription(SessionRelUser $subscription): self
831
    {
832
        if ($this->hasUser($subscription)) {
833
            $subscription->setSession(null);
834
            $this->users->removeElement($subscription);
835
            $this->nbrUsers--;
836
        }
837
838
        return $this;
839
    }
840
841
    public function getCategory(): ?SessionCategory
842
    {
843
        return $this->category;
844
    }
845
846
    public function setCategory(?SessionCategory $category): self
847
    {
848
        $this->category = $category;
849
850
        return $this;
851
    }
852
853
    /**
854
     * Check if session is visible.
855
     */
856
    public function isActive(): bool
857
    {
858
        $now = new DateTime('now');
859
860
        return $now > $this->getAccessStartDate();
861
    }
862
863
    public function getAccessStartDate(): ?DateTime
864
    {
865
        return $this->accessStartDate;
866
    }
867
868
    public function setAccessStartDate(?DateTime $accessStartDate): self
869
    {
870
        $this->accessStartDate = $accessStartDate;
871
872
        return $this;
873
    }
874
875
    public function isActiveForStudent(): bool
876
    {
877
        $start = $this->getAccessStartDate();
878
        $end = $this->getAccessEndDate();
879
880
        return $this->compareDates($start, $end);
881
    }
882
883
    public function getAccessEndDate(): ?DateTime
884
    {
885
        return $this->accessEndDate;
886
    }
887
888
    public function setAccessEndDate(?DateTime $accessEndDate): self
889
    {
890
        $this->accessEndDate = $accessEndDate;
891
892
        return $this;
893
    }
894
895
    public function isActiveForCoach(): bool
896
    {
897
        $start = $this->getCoachAccessStartDate();
898
        $end = $this->getCoachAccessEndDate();
899
900
        return $this->compareDates($start, $end);
901
    }
902
903
    public function getCoachAccessStartDate(): ?DateTime
904
    {
905
        return $this->coachAccessStartDate;
906
    }
907
908
    public function setCoachAccessStartDate(?DateTime $coachAccessStartDate): self
909
    {
910
        $this->coachAccessStartDate = $coachAccessStartDate;
911
912
        return $this;
913
    }
914
915
    public function getCoachAccessEndDate(): ?DateTime
916
    {
917
        return $this->coachAccessEndDate;
918
    }
919
920
    public function setCoachAccessEndDate(?DateTime $coachAccessEndDate): self
921
    {
922
        $this->coachAccessEndDate = $coachAccessEndDate;
923
924
        return $this;
925
    }
926
927
    /**
928
     * Compare the current date with start and end access dates.
929
     * Either missing date is interpreted as no limit.
930
     *
931
     * @return bool whether now is between the session access start and end dates
932
     */
933
    public function isCurrentlyAccessible(): bool
934
    {
935
        $now = new DateTime();
936
937
        return (!$this->accessStartDate || $now >= $this->accessStartDate) && (!$this->accessEndDate || $now <= $this->accessEndDate);
938
    }
939
940
    public function addCourse(Course $course): self
941
    {
942
        $sessionRelCourse = (new SessionRelCourse())->setCourse($course);
943
        $this->addCourses($sessionRelCourse);
944
945
        return $this;
946
    }
947
948
    /**
949
     * Removes a course from this session.
950
     *
951
     * @param Course $course the course to remove from this session
952
     *
953
     * @return bool whether the course was actually found in this session and removed from it
954
     */
955
    public function removeCourse(Course $course): bool
956
    {
957
        $relCourse = $this->getCourseSubscription($course);
958
        if (null !== $relCourse) {
959
            $this->courses->removeElement($relCourse);
960
            $this->setNbrCourses(\count($this->courses));
961
962
            return true;
963
        }
964
965
        return false;
966
    }
967
968
    /**
969
     * Add a user course subscription.
970
     * If user status in session is student, then increase number of course users.
971
     * Status example: Session::STUDENT.
972
     */
973
    public function addUserInCourse(int $status, User $user, Course $course): SessionRelCourseRelUser
974
    {
975
        $userRelCourseRelSession = (new SessionRelCourseRelUser())
976
            ->setCourse($course)
977
            ->setUser($user)
978
            ->setSession($this)
979
            ->setStatus($status)
980
        ;
981
982
        $this->addSessionRelCourseRelUser($userRelCourseRelSession);
983
984
        if (self::STUDENT === $status) {
985
            $sessionCourse = $this->getCourseSubscription($course);
986
            $sessionCourse->setNbrUsers($sessionCourse->getNbrUsers() + 1);
987
        }
988
989
        return $userRelCourseRelSession;
990
    }
991
992
    /**
993
     * currentCourse is set in CidReqListener.
994
     */
995
    public function getCurrentCourse(): ?Course
996
    {
997
        return $this->currentCourse;
998
    }
999
1000
    /**
1001
     * currentCourse is set in CidReqListener.
1002
     */
1003
    public function setCurrentCourse(Course $course): self
1004
    {
1005
        // If the session is registered in the course session list.
1006
        $exists = $this->getCourses()
1007
            ->exists(
1008
                fn ($key, $element) => $course->getId() === $element->getCourse()->getId()
1009
            )
1010
        ;
1011
1012
        if ($exists) {
1013
            $this->currentCourse = $course;
1014
        }
1015
1016
        return $this;
1017
    }
1018
1019
    public function getSendSubscriptionNotification(): bool
1020
    {
1021
        return $this->sendSubscriptionNotification;
1022
    }
1023
1024
    public function setSendSubscriptionNotification(bool $sendNotification): self
1025
    {
1026
        $this->sendSubscriptionNotification = $sendNotification;
1027
1028
        return $this;
1029
    }
1030
1031
    /**
1032
     * Get user from course by status.
1033
     */
1034
    public function getSessionRelCourseRelUsersByStatus(Course $course, int $status): Collection
1035
    {
1036
        $criteria = Criteria::create()
1037
            ->where(
1038
                Criteria::expr()->eq('course', $course)
1039
            )
1040
            ->andWhere(
1041
                Criteria::expr()->eq('status', $status)
1042
            )
1043
        ;
1044
1045
        return $this->sessionRelCourseRelUsers->matching($criteria);
1046
    }
1047
1048
    public function getSessionRelCourseRelUserInCourse(Course $course): Collection
1049
    {
1050
        $criteria = Criteria::create()
1051
            ->where(
1052
                Criteria::expr()->eq('course', $course)
1053
            )
1054
        ;
1055
1056
        return $this->sessionRelCourseRelUsers->matching($criteria);
1057
    }
1058
1059
    public function getIssuedSkills(): Collection
1060
    {
1061
        return $this->issuedSkills;
1062
    }
1063
1064
    public function getCurrentUrl(): AccessUrl
1065
    {
1066
        return $this->currentUrl;
1067
    }
1068
1069
    public function setCurrentUrl(AccessUrl $url): self
1070
    {
1071
        $urlList = $this->getUrls();
1072
        foreach ($urlList as $item) {
1073
            if ($item->getUrl()->getId() === $url->getId()) {
1074
                $this->currentUrl = $url;
1075
1076
                break;
1077
            }
1078
        }
1079
1080
        return $this;
1081
    }
1082
1083
    /**
1084
     * @return Collection<int, EntityAccessUrlInterface>
1085
     */
1086
    public function getUrls(): Collection
1087
    {
1088
        return $this->urls;
1089
    }
1090
1091
    public function setUrls(Collection $urls): self
1092
    {
1093
        $this->urls = new ArrayCollection();
1094
        foreach ($urls as $url) {
1095
            $this->addUrls($url);
1096
        }
1097
1098
        return $this;
1099
    }
1100
1101
    public function addUrls(AccessUrlRelSession $url): self
1102
    {
1103
        $url->setSession($this);
1104
        $this->urls->add($url);
1105
1106
        return $this;
1107
    }
1108
1109
    public function addAccessUrl(?AccessUrl $url): self
1110
    {
1111
        $accessUrlRelSession = new AccessUrlRelSession();
1112
        $accessUrlRelSession->setUrl($url);
1113
        $accessUrlRelSession->setSession($this);
1114
        $this->addUrls($accessUrlRelSession);
1115
1116
        return $this;
1117
    }
1118
1119
    public function getPosition(): int
1120
    {
1121
        return $this->position;
1122
    }
1123
1124
    public function setPosition(int $position): self
1125
    {
1126
        $this->position = $position;
1127
1128
        return $this;
1129
    }
1130
1131
    public function getSessionAdmins(): ReadableCollection
1132
    {
1133
        return $this->getGeneralAdminsSubscriptions()
1134
            ->map(fn (SessionRelUser $subscription) => $subscription->getUser())
1135
        ;
1136
    }
1137
1138
    public function getGeneralAdminsSubscriptions(): Collection
1139
    {
1140
        $criteria = Criteria::create()->where(Criteria::expr()->eq('relationType', self::SESSION_ADMIN));
1141
1142
        return $this->users->matching($criteria);
1143
    }
1144
1145
    public function hasUserAsSessionAdmin(User $user): bool
1146
    {
1147
        $criteria = Criteria::create()
1148
            ->where(
1149
                Criteria::expr()->eq('relationType', self::SESSION_ADMIN)
1150
            )
1151
            ->andWhere(
1152
                Criteria::expr()->eq('user', $user)
1153
            )
1154
        ;
1155
1156
        return $this->users->matching($criteria)->count() > 0;
1157
    }
1158
1159
    public function addSessionAdmin(User $sessionAdmin): self
1160
    {
1161
        return $this->addUserInSession(self::SESSION_ADMIN, $sessionAdmin);
1162
    }
1163
1164
    public function getSkills(): Collection
1165
    {
1166
        return $this->skills;
1167
    }
1168
1169
    public function getResourceLinks(): Collection
1170
    {
1171
        return $this->resourceLinks;
1172
    }
1173
1174
    public function getImage(): ?Asset
1175
    {
1176
        return $this->image;
1177
    }
1178
1179
    public function setImage(?Asset $asset): self
1180
    {
1181
        $this->image = $asset;
1182
1183
        return $this;
1184
    }
1185
1186
    public function hasImage(): bool
1187
    {
1188
        return null !== $this->image;
1189
    }
1190
1191
    public function setImageUrl(?string $imageUrl): self
1192
    {
1193
        $this->imageUrl = $imageUrl;
1194
1195
        return $this;
1196
    }
1197
1198
    public function getImageUrl(): ?string
1199
    {
1200
        return $this->imageUrl;
1201
    }
1202
1203
    /**
1204
     * Check if $user is course coach in any course.
1205
     */
1206
    public function hasCoachInCourseList(User $user): bool
1207
    {
1208
        foreach ($this->courses as $sessionCourse) {
1209
            if ($this->hasCourseCoachInCourse($user, $sessionCourse->getCourse())) {
1210
                return true;
1211
            }
1212
        }
1213
1214
        return false;
1215
    }
1216
1217
    public function hasCourseCoachInCourse(User $user, ?Course $course = null): bool
1218
    {
1219
        if (null === $course) {
1220
            return false;
1221
        }
1222
1223
        return $this->hasUserInCourse($user, $course, self::COURSE_COACH);
1224
    }
1225
1226
    /**
1227
     * @param int $status if not set it will check if the user is registered
1228
     *                    with any status
1229
     */
1230
    public function hasUserInCourse(User $user, Course $course, ?int $status = null): bool
1231
    {
1232
        $relation = $this->getUserInCourse($user, $course, $status);
1233
1234
        return $relation->count() > 0;
1235
    }
1236
1237
    public function getUserInCourse(User $user, Course $course, ?int $status = null): Collection
1238
    {
1239
        $criteria = Criteria::create()
1240
            ->where(
1241
                Criteria::expr()->eq('course', $course)
1242
            )
1243
            ->andWhere(
1244
                Criteria::expr()->eq('user', $user)
1245
            )
1246
        ;
1247
1248
        if (null !== $status) {
1249
            $criteria->andWhere(Criteria::expr()->eq('status', $status));
1250
        }
1251
1252
        return $this->getSessionRelCourseRelUsers()->matching($criteria);
1253
    }
1254
1255
    /**
1256
     * Check if $user is student in any course.
1257
     */
1258
    public function hasStudentInCourseList(User $user): bool
1259
    {
1260
        foreach ($this->courses as $sessionCourse) {
1261
            if ($this->hasStudentInCourse($user, $sessionCourse->getCourse())) {
1262
                return true;
1263
            }
1264
        }
1265
1266
        return false;
1267
    }
1268
1269
    public function hasStudentInCourse(User $user, Course $course): bool
1270
    {
1271
        return $this->hasUserInCourse($user, $course, self::STUDENT);
1272
    }
1273
1274
    protected function compareDates(?DateTime $start, ?DateTime $end = null): bool
1275
    {
1276
        $now = new DateTime('now');
1277
1278
        if (!empty($start) && !empty($end)) {
1279
            return $now >= $start && $now <= $end;
1280
        }
1281
1282
        if (!empty($start)) {
1283
            return $now >= $start;
1284
        }
1285
1286
        return !empty($end) && $now <= $end;
1287
    }
1288
1289
    /**
1290
     * @return Collection<int, SessionRelCourseRelUser>
1291
     */
1292
    #[Groups(['user_subscriptions:sessions'])]
1293
    public function getCourseCoachesSubscriptions(): Collection
1294
    {
1295
        return $this->getAllUsersFromCourse(self::COURSE_COACH);
1296
    }
1297
1298
    public function isAvailableByDurationForUser(User $user): bool
1299
    {
1300
        $duration = $this->duration * 24 * 60 * 60;
1301
1302
        if (0 === $user->getTrackECourseAccess()->count()) {
1303
            return true;
1304
        }
1305
1306
        $trackECourseAccess = $user->getFirstAccessToSession($this);
1307
1308
        $firstAccess = $trackECourseAccess
1309
            ? $trackECourseAccess->getLoginCourseDate()->getTimestamp()
1310
            : 0;
1311
1312
        $userDurationData = $user->getSubscriptionToSession($this);
1313
1314
        $userDuration = $userDurationData
1315
            ? ($userDurationData->getDuration() * 24 * 60 * 60)
1316
            : 0;
1317
1318
        $totalDuration = $firstAccess + $duration + $userDuration;
1319
        $currentTime = time();
1320
1321
        return $totalDuration > $currentTime;
1322
    }
1323
1324
    public function getDaysLeftByUser(User $user): int
1325
    {
1326
        $userSessionSubscription = $user->getSubscriptionToSession($this);
1327
1328
        $duration = $this->duration;
1329
1330
        if ($userSessionSubscription) {
1331
            $duration += $userSessionSubscription->getDuration();
1332
        }
1333
1334
        $courseAccess = $user->getFirstAccessToSession($this);
1335
1336
        if (!$courseAccess) {
1337
            return $duration;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $duration could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
1338
        }
1339
1340
        $endDateInSeconds = $courseAccess->getLoginCourseDate()->getTimestamp() + $duration * 24 * 60 * 60;
1341
        $currentTime = time();
1342
1343
        return (int) round(($endDateInSeconds - $currentTime) / 60 / 60 / 24);
1344
    }
1345
1346
    private function getAccessVisibilityByDuration(User $user): int
1347
    {
1348
        // Session duration per student.
1349
        if ($this->getDuration() > 0) {
1350
            if ($this->hasCoach($user)) {
1351
                return self::AVAILABLE;
1352
            }
1353
1354
            $duration = $this->getDuration() * 24 * 60 * 60;
1355
            $courseAccess = $user->getFirstAccessToSession($this);
1356
1357
            // If there is a session duration but there is no previous
1358
            // access by the user, then the session is still available
1359
            if (!$courseAccess) {
1360
                return self::AVAILABLE;
1361
            }
1362
1363
            $currentTime = time();
1364
            $firstAccess = $courseAccess->getLoginCourseDate()->getTimestamp();
1365
            $userSessionSubscription = $user->getSubscriptionToSession($this);
1366
            $userDuration = $userSessionSubscription
1367
                ? $userSessionSubscription->getDuration() * 24 * 60 * 60
1368
                : 0;
1369
1370
            $totalDuration = $firstAccess + $duration + $userDuration;
1371
1372
            return $totalDuration > $currentTime ? self::AVAILABLE : $this->visibility;
1373
        }
1374
1375
        return self::AVAILABLE;
1376
    }
1377
1378
    /**
1379
     * Checks whether the user is a course or session coach.
1380
     */
1381
    public function hasCoach(User $user): bool
1382
    {
1383
        return $this->hasUserAsGeneralCoach($user) || $this->hasCoachInCourseList($user);
1384
    }
1385
1386
    private function getAcessVisibilityByDates(User $user): int
1387
    {
1388
        $now = new DateTime();
1389
1390
        $userIsCoach = $this->hasCoach($user);
1391
1392
        $sessionEndDate = $userIsCoach && $this->coachAccessEndDate
1393
            ? $this->coachAccessEndDate
1394
            : $this->accessEndDate;
1395
1396
        if (!$userIsCoach && $this->accessStartDate && $now < $this->accessStartDate) {
1397
            return self::LIST_ONLY;
1398
        }
1399
1400
        if ($sessionEndDate) {
1401
            return $now <= $sessionEndDate ? self::AVAILABLE : $this->visibility;
1402
        }
1403
1404
        return self::AVAILABLE;
1405
    }
1406
1407
    public function setAccessVisibilityByUser(User $user, bool $ignoreVisibilityForAdmins = true): int
1408
    {
1409
        if (($user->isAdmin() || $user->isSuperAdmin()) && $ignoreVisibilityForAdmins) {
1410
            $this->accessVisibility = self::AVAILABLE;
1411
        } elseif (!$this->getAccessStartDate() && !$this->getAccessEndDate()) {
1412
            // I don't care the session visibility.
1413
            $this->accessVisibility = $this->getAccessVisibilityByDuration($user);
1414
        } else {
1415
            $this->accessVisibility = $this->getAcessVisibilityByDates($user);
1416
        }
1417
1418
        return $this->accessVisibility;
1419
    }
1420
1421
    public function getAccessVisibility(): int
1422
    {
1423
        if (0 === $this->accessVisibility) {
1424
            throw new LogicException('Access visibility by user is not set');
1425
        }
1426
1427
        return $this->accessVisibility;
1428
    }
1429
1430
    public function getClosedOrHiddenCourses(): Collection
1431
    {
1432
        $closedVisibilities = [
1433
            Course::CLOSED,
1434
            Course::HIDDEN,
1435
        ];
1436
1437
        return $this->courses->filter(fn (SessionRelCourse $sessionRelCourse) => \in_array(
1438
            $sessionRelCourse->getCourse()->getVisibility(),
1439
            $closedVisibilities
1440
        ));
1441
    }
1442
}
1443