Completed
Push — master ( 1f2b71...3f1d1d )
by Matze
07:04
created

IdGenerator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace BrainExe\Core\Util;
4
5
use BrainExe\Annotations\Annotations\Service;
6
use BrainExe\Core\Redis\Predis;
7
8
/**
9
 * @Service
10
 * @api
11
 */
12
class IdGenerator
13
{
14
15
    const ID_LENGTH    = 10;
16
    const KEY          = 'idgenerator:%s';
17
    const DEFAULT_TYPE = 'lastid';
18
19
    /**
20
     * @var Predis
21
     */
22
    private $redis;
23
24
    /**
25
     * @param Predis $client
26
     */
27 3
    public function __construct(Predis $client)
28
    {
29 3
        $this->redis = $client;
30 3
    }
31
32
    /**
33
     * @param string $type
34
     * @return int
35
     */
36 1
    public function generateUniqueId(string $type = self::DEFAULT_TYPE) : int
37
    {
38 1
        return (int)$this->redis->incr(sprintf(self::KEY, $type));
39
    }
40
41
    /**
42
     * @param int $length
43
     * @return string
44
     */
45 1
    public function generateRandomId(int$length = self::ID_LENGTH) : string
46
    {
47 1
        $randomId = md5(microtime() . mt_rand()) . mt_rand();
48
49 1
        return substr(base_convert($randomId, 10, 36), 0, $length);
50
    }
51
}
52