Completed
Push — master ( 6c7852...c45dbb )
by De Cramer
14s
created

CustomChat   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 243
Duplicated Lines 7.82 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 26
c 2
b 1
f 0
lcom 1
cbo 8
dl 19
loc 243
ccs 0
cts 89
cp 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
D onPlayerChat() 10 81 17
B sendChat() 0 41 3
A setStatus() 0 4 1
A onApplicationInit() 0 4 1
A onApplicationReady() 9 9 2
A onApplicationStop() 0 4 1

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
namespace eXpansion\Bundle\CustomChat\Plugins;
4
5
6
use eXpansion\Framework\AdminGroups\Helpers\AdminGroups;
7
use eXpansion\Framework\Core\DataProviders\Listener\ListenerInterfaceExpApplication;
8
use eXpansion\Framework\Core\Helpers\ChatNotification;
9
use eXpansion\Framework\Core\Services\Console;
10
use eXpansion\Framework\Core\Storage\Data\Player;
11
use eXpansion\Framework\Core\Storage\PlayerStorage;
12
use eXpansion\Framework\GameManiaplanet\DataProviders\Listener\ListenerInterfaceMpLegacyChat;
13
use eXpansion\Framework\Notifications\Services\Notifications;
14
use Maniaplanet\DedicatedServer\Connection;
15
use Psr\Log\LoggerInterface;
16
17
18
class CustomChat implements ListenerInterfaceExpApplication, ListenerInterfaceMpLegacyChat
19
{
20
    /** @var Connection */
21
    protected $connection;
22
23
    /** @var Console */
24
    protected $console;
25
26
    /** @var AdminGroups */
27
    protected $adminGroups;
28
29
    /** @var bool */
30
    protected $enabled = true;
31
    /**
32
     * @var ChatNotification
33
     */
34
    private $chatNotification;
35
    /**
36
     * @var PlayerStorage
37
     */
38
    private $playerStorage;
39
    /**
40
     * @var LoggerInterface
41
     */
42
    private $logger;
43
    /**
44
     * @var Notifications
45
     */
46
    private $notifications;
47
48
    /**
49
     * CustomChat constructor.
50
     * @param Connection       $connection
51
     * @param Console          $console
52
     * @param AdminGroups      $adminGroups
53
     * @param ChatNotification $chatNotification
54
     * @param PlayerStorage    $playerStorage
55
     * @param Notifications    $notifications
56
     * @param LoggerInterface  $logger
57
     */
58
    function __construct(
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...
59
        Connection $connection,
60
        Console $console,
61
        AdminGroups $adminGroups,
62
        ChatNotification $chatNotification,
63
        PlayerStorage $playerStorage,
64
        Notifications $notifications,
65
        LoggerInterface $logger
66
    ) {
67
        $this->connection = $connection;
68
        $this->console = $console;
69
        $this->adminGroups = $adminGroups;
70
        $this->chatNotification = $chatNotification;
71
        $this->playerStorage = $playerStorage;
72
        $this->logger = $logger;
73
        $this->notifications = $notifications;
74
    }
75
76
    /**
77
     * Called when a player chats.
78
     *
79
     * @param Player $player
80
     * @param        $text
81
     *
82
     * @return void
83
     */
84
    public function onPlayerChat(Player $player, $text)
85
    {
86
        $text = trim($text);
87
        $nick = trim($player->getNickName());
88
89
        if ($player->getPlayerId() == 0) {
90
            return;
91
        }
92
93
        if ($player->getPlayerId() != 0 && substr($text, 0, 1) != "/") {
94
            $matches = [];
95
96
            if ($this->enabled || $this->adminGroups->isAdmin($player->getLogin())) {
97
                $matchFound = false;
98
                $matchLogin = [];
99
100
                //match urls and shorten them to fit in chat.
101
                if (preg_match_all('/(\$l\[?){0,1}(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)(\]?)/',
102
                    $text, $urls)) {
103
                    foreach ($urls[0] as $k => $url) {
104
                        if ($urls[1][$k] != '$l[') {
105
                            $url = str_replace('$l', '', $url);
106
                            $text = str_replace('$l', '', $text);
107
108
                            if (strlen($url) >= 33) {
109
                                $short = substr($url, 0, 30)."...";
110
                                $text = str_replace($url, '$l['.$url.']'.$short.'$l', $text);
111
                            } else {
112
                                $text = str_replace($url, '$l'.$url.'$l', $text);
113
                            }
114
                        }
115
116
                    }
117
118
                }
119
120
                if (preg_match_all("/(\s|\G)(\@(?P<login>[\w-\._]+)[\s]{0,1})/", $text, $matches)) {
121
                    $group = [];
122
123
                    foreach ($matches['login'] as $login) {
124
                        foreach ($this->playerStorage->getOnline() as $player2) {
125
                            if ($player2->getLogin() == $login) {
126
                                $matchFound = true;
127
                                $matchLogin[$player2->getLogin()] = $player2->getLogin();
128
                            } else {
129
                                if (!in_array($player->getLogin(), $matchLogin)) {
130
                                    $group[$player2->getLogin()] = $player2->getLogin();
131
                                }
132
                            }
133
                        }
134
                    }
135
136
                    $diff = array_diff($group, $matchLogin);
137
138
                    if ($matchFound) {
139
                        $this->sendChat($player, $text, '$f90', $matchLogin);
140
                        $this->notifications->notice($text, [], "Chat Notification", 0, $matchLogin);
0 ignored issues
show
Documentation introduced by
$matchLogin is of type array, but the function expects a string|object<eXpansion\...\UserGroups\Group>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
141
                        if (count($diff) > 0) {
142
                            $this->sendChat($player, $text, '$ff0', $group);
143
                        }
144
                        $this->console->writeln('$ff0['.$nick.'$ff0] '.$text);
145
146
                        return;
147 View Code Duplication
                    } else {
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...
148
                        $this->sendChat($player, $text, '$ff0', null);
149
                        $this->console->writeln('$ff0['.$nick.'$ff0] '.$text);
150
151
                        return;
152
                    }
153 View Code Duplication
                } else {
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...
154
                    $this->sendChat($player, $text, '$ff0', null);
155
                    $this->console->writeln('$ff0['.$nick.'$ff0] '.$text);
156
                }
157
            } else {
158
                $this->console->writeln('$333['.$nick.'$333] '.$text);
159
                $this->chatNotification->sendMessage('expansion_customchat.chat.disabledstate',
160
                    $player->getLogin());
161
            }
162
        }
163
164
    }
165
166
    /**
167
     * @param Player        $player
168
     * @param        string $text
169
     * @param        string $color
170
     * @param null          $group
171
     */
172
    private function sendChat(Player $player, $text, $color, $group = null)
173
    {
174
        $nick = trim($player->getNickName());
175
        $nick = str_ireplace('$w', '', $nick);
176
        $nick = str_ireplace('$z', '$z$s', $nick);
177
        $replacements = [
178
            "(y)" => "",
179
            ":yes:" => "",
180
            ":thumbsup:" => "",
181
            ":no:" => "",
182
            ":thumbsdown:" => "",
183
            "(n)" => "",
184
            ":happy:" => "",
185
            ":smile:" => "",
186
            ":sad:" => "",
187
            ":heart:" => '$d00$z$s',
188
            "<3" => '$d00$z$s',
189
190
        ];
191
        // fix for chat...
192
        $nick = str_replace(['$<', '$>'], '', $nick);
193
        $text = str_replace(['$<', '$>'], '', $text);
194
        $text = str_replace(array_keys($replacements), array_values($replacements), $text);
195
        $separator = '$aaa⏵';
196
        $prefix = '';
197
        $postfix = '';
198
        if ($this->adminGroups->isAdmin($player->getLogin())) {
199
            $separator = ' $eed$n►$z$s';
200
            $prefix = '';
201
            $postfix = '';
202
        }
203
204
        try {
205
            $this->connection->chatSendServerMessage(
206
                $prefix.'$fff$<'.$nick.'$>$z$s'.$postfix.$separator.' '.$color.$text, $group
207
            );
208
        } catch (\Exception $e) {
209
            $this->console->writeln('$ff0 error while sending chat: $fff'.$e->getMessage());
210
            $this->logger->error("Error while sending custom chat", ['exception' => $e]);
211
        }
212
    }
213
214
    /**
215
     * Set the status of the plugin
216
     *
217
     * @param boolean $status
218
     *
219
     * @return void
220
     */
221
    public function setStatus($status)
222
    {
223
        $this->enabled = $status;
224
    }
225
226
    /**
227
     * called at eXpansion init
228
     *
229
     * @return void
230
     */
231
    public function onApplicationInit()
232
    {
233
        // do nothing
234
    }
235
236
    /**
237
     * called when init is done and callbacks are enabled
238
     *
239
     * @return void
240
     */
241 View Code Duplication
    public function onApplicationReady()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
242
    {
243
        try {
244
            $this->connection->chatEnableManualRouting();
245
        } catch (\Exception $e) {
246
            $this->console->writeln('Error while enabling custom chat: $f00'.$e->getMessage());
247
            $this->logger->error("Error enabling custom chat", ['exception' => $e]);
248
        }
249
    }
250
251
    /**
252
     * called when requesting application stop
253
     *
254
     * @return void
255
     */
256
    public function onApplicationStop()
257
    {
258
        // do nothing
259
    }
260
}
261