Completed
Push — master ( 4e0b70...c818a0 )
by Peter
01:42 queued 12s
created

RandomBinaryGenerator::generate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.9
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 3
1
<?php
2
3
/**
4
 * GpsLab component.
5
 *
6
 * @author    Peter Gribanov <[email protected]>
7
 * @copyright Copyright (c) 2011, Peter Gribanov
8
 * @license   http://opensource.org/licenses/MIT
9
 */
10
11
namespace GpsLab\Component\Base64UID\Generator\Binary;
12
13
use GpsLab\Component\Base64UID\Exception\ArgumentTypeException;
14
use GpsLab\Component\Base64UID\Exception\ProcessorArchitectureException;
15
use GpsLab\Component\Base64UID\Exception\ZeroArgumentException;
16
17
class RandomBinaryGenerator implements BinaryGenerator
18
{
19
    /**
20
     * @var int
21
     */
22
    private $uid_bitmap_length;
23
24
    /**
25
     * @param int $uid_bitmap_length
26
     */
27 8
    public function __construct($uid_bitmap_length)
28
    {
29 8
        if (!is_int($uid_bitmap_length)) {
30 1
            throw new ArgumentTypeException(sprintf('Length of bitmap for UID should be integer, got "%s" instead.', gettype($uid_bitmap_length)));
31
        }
32
33 7
        if ($uid_bitmap_length <= 0) {
34 2
            throw new ZeroArgumentException(sprintf('Length of bitmap for UID should be grate then "0", got "%d" instead.', $uid_bitmap_length));
35
        }
36
37 5 View Code Duplication
        if ($uid_bitmap_length >= PHP_INT_SIZE * 8) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
38 1
            throw new ProcessorArchitectureException(sprintf('Your processor architecture support %d-bit mode, got "%d" instead.', PHP_INT_SIZE * 8, $uid_bitmap_length));
39
        }
40
41 4
        $this->uid_bitmap_length = $uid_bitmap_length;
42 4
    }
43
44
    /**
45
     * @return int
46
     */
47 4
    public function generate()
48
    {
49 4
        $uid = 0;
50 4
        for ($i = 0; $i < $this->uid_bitmap_length; ++$i) {
51 4
            if (random_int(0, 1)) {
52 4
                $uid |= 1 << $i;
53
            }
54
        }
55
56 4
        return $uid;
57
    }
58
}
59