AbstractGenerator::getBytes()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Riimu\Kit\SecureRandom\Generator;
4
5
use Riimu\Kit\SecureRandom\GeneratorException;
6
7
/**
8
 * Abstract generator for handling byte generator errors.
9
 * @author Riikka Kalliomäki <[email protected]>
10
 * @copyright Copyright (c) 2014-2017 Riikka Kalliomäki
11
 * @license http://opensource.org/licenses/mit-license.php MIT License
12
 */
13
abstract class AbstractGenerator implements Generator
14
{
15 27
    public function getBytes($count)
16
    {
17 27
        $count = (int) $count;
18
19 27
        if ($count === 0) {
20 3
            return '';
21
        }
22
23 24
        $bytes = $this->readBytes($count);
24
25 24
        if (!is_string($bytes)) {
26 3
            throw new GeneratorException('The random byte generator did not return a string');
27
        }
28
29 21
        if (strlen($bytes) !== $count) {
30 3
            throw new GeneratorException('The random byte generator returned an invalid number of bytes');
31
        }
32
33 18
        return $bytes;
34
    }
35
36
    /**
37
     * Reads bytes from the randomness source.
38
     * @param int $count number of bytes to read
39
     * @return string|false The bytes read from the randomness source or false on error
40
     * @throws GeneratorException If error occurs in byte generation
41
     */
42
    abstract protected function readBytes($count);
43
}
44