Completed
Pull Request — master (#104)
by
unknown
03:28
created

Connection::isConnected()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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
79
    /**
80
     * Connection constructor.
81
     *
82
     * @param Dispatcher $dispatcher
83
     * @param Http $http
84
     * @param GameDataStorage $gameDataStorage
85
     * @param MapStorage $mapStorage
86
     * @param Console $console
87
     */
88
    public function __construct(
89
        Dispatcher $dispatcher,
90
        Http $http,
91
        GameDataStorage $gameDataStorage,
92
        MapStorage $mapStorage,
93
        Console $console
94
    ) {
95
        $this->dispatcher = $dispatcher;
96
        $this->http = $http;
0 ignored issues
show
Bug introduced by
The property http does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
97
        $this->gameDataStorage = $gameDataStorage;
98
        $this->mapStorage = $mapStorage;
99
        $this->console = $console;
100
    }
101
102
103
    /**
104
     * connect to MX karma
105
     *
106
     * @param string $serverLogin
107
     * @param string $apiKey
108
     */
109
    public function connect($serverLogin, $apiKey)
110
    {
111
        $this->apiKey = $apiKey;
112
113
        $params = array(
114
            "serverLogin" => $serverLogin,
115
            "applicationIdentifier" => "eXpansion v ".AbstractApplication::EXPANSION_VERSION,
116
            "testMode" => "false",
117
        );
118
        $this->console->writeln('> MxKarma attempting to connect...');
119
        $this->http->get(
120
            $this->buildUrl(
121
                "startSession", $params),
122
            [$this, "xConnect"]
123
        );
124
    }
125
126
    /**
127
     * @param HttpResult $result
128
     */
129
    public function xConnect(HttpResult $result)
130
    {
131
132
        if ($result->hasError()) {
133
            $this->console->writeln('> MxKarma connection $f00 failure: '.$result->getError());
134
            $this->disconnect();
135
136
            return;
137
        }
138
139
        $data = $this->getObject($result->getResponse());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $data is correct as $this->getObject($result->getResponse()) (which targets eXpansion\Bundle\MxKarma...Connection::getObject()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
140
141
        if ($data === null) {
142
            return;
143
        }
144
145
        $this->sessionKey = $data->sessionKey;
146
        $this->sessionSeed = $data->sessionSeed;
147
148
        $outHash = hash("sha512", ($this->apiKey.$this->sessionSeed));
149
150
        $params = array("sessionKey" => $this->sessionKey, "activationHash" => $outHash);
151
        $this->console->writeln('> MxKarma attempting to activate session...');
152
        $this->http->get(
153
            $this->buildUrl("activateSession", $params),
154
            [$this, "xActivate"],
155
            [],
156
            $this->options
157
        );
158
    }
159
160 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...
161
    {
162
163
        if ($result->hasError()) {
164
            $this->console->writeln('> MxKarma connection $f00 failure: '.$result->getError());
165
166
            return;
167
        }
168
169
        $data = $this->getObject($result->getResponse());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $data is correct as $this->getObject($result->getResponse()) (which targets eXpansion\Bundle\MxKarma...Connection::getObject()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
170
171
        if ($data === null) {
172
            return;
173
        }
174
175
        if ($data->activated) {
176
            $this->connected = true;
177
            $this->console->writeln('> MxKarma connection $0f0success!');
178
            $this->dispatcher->dispatch(self::EVENT_CONNECT, []);
179
        }
180
    }
181
182
    /**
183
     * loads votes from server
184
     * @param array $players
185
     * @param bool $getVotesOnly
186
     */
187
    public function loadVotes($players = array(), $getVotesOnly = false)
188
    {
189
        if (!$this->connected) {
190
            $this->console->writeln('> MxKarma trying to load votes when not connected!');
191
192
            return;
193
        }
194
195
        $this->console->writeln('> MxKarma attempting to load votes...');
196
        $params = array("sessionKey" => $this->sessionKey);
197
        $postData = [
198
            "gamemode" => $this->getGameMode(),
199
            "titleid" => $this->gameDataStorage->getTitle(),
200
            "mapuid" => $this->mapStorage->getCurrentMap()->uId,
201
            "getvotesonly" => $getVotesOnly,
202
            "playerlogins" => $players,
203
        ];
204
        $this->http->post(
205
            $this->buildUrl("getMapRating", $params),
206
            json_encode($postData),
207
            array($this, "xGetRatings"),
208
            [],
209
            $this->options
210
        );
211
    }
212
213
    /**
214
     * @param Map $map
215
     * @param int $time time in seconds from BeginMap to EndMap
216
     * @param MxVote[] $votes
217
     */
218
    public function saveVotes(Map $map, $time, $votes)
219
    {
220
        if (!$this->connected) {
221
            $this->console->writeln('> MxKarma not connected.');
222
223
            return;
224
        }
225
226
        $params = array("sessionKey" => $this->sessionKey);
227
        $postData = array(
228
            "gamemode" => $this->getGameMode(),
229
            "titleid" => $this->gameDataStorage->getTitle(),
230
            "mapuid" => $map->uId,
231
            "mapname" => $map->name,
232
            "mapauthor" => $map->author,
233
            "isimport" => false,
234
            "maptime" => $time,
235
            "votes" => $votes,
236
        );
237
238
239
        $this->console->writeln('> MxKarma attempting to save votes...');
240
        $this->http->post(
241
            $this->buildUrl("saveVotes", $params),
242
            json_encode($postData),
243
            [$this, "xSaveVotes"],
244
            [],
245
            $this->options
246
        );
247
    }
248
249
    /**
250
     * @param HttpResult $result
251
     */
252 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...
253
    {
254
255
        if ($result->hasError()) {
256
            $this->console->writeln('> MxKarma save votes $f00 failure: '.$result->getError());
257
            return;
258
        }
259
260
        $data = $this->getObject($result->getResponse());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $data is correct as $this->getObject($result->getResponse()) (which targets eXpansion\Bundle\MxKarma...Connection::getObject()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
261
262
        if ($data === null) {
263
            return;
264
        }
265
        $this->console->writeln('> MxKarma save votes $0f0success!');
266
        $this->dispatcher->dispatch(self::EVENT_VOTESAVE, ["updated" => $data->updated]);
267
    }
268
269
    /**
270
     * @param HttpResult $result
271
     * @return MxRating|null
272
     */
273
    public function xGetRatings(HttpResult $result)
274
    {
275
276
        if ($result->hasError()) {
277
            $this->console->writeln('> MxKarma load votes $f00 failure: '.$result->getError());
278
279
            return null;
280
        }
281
282
        $data = $this->getObject($result->getResponse());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $data is correct as $this->getObject($result->getResponse()) (which targets eXpansion\Bundle\MxKarma...Connection::getObject()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
283
284
        if ($data === null) {
285
            return null;
286
        }
287
288
        $this->ratings = new MXRating();
289
        $this->ratings->append($data);
290
291
        $this->console->writeln('> MxKarma load $0f0success!');
292
        $this->dispatcher->dispatch(self::EVENT_VOTELOAD, ["ratings" => $this->ratings]);
293
294
        return $this->ratings;
295
    }
296
297
    /**
298
     * @return string
299
     */
300
    public function getGameMode()
301
    {
302
        $gamemode = "";
303
        switch ($this->gameDataStorage->getGameInfos()->gameMode) {
304
            case GameInfos::GAMEMODE_SCRIPT:
305
                $gamemode = strtolower($this->gameDataStorage->getGameInfos()->scriptName);
306
                break;
307
            case GameInfos::GAMEMODE_ROUNDS:
308
                $gamemode = "Rounds";
309
                break;
310
            case GameInfos::GAMEMODE_CUP:
311
                $gamemode = "Cup";
312
                break;
313
            case GameInfos::GAMEMODE_TEAM:
314
                $gamemode = "Team";
315
                break;
316
            case GameInfos::GAMEMODE_LAPS:
317
                $gamemode = "Laps";
318
                break;
319
            case GameInfos::GAMEMODE_TIMEATTACK:
320
                $gamemode = "TimeAttack";
321
                break;
322
        }
323
324
        return $gamemode;
325
    }
326
327
    /**
328
     * @param string $data json data
329
     *
330
     * @return null
331
     */
332
    public function getObject($data)
333
    {
334
        $obj = (object)json_decode($data);
335
        if ($obj->success === false) {
336
            $this->handleErrors($obj);
337
338
            return null;
339
        }
340
341
        return $obj->data;
342
    }
343
344
    /**
345
     * @param object $obj
346
     */
347
    public function handleErrors($obj)
348
    {
349
        switch ($obj->data->code) {
350
            case 1:
351
                $this->console->writeln('> MxKarma $fffinternal server error');
352
                break;
353
            case 2:
354
                $this->console->writeln('> MxKarma $fffSession key is invalid (not activated, experied or got disabled).');
355
                break;
356
            case 4:
357
                $this->console->writeln('> MxKarma $fffSome parameters are not provided.');
358
                break;
359
            case 5:
360
                $this->console->writeln('> MxKarma $fffAPI key not found or suspended.');
361
                $this->disconnect();
362
                break;
363
            case 6:
364
                $this->console->writeln('> MxKarma $fffServer not found or suspended.');
365
                $this->disconnect();
366
                break;
367
            case 7:
368
                $this->console->writeln('> MxKarma $fffCross-server call rejected.');
369
                break;
370
            case 8:
371
                $this->console->writeln('> MxKarma $fffInvalid activation hash provided, session closed.');
372
                $this->disconnect();
373
                break;
374
            case 9:
375
                $this->console->writeln('> MxKarma $fffSession already active.');
376
                $this->disconnect();
377
                break;
378
            case 10:
379
                $this->console->writeln('> MxKarma $fffUnsupported Content-Type.');
380
                break;
381
            case 11:
382
                $this->console->writeln('> MxKarma $fffToo many logins requested.');
383
                break;
384
            case 12:
385
                $this->console->writeln('> MxKarma $fffInvalid JSON or invalid structure.');
386
                break;
387
            case 13:
388
                $this->console->writeln('> MxKarma $fffMalformed vote request.');
389
                break;
390
            case 14:
391
                $this->console->writeln('> MxKarma $fffno votes cast - please do not make requests if there are no votes!');
392
                break;
393
            case 15:
394
                $this->console->writeln('> MxKarma $ffftoo many import votes - request a limit raise if needed');
395
                break;
396
            case 16:
397
                $this->console->writeln('> MxKarma $fffImport rejected.');
398
                break;
399
            default:
400
                $this->console->writeln('> MxKarma $fffUnknown api error');
401
                break;
402
        }
403
404
        //   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...
405
    }
406
407
    /**
408
     * @param string $method
409
     * @param array $params
410
     *
411
     * @return string
412
     */
413
    private function buildUrl($method, $params)
414
    {
415
        $url = $this->address.$method;
416
417
        return $url."?".http_build_query($params);
418
    }
419
420
    /**
421
     * @return bool
422
     */
423
    public function isConnected()
424
    {
425
        return $this->connected;
426
    }
427
428
429
    /**
430
     *
431
     */
432
    public function disconnect()
433
    {
434
        $this->connected = false;
435
        $this->console->writeln('> MxKarma $f00disconnected!');
436
        $this->dispatcher->dispatch(self::EVENT_DISCONNECT, []);
437
    }
438
439
440
}
441