CustomChat::onPlayerChat()   D
last analyzed

Complexity

Conditions 21
Paths 35

Size

Total Lines 91

Duplication

Lines 22
Ratio 24.18 %

Code Coverage

Tests 0
CRAP Score 462

Importance

Changes 0
Metric Value
dl 22
loc 91
ccs 0
cts 75
cp 0
rs 4.1666
c 0
b 0
f 0
cc 21
nc 35
nop 2
crap 462

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
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\Services\DedicatedConnection\Factory;
11
use eXpansion\Framework\Core\Storage\Data\Player;
12
use eXpansion\Framework\Core\Storage\PlayerStorage;
13
use eXpansion\Framework\GameManiaplanet\DataProviders\Listener\ListenerInterfaceMpLegacyChat;
14
use eXpansion\Framework\Notifications\Services\Notifications;
15
use Maniaplanet\DedicatedServer\Connection;
16
use Psr\Log\LoggerInterface;
17
18
19
class CustomChat implements ListenerInterfaceExpApplication, ListenerInterfaceMpLegacyChat
20
{
21
    /** @var Factory */
22
    protected $factory;
23
24
    /** @var Console */
25
    protected $console;
26
27
    /** @var AdminGroups */
28
    protected $adminGroups;
29
30
    /** @var bool */
31
    protected $enabled = true;
32
    /**
33
     * @var ChatNotification
34
     */
35
    private $chatNotification;
36
    /**
37
     * @var PlayerStorage
38
     */
39
    private $playerStorage;
40
    /**
41
     * @var LoggerInterface
42
     */
43
    private $logger;
44
    /**
45
     * @var Notifications
46
     */
47
    private $notifications;
48
49
    /**
50
     * CustomChat constructor.
51
     * @param Factory       $factory
52
     * @param Console          $console
53
     * @param AdminGroups      $adminGroups
54
     * @param ChatNotification $chatNotification
55
     * @param PlayerStorage    $playerStorage
56
     * @param Notifications    $notifications
57
     * @param LoggerInterface  $logger
58
     */
59 View Code Duplication
    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...
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...
60
        Factory $factory,
61
        Console $console,
62
        AdminGroups $adminGroups,
63
        ChatNotification $chatNotification,
64
        PlayerStorage $playerStorage,
65
        Notifications $notifications,
66
        LoggerInterface $logger
67
    ) {
68
        $this->factory = $factory;
69
        $this->console = $console;
70
        $this->adminGroups = $adminGroups;
71
        $this->chatNotification = $chatNotification;
72
        $this->playerStorage = $playerStorage;
73
        $this->logger = $logger;
74
        $this->notifications = $notifications;
75
    }
76
77
    /**
78
     * Called when a player chats.
79
     *
80
     * @param Player $player
81
     * @param        $text
82
     *
83
     * @return void
84
     */
85
    public function onPlayerChat(Player $player, $text)
86
    {
87
        $text = trim($text);
88
        $nick = trim($player->getNickName());
89
90
        if ($player->getPlayerId() == 0) {
91
            return;
92
        }
93
94
        if ($player->getPlayerId() != 0 && substr($text, 0, 1) != "/") {
95
            $matches = [];
96
97
            if ($this->enabled || $this->adminGroups->isAdmin($player->getLogin())) {
98
                $matchFound = false;
99
                $matchLogin = [];
100
101
                //match urls and shorten them to fit in chat.
102
                if (preg_match_all('/(\$[l,h]\[?){0,1}(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)(\]?)/',
103
                    $text, $urls)) {
104
                    foreach ($urls[0] as $k => $url) {
105
                        if ($urls[1][$k] == '$l' || $urls[1][$k] == '$L') {
106
                            $url = str_replace(['$l', '$L'], '', $url);
107
                            $text = str_replace(['$l', '$L'], '', $text);
108
109 View Code Duplication
                            if (strlen($url) >= 33) {
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...
110
                                $short = substr($url, 0, 30)."...";
111
                                $text = str_replace($url, '$l['.$url.']'.$short.'$l', $text);
112
                            } else {
113
                                $text = str_replace($url, '$l'.$url.'$l', $text);
114
                            }
115
                        } elseif ($urls[1][$k] == '$h' || $urls[1][$k] == '$H') {
116
                            $url = str_replace(['$h', '$H'], '', $url);
117
                            $text = str_replace(['$h', '$H'], '', $text);
118
119 View Code Duplication
                            if (strlen($url) >= 33) {
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...
120
                                $short = substr($url, 0, 30)."...";
121
                                $text = str_replace($url, '$h['.$url.']'.$short.'$h', $text);
122
                            } else {
123
                                $text = str_replace($url, '$h'.$url.'$h', $text);
124
                            }
125
                        }
126
127
                    }
128
129
                }
130
131
                if (preg_match_all("/(\s|\G)(\@(?P<login>[\w-\._]+)[\s]{0,1})/", $text, $matches)) {
132
                    $group = [];
133
134
                    foreach ($matches['login'] as $login) {
135
                        foreach ($this->playerStorage->getOnline() as $player2) {
136
                            if ($player2->getLogin() == $login) {
137
                                $matchFound = true;
138
                                $matchLogin[$player2->getLogin()] = $player2->getLogin();
139
                            } else {
140
                                if (!in_array($player->getLogin(), $matchLogin)) {
141
                                    $group[$player2->getLogin()] = $player2->getLogin();
142
                                }
143
                            }
144
                        }
145
                    }
146
147
                    $diff = array_diff($group, $matchLogin);
148
149
                    if ($matchFound) {
150
                        $this->sendChat($player, $text, '$f90', $matchLogin);
151
                        $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...
152
                        if (count($diff) > 0) {
153
                            $this->sendChat($player, $text, '$ff0', $group);
154
                        }
155
                        $this->console->writeln('$ff0['.$nick.'$ff0] '.$text);
156
157
                        return;
158 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...
159
                        $this->sendChat($player, $text, '$ff0', null);
160
                        $this->console->writeln('$ff0['.$nick.'$ff0] '.$text);
161
162
                        return;
163
                    }
164 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...
165
                    $this->sendChat($player, $text, '$ff0', null);
166
                    $this->console->writeln('$ff0['.$nick.'$ff0] '.$text);
167
                }
168
            } else {
169
                $this->console->writeln('$333['.$nick.'$333] '.$text);
170
                $this->chatNotification->sendMessage('expansion_customchat.chat.disabledstate',
171
                    $player->getLogin());
172
            }
173
        }
174
175
    }
176
177
    /**
178
     * @param Player        $player
179
     * @param        string $text
180
     * @param        string $color
181
     * @param null          $group
182
     */
183
    private function sendChat(Player $player, $text, $color, $group = null)
184
    {
185
        $nick = trim($player->getNickName());
186
        $nick = str_ireplace('$w', '', $nick);
187
        $nick = str_ireplace('$z', '$z$s', $nick);
188
        $replacements = [
189
            "(y)" => "",
190
            ":yes:" => "",
191
            ":thumbsup:" => "",
192
            ":no:" => "",
193
            ":thumbsdown:" => "",
194
            "(n)" => "",
195
            ":happy:" => "",
196
            ":smile:" => "",
197
            ":sad:" => "",
198
            ":heart:" => '$d00$z$s',
199
            "<3" => '$d00$z$s',
200
201
        ];
202
        // fix for chat...
203
        $nick = str_replace(['$<', '$>'], '', $nick);
204
        $text = str_replace(['$<', '$>'], '', $text);
205
        $text = str_replace(array_keys($replacements), array_values($replacements), $text);
206
        $separator = '$aaa⏵';
207
        $prefix = '';
208
        $postfix = '';
209
        if ($this->adminGroups->isAdmin($player->getLogin())) {
210
            $separator = ' $eed$n►$z$s';
211
            $prefix = '';
212
            $postfix = '';
213
        }
214
215
        try {
216
            $this->factory->getConnection()->chatSendServerMessage(
217
                $prefix.'$fff$<'.$nick.'$>$z$s'.$postfix.$separator.' '.$color.$text, $group
218
            );
219
        } catch (\Exception $e) {
220
            $this->console->writeln('$ff0 error while sending chat: $fff'.$e->getMessage());
221
            $this->logger->error("Error while sending custom chat", ['exception' => $e]);
222
        }
223
    }
224
225
    /**
226
     * Set the status of the plugin
227
     *
228
     * @param boolean $status
229
     *
230
     * @return void
231
     */
232
    public function setStatus($status)
233
    {
234
        $this->enabled = $status;
235
    }
236
237
    /**
238
     * called at eXpansion init
239
     *
240
     * @return void
241
     */
242
    public function onApplicationInit()
243
    {
244
        // do nothing
245
    }
246
247
    /**
248
     * called when init is done and callbacks are enabled
249
     *
250
     * @return void
251
     */
252 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...
253
    {
254
        try {
255
            $this->factory->getConnection()->chatEnableManualRouting();
256
        } catch (\Exception $e) {
257
            $this->console->writeln('Error while enabling custom chat: $f00'.$e->getMessage());
258
            $this->logger->error("Error enabling custom chat", ['exception' => $e]);
259
        }
260
    }
261
262
    /**
263
     * called when requesting application stop
264
     *
265
     * @return void
266
     */
267
    public function onApplicationStop()
268
    {
269
        // do nothing
270
    }
271
}
272