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

RandomBytesGenerator::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
ccs 7
cts 7
cp 1
rs 9.8666
cc 3
nc 3
nop 1
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;
12
13
use GpsLab\Component\Base64UID\Exception\ArgumentTypeException;
14
use GpsLab\Component\Base64UID\Exception\ZeroArgumentException;
15
16
class RandomBytesGenerator implements Generator
17
{
18
    /**
19
     * @var int
20
     */
21
    private $bytes_length;
22
23
    /**
24
     * @param int $bytes_length
25
     */
26 4
    public function __construct($bytes_length = 8)
27
    {
28 4
        if (!is_int($bytes_length)) {
29 1
            throw new ArgumentTypeException(sprintf('Length of bytes should be integer, got "%s" instead.', gettype($bytes_length)));
30
        }
31
32 3
        if ($bytes_length <= 0) {
33 1
            throw new ZeroArgumentException(sprintf('Length of bytes should be grate then "0", got "%d" instead.', $bytes_length));
34
        }
35
36 2
        $this->bytes_length = $bytes_length;
37 2
    }
38
39
    /**
40
     * @return string
41
     */
42 2
    public function generate()
43
    {
44 2
        $uid = random_bytes($this->bytes_length);
45 2
        $uid = base64_encode($uid);
46 2
        $uid = str_replace('=', '', $uid);
47
48 2
        return $uid;
49
    }
50
}
51