Completed
Push — master ( 52a46f...98e19a )
by Petrică
02:29
created

MemoryGauge::getCollection()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 11
cts 11
cp 1
rs 9.2
cc 4
eloc 10
nc 2
nop 0
crap 4
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Petrica
5
 * Date: 3/24/2016
6
 * Time: 1:17
7
 */
8
namespace Petrica\StatsdSystem\Gauge;
9
10
use Petrica\StatsdSystem\Collection\ValuesCollection;
11
12
class MemoryGauge implements GaugeInterface
13
{
14
    const MEMINFO_PATH = '/proc/meminfo';
15
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function getSamplingPeriod()
20
    {
21
        return 10;
22
    }
23
24
    /**
25
     * {@inheritdoc}
26
     */
27 1
    public function getCollection()
28
    {
29 1
        $collection = new ValuesCollection();
30
31 1
        $info = $this->getSystemMemoryInfo();
32
33 1
        if (!empty($info) &&
34 1
            isset($info['MemTotal']) &&
35 1
            isset($info['MemFree'])) {
36
37 1
            $collection->add('total.value', $info['MemTotal']);
38 1
            $collection->add('free.value', $info['MemFree']);
39 1
            $collection->add('used.value', $this->getUsedMemory($info));
40 1
        }
41
42 1
        return $collection;
43
    }
44
45
    /**
46
     * Only for linux/unix OS
47
     *
48
     * @return array
49
     */
50
    protected function getSystemMemoryInfo()
51
    {
52
        $meminfo = array();
53
54
        if (file_exists(static::MEMINFO_PATH)) {
55
            $data = explode("\n", file_get_contents(static::MEMINFO_PATH));
56
            $meminfo = array();
57
            foreach ($data as $line) {
58
                if (!empty($line)) {
59
                    list($key, $val) = explode(":", $line);
60
61
                    $meminfo[$key] = intval($val);
62
                }
63
            }
64
        }
65
66
        return $meminfo;
67
    }
68
69
    /**
70
     * Return used memory
71
     *
72
     * @param $info
73
     * @return null
74
     */
75 1
    protected function getUsedMemory($info)
76
    {
77 1
        if (isset($info['MemFree'])
78 1
            && isset($info['MemTotal'])) {
79 1
            return $info['MemTotal'] - $info['MemFree'];
80
        }
81
82
        return null;
83
    }
84
}
85