Completed
Push — master ( 9219af...a340f3 )
by Paul
08:18
created

component::getComponents()   F

Complexity

Conditions 19
Paths 608

Size

Total Lines 101
Code Lines 47

Duplication

Lines 3
Ratio 2.97 %
Metric Value
cc 19
eloc 47
nc 608
nop 2
dl 3
loc 101
rs 2.3386

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
 * LibreNMS module to Interface with the Component System
4
 *
5
 * Copyright (c) 2015 Aaron Daniels <[email protected]>
6
 *
7
 * This program is free software: you can redistribute it and/or modify it
8
 * under the terms of the GNU General Public License as published by the
9
 * Free Software Foundation, either version 3 of the License, or (at your
10
 * option) any later version.  Please see LICENSE.txt at the top level of
11
 * the source code distribution for details.
12
 */
13
14
class component {
15
    /*
16
     * These fields are used in the component table. They are returned in the array
17
     * so that they can be modified but they can not be set as user attributes. We
18
     * also set their default values.
19
     */
20
    private $reserved = array(
21
        'type'      => '',
22
        'label'     => '',
23
        'status'    => 1,
24
        'ignore'    => 0,
25
        'disabled'  => 0,
26
        'error'     => '',
27
    );
28
29
    public function getComponentType($TYPE=null) {
30
        if (is_null($TYPE)) {
31
            $SQL = "SELECT DISTINCT `type` as `name` FROM `component` ORDER BY `name`";
32
            $row = dbFetchRow($SQL, array());
33
        }
34
        else {
35
            $SQL = "SELECT DISTINCT `type` as `name` FROM `component` WHERE `type` = ? ORDER BY `name`";
36
            $row = dbFetchRow($SQL, array($TYPE));
37
        }
38
39
        if (!isset($row)) {
40
            // We didn't find any component types
41
            return false;
42
        }
43
        else {
44
            // We found some..
45
            return $row;
46
        }
47
    }
48
49
    public function getComponents($device_id=null,$options=array()) {
50
        // Define our results array, this will be set even if no rows are returned.
51
        $RESULT = array();
52
        $PARAM = array();
53
54
        // Our base SQL Query, with no options.
55
        $SQL = "SELECT `C`.`id`,`C`.`device_id`,`C`.`type`,`C`.`label`,`C`.`status`,`C`.`disabled`,`C`.`ignore`,`C`.`error`,`CP`.`attribute`,`CP`.`value` FROM `component` as `C` LEFT JOIN `component_prefs` as `CP` on `C`.`id`=`CP`.`component` WHERE ";
56
57
        // Device_id is shorthand for filter C.device_id = $device_id.
58
        if (!is_null($device_id)) {
59
            $options['filter']['device_id'] = array('=', $device_id);
60
        }
61
62
        // Type is shorthand for filter type = $type.
63 View Code Duplication
        if (isset($options['type'])) {
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...
64
            $options['filter']['type'] = array('=', $options['type']);
65
        }
66
67
        // filter   field => array(operator,value)
68
        //          Filters results based on the field, operator and value
69
        $COUNT = 0;
70
        if (isset($options['filter'])) {
71
            $COUNT++;
72
            $validFields = array('device_id','type','id','label','status','disabled','ignore','error');
73
            $SQL .= " ( ";
74
            foreach ($options['filter'] as $field => $array) {
75
                // Only add valid fields to the query
76
                if (in_array($field,$validFields)) {
77
                    if ($array[0] == 'LIKE') {
78
                        $SQL .= "`".$field."` LIKE ? AND ";
79
                        $array[1] = "%".$array[1]."%";
80
                    }
81
                    else {
82
                        // Equals operator is the default
83
                        $SQL .= "`".$field."` = ? AND ";
84
                    }
85
                    array_push($PARAM,$array[1]);
86
                }
87
            }
88
            // Strip the last " AND " before closing the bracket.
89
            $SQL = substr($SQL,0,-5)." )";
90
        }
91
92
        if ($COUNT == 0) {
93
            // Strip the " WHERE " that we didn't use.
94
            $SQL = substr($SQL,0,-7);
95
        }
96
97
        // sort     column direction
98
        //          Add SQL sorting to the results
99
        if (isset($options['sort'])) {
100
            $SQL .= " ORDER BY ".$options['sort'];
101
        }
102
103
        // Get our component records using our built SQL.
104
        $COMPONENTS = dbFetchRows($SQL, $PARAM);
105
106
        // if we have no components we need to return nothing
107
        if (count($COMPONENTS) == 0) {
108
            return $RESULT;
109
        }
110
111
        // Add the AVP's to the array.
112
        foreach ($COMPONENTS as $COMPONENT) {
113
            if ($COMPONENT['attribute'] != "") {
114
                // if this component has attributes, set them in the array.
115
                $RESULT[$COMPONENT['device_id']][$COMPONENT['id']][$COMPONENT['attribute']] = $COMPONENT['value'];
116
            }
117
        }
118
119
        // Populate our reserved fields into the Array, these cant be used as user attributes.
120
        foreach ($COMPONENTS as $COMPONENT) {
121
            foreach ($this->reserved as $k => $v) {
122
                $RESULT[$COMPONENT['device_id']][$COMPONENT['id']][$k] = $COMPONENT[$k];
123
            }
124
125
            // Sort each component array so the attributes are in order.
126
            ksort($RESULT[$RESULT[$COMPONENT['device_id']][$COMPONENT['id']]]);
127
            ksort($RESULT[$RESULT[$COMPONENT['device_id']]]);
128
        }
129
130
        // limit    array(start,count)
131
        if (isset($options['limit'])) {
132
            $TEMP = array();
133
            $COUNT = 0;
134
            // k = device_id, v = array of components for that device_id
135
            foreach ($RESULT as $k => $v) {
136
                // k1 = component id, v1 = component array
137
                foreach ($v as $k1 => $v1) {
138
                    if ( ($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) {
139
                        $TEMP[$k][$k1] = $v1;
140
                    }
141
                    // We are counting components.
142
                    $COUNT++;
143
                }
144
            }
145
            $RESULT = $TEMP;
146
        }
147
148
        return $RESULT;
149
    }
150
151
    public function createComponent ($device_id,$TYPE) {
152
        // Prepare our default values to be inserted.
153
        $DATA = $this->reserved;
154
155
        // Add the device_id and type
156
        $DATA['device_id']  = $device_id;
157
        $DATA['type']       = $TYPE;
158
159
        // Insert a new component into the database.
160
        $id = dbInsert($DATA, 'component');
161
162
        // Create a default component array based on what was inserted.
163
        $ARRAY = array();
164
        $ARRAY[$id] = $DATA;
165
        unset ($ARRAY[$id]['device_id']);     // This doesn't belong here.
166
        return $ARRAY;
167
    }
168
169
    public function deleteComponent ($id) {
170
        // Delete a component from the database.
171
        return dbDelete('component', "`id` = ?",array($id));
172
    }
173
174
    public function setComponentPrefs ($device_id,$ARRAY) {
175
        // Compare the arrays. Update/Insert where necessary.
176
177
        $OLD = $this->getComponents($device_id);
178
        // Loop over each component.
179
        foreach ($ARRAY as $COMPONENT => $AVP) {
180
181
            // Make sure the component already exists.
182
            if (!isset($OLD[$device_id][$COMPONENT])) {
183
                // Error. Component doesn't exist in the database.
184
                continue;
185
            }
186
187
            // Ignore type, we cant change that.
188
            unset($AVP['type'],$OLD[$device_id][$COMPONENT]['type']);
189
190
            // Process our reserved components first.
191
            $UPDATE = array();
192
            foreach ($this->reserved as $k => $v) {
193
                // does the reserved field exist, if not skip.
194
                if (isset($AVP[$k])) {
195
196
                    // Has the value changed?
197
                    if ($AVP[$k] != $OLD[$device_id][$COMPONENT][$k]) {
198
                        // The value has been modified, add it to our update array.
199
                        $UPDATE[$k] = $AVP[$k];
200
                    }
201
202
                    // Unset the reserved field. We don't want to insert it below.
203
                    unset($AVP[$k],$OLD[$device_id][$COMPONENT][$k]);
204
                }
205
            }
206
207
            // Has anything changed, do we need to update?
208
            if (count($UPDATE) > 0) {
209
                // We have data to update
210
                dbUpdate($UPDATE, 'component', '`id` = ?', array($COMPONENT));
211
212
                // Log the update to the Eventlog.
213
                $MSG = "Component ".$COMPONENT." has been modified: ";
214
                foreach ($UPDATE as $k => $v) {
215
                    $MSG .= $k." => ".$v.",";
216
                }
217
                $MSG = substr($MSG,0,-1);
218
                log_event($MSG,$device_id,'component',$COMPONENT);
219
            }
220
221
            // Process our AVP Adds and Updates
222
            foreach ($AVP as $ATTR => $VALUE) {
223
                // We have our AVP, lets see if we need to do anything with it.
224
225
                if (!isset($OLD[$device_id][$COMPONENT][$ATTR])) {
226
                    // We have a newly added attribute, need to insert into the DB
227
                    $DATA = array('component'=>$COMPONENT, 'attribute'=>$ATTR, 'value'=>$VALUE);
228
                    dbInsert($DATA, 'component_prefs');
229
230
                    // Log the addition to the Eventlog.
231
                    log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT);
232
                }
233
                elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) {
234
                    // Attribute exists but the value is different, need to update
235
                    $DATA = array('value'=>$VALUE);
236
                    dbUpdate($DATA, 'component_prefs', '`component` = ? AND `attribute` = ?', array($COMPONENT, $ATTR));
237
238
                    // Add the modification to the Eventlog.
239
                    log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE,$device_id,'component',$COMPONENT);
240
                }
241
242
            } // End Foreach COMPONENT
243
244
            // Process our Deletes.
245
            $DELETE = array_diff_key($OLD[$device_id][$COMPONENT], $AVP);
246
            foreach ($DELETE as $KEY => $VALUE) {
247
                // As the Attribute has been removed from the array, we should remove it from the database.
248
                dbDelete('component_prefs', "`component` = ? AND `attribute` = ?",array($COMPONENT,$KEY));
249
250
                // Log the addition to the Eventlog.
251
                log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT);
252
            }
253
254
        }
255
256
        return true;
257
    }
258
259
}