MDStatus::execute()   F
last analyzed

Complexity

Conditions 21
Paths 777

Size

Total Lines 101
Code Lines 80

Duplication

Lines 3
Ratio 2.97 %

Importance

Changes 0
Metric Value
cc 21
eloc 80
nc 777
nop 0
dl 3
loc 101
rs 2.3015
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * MDStatus Plugin
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PSI_Plugin_MDStatus
9
 * @author    Michael Cramer <[email protected]>
10
 * @copyright 2009 phpSysInfo
11
 * @license   http://opensource.org/licenses/gpl-2.0.php GNU General Public License
12
 * @version   SVN: $Id: class.mdstatus.inc.php 661 2012-08-27 11:26:39Z namiltd $
13
 * @link      http://phpsysinfo.sourceforge.net
14
 */
15
 /**
16
 * mdstatus Plugin, which displays a snapshot of the kernel's RAID/md state
17
 * a simple view which shows supported types and RAID-Devices which are determined by
18
 * parsing the "/proc/mdstat" file, another way is to provide
19
 * a file with the output of the /proc/mdstat file, so there is no need to run a execute by the
20
 * webserver, the format of the command is written down in the phpsysinfo.ini file, where also
21
 * the method of getting the information is configured
22
 *
23
 * @category  PHP
24
 * @package   PSI_Plugin_MDStatus
25
 * @author    Michael Cramer <[email protected]>
26
 * @copyright 2009 phpSysInfo
27
 * @license   http://opensource.org/licenses/gpl-2.0.php GNU General Public License
28
 * @version   Release: 3.0
29
 * @link      http://phpsysinfo.sourceforge.net
30
 */
31
class MDStatus extends PSI_Plugin
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
32
{
33
    /**
34
     * variable, which holds the content of the command
35
     * @var array
36
     */
37
    private $_filecontent = "";
38
39
    /**
40
     * variable, which holds the result before the xml is generated out of this array
41
     * @var array
42
     */
43
    private $_result = array();
44
45
    /**
46
     * read the data into an internal array and also call the parent constructor
47
     *
48
     * @param String $enc encoding
49
     */
50 View Code Duplication
    public function __construct($enc)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
    {
52
        $buffer = "";
53
        parent::__construct(__CLASS__, $enc);
54
        switch (strtolower(PSI_PLUGIN_MDSTATUS_ACCESS)) {
55
        case 'file':
56
            CommonFunctions::rfts("/proc/mdstat", $buffer);
57
            break;
58
        case 'data':
59
            CommonFunctions::rfts(APP_ROOT."/data/mdstat.txt", $buffer);
60
            break;
61
        default:
62
            $this->global_error->addConfigError("__construct()", "PSI_PLUGIN_MDSTATUS_ACCESS");
63
            break;
64
        }
65
        if (trim($buffer) != "") {
66
            $this->_filecontent = preg_split("/\n/", $buffer, -1, PREG_SPLIT_NO_EMPTY);
67
        } else {
68
            $this->_filecontent = array();
69
        }
70
    }
71
72
    /**
73
     * doing all tasks to get the required informations that the plugin needs
74
     * result is stored in an internal array<br>the array is build like a tree,
75
     * so that it is possible to get only a specific process with the childs
76
     *
77
     * @return void
78
     */
79
    public function execute()
80
    {
81
        if (empty($this->_filecontent)) {
82
            return;
83
        }
84
        // get the supported types
85
        if (preg_match('/[a-zA-Z]* : (\[([a-z0-9])*\]([ \n]))+/', $this->_filecontent[0], $res)) {
86
            $parts = preg_split("/ : /", $res[0]);
87
            $parts = preg_split("/ /", $parts[1]);
88
            $count = 0;
89
            foreach ($parts as $types) {
90
                if (trim($types) != "") {
91
                    $this->_result['supported_types'][$count++] = substr(trim($types), 1, -1);
92
                }
93
            }
94
        }
95
        // get disks
96
        if (preg_match("/^read_ahead/", $this->_filecontent[1])) {
97
            $count = 2;
98
        } else {
99
            $count = 1;
100
        }
101
        $cnt_filecontent = count($this->_filecontent);
102
        do {
103
            $parts = preg_split("/ : /", $this->_filecontent[$count]);
104
            $dev = trim($parts[0]);
105
            if (count($parts) == 2) {
106
                $details = preg_split('/ /', $parts[1]);
107
                if (!strstr($details[0], 'inactive')) {
108
                    $this->_result['devices'][$dev]['level'] = $details[1];
109
                } else {
110
                    $this->_result['devices'][$dev]['level'] = "none";
111
                }
112
                $this->_result['devices'][$dev]['status'] = $details[0];
113
                for ($i = 2, $cnt_details = count($details); $i < $cnt_details; $i++) {
114
                    preg_match('/(([a-z0-9])+)(\[([0-9]+)\])(\([SF ]\))?/', trim($details[$i]), $partition);
115
                    if (count($partition) == 5 || count($partition) == 6) {
116
                        $this->_result['devices'][$dev]['partitions'][$partition[1]]['raid_index'] = substr(trim($partition[3]), 1, -1);
117
                        if (isset($partition[5])) {
118
                            $search = array("(", ")");
119
                            $replace = array("", "");
120
                            $this->_result['devices'][$dev]['partitions'][$partition[1]]['status'] = str_replace($search, $replace, trim($partition[5]));
121 View Code Duplication
                        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
                            $this->_result['devices'][$dev]['partitions'][$partition[1]]['status'] = "ok";
123
                        }
124
                    }
125
                }
126
                $count++;
127
                $optionline = $this->_filecontent[$count - 1].$this->_filecontent[$count];
128
                if (preg_match('/([^\sk]*)k chunk/', $optionline, $chunksize)) {
129
                    $this->_result['devices'][$dev]['chunk_size'] = $chunksize[1];
130
                } else {
131
                    $this->_result['devices'][$dev]['chunk_size'] = -1;
132
                }
133
                if ($pos = strpos($optionline, "super non-persistent")) {
0 ignored issues
show
Unused Code introduced by
$pos is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
134
                    $this->_result['devices'][$dev]['pers_superblock'] = 0;
135
                } else {
136
                    $this->_result['devices'][$dev]['pers_superblock'] = 1;
137
                }
138
                if ($pos = strpos($optionline, "algorithm")) {
139
                    $this->_result['devices'][$dev]['algorithm'] = trim(substr($optionline, $pos + 9, 2));
140
                } else {
141
                    $this->_result['devices'][$dev]['algorithm'] = -1;
142
                }
143
                if (preg_match('/(\[[0-9]?\/[0-9]\])/', $optionline, $res)) {
144
                    $slashpos = strpos($res[0], '/');
145
                    $this->_result['devices'][$dev]['registered'] = substr($res[0], 1, $slashpos - 1);
146
                    $this->_result['devices'][$dev]['active'] = substr($res[0], $slashpos + 1, strlen($res[0]) - $slashpos - 2);
147
                } else {
148
                    $this->_result['devices'][$dev]['registered'] = -1;
149
                    $this->_result['devices'][$dev]['active'] = -1;
150
                }
151
                if (preg_match(('/([a-z]+)( *)=( *)([0-9\.]+)%/'), $this->_filecontent[$count + 1], $res) || (preg_match(('/([a-z]+)( *)=( *)([0-9\.]+)/'), $optionline, $res))) {
152
                    list($this->_result['devices'][$dev]['action']['name'], $this->_result['devices'][$dev]['action']['percent']) = preg_split("/=/", str_replace("%", "", $res[0]));
153
                    if (preg_match(('/([a-z]*=[0-9\.]+[a-z]+)/'), $this->_filecontent[$count + 1], $res)) {
154
                        $time = preg_split("/=/", $res[0]);
155
                        list($this->_result['devices'][$dev]['action']['finish_time'], $this->_result['devices'][$dev]['action']['finish_unit']) = sscanf($time[1], '%f%s');
156
                    } else {
157
                        $this->_result['devices'][$dev]['action']['finish_time'] = -1;
158
                        $this->_result['devices'][$dev]['action']['finish_unit'] = -1;
159
                    }
160
                } else {
161
                    $this->_result['devices'][$dev]['action']['name'] = -1;
162
                    $this->_result['devices'][$dev]['action']['percent'] = -1;
163
                    $this->_result['devices'][$dev]['action']['finish_time'] = -1;
164
                    $this->_result['devices'][$dev]['action']['finish_unit'] = -1;
165
                }
166
            } else {
167
                $count++;
168
            }
169
        } while ($cnt_filecontent > $count);
170
        $lastline = $this->_filecontent[$cnt_filecontent - 2];
171
        if (strpos($lastline, "unused devices") !== false) {
172
            $parts = preg_split("/:/", $lastline);
173
            $search = array("<", ">");
174
            $replace = array("", "");
175
            $this->_result['unused_devs'] = trim(str_replace($search, $replace, $parts[1]));
176
        } else {
177
            $this->_result['unused_devs'] = -1;
178
        }
179
    }
180
181
    /**
182
     * generates the XML content for the plugin
183
     *
184
     * @return SimpleXMLObject entire XML content for the plugin
0 ignored issues
show
Documentation introduced by
Should the return type not be SimpleXMLElement?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
185
     */
186
    public function xml()
187
    {
188
        if (empty($this->_result)) {
189
            return $this->xml->getSimpleXmlElement();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->xml->getSimpleXmlElement(); (SimpleXMLElement) is incompatible with the return type declared by the interface PSI_Interface_Plugin::xml of type SimpleXMLObject.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
190
        }
191
        $hideRaids = array();
192 View Code Duplication
        if (defined('PSI_PLUGIN_MDSTATUS_HIDE_RAID_DEVICES') && is_string(PSI_PLUGIN_MDSTATUS_HIDE_RAID_DEVICES)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
193
            if (preg_match(ARRAY_EXP, PSI_PLUGIN_MDSTATUS_HIDE_RAID_DEVICES)) {
194
                $hideRaids = eval(PSI_PLUGIN_MDSTATUS_HIDE_RAID_DEVICES);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
195
            } else {
196
                $hideRaids = array(PSI_PLUGIN_MDSTATUS_HIDE_RAID_DEVICES);
197
            }
198
        }
199
        $sup = $this->xml->addChild("Supported_Types");
200
        foreach ($this->_result['supported_types'] as $type) {
201
            $typ = $sup->addChild("Type");
202
            $typ->addAttribute("Name", $type);
203
        }
204
        if (isset($this->_result['devices'])) foreach ($this->_result['devices'] as $key=>$device) {
205
            if (!in_array($key, $hideRaids, true)) {
206
                $dev = $this->xml->addChild("Raid");
207
                $dev->addAttribute("Device_Name", $key);
208
                $dev->addAttribute("Level", $device["level"]);
209
                $dev->addAttribute("Disk_Status", $device["status"]);
210
                $dev->addAttribute("Chunk_Size", $device["chunk_size"]);
211
                $dev->addAttribute("Persistend_Superblock", $device["pers_superblock"]);
212
                $dev->addAttribute("Algorithm", $device["algorithm"]);
213
                $dev->addAttribute("Disks_Registered", $device["registered"]);
214
                $dev->addAttribute("Disks_Active", $device["active"]);
215
                $action = $dev->addChild("Action");
216
                $action->addAttribute("Percent", $device['action']['percent']);
217
                $action->addAttribute("Name", $device['action']['name']);
218
                $action->addAttribute("Time_To_Finish", $device['action']['finish_time']);
219
                $action->addAttribute("Time_Unit", $device['action']['finish_unit']);
220
                $disks = $dev->addChild("Disks");
221 View Code Duplication
                foreach ($device['partitions'] as $diskkey=>$disk) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
222
                    $disktemp = $disks->addChild("Disk");
223
                    $disktemp->addAttribute("Name", $diskkey);
224
                    $disktemp->addAttribute("Status", $disk['status']);
225
                    $disktemp->addAttribute("Index", $disk['raid_index']);
226
                }
227
            }
228
        }
229
        if ($this->_result['unused_devs'] !== - 1) {
230
            $unDev = $this->xml->addChild("Unused_Devices");
231
            $unDev->addAttribute("Devices", $this->_result['unused_devs']);
232
        }
233
234
        return $this->xml->getSimpleXmlElement();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->xml->getSimpleXmlElement(); (SimpleXMLElement) is incompatible with the return type declared by the interface PSI_Interface_Plugin::xml of type SimpleXMLObject.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
235
    }
236
}
237