Passed
Push — master ( 6cca8a...41d019 )
by Eugene
05:46
created

Greeting::parse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of the Tarantool Client package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Tarantool\Client\Connection;
15
16
use Tarantool\Client\Exception\UnexpectedResponse;
17
18
final class Greeting
19
{
20
    public const SIZE_BYTES = 128;
21
22
    private $greeting;
23
    private $salt;
24
    private $serverVersion;
25
    private $serverVersionId;
26
27 419
    private function __construct($greeting)
28
    {
29 419
        $this->greeting = $greeting;
30 419
    }
31
32 449
    public static function parse(string $greeting) : self
33
    {
34 449
        if (0 === \strpos($greeting, 'Tarantool')) {
35 419
            return new self($greeting);
36
        }
37
38 30
        throw new UnexpectedResponse('Unable to recognize Tarantool server.');
39
    }
40
41 36
    public function getSalt() : string
42
    {
43 36
        if (null !== $this->salt) {
44 3
            return $this->salt;
45
        }
46
47 36
        if (false === $salt = \base64_decode(\substr($this->greeting, 64, 44), true)) {
48 6
            throw new UnexpectedResponse('Unable to decode salt.');
49
        }
50
51 30
        $salt = \substr($salt, 0, 20);
52
53 30
        if (isset($salt[19])) {
54 21
            return $this->salt = $salt;
55
        }
56
57 9
        throw new UnexpectedResponse('Salt is too short.');
58
    }
59
60 27
    public function getServerVersion() : string
61
    {
62 27
        if (null !== $this->serverVersion) {
63
            return $this->serverVersion;
64
        }
65
66 27
        return $this->serverVersion = \substr($this->greeting, 10, \strspn($this->greeting, '0123456789.', 10));
67
    }
68
69 68
    public function getServerVersionId() : int
70
    {
71 68
        if (null !== $this->serverVersionId) {
72
            return $this->serverVersionId;
73
        }
74
75 68
        [$major, $minor, $patch] = \sscanf($this->greeting, 'Tarantool %d.%d.%d');
76
77 68
        return $this->serverVersionId = $major * 10000 + $minor * 100 + $patch;
78
    }
79
}
80