Decimal::parse()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 15
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 8.8571
cc 5
eloc 14
nc 8
nop 1
1
<?php
2
namespace Cassandra\Type;
3
4
class Decimal extends Base{
5
6
    /**
7
     * @param string $value
8
     * @throws Exception
9
     */
10
    public function __construct($value = null){
11
        if (!is_numeric($value))
12
            throw new Exception('Incoming value must be numeric string.');
13
14
        $this->_value = $value;
15
    }
16
    
17
    public static function binary($value){
18
            $pos = strpos($value, '.');
19
            $scaleLen = $pos === false ? 0 : strlen($value) - $pos - 1;
20
            $value *= pow(10, $scaleLen);
21
            $higher = ($value & 0xffffffff00000000) >> 32;
22
            $lower = $value & 0x00000000ffffffff;
23
            $binary = pack('NNN', $scaleLen, $higher, $lower);
24
        return $binary;
25
    }
26
    
27
    /**
28
     * @return string
29
     */
30
    public static function parse($binary){
0 ignored issues
show
Unused Code introduced by
The parameter $binary is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
31
        $unpacked = unpack('N1scale/C*', $this->_binary);
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
32
        $valueByteLen = $length - 4;
0 ignored issues
show
Bug introduced by
The variable $length does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
33
        $value = 0;
34
        for ($i = 1; $i <= $valueByteLen; ++$i)
35
            $value |= $unpacked[$i] << (($valueByteLen - $i) * 8);
36
        $shift = (\PHP_INT_SIZE - $valueByteLen) * 8;
37
        $value = $value << $shift >> $shift;
38
        if ($unpacked['scale'] === 0)
39
            return (string) $value;
40
        elseif (strlen($value) > $unpacked['scale'])
41
            return substr($value, 0, -$unpacked['scale']) . '.' . substr($value, -$unpacked['scale']);
42
        else
43
            return $value >= 0 ? sprintf("0.%0$unpacked[scale]d", $value) : sprintf("-0.%0$unpacked[scale]d", -$value);
44
    }
45
}
46