TopCommand   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 53.33%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 7
c 1
b 0
f 1
lcom 1
cbo 2
dl 0
loc 82
ccs 16
cts 30
cp 0.5333
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A run() 0 13 2
A parse() 0 14 2
A buildCommand() 0 10 1
A getCommand() 0 4 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Petrica
5
 * Date: 5/29/2016
6
 * Time: 0:01
7
 */
8
namespace Petrica\StatsdSystem\Model;
9
10
use Tivie\Command\Argument;
11
use Tivie\Command\Command;
12
13
/**
14
 * Class TopCommand
15
 *
16
 * Return parsed unix top command information
17
 *
18
 * @package Petrica\StatsdTop\Model
19
 */
20
class TopCommand
21
{
22
    /**
23
     * Command to run in order to return git tags
24
     *
25
     * @var null|Command
26
     */
27
    protected $command = null;
28
29 3
    public function __construct()
30
    {
31 3
        $this->command = $this->buildCommand();
32 3
    }
33
34
    /**
35
     * Run configured command
36
     *
37
     * @return string
38
     */
39 1
    public function run()
40
    {
41 1
        $result = $this->getCommand()->run();
42
43 1
        if ($result->getExitCode() != 0) {
44 1
            throw new \RuntimeException(sprintf(
45 1
                'Command failed. Exit code %d, output %s',
46 1
                $result->getExitCode(),
47 1
                $result->getStdErr()));
48
        }
49
50
        return $this->parse($result->getStdOut());
51
    }
52
53
    /**
54
     * Parse top utility command output
55
     *
56
     * Returns an array of lines with the same top columns
57
     *
58
     * @param $output
59
     * @return array
60
     */
61
    protected function parse($output)
62
    {
63
        $lines = explode(PHP_EOL, $output);
64
        $stats = array();
65
        foreach ($lines as $line) {
66
            $data = explode(' ', $line);
67
            array_walk($data, 'trim');
68
            $stats[] = array_values(array_filter($data, function ($value) {
69
                return strlen($value) > 0;
70
            }));
71
        }
72
73
        return $stats;
74
    }
75
76
    /**
77
     * Build commit command
78
     *
79
     * @return Command
80
     * @throws \Tivie\Command\Exception\Exception
81
     * @throws \Tivie\Command\Exception\InvalidArgumentException
82
     */
83 3
    protected function buildCommand()
84
    {
85 3
        $command = new Command(\Tivie\Command\ESCAPE);
86
        $command
87 3
            ->setCommand('top')
88 3
            ->addArgument(new Argument('-b'))
89 3
            ->addArgument(new Argument('-n', 1));
90
91 3
        return $command;
92
    }
93
94
    /**
95
     * @return null|Command
96
     */
97
    protected function getCommand()
98
    {
99
        return $this->command;
100
    }
101
}