Completed
Pull Request — master (#104)
by
unknown
12:26
created

ManiaExchange   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 243
Duplicated Lines 7 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 11
dl 17
loc 243
ccs 0
cts 138
cp 0
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 17 17 1
B addMap() 0 32 3
B callbackAddMap1() 0 40 3
A callbackAddMap2() 0 56 3
A cleanString() 0 4 1
A onApplicationInit() 0 4 1
A onApplicationReady() 0 4 1
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\Maps\Plugins;
4
5
use eXpansion\Bundle\Maps\Services\JukeboxService;
6
use eXpansion\Bundle\Maps\Structure\MxInfo;
7
use eXpansion\Framework\AdminGroups\Helpers\AdminGroups;
8
use eXpansion\Framework\Core\DataProviders\Listener\ListenerInterfaceExpApplication;
9
use eXpansion\Framework\Core\Helpers\ChatNotification;
10
use eXpansion\Framework\Core\Helpers\Http;
11
use eXpansion\Framework\Core\Helpers\Structures\HttpResult;
12
use eXpansion\Framework\Core\Helpers\TMString;
13
use eXpansion\Framework\Core\Services\Application\AbstractApplication;
14
use eXpansion\Framework\Core\Services\Console;
15
use eXpansion\Framework\Core\Storage\GameDataStorage;
16
use Maniaplanet\DedicatedServer\Connection;
17
18
class ManiaExchange implements ListenerInterfaceExpApplication
19
{
20
21
    const SITE_TM = "TM";
22
    const SITE_SM = "SM";
23
24
    /**
25
     * @var Connection
26
     */
27
    private $connection;
28
    /**
29
     * @var ChatNotification
30
     */
31
    private $chatNotification;
32
    /**
33
     * @var Http
34
     */
35
    private $http;
36
    /**
37
     * @var AdminGroups
38
     */
39
    private $adminGroups;
40
    /**
41
     * @var GameDataStorage
42
     */
43
    private $gameDataStorage;
44
    /**
45
     * @var Console
46
     */
47
    private $console;
48
    /**
49
     * @var JukeboxService
50
     */
51
    private $jukebox;
52
53
54
    /**
55
     * ManiaExchange constructor.
56
     * @param Connection $connection
57
     * @param ChatNotification $chatNotification
58
     * @param Http $http
59
     * @param AdminGroups $adminGroups
60
     * @param GameDataStorage $gameDataStorage
61
     * @param Console $console
62
     * @param JukeboxService $jukebox
63
     */
64 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...
65
        Connection $connection,
66
        ChatNotification $chatNotification,
67
        Http $http,
68
        AdminGroups $adminGroups,
69
        GameDataStorage $gameDataStorage,
70
        Console $console,
71
        JukeboxService $jukebox
72
    ) {
73
        $this->connection = $connection;
74
        $this->chatNotification = $chatNotification;
75
        $this->http = $http;
76
        $this->adminGroups = $adminGroups;
77
        $this->gameDataStorage = $gameDataStorage;
78
        $this->console = $console;
79
        $this->jukebox = $jukebox;
80
    }
81
82
    /**
83
     * @param string $login
84
     * @param integer $id
85
     * @param string $mxsite "TM" or "SM"
86
     */
87
    public function addMap($login, $id, $mxsite)
88
    {
89
90
        if (!$this->adminGroups->hasPermission($login, "mania_exchange.add")) {
91
            $this->chatNotification->sendMessage('expansion_mx.chat.nopermission', $login);
92
93
            return;
94
        }
95
        $options = [
96
            CURLOPT_HTTPHEADER => [
97
                "Content-Type" => "application/json",
98
                "X-ManiaPlanet-ServerLogin" => $this->gameDataStorage->getSystemInfo()->serverLogin,
99
            ],
100
        ];
101
102
        if (!$mxsite) {
103
            $mxsite = "TM";
104
        }
105
106
        $group = $this->adminGroups->getLoginUserGroups($login);
107
108
        $this->chatNotification->sendMessage(
109
            'expansion_mx.chat.start',
110
            $group,
111
            ["%id%" => $id, "%site%" => $mxsite]
112
        );
113
114
        $this->http->get("https://api.mania-exchange.com/".strtolower($mxsite)."/maps?ids=".$id,
115
            [$this, 'callbackAddMap1'],
116
            ['login' => $login, 'site' => $mxsite, 'mxId' => $id], $options);
117
118
    }
119
120
121
    public function callbackAddMap1(HttpResult $result)
122
    {
123
        $additionalData = $result->getAdditionalData();
124
        $group = $this->adminGroups->getLoginUserGroups($additionalData['login']);
125
126
        $json = json_decode($result->getResponse(), true);
127
        if (isset($json['StatusCode'])) {
128
            $this->chatNotification->sendMessage(
129
                'expansion_mx.chat.apierror',
130
                $group,
131
                ["%status%" => $json['StatusCode'], "%message%" => $json['Message']]
132
            );
133
134
            return;
135
        } else {
136
            $mxInfo = new MxInfo($json);
137
        }
138
139
        $additionalData['mxInfo'] = $mxInfo;
140
141
        if (!$result->hasError()) {
142
            $options = [
143
                CURLOPT_HTTPHEADER => [
144
                    "Content-Type" => "application/json",
145
                    "X-ManiaPlanet-ServerLogin" => $this->gameDataStorage->getSystemInfo()->serverLogin,
146
                ],
147
            ];
148
149
            $this->http->get("https://".strtolower($additionalData['site']).
150
                ".mania-exchange.com/tracks/download/".$additionalData['mxId'],
151
                [$this, 'callbackAddMap2'],
152
                $additionalData, $options);
153
        } else {
154
            $this->chatNotification->sendMessage(
155
                'expansion_mx.chat.httperror',
156
                $group,
157
                ["%status%" => $result->getHttpCode(), "%message%" => $result->getError()]
158
            );
159
        }
160
    }
161
162
    public function callbackAddMap2(HttpResult $result)
163
    {
164
        $data = $result->getAdditionalData();
165
        $group = $this->adminGroups->getLoginUserGroups($data['login']);
166
167
        if ($result->hasError()) {
168
            $this->chatNotification->sendMessage(
169
                'expansion_mx.chat.httperror',
170
                $group,
171
                ["%status%" => $result->getHttpCode(), "%message%" => $result->getError()]
172
            );
173
174
            return;
175
        }
176
177
        /** @var MxInfo $info */
178
        $info = $data['mxInfo'];
179
        $authorName = $this->cleanString($info->Username);
180
        $mapName = $this->cleanString(
181
            trim(
182
                mb_convert_encoding(
183
                    substr(TMString::trimStyles($info->GbxMapName), 0, 20),
184
                    "7bit",
185
                    "UTF-8"
186
                )
187
            )
188
        );
189
190
        $filename = $data['mxId']."-".$authorName."-".$mapName.".Map.Gbx";
191
        try {
192
            // @todo write mx info from map to database!
193
194
            $this->connection->writeFile($filename, $result->getResponse());
195
            $this->connection->addMap($filename);
196
197
            $map = $this->connection->getMapInfo($filename);
198
            $this->jukebox->addMap($map, $data['login']);
199
            $this->chatNotification->sendMessage(
200
                'expansion_mx.chat.success',
201
                null,
202
                [
203
                    "%mxid%" => $data['mxId'],
204
                    "%mapauthor%" => $map->author,
205
                    "%mapname%" => TMString::trimControls($map->name),
206
                ]
207
            );
208
        } catch (\Exception $e) {
209
            $this->chatNotification->sendMessage(
210
                'expansion_mx.chat.dedicatedexception',
211
                $group,
212
                [
213
                    "%message%" => $e->getMessage(),
214
                ]
215
            );
216
        }
217
    }
218
219
    /**
220
     * Remove special characters from map name
221
     *
222
     * @param $string
223
     * @return mixed
224
     */
225
    protected function cleanString($string)
226
    {
227
        return str_replace(array("/", "\\", ":", ".", "?", "*", '"', "|", "<", ">", "'"), "", $string);
228
    }
229
230
231
    /**
232
     * called at eXpansion init
233
     *
234
     * @return void
235
     */
236
    public function onApplicationInit()
237
    {
238
        // TODO: Implement onApplicationInit() method.
239
    }
240
241
    /**
242
     * called when init is done and callbacks are enabled
243
     *
244
     * @return void
245
     */
246
    public function onApplicationReady()
247
    {
248
249
    }
250
251
    /**
252
     * called when requesting application stop
253
     *
254
     * @return void
255
     */
256
    public function onApplicationStop()
257
    {
258
        // TODO: Implement onApplicationStop() method.
259
    }
260
}
261