Passed
Push — master ( c493bc...401b4d )
by Nikita
03:14 queued 11s
created

Decoder   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 17
eloc 40
c 1
b 0
f 0
dl 0
loc 75
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A readSizeBlobWithType() 0 13 2
A readSizeStringWithType() 0 4 1
A detectType() 0 14 3
A readSizeContainerWithType() 0 10 2
B readSizeWithType() 0 24 9
1
<?php
2
3
namespace Knik\Binn\Decoder;
4
5
use Knik\Binn\Binn;
6
7
abstract class Decoder
8
{
9
    protected function detectType(string $bytes): int
10
    {
11
        if ($bytes === '') {
12
            return Binn::BINN_NULL;
13
        }
14
15
        $type = Unpacker::unpackType8($bytes[0]);
16
17
        if ($type & Binn::BINN_STORAGE_HAS_MORE) {
18
            $typeBytes = substr($bytes, 0, 2);
19
            $type = Unpacker::unpackType16($typeBytes);
20
        }
21
22
        return $type;
23
    }
24
25
    protected function readSizeWithType(string $bytes): int
26
    {
27
        $type = ($this->detectType($bytes) & ~ Binn::BINN_TYPE_MASK);
28
29
        switch ($type) {
30
            case Binn::BINN_STORAGE_NOBYTES:
31
                return 1;
32
            case Binn::BINN_STORAGE_BYTE:
33
                return 2;
34
            case Binn::BINN_STORAGE_WORD:
35
                return 3;
36
            case Binn::BINN_STORAGE_DWORD:
37
                return 5;
38
            case Binn::BINN_STORAGE_QWORD:
39
                return 9;
40
            case Binn::BINN_STORAGE_STRING:
41
                return $this->readSizeStringWithType($bytes);
42
            case Binn::BINN_STORAGE_BLOB:
43
                return $this->readSizeBlobWithType($bytes);
44
            case Binn::BINN_STORAGE_CONTAINER:
45
                return $this->readSizeContainerWithType($bytes);
46
        }
47
48
        return 0;
49
    }
50
51
    private function readSizeStringWithType(string $bytes): int
52
    {
53
        // type, size size, string size, null terminator
54
        return $this->readSizeBlobWithType($bytes) + 1;
55
    }
56
57
    private function readSizeBlobWithType(string $bytes): int
58
    {
59
        $size = Unpacker::unpackSize8($bytes[1]);
60
        $sizeSize = 1;
61
62
        if ($size > Binn::BINN_MAX_ONE_BYTE_SIZE) {
63
            $sizeBytes = substr($bytes, 1, 4);
64
            $size = Unpacker::unpackSize32($sizeBytes);
65
            $sizeSize = 4;
66
        }
67
68
        // type, size size, data size
69
        return $size + $sizeSize + 1;
70
    }
71
72
    private function readSizeContainerWithType(string $bytes): int
73
    {
74
        $size = Unpacker::unpackSize8($bytes[1]);
75
76
        if ($size > Binn::BINN_MAX_ONE_BYTE_SIZE) {
77
            $sizeBytes = substr($bytes, 1, 4);
78
            $size = Unpacker::unpackSize32($sizeBytes);
79
        }
80
81
        return $size;
82
    }
83
}
84