Completed
Push — master ( 7b04fe...bd89c1 )
by Philip
02:01
created

Redis::incrementMeasurement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the PHPProm package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace PHPProm\Storage;
13
14
class Redis implements StorageInterface {
15
16
    protected $redis;
17
18
    public function __construct($host, $password = null, $port = 6379, $prefix = 'PHPProm:', $dbIndex = null) {
19
        $this->redis = new \Redis();
20
        $this->redis->connect($host, $port);
21
        if ($password !== null) {
22
            $this->redis->auth($password);
23
        }
24
        if ($dbIndex !== null) {
25
            $this->redis->select($dbIndex);
26
        }
27
        $this->redis->setOption(\Redis::OPT_PREFIX, $prefix);
28
    }
29
30
    public function storeMeasurement($prefix, $key, $value) {
31
        $this->redis->set($prefix.':'.$key, $value);
32
    }
33
34
    public function incrementMeasurement($prefix, $key) {
35
        $this->redis->incr($prefix.':'.$key);
36
    }
37
38
    public function getMeasurements($prefix, array $keys, $defaultValue = 'Nan') {
39
        $measurements = [];
40
        $prefixedKeys = array_map(function($key) use ($prefix) {
41
            return $prefix.':'.$key;
42
        }, $keys);
43
        foreach ($this->redis->mget($prefixedKeys) as $i => $value) {
44
            $measurements[$keys[$i]] = $value !== false ? (float)$value : $defaultValue;
45
        }
46
        return $measurements;
47
    }
48
}
49