Completed
Pull Request — master (#21)
by Eugene
05:40
created

ArrayIteratorTransformer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace App\MessagePack;
4
5
use MessagePack\BufferUnpacker;
6
use MessagePack\Packer;
7
use MessagePack\TypeTransformer\Extension;
8
9
class ArrayIteratorTransformer implements Extension
10
{
11
    private $type;
12
13
    public function __construct($type)
14
    {
15
        $this->type = $type;
16
    }
17
18
    public function getType()
19
    {
20
        return $this->type;
21
    }
22
23
    public function pack(Packer $packer, $value)
24
    {
25
        if (!$value instanceof \ArrayIterator) {
26
            return null;
27
        }
28
29
        $size = 0;
30
        $data = '';
31
        foreach ($value as $item) {
32
            $data .= $packer->pack($item);
33
            ++$size;
34
        }
35
36
        if ($size <= 0xf) {
37
            $data = \chr(0x90 | $size).$data;
38
        } elseif ($size <= 0xffff) {
39
            $data = "\xdc".\chr($size >> 8).\chr($size).$data;
40
        } else {
41
            $data = \pack('CN', 0xdd, $size).$data;
42
        }
43
44
        return $packer->packExt($this->type, $data);
45
    }
46
47
    public function unpack(BufferUnpacker $unpacker, $length)
48
    {
49
        $c = $unpacker->unpackUint8();
50
51
        if ($c >= 0x90 && $c <= 0x9f) {
52
            $size = $c & 0xf;
53
        } elseif (0xdc === $c) {
54
            $size = $unpacker->unpackUint16();
55
        } else {
56
            $size = $unpacker->unpackUint32();
57
        }
58
59
        while ($size--) {
60
            yield $unpacker->unpack();
61
        }
62
    }
63
}
64