Completed
Push — master ( b2cd25...08acda )
by Paweł
26s queued 10s
created

UserLessonProvider::getCurrentUserLesson()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Provider;
4
5
use App\Factory\UserLessonFactoryInterface;
6
use App\Model\LessonInterface;
7
use App\Model\UserLessonInterface;
8
use App\Repository\UserLessonRepositoryInterface;
9
use Doctrine\ORM\EntityManagerInterface;
10
use Symfony\Component\Security\Core\Exception\AuthenticationException;
11
use Symfony\Component\Security\Core\Security;
12
use Symfony\Component\Security\Core\User\UserInterface;
13
14
class UserLessonProvider implements UserLessonProviderInterface
15
{
16
    private $userLessonRepository;
17
    private $security;
18
    private $userLessonFactory;
19
    private $entityManager;
20
21
    public function __construct(
22
        UserLessonRepositoryInterface $userLessonRepository,
23
        Security $security,
24
        UserLessonFactoryInterface $userLessonFactory,
25
        EntityManagerInterface $entityManager
26
    ) {
27
        $this->userLessonRepository = $userLessonRepository;
28
        $this->security = $security;
29
        $this->userLessonFactory = $userLessonFactory;
30
        $this->entityManager = $entityManager;
31
    }
32
33
    public function getCurrentUserLesson(LessonInterface $lesson): UserLessonInterface
34
    {
35
        $user = $this->security->getUser();
36
        if (!$user instanceof UserInterface) {
37
            throw new AuthenticationException('Looks like User is not authorized.');
38
        }
39
40
        $userLesson = $this->userLessonRepository->getOneByUserAndLesson($user, $lesson);
41
        if (null === $userLesson) {
42
            $userLesson = $this->userLessonFactory->create($user, $lesson);
43
            $this->entityManager->persist($userLesson);
44
        }
45
46
        return $userLesson;
47
    }
48
}
49