Passed
Pull Request — master (#5329)
by Angel Fernando Quiroz
07:03
created

ChatController::ajax()   C

Complexity

Conditions 12
Paths 16

Size

Total Lines 101
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 63
nc 16
nop 2
dl 0
loc 101
rs 6.3806
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
10
use Chamilo\CoreBundle\Traits\ControllerTrait;
11
use Chamilo\CoreBundle\Traits\CourseControllerTrait;
12
use Chamilo\CoreBundle\Traits\ResourceControllerTrait;
13
use Chamilo\CourseBundle\Controller\CourseControllerInterface;
14
use Chamilo\CourseBundle\Repository\CChatConversationRepository;
15
use CourseChatUtils;
16
use Event;
17
use Symfony\Component\HttpFoundation\JsonResponse;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\Routing\Annotation\Route;
21
22
class ChatController extends AbstractResourceController implements CourseControllerInterface
23
{
24
    use ControllerTrait;
25
    use CourseControllerTrait;
26
    use ResourceControllerTrait;
27
28
    #[Route(path: '/resources/chat/', name: 'chat_home', options: ['expose' => true])]
29
    public function index(): Response
30
    {
31
        Event::event_access_tool(TOOL_CHAT);
0 ignored issues
show
Bug introduced by
The method event_access_tool() does not exist on Event. ( Ignorable by Annotation )

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

31
        Event::/** @scrutinizer ignore-call */ 
32
               event_access_tool(TOOL_CHAT);

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...
32
        $logInfo = [
33
            'tool' => TOOL_CHAT,
34
            'action' => 'start',
35
            'action_details' => 'start-chat',
36
        ];
37
        Event::registerLog($logInfo);
0 ignored issues
show
Bug introduced by
The method registerLog() does not exist on Event. ( Ignorable by Annotation )

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

37
        Event::/** @scrutinizer ignore-call */ 
38
               registerLog($logInfo);

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...
38
39
        return $this->render(
40
            '@ChamiloCore/Chat/chat.html.twig',
41
            [
42
                'restrict_to_coach' => ('true' === api_get_setting('chat.course_chat_restrict_to_coach')),
43
                'user' => api_get_user_info(),
44
            ]
45
        );
46
    }
47
48
    #[Route(path: '/resources/chat/conversations/', name: 'chat_ajax', options: ['expose' => true])]
49
    public function ajax(Request $request, ResourceNodeRepository $repo): Response
50
    {
51
        if (!api_protect_course_script(false)) {
52
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return Symfony\Component\HttpFoundation\Response. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
53
        }
54
55
        /** @var CChatConversationRepository $resourceRepo */
56
        $resourceRepo = $this->getRepository('chat', 'conversations');
57
58
        $courseId = api_get_course_int_id();
59
        $userId = api_get_user_id();
60
        $sessionId = api_get_session_id();
61
        $groupId = api_get_group_id();
62
        $json = [
63
            'status' => false,
64
        ];
65
        $parentResourceNode = $this->getParentResourceNode($request);
66
67
        $courseChatUtils = new CourseChatUtils(
68
            $courseId,
69
            $userId,
70
            $sessionId,
71
            $groupId,
72
            $parentResourceNode,
73
            $resourceRepo
74
        );
75
76
        $action = $request->get('action');
77
78
        switch ($action) {
79
            case 'chat_logout':
80
                $logInfo = [
81
                    'tool' => TOOL_CHAT,
82
                    'action' => 'exit',
83
                    'action_details' => 'exit-chat',
84
                ];
85
                Event::registerLog($logInfo);
86
87
                break;
88
89
            case 'track':
90
                $courseChatUtils->keepUserAsConnected();
91
                $courseChatUtils->disconnectInactiveUsers();
92
93
                $friend = isset($_REQUEST['friend']) ? (int) $_REQUEST['friend'] : 0;
94
                // $filePath = $courseChatUtils->getFileName(true, $friend);
95
                // $newFileSize = file_exists($filePath) ? filesize($filePath) : 0;
96
                // $oldFileSize = isset($_GET['size']) ? (int) $_GET['size'] : -1;
97
                $newUsersOnline = $courseChatUtils->countUsersOnline();
98
                $oldUsersOnline = isset($_GET['users_online']) ? (int) $_GET['users_online'] : 0;
99
100
                $json = [
101
                    'status' => true,
102
                    'data' => [
103
                        // 'oldFileSize' => file_exists($filePath) ? filesize($filePath) : 0,
104
                        'oldFileSize' => false,
105
                        'history' => $courseChatUtils->readMessages(false, $friend),
106
                        'usersOnline' => $newUsersOnline,
107
                        'userList' => $newUsersOnline !== $oldUsersOnline ? $courseChatUtils->listUsersOnline() : null,
108
                        'currentFriend' => $friend,
109
                    ],
110
                ];
111
112
                break;
113
114
            case 'preview':
115
                $json = [
116
                    'status' => true,
117
                    'data' => [
118
                        'message' => $courseChatUtils->prepareMessage($_REQUEST['message']),
119
                    ],
120
                ];
121
122
                break;
123
124
            case 'reset':
125
                $friend = isset($_REQUEST['friend']) ? (int) $_REQUEST['friend'] : 0;
126
127
                $json = [
128
                    'status' => true,
129
                    'data' => $courseChatUtils->readMessages(true, $friend),
130
                ];
131
132
                break;
133
134
            case 'write':
135
                $friend = isset($_REQUEST['friend']) ? (int) $_REQUEST['friend'] : 0;
136
                $status = $courseChatUtils->saveMessage($_REQUEST['message'], $friend);
137
138
                $json = [
139
                    'status' => $status,
140
                    'data' => [
141
                        'writed' => $status,
142
                    ],
143
                ];
144
145
                break;
146
        }
147
148
        return new JsonResponse($json);
149
    }
150
}
151