Passed
Pull Request — master (#62)
by Eugene
07:10
created

Response::getBodyField()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
rs 10
cc 3
nc 4
nop 1
crap 3.0416
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;
15
16
final class Response
17
{
18
    public const TYPE_ERROR = 0x8000;
19
20
    private $header;
21
    private $bodyGetter;
22
    private $body;
23
24 216
    public function __construct(array $header, \Closure $bodyGetter)
25
    {
26 216
        $this->header = $header;
27 216
        $this->bodyGetter = $bodyGetter;
28 216
    }
29
30 188
    public function isError() : bool
31
    {
32 188
        $code = $this->header[Keys::CODE];
33
34 188
        return $code >= self::TYPE_ERROR;
35
    }
36
37 30
    public function getCode() : int
38
    {
39 30
        return $this->header[Keys::CODE];
40
    }
41
42 190
    public function getSync() : int
43
    {
44 190
        return $this->header[Keys::SYNC];
45
    }
46
47
    public function getSchemaId() : int
48
    {
49
        return $this->header[Keys::SCHEMA_ID];
50
    }
51
52 182
    public function getBodyField(int $key)
53
    {
54 182
        if (null === $this->body) {
55 182
            $this->body = ($this->bodyGetter)();
56
        }
57
58 182
        if (!isset($this->body[$key])) {
59
            throw new \OutOfRangeException(\sprintf('Invalid body key 0x%x.', $key));
60
        }
61
62 182
        return $this->body[$key];
63
    }
64
65 2
    public function tryGetBodyField(int $key, $default = null)
66
    {
67 2
        if (null === $this->body) {
68 2
            $this->body = ($this->bodyGetter)();
69
        }
70
71
        return $this->body[$key] ?? $default;
72
    }
73
}
74