Completed
Push — master ( 220ce5...be682d )
by
unknown
17s
created

Connection::handleErrors()   C

Complexity

Conditions 16
Paths 16

Size

Total Lines 59
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 272

Importance

Changes 0
Metric Value
dl 0
loc 59
c 0
b 0
f 0
rs 6.364
ccs 0
cts 57
cp 0
cc 16
eloc 54
nc 16
nop 1
crap 272

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
/*
4
 * Copyright (C) 2014 Reaby
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
namespace eXpansion\Bundle\MxKarma\Plugins;
21
22
use eXpansion\Bundle\MxKarma\Entity\MxRating;
23
use eXpansion\Bundle\MxKarma\Entity\MxVote;
24
use eXpansion\Framework\Core\Helpers\Http;
25
use eXpansion\Framework\Core\Helpers\Structures\HttpResult;
26
use eXpansion\Framework\Core\Services\Application\AbstractApplication;
27
use eXpansion\Framework\Core\Services\Application\Dispatcher;
28
use eXpansion\Framework\Core\Services\Console;
29
use eXpansion\Framework\Core\Storage\GameDataStorage;
30
use eXpansion\Framework\Core\Storage\MapStorage;
31
use Maniaplanet\DedicatedServer\Structures\GameInfos;
32
use Maniaplanet\DedicatedServer\Structures\Map;
33
use oliverde8\AsynchronousJobs\Job\CallbackCurl;
34
35
/**
36
 * Description of Connection
37
 *
38
 * @author Reaby
39
 */
40
class Connection
41
{
42
43
    const EVENT_CONNECT = "expansion.mxkarma.connect";
44
    const EVENT_VOTESAVE = "expansion.mxkarma.votesave";
45
    const EVENT_VOTELOAD = 'expansion.mxkarma.voteload';
46
    const EVENT_DISCONNECT = 'expansion.mxkarma.disconnect';
47
48
    private $address = "http://karma.mania-exchange.com/api2/";
49
    private $options = [CURLOPT_HTTPHEADER => ["Content-Type:application/json"]];
50
51
    private $connected = false;
52
53
    private $sessionKey = null;
54
55
    private $sessionSeed = null;
56
57
    private $apiKey = "";
58
59
    /** @var MxRating */
60
    private $ratings = null;
61
    /**
62
     * @var Dispatcher
63
     */
64
    private $dispatcher;
65
    /**
66
     * @var GameDataStorage
67
     */
68
    private $gameDataStorage;
69
    /**
70
     * @var MapStorage
71
     */
72
    private $mapStorage;
73
    /**
74
     * @var Console
75
     */
76
    private $console;
77
78
    /** @var Http */
79
    private $http;
80
81
    /**
82
     * Connection constructor.
83
     *
84
     * @param Dispatcher $dispatcher
85
     * @param Http $http
86
     * @param GameDataStorage $gameDataStorage
87
     * @param MapStorage $mapStorage
88
     * @param Console $console
89
     */
90
    public function __construct(
91
        Dispatcher $dispatcher,
92
        Http $http,
93
        GameDataStorage $gameDataStorage,
94
        MapStorage $mapStorage,
95
        Console $console
96
    ) {
97
        $this->dispatcher = $dispatcher;
98
        $this->http = $http;
99
        $this->gameDataStorage = $gameDataStorage;
100
        $this->mapStorage = $mapStorage;
101
        $this->console = $console;
102
    }
103
104
105
    /**
106
     * connect to MX karma
107
     *
108
     * @param string $serverLogin
109
     * @param string $apiKey
110
     */
111
    public function connect($serverLogin, $apiKey)
112
    {
113
        $this->apiKey = $apiKey;
114
115
        $params = array(
116
            "serverLogin" => $serverLogin,
117
            "applicationIdentifier" => "eXpansion v ".AbstractApplication::EXPANSION_VERSION,
118
            "testMode" => "false",
119
        );
120
        $this->console->writeln('> MxKarma attempting to connect...');
121
        $this->http->get(
122
            $this->buildUrl(
123
                "startSession", $params),
124
            [$this, "xConnect"]
125
        );
126
    }
127
128
    /**
129
     * @param HttpResult $result
130
     */
131
    public function xConnect(HttpResult $result)
132
    {
133
134
        if ($result->hasError()) {
135
            $this->console->writeln('> MxKarma connection $f00 failure: '.$result->getError());
136
            $this->disconnect();
137
138
            return;
139
        }
140
141
        $data = $this->getObject($result->getResponse());
142
143
        if ($data === null) {
144
            return;
145
        }
146
147
        $this->sessionKey = $data->sessionKey;
148
        $this->sessionSeed = $data->sessionSeed;
149
150
        $outHash = hash("sha512", ($this->apiKey.$this->sessionSeed));
151
152
        $params = array("sessionKey" => $this->sessionKey, "activationHash" => $outHash);
153
        $this->console->writeln('> MxKarma attempting to activate session...');
154
        $this->http->get(
155
            $this->buildUrl("activateSession", $params),
156
            [$this, "xActivate"],
157
            [],
158
            $this->options
159
        );
160
    }
161
162 View Code Duplication
    public function xActivate(HttpResult $result)
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...
163
    {
164
165
        if ($result->hasError()) {
166
            $this->console->writeln('> MxKarma connection $f00 failure: '.$result->getError());
167
            return;
168
        }
169
170
        $data = $this->getObject($result->getResponse());
171
172
        if ($data === null) {
173
            return;
174
        }
175
176
        if ($data->activated) {
177
            $this->connected = true;
178
            $this->console->writeln('> MxKarma connection $0f0success!');
179
            $this->dispatcher->dispatch(self::EVENT_CONNECT, []);
180
        }
181
    }
182
183
    /**
184
     * loads votes from server
185
     * @param array $players
186
     * @param bool $getVotesOnly
187
     */
188
    public function loadVotes($players = array(), $getVotesOnly = false)
189
    {
190
        if (!$this->connected) {
191
            $this->console->writeln('> MxKarma trying to load votes when not connected!');
192
193
            return;
194
        }
195
196
        $this->console->writeln('> MxKarma attempting to load votes...');
197
        $params = array("sessionKey" => $this->sessionKey);
198
        $postData = [
199
            "gamemode" => $this->getGameMode(),
200
            "titleid" => $this->gameDataStorage->getTitle(),
201
            "mapuid" => $this->mapStorage->getCurrentMap()->uId,
202
            "getvotesonly" => $getVotesOnly,
203
            "playerlogins" => $players,
204
        ];
205
        $this->http->post(
206
            $this->buildUrl("getMapRating", $params),
207
            json_encode($postData),
208
            array($this, "xGetRatings"),
209
            [],
210
            $this->options
211
        );
212
    }
213
214
    /**
215
     * @param Map $map
216
     * @param int $time time in seconds from BeginMap to EndMap
217
     * @param MxVote[] $votes
218
     */
219
    public function saveVotes(Map $map, $time, $votes)
220
    {
221
        if (!$this->connected) {
222
            $this->console->writeln('> MxKarma not connected.');
223
224
            return;
225
        }
226
227
        $params = array("sessionKey" => $this->sessionKey);
228
        $postData = array(
229
            "gamemode" => $this->getGameMode(),
230
            "titleid" => $this->gameDataStorage->getTitle(),
231
            "mapuid" => $map->uId,
232
            "mapname" => $map->name,
233
            "mapauthor" => $map->author,
234
            "isimport" => false,
235
            "maptime" => $time,
236
            "votes" => $votes,
237
        );
238
239
240
        $this->console->writeln('> MxKarma attempting to save votes...');
241
        $this->http->post(
242
            $this->buildUrl("saveVotes", $params),
243
            json_encode($postData),
244
            [$this, "xSaveVotes"],
245
            [],
246
            $this->options
247
        );
248
    }
249
250
    /**
251
     * @param HttpResult $result
252
     */
253 View Code Duplication
    public function xSaveVotes(HttpResult $result)
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...
254
    {
255
256
        if ($result->hasError()) {
257
            $this->console->writeln('> MxKarma save votes $f00 failure: '.$result->getError());
258
259
            return;
260
        }
261
262
        $data = $this->getObject($result->getResponse());
263
264
        if ($data === null) {
265
            return;
266
        }
267
        $this->console->writeln('> MxKarma save votes $0f0success!');
268
        $this->dispatcher->dispatch(self::EVENT_VOTESAVE, ["updated" => $data->updated]);
269
    }
270
271
    /**
272
     * @param HttpResult $result
273
     * @return MxRating|null
274
     */
275
    public function xGetRatings(HttpResult $result)
276
    {
277
278
        if ($result->hasError()) {
279
            $this->console->writeln('> MxKarma load votes $f00 failure: '.$result->getError());
280
281
            return null;
282
        }
283
284
        $data = $this->getObject($result->getResponse());
285
286
        if ($data === null) {
287
            return null;
288
        }
289
290
        $this->ratings = new MXRating();
291
        $this->ratings->append($data);
292
293
        $this->console->writeln('> MxKarma load $0f0success!');
294
        $this->dispatcher->dispatch(self::EVENT_VOTELOAD, ["ratings" => $this->ratings]);
295
296
        return $this->ratings;
297
    }
298
299
    /**
300
     * @return string
301
     */
302
    public function getGameMode()
303
    {
304
        $gamemode = "";
305
        switch ($this->gameDataStorage->getGameInfos()->gameMode) {
306
            case GameInfos::GAMEMODE_SCRIPT:
307
                $gamemode = strtolower($this->gameDataStorage->getGameInfos()->scriptName);
308
                break;
309
            case GameInfos::GAMEMODE_ROUNDS:
310
                $gamemode = "Rounds";
311
                break;
312
            case GameInfos::GAMEMODE_CUP:
313
                $gamemode = "Cup";
314
                break;
315
            case GameInfos::GAMEMODE_TEAM:
316
                $gamemode = "Team";
317
                break;
318
            case GameInfos::GAMEMODE_LAPS:
319
                $gamemode = "Laps";
320
                break;
321
            case GameInfos::GAMEMODE_TIMEATTACK:
322
                $gamemode = "TimeAttack";
323
                break;
324
        }
325
326
        return $gamemode;
327
    }
328
329
    /**
330
     * @param string $data json data
331
     *
332
     * @return object|null
333
     */
334
    public function getObject($data)
335
    {
336
        $obj = (object)json_decode($data);
337
        if ($obj->success === false) {
338
            $this->handleErrors($obj);
339
340
            return null;
341
        }
342
343
        return $obj->data;
344
    }
345
346
    /**
347
     * @param object $obj
348
     */
349
    public function handleErrors($obj)
350
    {
351
        switch ($obj->data->code) {
352
            case 1:
353
                $this->console->writeln('> MxKarma $fffinternal server error');
354
                break;
355
            case 2:
356
                $this->console->writeln('> MxKarma $fffSession key is invalid (not activated, experied or got disabled).');
357
                break;
358
            case 4:
359
                $this->console->writeln('> MxKarma $fffSome parameters are not provided.');
360
                break;
361
            case 5:
362
                $this->console->writeln('> MxKarma $fffAPI key not found or suspended.');
363
                $this->disconnect();
364
                break;
365
            case 6:
366
                $this->console->writeln('> MxKarma $fffServer not found or suspended.');
367
                $this->disconnect();
368
                break;
369
            case 7:
370
                $this->console->writeln('> MxKarma $fffCross-server call rejected.');
371
                break;
372
            case 8:
373
                $this->console->writeln('> MxKarma $fffInvalid activation hash provided, session closed.');
374
                $this->disconnect();
375
                break;
376
            case 9:
377
                $this->console->writeln('> MxKarma $fffSession already active.');
378
                $this->disconnect();
379
                break;
380
            case 10:
381
                $this->console->writeln('> MxKarma $fffUnsupported Content-Type.');
382
                break;
383
            case 11:
384
                $this->console->writeln('> MxKarma $fffToo many logins requested.');
385
                break;
386
            case 12:
387
                $this->console->writeln('> MxKarma $fffInvalid JSON or invalid structure.');
388
                break;
389
            case 13:
390
                $this->console->writeln('> MxKarma $fffMalformed vote request.');
391
                break;
392
            case 14:
393
                $this->console->writeln('> MxKarma $fffno votes cast - please do not make requests if there are no votes!');
394
                break;
395
            case 15:
396
                $this->console->writeln('> MxKarma $ffftoo many import votes - request a limit raise if needed');
397
                break;
398
            case 16:
399
                $this->console->writeln('> MxKarma $fffImport rejected.');
400
                break;
401
            default:
402
                $this->console->writeln('> MxKarma $fffUnknown api error');
403
                break;
404
        }
405
406
        //   Dispatcher::dispatch(new MXKarmaEvent(MXKarmaEvent::ON_ERROR, $origin, $obj->data->code, $obj->data->message));
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...
407
    }
408
409
    /**
410
     * @param string $method
411
     * @param array $params
412
     *
413
     * @return string
414
     */
415
    private function buildUrl($method, $params)
416
    {
417
        $url = $this->address.$method;
418
419
        return $url."?".http_build_query($params);
420
    }
421
422
    /**
423
     * @return bool
424
     */
425
    public function isConnected()
426
    {
427
        return $this->connected;
428
    }
429
430
431
    /**
432
     *
433
     */
434
    public function disconnect()
435
    {
436
        $this->connected = false;
437
        $this->console->writeln('> MxKarma $f00disconnected!');
438
        $this->dispatcher->dispatch(self::EVENT_DISCONNECT, []);
439
    }
440
441
442
}
443