Completed
Push — v3 ( 065f93...781e5e )
by Austin
10:22 queued 06:22
created

Gamespy3::processResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 54
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 54
ccs 20
cts 20
cp 1
rs 9.6716
cc 2
eloc 19
nc 2
nop 0
crap 2

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
 * This file is part of GameQ.
4
 *
5
 * GameQ is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * GameQ is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace GameQ\Protocols;
20
21
use GameQ\Protocol;
22
use GameQ\Buffer;
23
use GameQ\Result;
24
25
/**
26
 * GameSpy3 Protocol class
27
 *
28
 * Given the ability for non utf-8 characters to be used as hostnames, player names, etc... this
29
 * version returns all strings utf-8 encoded (utf8_encode).  To access the proper version of a
30
 * string response you must use utf8_decode() on the specific response.
31
 *
32
 * @author Austin Bischoff <[email protected]>
33
 */
34
class Gamespy3 extends Protocol
35
{
36
37
    /**
38
     * Array of packets we want to look up.
39
     * Each key should correspond to a defined method in this or a parent class
40
     *
41
     * @type array
42
     */
43
    protected $packets = [
44
        self::PACKET_CHALLENGE => "\xFE\xFD\x09\x10\x20\x30\x40",
45
        self::PACKET_ALL       => "\xFE\xFD\x00\x10\x20\x30\x40%s\xFF\xFF\xFF\x01",
46
    ];
47
48
    /**
49
     * The query protocol used to make the call
50
     *
51
     * @type string
52
     */
53
    protected $protocol = 'gamespy3';
54
55
    /**
56
     * String name of this protocol class
57
     *
58
     * @type string
59
     */
60
    protected $name = 'gamespy3';
61
62
    /**
63
     * Longer string name of this protocol class
64
     *
65
     * @type string
66
     */
67
    protected $name_long = "GameSpy3 Server";
68
69
    /**
70
     * The client join link
71
     *
72
     * @type string
73
     */
74
    protected $join_link = null;
75
76
    /**
77
     * Parse the challenge response and apply it to all the packet types
78
     *
79
     * @param \GameQ\Buffer $challenge_buffer
80
     *
81
     * @return bool
82
     * @throws \GameQ\Exception\Protocol
83
     */
84
    public function challengeParseAndApply(Buffer $challenge_buffer)
85
    {
86
87
        // Pull out the challenge
88
        $challenge = substr(preg_replace("/[^0-9\-]/si", "", $challenge_buffer->getBuffer()), 1);
89
        $challenge_result = sprintf(
90
            "%c%c%c%c",
91
            ($challenge >> 24),
92
            ($challenge >> 16),
93
            ($challenge >> 8),
94
            ($challenge >> 0)
95
        );
96
97
        // Apply the challenge and return
98
        return $this->challengeApply($challenge_result);
99
    }
100
101
    /**
102
     * Process the response
103
     *
104
     * @return array
105
     */
106 3
    public function processResponse()
107
    {
108
109
        // Holds the processed packets
110 3
        $processed = [ ];
111
112
        // Iterate over the packets
113 3
        foreach ($this->packets_response as $response) {
114
            // Make a buffer
115 3
            $buffer = new Buffer($response, Buffer::NUMBER_TYPE_BIGENDIAN);
116
117
            // Packet type = 0
118 3
            $buffer->readInt8();
119
120
            // Session Id
121 3
            $buffer->readInt32();
122
123
            // We need to burn the splitnum\0 because it is not used
124 3
            $buffer->skip(9);
125
126
            // Get the id
127 3
            $id = $buffer->readInt8();
128
129
            // Burn next byte not sure what it is used for
130 3
            $buffer->skip(1);
131
132
            // Add this packet to the processed
133 3
            $processed[$id] = $buffer->getBuffer();
134
135 3
            unset($buffer, $id);
136 3
        }
137
138
        // Sort packets, reset index
139 3
        ksort($processed);
140
141
        // Offload cleaning up the packets if they happen to be split
142 3
        $packets = $this->cleanPackets(array_values($processed));
143
144
        // Create a new buffer
145 3
        $buffer = new Buffer(implode('', $packets), Buffer::NUMBER_TYPE_BIGENDIAN);
146
147
        // Create a new result
148 3
        $result = new Result();
149
150
        // Parse the server details
151 3
        $this->processDetails($buffer, $result);
152
153
        // Parse the player and team information
154 3
        $this->processPlayersAndTeams($buffer, $result);
155
156 3
        unset($buffer);
157
158 3
        return $result->fetch();
159
    }
160
161
    /*
162
     * Internal methods
163
     */
164
165
    /**
166
     * Handles cleaning up packets since the responses can be a bit "dirty"
167
     *
168
     * @param array $packets
169
     *
170
     * @return array
171
     */
172 3
    protected function cleanPackets(array $packets = [ ])
173
    {
174
175
        // Get the number of packets
176 3
        $packetCount = count($packets);
177
178
        // Compare last var of current packet with first var of next packet
179
        // On a partial match, remove last var from current packet,
180
        // variable header from next packet
181 3
        for ($i = 0, $x = $packetCount; $i < $x - 1; $i++) {
182
            // First packet
183 1
            $fst = substr($packets[$i], 0, -1);
184
            // Second packet
185 1
            $snd = $packets[$i + 1];
186
            // Get last variable from first packet
187 1
            $fstvar = substr($fst, strrpos($fst, "\x00") + 1);
188
            // Get first variable from last packet
189 1
            $snd = substr($snd, strpos($snd, "\x00") + 2);
190 1
            $sndvar = substr($snd, 0, strpos($snd, "\x00"));
191
            // Check if fstvar is a substring of sndvar
192
            // If so, remove it from the first string
193 1
            if (!empty($fstvar) && strpos($sndvar, $fstvar) !== false) {
194
                $packets[$i] = preg_replace("#(\\x00[^\\x00]+\\x00)$#", "\x00", $packets[$i]);
195
            }
196 1
        }
197
198
        // Now let's loop the return and remove any dupe prefixes
199 3
        for ($x = 1; $x < $packetCount; $x++) {
200 1
            $buffer = new Buffer($packets[$x], Buffer::NUMBER_TYPE_BIGENDIAN);
201
202 1
            $prefix = $buffer->readString();
203
204
            // Check to see if the return before has the same prefix present
205 1
            if ($prefix != null && strstr($packets[($x - 1)], $prefix)) {
206
                // Update the return by removing the prefix plus 2 chars
207
                $packets[$x] = substr(str_replace($prefix, '', $packets[$x]), 2);
208
            }
209
210 1
            unset($buffer);
211 1
        }
212
213 3
        unset($x, $i, $snd, $sndvar, $fst, $fstvar);
214
215
        // Return cleaned packets
216 3
        return $packets;
217
    }
218
219
    /**
220
     * Handles processing the details data into a usable format
221
     *
222
     * @param \GameQ\Buffer $buffer
223
     * @param \GameQ\Result $result
224
     */
225 3
    protected function processDetails(Buffer &$buffer, Result &$result)
226
    {
227
228
        // We go until we hit an empty key
229 3
        while ($buffer->getLength()) {
230 3
            $key = $buffer->readString();
231 3
            if (strlen($key) == 0) {
232 3
                break;
233
            }
234 3
            $result->add($key, utf8_encode($buffer->readString()));
235 3
        }
236 3
    }
237
238
    /**
239
     * Handles processing the player and team data into a usable format
240
     *
241
     * @param \GameQ\Buffer $buffer
242
     * @param \GameQ\Result $result
243
     */
244 3
    protected function processPlayersAndTeams(Buffer &$buffer, Result &$result)
245
    {
246
247
        /*
248
         * Explode the data into groups. First is player, next is team (item_t)
249
         * Each group should be as follows:
250
         *
251
         * [0] => item_
252
         * [1] => information for item_
253
         * ...
254
         */
255 3
        $data = explode("\x00\x00", $buffer->getBuffer());
256
257
        // By default item_group is blank, this will be set for each loop thru the data
258 3
        $item_group = '';
259
        // By default the item_type is blank, this will be set on each loop
260 3
        $item_type = '';
261
        // Loop through all of the $data for information and pull it out into the result
262 3
        for ($x = 0; $x < count($data) - 1; $x++) {
263
            // Pull out the item
264 3
            $item = $data[$x];
265
            // If this is an empty item, move on
266 3
            if ($item == '' || $item == "\x00") {
267 1
                continue;
268
            }
269
            /*
270
            * Left as reference:
271
            *
272
            * Each block of player_ and team_t have preceding junk chars
273
            *
274
            * player_ is actually \x01player_
275
            * team_t is actually \x00\x02team_t
276
            *
277
            * Probably a by-product of the change to exploding the data from the original.
278
            *
279
            * For now we just strip out these characters
280
            */
281
            // Check to see if $item has a _ at the end, this is player info
282 3
            if (substr($item, -1) == '_') {
283
                // Set the item group
284 3
                $item_group = 'players';
285
                // Set the item type, rip off any trailing stuff and bad chars
286 3
                $item_type = rtrim(str_replace("\x01", '', $item), '_');
287 3
            } elseif (substr($item, -2) == '_t') {
288
                // Check to see if $item has a _t at the end, this is team info
289
                // Set the item group
290 1
                $item_group = 'teams';
291
                // Set the item type, rip off any trailing stuff and bad chars
292 1
                $item_type = rtrim(str_replace([ "\x00", "\x02" ], '', $item), '_t');
293 1
            } else {
294
                // We can assume it is data belonging to a previously defined item
295
296
                // Make a temp buffer so we have easier access to the data
297 3
                $buf_temp = new Buffer($item, Buffer::NUMBER_TYPE_BIGENDIAN);
298
                // Get the values
299 3
                while ($buf_temp->getLength()) {
300
                    // No value so break the loop, end of string
301 3
                    if (($val = $buf_temp->readString()) === '') {
302
                        break;
303
                    }
304
                    // Add the value to the proper item in the correct group
305 3
                    $result->addSub($item_group, $item_type, utf8_encode(trim($val)));
306 3
                }
307
                // Unset our buffer
308 3
                unset($buf_temp);
309
            }
310 3
        }
311
        // Free up some memory
312 3
        unset($data, $item, $item_group, $item_type, $val);
313 3
    }
314
}
315