Completed
Pull Request — master (#41)
by Nicolas
07:53
created

ChunkSize::__construct()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 21
ccs 15
cts 15
cp 1
rs 9.0534
c 1
b 0
f 1
cc 4
eloc 10
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Puzzle\AMQP\Messages\Chunks;
4
5
final class ChunkSize
6
{
7
    private
8
        $size,
9
        $unit;
10
11 12
    public function __construct($size)
12
    {
13 12
        $exception = new \InvalidArgumentException("Given chunk size is not valid");
14
15 12
        if(preg_match("~^(\d+)(K|M)?$~", $size, $matches) !== 1)
16 12
        {
17 5
            throw $exception;
18
        }
19
20 7
        $this->size = (int) $matches[1];
21 7
        if($this->size <= 0)
22 7
        {
23 2
            throw $exception;
24
        }
25
26 5
        $this->unit = null;
27 5
        if(isset($matches[2]))
28 5
        {
29 2
            $this->unit = $matches[2];
30 2
        }
31 5
    }
32
33 7
    public function toBytes()
34
    {
35
        $unitsConversion = [
36 7
            "K" => 1024,
37 7
            "M" => pow(1024, 2),
38 7
        ];
39
40 7
        if(empty($this->unit))
41 7
        {
42 3
            return $this->size;
43
        }
44
45 4
        return $this->size * $unitsConversion[$this->unit];
46
    }
47
}
48