Analytics::onPostLoop()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace eXpansion\Framework\Core\Plugins;
4
5
use eXpansion\Framework\Core\DataProviders\Listener\ListenerInterfaceExpTimer;
6
use eXpansion\Framework\Core\Helpers\Countries;
7
use eXpansion\Framework\Core\Helpers\Http;
8
use eXpansion\Framework\Core\Helpers\Structures\HttpResult;
9
use eXpansion\Framework\Core\Helpers\Version;
10
use eXpansion\Framework\Core\Services\Application;
11
use eXpansion\Framework\Core\Storage\GameDataStorage;
12
use eXpansion\Framework\Core\Storage\PlayerStorage;
13
use Psr\Log\LoggerInterface;
14
15
/**
16
 * Class Analytics
17
 *
18
 * @author    de Cramer Oliver<[email protected]>
19
 * @copyright 2018 eXpansion
20
 * @package eXpansion\Framework\Core\Plugins
21
 */
22
class Analytics implements ListenerInterfaceExpTimer, StatusAwarePluginInterface
23
{
24
    /** @var Http */
25
    protected $http;
26
27
    /** @var GameDataStorage */
28
    protected $gameData;
29
30
    /** @var PlayerStorage */
31
    protected $playerStorage;
32
33
    /** @var Countries */
34
    protected $countries;
35
36
    /** @var LoggerInterface */
37
    protected $logger;
38
39
    /** @var Version */
40
    protected $version;
41
42
    /** @var string  */
43
    protected $handshakeUrl;
44
45
    /** @var string  */
46
    protected $pingUrl;
47
48
    /** @var int */
49
    protected $pingInterval;
50
51
    /** @var int */
52
    protected $retryInterval;
53
54
    /** @var bool Is a call in progress. */
55
    protected $operationInProgress = false;
56
57
    /** @var string */
58
    protected $key = null;
59
60
    /** @var int */
61
    protected $lastPing;
62
63
    /**
64
     * Analytics constructor.
65
     *
66
     * @param Http $http
67
     * @param GameDataStorage $gameData
68
     * @param PlayerStorage $playerStorage
69
     * @param LoggerInterface $logger
70
     * @param string $url
0 ignored issues
show
Bug introduced by
There is no parameter named $url. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
71
     * @param int $pingInterval
72
     * @param int $retryInterval
73
     */
74
    public function __construct(
75
        Http $http,
76
        GameDataStorage $gameData,
77
        PlayerStorage $playerStorage,
78
        Countries $countries,
79
        LoggerInterface $logger,
80
        Version $version,
81
        string $handshakeUrl,
82
        string $pingUrl,
83
        int $pingInterval,
84
        int $retryInterval
85
    ) {
86
        $this->http = $http;
87
        $this->gameData = $gameData;
88
        $this->playerStorage = $playerStorage;
89
        $this->countries = $countries;
90
        $this->logger = $logger;
91
        $this->version   = $version;
92
        $this->handshakeUrl = $handshakeUrl;
93
        $this->pingUrl = $pingUrl;
94
        $this->pingInterval = $pingInterval;
95
        $this->retryInterval = $retryInterval;
96
    }
97
98
99
    /**
100
     * Set the status of the plugin
101
     *
102
     * @param boolean $status
103
     *
104
     * @return null
105
     */
106
    public function setStatus($status)
107
    {
108
        if ($status && !$this->operationInProgress) {
109
            $this->handshake();
110
        }
111
    }
112
113
    /**
114
     * Handshake with analytics tool!
115
     */
116
    protected function handshake()
117
    {
118
        $key =        &$this->key;
119
        $lastPing =   &$this->lastPing;
120
        $that = $this;
121
        $logger = $this->logger;
122
123
        $query = http_build_query(
124
            ['login' => $this->gameData->getSystemInfo()->serverLogin]
125
        );
126
        $url = $this->handshakeUrl . '?' . $query;
127
128
        $lastPing = time();
129
        $this->logger->debug("[eXpansion analytics]Starting handshake");
130
131
132
        $this->http->put(
133
            $url,
134
            [],
135
            function (HttpResult $result) use (&$key, &$lastPing, $logger, $that) {
136
                $key = null;
137
                if ($result->getHttpCode() != '200') {
138
                    $logger->debug('[eXpansion analytics]Handshake failed', ['http_code' => $result->getHttpCode()]);
139
                    return;
140
                }
141
142
                $json = json_decode($result->getResponse());
143
                if (isset($json->key) && !empty($json->key)) {
144
                    $logger->debug('[eXpansion analytics]Handshake successfull', ['key' => $json->key]);
145
146
                    $key = $json->key;
147
                    $that->ping();
148
149
                    // allow ping just after handshake.
150
                    $lastPing = 0;
151
                }
152
            }
153
        );
154
    }
155
156
    /**
157
     * Ping the analytics server with proper information.
158
     */
159
    public function ping()
160
    {
161
        if (!$this->key || $this->operationInProgress || (time() - $this->lastPing) < $this->pingInterval) {
162
            // Attempt a new handshake.
163
            if (is_null($this->key) && (time() - $this->lastPing) > $this->retryInterval) {
164
                $this->lastPing = time();
165
                $this->handshake();
166
            }
167
168
            return;
169
        }
170
171
        $data = $this->getBasePingData();
172
        $query = http_build_query(
173
            $data
174
        );
175
        $url = $this->pingUrl . '?' . $query;
176
177
        $this->operationInProgress = true;
178
        $this->lastPing = time();
179
        $operationInProgress = &$this->operationInProgress;
180
        $key = &$this->key;
181
        $logger = $this->logger;
182
183
        $logger->debug('[eXpansion analytics]Starting ping');
184
        $this->http->put(
185
            $url,
186
            [],
187
            function (HttpResult $result) use (&$operationInProgress, &$key, $logger) {
188
                if ($result->getHttpCode() == '200') {
189
                    $operationInProgress = false;
190
                    $logger->debug('[eXpansion analytics]Ping successfull');
191
                } else {
192
                    $logger->debug('[eXpansion analytics]Ping failed', ['http_code' => $result->getHttpCode(), 'result' => $result->getResponse()]);
193
                    $key = null;
194
                }
195
            }
196
        );
197
    }
198
199
    /**
200
     * Get base data for pinging the server.
201
     *
202
     * @return array
203
     */
204
    protected function getBasePingData()
205
    {
206
        return [
207
            'key' => $this->key,
208
            'nbPlayers' => count($this->playerStorage->getOnline()),
209
            'country' => $this->countries->getIsoAlpha2FromName($this->countries->parseCountryFromPath($this->gameData->getServerPath())),
210
            'version' => $this->version->getExpansionVersion(),
211
            'php_version' => $this->gameData->getServerCleanPhpVersion(),
212
            'php_version_short' => $this->gameData->getServerMajorPhpVersion(),
213
            'mysql_version' => 'unknown',
214
            'memory' => memory_get_usage(),
215
            'memory_peak' => memory_get_peak_usage(),
216
            'title' => str_replace('@','_by_', $this->gameData->getVersion()->titleId),
217
            'game' => $this->gameData->getTitleGame(),
218
            'mode' => strtolower($this->gameData->getGameInfos()->scriptName),
219
            'serverOs' => $this->gameData->getServerOs(),
220
        ];
221
    }
222
223
    /**
224
     * @inheritdoc
225
     */
226
    public function onPreLoop()
227
    {
228
        // Nothing.
229
    }
230
231
    /**
232
     * @inheritdoc
233
     */
234
    public function onPostLoop()
235
    {
236
        // Nothing.
237
    }
238
239
    /**
240
     * @inheritdoc
241
     */
242
    public function onEverySecond()
243
    {
244
        $this->ping();
245
    }
246
}