Completed
Pull Request — master (#23)
by Eugene
09:44
created

UnpackOptions::fromDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the rybakit/msgpack.php package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace MessagePack;
13
14
use MessagePack\Exception\InvalidOptionException;
15
16
final class UnpackOptions
17
{
18
    public const BIGINT_AS_STR       = 0b001;
19
    public const BIGINT_AS_GMP       = 0b010;
20
    public const BIGINT_AS_EXCEPTION = 0b100;
21
22
    private $bigIntMode;
23
24 132
    private function __construct()
25
    {
26 132
    }
27
28 132
    public static function fromDefaults() : self
29
    {
30 132
        $self = new self();
31
        $self->bigIntMode = self::BIGINT_AS_STR;
32 132
33 132
        return $self;
34 132
    }
35 132
36 124
    public static function fromBitmask(int $bitmask) : self
37
    {
38 131
        $self = new self();
39
40
        $self->bigIntMode = self::getSingleOption('bigint', $bitmask,
41 127
            self::BIGINT_AS_STR |
42
            self::BIGINT_AS_GMP |
43 127
            self::BIGINT_AS_EXCEPTION
44
        ) ?: self::BIGINT_AS_STR;
45
46 127
        return $self;
47
    }
48 127
49
    public function isBigIntAsStrMode() : bool
50
    {
51 132
        return self::BIGINT_AS_STR === $this->bigIntMode;
52
    }
53 132
54 132
    public function isBigIntAsGmpMode() : bool
55 131
    {
56
        return self::BIGINT_AS_GMP === $this->bigIntMode;
57
    }
58 5
59
    private static function getSingleOption(string $name, int $bitmask, int $validBitmask) : int
60
    {
61
        $option = $bitmask & $validBitmask;
62
        if ($option === ($option & -$option)) {
63
            return $option;
64 5
        }
65 5
66 5
        static $map = [
67
            self::BIGINT_AS_STR => 'BIGINT_AS_STR',
68
            self::BIGINT_AS_GMP => 'BIGINT_AS_GMP',
69 5
            self::BIGINT_AS_EXCEPTION => 'BIGINT_AS_EXCEPTION',
70
        ];
71
72
        $validOptions = [];
73
        for ($i = $validBitmask & -$validBitmask; $i <= $validBitmask; $i <<= 1) {
74
            $validOptions[] = __CLASS__.'::'.$map[$i];
75
        }
76
77
        throw InvalidOptionException::fromValidOptions($name, $validOptions);
78
    }
79
}
80