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

ArrayIteratorTransformer   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 2
dl 0
loc 55
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getType() 0 4 1
B pack() 0 23 5
B unpack() 0 16 5
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