SMART::__construct()   C
last analyzed

Complexity

Conditions 28
Paths 19

Size

Total Lines 78
Code Lines 58

Duplication

Lines 41
Ratio 52.56 %

Importance

Changes 0
Metric Value
cc 28
eloc 58
nc 19
nop 1
dl 41
loc 78
rs 5.0538
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
 * SMART Plugin
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PSI_Plugin_SMART
9
 * @author    Antoine Bertin <[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.smart.inc.php 707 2012-11-28 10:20:49Z namiltd $
13
 * @link      http://phpsysinfo.sourceforge.net
14
 */
15
/**
16
 * SMART plugin, which displays all SMART informations available
17
 *
18
 * @category  PHP
19
 * @package   PSI_Plugin_SMART
20
 * @author    Antoine Bertin <[email protected]>
21
 * @copyright 2009 phpSysInfo
22
 * @license   http://opensource.org/licenses/gpl-2.0.php GNU General Public License
23
 * @version   Release: 3.0
24
 * @link      http://phpsysinfo.sourceforge.net
25
 */
26
class SMART 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...
27
{
28
    /**
29
     * variable, which holds the content of the command
30
     * @var array
31
     */
32
    private $_filecontent = array();
33
34
    /**
35
     * variable, which holds the result before the xml is generated out of this array
36
     * @var array
37
     */
38
    private $_result = array();
39
40
    /**
41
     * variable, which holds PSI_PLUGIN_SMART_IDS well formated datas
42
     * @var array
43
     */
44
    private $_ids = array();
45
46
    /**
47
     * read the data into an internal array and also call the parent constructor
48
     *
49
     * @param String $enc target encoding
50
     */
51
    public function __construct($enc)
52
    {
53
        parent::__construct(__CLASS__, $enc);
54
        switch (strtolower(PSI_PLUGIN_SMART_ACCESS)) {
55
            case 'command':
56
                if (defined('PSI_PLUGIN_SMART_DEVICES') && is_string(PSI_PLUGIN_SMART_DEVICES)) {
57
                    if (preg_match(ARRAY_EXP, PSI_PLUGIN_SMART_DEVICES)) {
58
                        $disks = eval(PSI_PLUGIN_SMART_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...
59
                    } else {
60
                        $disks = array(PSI_PLUGIN_SMART_DEVICES);
61
                    }
62
                    foreach ($disks as $disk) {
63
                        if (trim($disk) != "") {
64
                            $diskdev = "";
65
                            if (preg_match("/\s*\(([^\(\(]*)\)\s*(.*)/", $disk, $devdisk)) {
66
                                $diskname = trim($devdisk[2]);
67
                                if (trim($devdisk[1]) != "") {
68
                                    $diskdev = "--device ".preg_replace('/\./', ',', trim($devdisk[1]));
69
                                }
70
                            } else {
71
                                $diskname = trim($disk);
72
                            }
73
                            $buffer = "";
74
                            if (trim($diskname != "") && (CommonFunctions::executeProgram('smartctl', '--all'.' '.$diskdev.' '.$diskname, $buffer, PSI_DEBUG))) {
75
                                $this->_filecontent[trim($disk)] = $buffer;
76
                            }
77
                        }
78
                    }
79
                }
80 View Code Duplication
                if (defined('PSI_PLUGIN_SMART_IDS') && is_string(PSI_PLUGIN_SMART_IDS)) {
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...
81
                    if (preg_match(ARRAY_EXP, PSI_PLUGIN_SMART_IDS)) {
82
                        $fullIds = eval(PSI_PLUGIN_SMART_IDS);
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...
83
                    } else {
84
                        $fullIds = array(PSI_PLUGIN_SMART_IDS);
85
                    }
86
                    foreach ($fullIds as $fullId) {
87
                        $arrFullId = preg_split('/-/', $fullId);
88
                        $this->_ids[intval($arrFullId[0])] = strtolower($arrFullId[1]);
89
                        if (!empty($arrFullId[2]))
90
                            $this->_ids[intval($arrFullId[2])] = "#replace-".intval($arrFullId[0]);
91
                    }
92
                }
93
                break;
94
            case 'data':
95 View Code Duplication
                if (defined('PSI_PLUGIN_SMART_DEVICES') && is_string(PSI_PLUGIN_SMART_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...
96
                    if (preg_match(ARRAY_EXP, PSI_PLUGIN_SMART_DEVICES)) {
97
                        $disks = eval(PSI_PLUGIN_SMART_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...
98
                    } else {
99
                        $disks = array(PSI_PLUGIN_SMART_DEVICES);
100
                    }
101
                    $dn=0;
102
                    foreach ($disks as $disk) {
103
                        $buffer="";
104
                        if (CommonFunctions::rfts(APP_ROOT."/data/smart{$dn}.txt", $buffer) && !empty($buffer)) {
105
                            $this->_filecontent[$disk] = $buffer;
106
                        }
107
                        $dn++;
108
                    }
109
                }
110 View Code Duplication
                if (defined('PSI_PLUGIN_SMART_IDS') && is_string(PSI_PLUGIN_SMART_IDS)) {
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...
111
                    if (preg_match(ARRAY_EXP, PSI_PLUGIN_SMART_IDS)) {
112
                        $fullIds = eval(PSI_PLUGIN_SMART_IDS);
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...
113
                    } else {
114
                        $fullIds = array(PSI_PLUGIN_SMART_IDS);
115
                    }
116
                    foreach ($fullIds as $fullId) {
117
                        $arrFullId = preg_split('/-/', $fullId);
118
                        $this->_ids[intval($arrFullId[0])] = strtolower($arrFullId[1]);
119
                        if (!empty($arrFullId[2]))
120
                            $this->_ids[intval($arrFullId[2])] = "#replace-".intval($arrFullId[0]);
121
                    }
122
                }
123
                break;
124
            default:
125
                $this->global_error->addError("switch(PSI_PLUGIN_SMART_ACCESS)", "Bad SMART configuration in phpsysinfo.ini");
126
                break;
127
        }
128
    }
129
130
    /**
131
     * doing all tasks to get the required informations that the plugin needs
132
     * result is stored in an internal array
133
     *
134
     * @return void
135
     */
136
    public function execute()
137
    {
138
        if (empty($this->_filecontent) || empty($this->_ids)) {
139
            return;
140
        }
141
        foreach ($this->_filecontent as $disk=>$result) {
142
            // set the start and end offset in the result string at the beginning and end respectively
143
            // just in case we don't find the two strings, so that it still works as expected.
144
            $startIndex = 0;
145
            $endIndex = 0;
146
            $vendorInfos = "";
147
148
            // locate the beginning string offset for the attributes
149
            if (preg_match('/(Vendor Specific SMART Attributes with Thresholds)/', $result, $matches, PREG_OFFSET_CAPTURE))
150
               $startIndex = $matches[0][1];
151
152
            // locate the end string offset for the attributes, this is usually right before string "SMART Error Log Version" or "SMART Error Log not supported" or "Error SMART Error Log Read failed" (hopefully every output has it!)
153
            if (preg_match('/(SMART Error Log Version)|(SMART Error Log not supported)|(Error SMART Error Log Read failed)/', $result, $matches, PREG_OFFSET_CAPTURE))
154
               $endIndex = $matches[0][1];
155
156
            if ($startIndex && $endIndex && ($endIndex>$startIndex))
157
                 $vendorInfos = preg_split("/\n/", substr($result, $startIndex, $endIndex - $startIndex));
158
159
            if (!empty($vendorInfos)) {
160
                $labels = preg_split('/\s+/', $vendorInfos[1]);
161
                foreach ($labels as $k=>$v) {
162
                    $labels[$k] = str_replace('#', '', strtolower($v));
163
                }
164
                $i = 0; // Line number
165
                foreach ($vendorInfos as $line) {
0 ignored issues
show
Bug introduced by
The expression $vendorInfos of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
166
                    $line = preg_replace('/^\s+/', '', $line);
167
                    $values = preg_split('/\s+/', $line);
168
                    if (count($values) > count($labels)) {
169
                        $values = array_slice($values, 0, count($labels), true);
170
                    }
171
                    $j = 0;
172
                    $found = false;
173
                    foreach ($values as $value) {
174
                        if ((in_array($value, array_keys($this->_ids)) && $labels[$j] == 'id')) {
175
                          $arrFullVa = preg_split('/-/', $this->_ids[$value]);
176
                          if (($arrFullVa[0]=="#replace") && !empty($arrFullVa[1]))
177
                              $value=$arrFullVa[1];
178
                        }
179
                        if (((in_array($value, array_keys($this->_ids)) && $labels[$j] == 'id') || ($found && (in_array($labels[$j], array_values($this->_ids)))) || ($found && $labels[$j] == 'attribute_name'))) {
180
                            $this->_result[$disk][$i][$labels[$j]] = $value;
181
                            $found = true;
182
                        }
183
                        $j++;
184
                    }
185
                    $i++;
186
                }
187
            } else {
188
                //SCSI devices
189 View Code Duplication
                if (!empty($this->_ids[1]) && ($this->_ids[1]=="raw_value")) {
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...
190
                    preg_match('/read\: (.*)\n/', $result, $lines);
191
                    if (!empty($lines) && !empty($lines[0])) {
192
                        $values=preg_split('/\s+/', $lines[0]);
193
                        if (!empty($values) && ($values[7]!=null)) {
194
                            $vals=preg_split('/[,\.]/', $values[7]);
195
                            $this->_result[$disk][0]['id'] = 1;
196
                            $this->_result[$disk][0]['attribute_name'] = "Raw_Read_Error_Rate";
197
                            $this->_result[$disk][0]['raw_value'] = $vals[0];
198
                        }
199
                    }
200
                }
201 View Code Duplication
                if (!empty($this->_ids[5]) && ($this->_ids[5]=="raw_value")) {
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...
202
                    preg_match('/Elements in grown defect list\: (.*)\n/', $result, $lines);
203
                    if (!empty($lines) && !empty($lines[0])) {
204
                        $values=preg_split('/\s+/', $lines[0]);
205
                        if (!empty($values) && ($values[5]!=null)) {
206
                            $vals=preg_split('/[,\.]/', $values[5]);
207
                            $this->_result[$disk][1]['id'] = 5;
208
                            $this->_result[$disk][1]['attribute_name'] = "Reallocated_Sector_Ct";
209
                            $this->_result[$disk][1]['raw_value'] = $vals[0];
210
                        }
211
                    }
212
                }
213 View Code Duplication
                if (!empty($this->_ids[9]) && ($this->_ids[9]=="raw_value")) {
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...
214
                    preg_match('/ number of hours powered up = (.*)\n/', $result, $lines);
215
                    if (!empty($lines) && !empty($lines[0])) {
216
                        $values=preg_split('/\s+/', $lines[0]);
217
                        if (!empty($values) && ($values[7]!=null)) {
218
                            $vals=preg_split('/[,\.]/', $values[7]);
219
                            $this->_result[$disk][2]['id'] = 9;
220
                            $this->_result[$disk][2]['attribute_name'] = "Power_On_Hours";
221
                            $this->_result[$disk][2]['raw_value'] =  $vals[0];
222
                        }
223
                    }
224
                }
225 View Code Duplication
                if (!empty($this->_ids[194]) && ($this->_ids[194]=="raw_value")) {
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...
226
                    preg_match('/Current Drive Temperature\: (.*)\n/', $result, $lines);
227
                    if (!empty($lines) && !empty($lines[0])) {
228
                        $values=preg_split('/\s+/', $lines[0]);
229
                        if (!empty($values) && ($values[3]!=null)) {
230
                            $vals=preg_split('/[,\.]/', $values[3]);
231
                            $this->_result[$disk][3]['id'] = 194;
232
                            $this->_result[$disk][3]['attribute_name'] = "Temperature_Celsius";
233
                            $this->_result[$disk][3]['raw_value'] = $vals[0];
234
                        }
235
                    }
236
                }
237
            }
238
        }
239
        //Usage test
240
        $newIds = array();
241
        foreach ($this->_ids as $id=>$column_name) {
242
            $found = 0;
243
            foreach ($this->_result as $diskName=>$diskInfos) {
244
                if ($found!=2) foreach ($diskInfos as $lineInfos) {
245
                    if ($found!=2) {
246
                        $found = 0;
247
                        foreach ($lineInfos as $label=>$value) {
248
                            if (($found==0) && ($label=="id") && ($value==$id))
249
                                $found = 1;
250
                            if (($found==1) && ($label==$column_name))
251
                                $found = 2;
252
                        }
253
                    }
254
                }
255
            }
256
            if ($found==2) $newIds[$id] = $this->_ids[$id];
257
        }
258
        $this->_ids = $newIds;
259
    }
260
261
    /**
262
     * generates the XML content for the plugin
263
     *
264
     * @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...
265
     */
266
    public function xml()
267
    {
268
        if (empty($this->_result) || empty($this->_ids)) {
269
            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...
270
        }
271
272
        $columnsChild = $this->xml->addChild('columns');
273
        // Fill the xml with preferences
274
        foreach ($this->_ids as $id=>$column_name) {
275
            $columnChild = $columnsChild->addChild('column');
276
            $columnChild->addAttribute('id', $id);
277
            $columnChild->addAttribute('name', $column_name);
278
        }
279
280
        $disksChild = $this->xml->addChild('disks');
281
        // Now fill the xml with S.M.A.R.T datas
282
        foreach ($this->_result as $diskName=>$diskInfos) {
283
            $diskChild = $disksChild->addChild('disk');
284
            $diskChild->addAttribute('name', $diskName);
285
            foreach ($diskInfos as $lineInfos) {
286
                $lineChild = $diskChild->addChild('attribute');
287
288
                if (($lineInfos['id'] == 9) && ($lineInfos['attribute_name'] == "Power_On_Hours_and_Msec")) {
289
                    $lineInfos['attribute_name'] = "Power_On_Hours";
290
                    $raw_value = preg_split("/h/", $lineInfos['raw_value'], -1, PREG_SPLIT_NO_EMPTY);
291
                    $lineInfos['raw_value'] = $raw_value[0];
292
                }
293
294
                foreach ($lineInfos as $label=>$value) {
295
                    $lineChild->addAttribute($label, $value);
296
                }
297
            }
298
        }
299
300
        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...
301
    }
302
}
303