VarString   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 6
dl 0
loc 53
ccs 16
cts 16
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A write() 0 9 2
A read() 0 14 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Buffertools\Types;
6
7
use BitWasp\Buffertools\Buffer;
8
use BitWasp\Buffertools\BufferInterface;
9
use BitWasp\Buffertools\Exceptions\ParserOutOfRange;
10
use BitWasp\Buffertools\Parser;
11
12
class VarString extends AbstractType
13
{
14
    /**
15
     * @var VarInt
16
     */
17
    private $varint;
18
19
    /**
20
     * @param VarInt $varInt
21
     */
22 22
    public function __construct(VarInt $varInt)
23
    {
24 22
        $this->varint = $varInt;
25 22
        parent::__construct($varInt->getByteOrder());
26 22
    }
27
28
    /**
29
     * {@inheritdoc}
30
     * @see \BitWasp\Buffertools\Types\TypeInterface::write()
31
     */
32 12
    public function write($buffer): string
33
    {
34 12
        if (!$buffer instanceof BufferInterface) {
35 2
            throw new \InvalidArgumentException('Must provide a buffer');
36
        }
37
38 10
        $binary = $this->varint->write($buffer->getSize()) . $buffer->getBinary();
39 10
        return $binary;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     * @see \BitWasp\Buffertools\Types\TypeInterface::write()
45
     * @param Parser $parser
46
     * @return \BitWasp\Buffertools\BufferInterface
47
     * @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange
48
     * @throws \Exception
49
     */
50 14
    public function read(Parser $parser): BufferInterface
51
    {
52 14
        $length = $this->varint->read($parser);
53
54 14
        if ($length > $parser->getSize() - $parser->getPosition()) {
55 2
            throw new ParserOutOfRange("Insufficient data remaining for VarString");
56
        }
57
58 12
        if (gmp_cmp(gmp_init($length, 10), gmp_init(0, 10)) == 0) {
59 2
            return new Buffer();
60
        }
61
62 10
        return $parser->readBytes((int) $length);
63
    }
64
}
65