Passed
Push — master ( 64683c...c493bc )
by Nikita
04:07 queued 10s
created

Binn   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 66
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A serialize() 0 9 3
A unserialize() 0 15 3
1
<?php
2
/**
3
 * Binn. Serialize to bin string.
4
 * Binn Specification: https://github.com/liteserver/binn/blob/master/spec.md
5
 *
6
 * Note! This class not support Map and Object, only List support. Sorry, i am working on this.
7
 *
8
 * Original Binn Library for C++ - https://github.com/liteserver/binn
9
 *
10
 *
11
 * @author      Nikita Kuznetsov (NiK)
12
 * @copyright   Copyright (c) 2016, Nikita Kuznetsov ([email protected])
13
 * @license     GNU GPL
14
 * @link        http://www.gameap.ru
15
 *
16
 */
17
18
namespace Knik\Binn;
19
20
class Binn extends BinnAbstract {
21
22
    /**
23
     * Size bin string in bytes
24
     *
25
     * @var int
26
     * @access protected
27
     */
28
    protected $size         = 0;
29
30
    /**
31
     * Bin string
32
     *
33
     * @var string
34
     * @access protected
35
     */
36
    protected $binnString     = "";
37
38
    /**
39
     * Binn constructor
40
     */
41 17
    public function __construct()
42
    {
43 17
        $this->setContainersClasses([
44 17
            self::BINN_LIST => BinnList::class,
45 17
            self::BINN_MAP => BinnMap::class,
46 17
            self::BINN_OBJECT => BinnObject::class,
47
        ]);
48 17
    }
49
50
    /**
51
     * @param array $array
52
     * @return string
53
     */
54 14
    public function serialize($array = [])
55
    {
56 14
        $this->binnFree();
57
58 14
        foreach ($this->containersClasses as $contanerType => $containersClass)
59
        {
60 12
            if ($containersClass::validArray($array)) {
61 12
                $container = new $containersClass();
62 12
                return $container->serialize($array);
63
            }
64
        }
65 2
    }
66
67
    /**
68
     * @param string $binnString
69
     * @return array|null
70
     */
71 9
    public function unserialize($binnString = '')
72
    {
73 9
        if (empty($binnString)) {
74 3
            return $this->getBinnArr();
75
        }
76
77 9
        $this->binnFree();
78
79 9
        $type = $this->unpack(Binn::BINN_UINT8, $binnString[0]);
80
81 9
        if (array_key_exists($type, $this->containersClasses)) {
82 9
            $binnContainer = new $this->containersClasses[$type]($binnString);
83 9
            return $binnContainer->unserialize();
84
        } else {
85 3
            return null;
86
        }
87
    }
88
}