Passed
Push — develop ( ef53f3...80bc53 )
by BENARD
08:34
created

MarkAsRead   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 26
c 1
b 0
f 0
dl 0
loc 46
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 32 4
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ProjetNormandie\ForumBundle\Controller\Topic;
6
7
use ProjetNormandie\ForumBundle\Entity\Topic;
8
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
9
use ProjetNormandie\ForumBundle\Service\TopicReadService;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Contracts\Translation\TranslatorInterface;
12
13
class MarkAsRead extends AbstractController
14
{
15
    private TopicReadService $topicReadService;
16
    private TranslatorInterface $translator;
17
18
    public function __construct(TopicReadService $topicReadService, TranslatorInterface $translator)
19
    {
20
        $this->topicReadService = $topicReadService;
21
        $this->translator = $translator;
22
    }
23
24
    /**
25
     * Marque un topic comme lu pour l'utilisateur connecté
26
     */
27
    public function __invoke(Topic $topic): JsonResponse
28
    {
29
        $user = $this->getUser();
30
31
        if (!$user) {
32
            return new JsonResponse([
33
                'error' => $this->translator->trans('error.authentication_required')
34
            ], 401);
35
        }
36
37
        try {
38
            $result = $this->topicReadService->markTopicAsRead($user, $topic);
39
40
            if ($result['wasAlreadyRead']) {
41
                return new JsonResponse([
42
                    'success' => true,
43
                    'message' => $this->translator->trans('topic.already_read'),
44
                    'forumAlsoMarkedAsRead' => false
45
                ]);
46
            }
47
48
            return new JsonResponse([
49
                'success' => true,
50
                'message' => $this->translator->trans('topic.marked_as_read'),
51
                'forumAlsoMarkedAsRead' => $result['forumMarkedAsRead']
52
            ]);
53
54
        } catch (\Exception $e) {
55
            return new JsonResponse([
56
                'success' => false,
57
                'error' => $this->translator->trans('error.mark_as_read_failed')
58
            ], 500);
59
        }
60
    }
61
}
62