Completed
Pull Request — master (#78)
by thomas
22:03
created

ByteString::write()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 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\ByteOrder;
10
use BitWasp\Buffertools\Parser;
11
12
class ByteString extends AbstractType
13
{
14
    /**
15
     * @var int|string
16
     */
17
    private $length;
18
19
    /**
20
     * @param int           $length
21
     * @param int           $byteOrder
22
     */
23 14
    public function __construct(int $length, int $byteOrder = ByteOrder::BE)
24
    {
25 14
        $this->length = $length;
26 14
        parent::__construct($byteOrder);
27 14
    }
28
29
    /**
30
     * @param Buffer $string
31
     * @return string
32
     * @throws \Exception
33 12
     */
34
    public function write($string): string
35 12
    {
36 12
        if (!($string instanceof Buffer)) {
37 12
            throw new \InvalidArgumentException('FixedLengthString::write() must be passed a Buffer');
38 12
        }
39 12
40
        $data = new Buffer($string->getBinary(), $this->length);
41
        if (!$this->isBigEndian()) {
42 12
            $data = $data->flip();
43
        }
44
        return $data->getBinary();
45
    }
46
47
    /**
48
     * @param Parser $parser
49
     * @return BufferInterface
50 12
     * @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange
51
     */
52 12
    public function read(Parser $parser): BufferInterface
53
    {
54
        $data = $parser->readBytes($this->length);
55
        if (!$this->isBigEndian()) {
56 12
            $data = $data->flip();
57 6
        }
58 12
59
        return $data;
60 12
    }
61
}
62