Passed
Push — develop ( cd696f...5a6fe9 )
by BENARD
02:18
created

ReadTopicSubscriber   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 18
c 1
b 0
f 0
dl 0
loc 37
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setRead() 0 16 5
A __construct() 0 4 1
A getSubscribedEvents() 0 4 1
1
<?php
2
namespace ProjetNormandie\ForumBundle\EventSubscriber;
3
4
use ApiPlatform\Symfony\EventListener\EventPriorities as EventPrioritiesAlias;
5
use ProjetNormandie\ForumBundle\Entity\Topic;
6
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpKernel\KernelEvents;
9
use Symfony\Component\HttpKernel\Event\RequestEvent;
10
use Doctrine\ORM\EntityManagerInterface;
11
use Symfony\Component\Security\Core\Security;
12
13
final class ReadTopicSubscriber implements EventSubscriberInterface
14
{
15
    private Security $security;
16
    private EntityManagerInterface $em;
17
18
    public function __construct(Security $security, EntityManagerInterface $em)
19
    {
20
        $this->security = $security;
21
        $this->em = $em;
22
    }
23
24
    public static function getSubscribedEvents(): array
25
    {
26
        return [
27
            KernelEvents::REQUEST => ['setRead', EventPrioritiesAlias::POST_READ],
28
        ];
29
    }
30
31
    /**
32
     * @param RequestEvent $event
33
     */
34
    public function setRead(RequestEvent $event)
35
    {
36
        $topic = $event->getRequest()->attributes->get('data');
37
        $method = $event->getRequest()->getMethod();
38
        $user = $this->security->getUser();
39
40
        if ($user && ($topic instanceof Topic) && $method == Request::METHOD_GET) {
41
            $userTopic = $this->em->getRepository('ProjetNormandie\ForumBundle\Entity\TopicUser')->findOneBy(
42
                array(
43
                    'user' => $user,
44
                    'topic' => $topic,
45
                )
46
            );
47
            if ($userTopic) {
48
                $userTopic->setBoolRead(true);
49
                $this->em->flush();
50
            }
51
        }
52
    }
53
}
54