Completed
Push — master ( 57b85a...97c445 )
by De Cramer
9s
created

PlayersWindow::createContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 70
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 70
ccs 0
cts 46
cp 0
rs 9.1724
c 0
b 0
f 0
cc 2
eloc 45
nc 2
nop 1
crap 6

How to fix   Long Method   

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\Players\Plugins\Gui;
4
5
use eXpansion\Framework\AdminGroups\Helpers\AdminGroups;
6
use eXpansion\Framework\Core\Helpers\Countries;
7
use eXpansion\Framework\Core\Helpers\TMString;
8
use eXpansion\Framework\Core\Model\Gui\Grid\DataCollectionFactory;
9
use eXpansion\Framework\Core\Model\Gui\Grid\GridBuilderFactory;
10
use eXpansion\Framework\Core\Model\Gui\ManialinkInterface;
11
use eXpansion\Framework\Core\Model\Gui\Window;
12
use eXpansion\Framework\Core\Model\Gui\WindowFactoryContext;
13
use eXpansion\Framework\Core\Plugins\Gui\GridWindowFactory;
14
use eXpansion\Framework\Core\Storage\PlayerStorage;
15
use eXpansion\Framework\GameManiaplanet\DataProviders\ChatCommandDataProvider;
16
use eXpansion\Framework\Gui\Components\uiButton;
17
use eXpansion\Framework\Gui\Components\uiLabel;
18
use eXpansion\Framework\Gui\Layouts\layoutRow;
19
use FML\Controls\Frame;
20
use Maniaplanet\DedicatedServer\Connection;
21
22
class PlayersWindow extends GridWindowFactory
23
{
24
    /**
25
     * @var PlayerStorage
26
     */
27
    private $playerStorage;
28
    /**
29
     * @var ChatCommandDataProvider
30
     */
31
    private $chatCommandDataProvider;
32
    /**
33
     * @var Connection
34
     */
35
    private $connection;
36
    /**
37
     * @var AdminGroups
38
     */
39
    private $adminGroups;
40
41
    /** @var Countries */
42
    protected $countries;
43
44
    /** @var null|string */
45
    protected $playerToSet = null;
46
47
    /**
48
     * PlayersWindow constructor.
49
     * @param                         $name
50
     * @param                         $sizeX
51
     * @param                         $sizeY
52
     * @param null                    $posX
53
     * @param null                    $posY
54
     * @param WindowFactoryContext    $context
55
     * @param PlayerStorage           $playerStorage
56
     * @param DataCollectionFactory   $dataCollectionFactory
57
     * @param GridBuilderFactory      $gridBuilderFactory
58
     * @param ChatCommandDataProvider $chatCommandDataProvider
59
     * @param Connection              $connection
60
     * @param AdminGroups             $adminGroups
61
     */
62 View Code Duplication
    public function __construct(
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...
63
        $name,
64
        $sizeX,
65
        $sizeY,
66
        $posX = null,
67
        $posY = null,
68
        WindowFactoryContext $context,
69
        PlayerStorage $playerStorage,
70
        DataCollectionFactory $dataCollectionFactory,
71
        GridBuilderFactory $gridBuilderFactory,
72
        ChatCommandDataProvider $chatCommandDataProvider,
73
        Connection $connection,
74
        AdminGroups $adminGroups,
75
        Countries $countries
76
    ) {
77
        parent::__construct($name, $sizeX, $sizeY, $posX, $posY, $context);
78
79
        $this->playerStorage = $playerStorage;
80
        $this->dataCollectionFactory = $dataCollectionFactory;
81
        $this->gridBuilderFactory = $gridBuilderFactory;
82
        $this->chatCommandDataProvider = $chatCommandDataProvider;
83
        $this->connection = $connection;
84
        $this->adminGroups = $adminGroups;
85
        $this->countries = $countries;
86
    }
87
88
    protected function createContent(ManialinkInterface $manialink)
89
    {
90
        parent::createContent($manialink);
91
92
        $manialink->setData('playerActions', []);
93
        $this->setPlayer($manialink, $manialink->getUserGroup()->getLogins()[0]);
94
95
        $recipient = $manialink->getUserGroup()->getLogins()[0];
96
97
        if ($this->adminGroups->isAdmin($recipient)) {
98
99
            $ignoreList = $this->uiFactory->createButton("expansion_players.gui.players.window.ignorelist")
100
                ->setTranslate(true)
101
                ->setAction(
102
                    $this->actionFactory->createManialinkAction(
103
                        $manialink,
104
                        [$this, "callbackChatCommand"],
105
                        ["action" => "//ignorelist"],
106
                        true
107
                    )
108
                );
109
110
            $guestList = $this->uiFactory->createButton("expansion_players.gui.players.window.guestlist")
111
                ->setTranslate(true)
112
                ->setAction(
113
                    $this->actionFactory->createManialinkAction(
114
                        $manialink,
115
                        [$this, "callbackChatCommand"],
116
                        ["action" => "//guestlist"],
117
                        true
118
                    )
119
                );
120
121
            $banList = $this->uiFactory->createButton("expansion_players.gui.players.window.banlist")
122
                ->setTranslate(true)
123
                ->setAction(
124
                    $this->actionFactory->createManialinkAction(
125
                        $manialink,
126
                        [$this, "callbackChatCommand"],
127
                        ["action" => "//banlist"],
128
                        true
129
                    )
130
                );
131
132
            $blackList = $this->uiFactory->createButton("expansion_players.gui.players.window.blacklist")
133
                ->setTranslate(true)
134
                ->setAction(
135
                    $this->actionFactory->createManialinkAction(
136
                        $manialink,
137
                        [$this, "callbackChatCommand"],
138
                        ["action" => "//blacklist"],
139
                        true
140
                    )
141
                );
142
143
            $row = $this->uiFactory->createLayoutLine(125, 0,
144
                [$guestList, $ignoreList, $banList, $blackList], 2);
145
            $manialink->addChild($row);
146
147
148
        }
149
150
151
        $frame = Frame::create();;
152
        $frame->setPosition(120, -16);
153
154
        $manialink->setData("playerFrame", $frame);
155
        $manialink->addChild($frame);
156
157
    }
158
159
    protected function updateContent(ManialinkInterface $manialink)
160
    {
161
        parent::updateContent($manialink);
162
163
        if ($this->playerToSet) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->playerToSet of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
164
            $this->setPlayer($manialink, $this->playerToSet);
165
            $this->playerToSet = null;
166
        }
167
168
        $width = 60;
169
        $recipient = $manialink->getUserGroup()->getLogins()[0];
170
171
        /** @var Frame $frame */
172
        $login = $manialink->getData('playerLogin');
173
        $player = $this->playerStorage->getPlayerInfo($login);
174
175
        $frame = $manialink->getData('playerFrame');
176
        $frame->removeAllChildren();
177
178
        $row = $this->uiFactory->createLayoutRow(0, 0, [], -2);
179
180
181
        $element = $this->uiFactory->createLabel($player->getNickName(), uiLabel::TYPE_HEADER);
182
        $element->setTextSize(5)->setSize($width, 10)->setAlign("center", "top")
183
            ->setPosition($width / 2, 0);
184
        $row->addChild($element);
185
186
        $elem = [
187
            $this->uiFactory->createLabel("expansion_players.gui.players.window.column.from")
188
                ->setSize(20, 5)->setTranslate(true),
189
            $this->uiFactory->createLabel($player->getPath()),
190
        ];
191
        $line = $this->uiFactory->createLayoutLine(0, 0, $elem, 2);
192
        $row->addChild($line);
193
194
195
        $elem = [
196
            $this->uiFactory->createLabel("expansion_players.gui.players.window.language")
197
                ->setSize(20, 5)->setTranslate(true),
198
            $this->uiFactory->createLabel($player->getLanguage()),
199
        ];
200
        $line = $this->uiFactory->createLayoutLine(0, 0, $elem, 2);
201
        $row->addChild($line);
202
203
        $elem = [
204
            $this->uiFactory->createLabel("expansion_players.gui.players.window.gameversion")
205
                ->setSize(20, 5)->setTranslate(true),
206
            $this->uiFactory->createLabel($player->getClientVersion()),
207
        ];
208
        $line = $this->uiFactory->createLayoutLine(0, 0, $elem, 2);
209
        $row->addChild($line);
210
211
        $elem = [
212
            $this->uiFactory->createLabel("expansion_players.gui.players.window.ladder")
213
                ->setSize(20, 5)->setTranslate(true),
214
            $this->uiFactory->createLabel(floor($player->getLadderScore())),
215
        ];
216
217
        $line = $this->uiFactory->createLayoutLine(0, 0, $elem, 1);
218
        $row->addChild($line);
219
220
221
        if ($this->adminGroups->isAdmin($recipient)) {
222
            $this->createAdminControls($manialink, $row);
223
        }
224
225
        $frame->addChild($row);
226
    }
227
228
229
    /**
230
     * @param ManialinkInterface $manialink
231
     * @param layoutRow          $row
232
     */
233
    private function createAdminControls($manialink, $row)
234
    {
235
        $actions = $manialink->getData('playerActions');
236
        $login = $manialink->getData('playerLogin');
237
238
        if ($this->getIgnoredStatus($login)) {
239
            $muteText = "Allow";
240
            $color = uiButton::COLOR_SUCCESS;
241
        } else {
242
            $muteText = "Mute";
243
            $color = uiButton::COLOR_WARNING;
244
        }
245
246
        $elem = [
247
            $this->uiFactory->createConfirmButton($muteText, uiButton::TYPE_DEFAULT)
248
                ->setAction($actions['mute'])
249
                ->setBackgroundColor($color),
250
            $this->uiFactory->createConfirmButton("Guest", uiButton::TYPE_DEFAULT)
251
                ->setAction($actions['guest'])
252
                ->setBackgroundColor(UiButton::COLOR_DEFAULT),
253
        ];
254
        $line = $this->uiFactory->createLayoutLine(10, 0, $elem, 2);
255
        $row->addChild($line);
256
257
        $separator = $this->uiFactory->createLine(0, 0)->setLength(60)->setStroke(0.5);
258
        $row->addChild($separator);
259
260
261
        $elem = $this->uiFactory->createLabel("expansion_players.gui.players.window.reason")
262
            ->setSize(20, 5)
263
            ->setTranslate(true);
264
        $row->addChild($elem);
265
        $elem = $this->uiFactory->createInput('reason', "", 60);
266
        $row->addChild($elem);
267
268
269
        $elem = [
270
            $this->uiFactory->createConfirmButton("Kick", uiButton::TYPE_DEFAULT)
271
                ->setAction($actions['kick'])
272
                ->setBackgroundColor(UiButton::COLOR_DEFAULT),
273
            $this->uiFactory->createConfirmButton("Ban", uiButton::TYPE_DEFAULT)
274
                ->setAction($actions['ban'])
275
                ->setBackgroundColor(UiButton::COLOR_DEFAULT),
276
            $this->uiFactory->createConfirmButton("Black", uiButton::TYPE_DEFAULT)
277
                ->setAction($actions['black'])
278
                ->setBackgroundColor(UiButton::COLOR_SECONDARY),
279
280
281
        ];
282
        $line = $this->uiFactory->createLayoutLine(10, 0, $elem, 2);
283
        $row->addChild($line);
284
    }
285
286
287
    /**
288
     * @param ManialinkInterface $manialink
289
     */
290
    protected function createGrid(ManialinkInterface $manialink)
291
    {
292
        $this->updateData($manialink);
293
294
        $selectButton = $this->uiFactory->createButton('expansion_players.gui.players.window.column.select',
295
            uiButton::TYPE_DEFAULT)->setSize(10, 5)->setTranslate(true);
296
297
        $gridBuilder = $this->gridBuilderFactory->create();
298
        $gridBuilder->setManialink($manialink)
299
            ->setDataCollection($manialink->getData('dataCollection'))
300
            ->setManialinkFactory($this)
301
            ->addIconColumn('zoneIcon', '#', 1)
302
            ->addTextColumn(
303
                'country',
304
                'expansion_players.gui.players.window.column.from',
305
                4,
306
                true,
307
                true
308
309
            )
310
            ->addTextColumn(
311
                'login',
312
                'expansion_players.gui.players.window.column.login',
313
                4,
314
                true,
315
                true
316
317
            )
318
            ->addTextColumn(
319
                'nickname',
320
                'expansion_players.gui.players.window.column.nickname',
321
                6,
322
                true,
323
                true
324
325
            )
326
            ->addActionColumn('login', "expansion_players.gui.players.window.column.select",
327
                3, [$this, "callbackSetPlayer"], $selectButton);
328
329
330
        $manialink->setData('grid', $gridBuilder);
331
332
        $frame = $manialink->getContentFrame();
333
        $this->setGridSize($frame->getWidth(), $frame->getHeight() - 10);
334
335
        $this->setGridSize(100, 90);
336
        $this->setGridPosition(0, 0);
337
338
    }
339
340
341
    /**
342
     * @param ManialinkInterface|Window $manialink
343
     * @param string                    $login
344
     * @param array                     $entries
345
     * @param array                     $args
346
     */
347
    public function callbackSetPlayer($manialink, $login, $entries, $args)
348
    {
349
        $this->playerToSet = $args['login'];
350
        $this->update($manialink->getUserGroup());
351
    }
352
353
    /**
354
     * @param ManialinkInterface|Window $manialink
355
     * @param string                    $login
356
     */
357
    public function setPlayer($manialink, $login)
358
    {
359
        var_dump('test');
0 ignored issues
show
Security Debugging Code introduced by
var_dump('test'); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
360
361
        $actions = [
362
            "mute" => (string)$this->actionFactory->createManialinkAction($manialink, [$this, 'callbackIgnore'],
363
                [
364
                    "login" => $login,
365
                ]),
366
            "kick" => (string)$this->actionFactory->createManialinkAction($manialink, [$this, 'callbackKick'],
367
                [
368
                    "login" => $login,
369
                ]),
370
            "ban" => (string)$this->actionFactory->createManialinkAction($manialink, [$this, 'callbackBan'],
371
                [
372
                    "login" => $login,
373
                ]),
374
            "black" => (string)$this->actionFactory->createManialinkAction($manialink, [$this, 'callbackBlack'],
375
                [
376
                    "login" => $login,
377
                ]),
378
            "guest" => (string)$this->actionFactory->createManialinkAction($manialink, [$this, 'callbackGuest'],
379
                [
380
                    "login" => $login,
381
                ]),
382
        ];
383
384
        $manialink->setData('playerActions', $actions);
385
        $manialink->setData("playerLogin", $login);
386
    }
387
388
    public function callbackIgnore($manialink, $login, $entries, $args)
389
    {
390
        $status = $this->getIgnoredStatus($login);
391
392
        if ($status) {
393
            $this->callChatCommand($login, "//unignore ".$args['login']);
394
        } else {
395
            $this->callChatCommand($login, "//ignore ".$args['login']);
396
        }
397
        $this->updateData($manialink);
398
        $this->callbackSetPlayer($manialink, $login, [], ['login' => $args['login']]);
399
    }
400
401
    public function callbackKick($manialink, $login, $entries, $args)
402
    {
403
        $this->callChatCommand($login, "//kick ".$args['login'].' "'.$entries['reason'].'"');
404
        $this->updateData($manialink);
405
        $this->callbackSetPlayer($manialink, $login, [], ['login' => $args['login']]);
406
    }
407
408
    public function callbackGuest($manialink, $login, $entries, $args)
409
    {
410
        $this->callChatCommand($login, "//addguest ".$args['login']);
411
        $this->updateData($manialink);
412
        $this->callbackSetPlayer($manialink, $login, [], ['login' => $args['login']]);
413
    }
414
415
    public function callbackBan($manialink, $login, $entries, $args)
416
    {
417
        $this->callChatCommand($login, "//ban ".$args['login'].' "'.$entries['reason'].'"');
418
        $this->updateData($manialink);
419
        $this->callbackSetPlayer($manialink, $login, [], ['login' => $args['login']]);
420
    }
421
422
    public function callbackBlack($manialink, $login, $entries, $args)
423
    {
424
        $this->callChatCommand($login, "//black ".$args['login'].' "'.$entries['reason'].'"');
425
        $this->updateData($manialink);
426
        $this->callbackSetPlayer($manialink, $login, [], ['login' => $args['login']]);
427
    }
428
429
    public function callbackChatCommand($manialink, $login, $entries, $args)
430
    {
431
        $this->callChatCommand($login, $args['action']);
432
    }
433
434
435
    public function updateData($manialink)
436
    {
437
        $players = $this->playerStorage->getOnline();
438
        $data = [];
439
        foreach ($players as $login => $player) {
440
            $country = $this->countries->parseCountryFromPath($player->getPath());
441
            $data[] = [
442
                "login" => $player->getLogin(),
443
                "nickname" => TMString::trimLinks($player->getNickName()),
444
                "country" => $country,
445
                "zoneIcon" => "file://Media/Flags/".$this->countries->getCodeFromCountry($country).".dds",
446
            ];
447
        }
448
        $this->setData($manialink, $data);
449
    }
450
451
452
    /**
453
     * @param $login
454
     * @param $command
455
     */
456
    public function callChatCommand($login, $command)
457
    {
458
        $this->chatCommandDataProvider->onPlayerChat($login, $login, $command, true);
459
    }
460
461
    /** Get ignore status for a player;
462
     *
463
     * @param string $login
464
     * @return bool
465
     */
466
    private function getIgnoredStatus($login)
467
    {
468
        try {
469
            $ignoreList = $this->connection->getIgnoreList();
470
            foreach ($ignoreList as $player) {
471
                if ($player->login === $login) {
472
                    return true;
473
                }
474
            }
475
476
            return false;
477
        } catch (\Exception $e) {
478
            return false;
479
        }
480
    }
481
482
}
483
484