Redis   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 63
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 3
A storeMeasurement() 0 3 1
A incrementMeasurement() 0 3 1
A getMeasurements() 0 10 3
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
/**
15
 * Class Redis
16
 * Storage implementation using Redis.
17
 * @package PHPProm\Storage
18
 */
19
class Redis extends AbstractStorage {
20
21
    /**
22
     * @var \Redis
23
     * The Redis connection.
24
     */
25
    protected $redis;
26
27
    /**
28
     * Redis constructor.
29
     *
30
     * @param string $host
31
     * the connection host
32
     * @param null|string $password
33
     * the password for authentication, null to ignore
34
     * @param int $port
35
     * the connection port, default 6379
36
     * @param string $prefix
37
     * the global key prefix to use, default 'PHPProm:'
38
     * @param null|string $dbIndex
39
     * the Redis DB index to use, null to ignore
40
     */
41
    public function __construct($host, $password = null, $port = 6379, $prefix = 'PHPProm:', $dbIndex = null) {
42
        parent::__construct();
43
        $this->redis = new \Redis();
44
        $this->redis->connect($host, $port);
45
        if ($password !== null) {
46
            $this->redis->auth($password);
47
        }
48
        if ($dbIndex !== null) {
49
            $this->redis->select($dbIndex);
50
        }
51
        $this->redis->setOption(\Redis::OPT_PREFIX, $prefix);
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function storeMeasurement($metric, $key, $value) {
58
        $this->redis->set($metric.':'.$key, $value);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function incrementMeasurement($metric, $key) {
65
        $this->redis->incr($metric.':'.$key);
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function getMeasurements($metric, array $keys, $defaultValue = 'Nan') {
72
        $measurements = [];
73
        $prefixedKeys = array_map(function($key) use ($metric) {
74
            return $metric.':'.$key;
75
        }, $keys);
76
        foreach ($this->redis->mget($prefixedKeys) as $i => $value) {
77
            $measurements[$keys[$i]] = $value !== false ? (float)$value : $defaultValue;
78
        }
79
        return $measurements;
80
    }
81
}
82