Completed
Branch master (ebb499)
by Alexey
04:15
created

ChatsController   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 136
Duplicated Lines 18.38 %

Coupling/Cohesion

Components 0
Dependencies 7

Importance

Changes 0
Metric Value
dl 25
loc 136
rs 10
c 0
b 0
f 0
wmc 23
lcom 0
cbo 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
C eventsAction() 5 53 9
A deleteMsgAction() 5 18 3
B banUserAction() 5 27 4
C sendFormAction() 10 31 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Chat Controller
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
class ChatsController extends Controller {
12
13
    public function eventsAction($chatId = 0) {
1 ignored issue
show
Coding Style introduced by
eventsAction uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
14
        $chatId = (int) $chatId;
15
        $result = new Server\Result();
16 View Code Duplication
        if (!$chatId || !($chat = \Chats\Chat::get($chatId))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
17
            $result->success = false;
18
            $result->content = 'Такого чата не существует';
19
            $result->send();
20
        }
21
        $where = [
22
            ['chat_id', $chatId],
23
            ['delete', 0]
24
        ];
25
        if (!empty($_GET['lastEventDate'])) {
26
            $where[] = ['date_create', $_GET['lastEventDate'], '>'];
27
        }
28
        $result->content = [
29
            'members' => [],
30
            'messages' => []
31
        ];
32
        if (Users\User::$cur->id) {
33
            $member = \Chats\Chat\Member::get([['chat_id', $chatId], ['user_id', Users\User::$cur->id]]);
34
            if (!$member) {
35
                $member = new \Chats\Chat\Member();
36
                $member->user_id = Users\User::$cur->id;
37
                $member->chat_id = $chatId;
38
            }
39
            $member->date_last_active = date('Y-m-d H:i:s');
40
            $member->save();
41
        }
42
43
        $messages = \Chats\Chat\Message::getList(['where' => $where, 'limit' => 20, 'order' => ['date_create', 'DESC']]);
44
        if ($messages) {
45
            $messages = array_reverse($messages);
46
            foreach ($messages as $message) {
47
                $msg = [
48
                    'message' => $message->_params,
49
                    'fullUserName' => $message->user->name(),
50
                    'userFirstName' => $message->user->info->first_name,
51
                    'userPhoto' => $message->user->info->photo ? $message->user->info->photo->path : '/static/system/images/no-image.png'
52
                ];
53
                $result->content['messages'][] = $msg;
54
            }
55
            /* $members = $this->module->getMembers($chatId);
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
56
              foreach ($members as $member) {
57
              $result->content['members'][$member->user_id] = [
58
              'fullUserName' => $member->user->name(),
59
              'userFirstName' => $member->user->info->first_name,
60
              'userPhoto' => $member->user->info->photo ? $member->user->info->photo->path : '/static/system/images/no-image.png'
61
              ];
62
              } */
63
        }
64
        $result->send();
65
    }
66
67
    function deleteMsgAction($messageId) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
68
        $result = new Server\Result();
69 View Code Duplication
        if (!\Users\User::$cur->isAdmin()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
70
            $result->success = false;
71
            $result->content = 'Вы не админ';
72
            $result->send();
73
        }
74
        $msg = Chats\Chat\Message::get((int) $messageId);
75
        if (!$msg) {
76
            $result->success = false;
77
            $result->content = 'Сообщение не найдено';
78
            $result->send();
79
        }
80
        $msg->delete = 1;
81
        $msg->save();
82
        $result->successMsg = 'Сообщение удалено';
83
        $result->send();
84
    }
85
86
    function banUserAction($messageId) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
87
        $result = new Server\Result();
88 View Code Duplication
        if (!\Users\User::$cur->isAdmin()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
            $result->success = false;
90
            $result->content = 'Вы не админ';
91
            $result->send();
92
        }
93
        $msg = Chats\Chat\Message::get((int) $messageId);
94
        if (!$msg) {
95
            $result->success = false;
96
            $result->content = 'Сообщение не найдено';
97
            $result->send();
98
        }
99
        $ban = new Chats\Chat\Ban();
100
        $ban->user_id = $msg->user_id;
101
        $ban->chat_id = $msg->chat_id;
102
        $ban->chat_message_id = $msg->id;
103
        $ban->save();
104
        $msgs = Chats\Chat\Message::getList(['where' => ['user_id', $ban->user_id]]);
105
        foreach ($msgs as $msg) {
106
            $msg->delete = 1;
107
            $msg->save();
108
        }
109
        $result->content = array_flip(array_keys($msgs));
110
        $result->successMsg = 'Сообщение удалено';
111
        $result->send();
112
    }
113
114
    public function sendFormAction($chatId = 0) {
1 ignored issue
show
Coding Style introduced by
sendFormAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
115
        $chatId = (int) $chatId;
116
        $result = new Server\Result();
117 View Code Duplication
        if (!$chatId || !($chat = \Chats\Chat::get($chatId))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
            $result->success = false;
119
            $result->content = 'Такого чата не существует';
120
            $result->send();
121
        }
122 View Code Duplication
        if (!Users\User::$cur->id) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
123
            $result->success = false;
124
            $result->content = 'Вы не авторизованы';
125
            $result->send();
126
        }
127
        if (empty($_POST['chat-message']) || !trim($_POST['chat-message'])) {
128
            $result->success = false;
129
            $result->content = 'Сообщение не может быть пустым';
130
            $result->send();
131
        }
132
        if (Chats\Chat\Ban::get(['user_id', \Users\User::$cur->id])) {
133
            $result->success = false;
134
            $result->content = 'Вы не можете писать в чат';
135
            $result->send();
136
        }
137
        $message = new \Chats\Chat\Message();
138
        $message->user_id = Users\User::$cur->id;
139
        $message->chat_id = $chatId;
140
        $message->text = htmlspecialchars(trim($_POST['chat-message']));
141
        $message->save();
142
        $result->successMsg = 'Ваше сообщение было отправлено';
143
        $result->send();
144
    }
145
146
}
147