Model   B
last analyzed

Complexity

Total Complexity 43

Size/Duplication

Total Lines 253
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 90
dl 0
loc 253
rs 8.96
c 0
b 0
f 0
wmc 43

12 Methods

Rating   Name   Duplication   Size   Complexity  
C save() 0 39 12
A __construct() 0 2 1
B update() 0 36 10
A javascript() 0 2 1
A get_all() 0 3 1
A display() 0 2 1
A delete() 0 18 5
A find() 0 11 3
A clean_parameters() 0 12 4
A getDataToExport() 0 3 1
A get_count() 0 10 1
A get() 0 18 3

How to fix   Complexity   

Complex Class

Complex classes like Model often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Model, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class Model.
6
 * This class provides basic methods to implement a CRUD for a new table in the
7
 * database see examples in: career.lib.php and promotion.lib.php
8
 * Include/require it in your code to use its features.
9
 */
10
class Model
11
{
12
    public $table;
13
    public $columns;
14
    public $required;
15
    public $is_course_model = false;
16
17
    /**
18
     * Constructor.
19
     */
20
    public function __construct()
21
    {
22
    }
23
24
    /**
25
     * Useful finder - experimental akelos like only use in notification.lib.php send function.
26
     *
27
     * @param string $type
28
     * @param array  $options
29
     *
30
     * @return array
31
     */
32
    public function find($type, $options = null)
33
    {
34
        switch ($type) {
35
            case 'all':
36
                return self::get_all($options);
0 ignored issues
show
Bug Best Practice introduced by
The method Model::get_all() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

36
                return self::/** @scrutinizer ignore-call */ get_all($options);
Loading history...
37
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
38
            default:
39
                if (is_numeric($type)) {
40
                    return self::get($type);
0 ignored issues
show
Bug Best Practice introduced by
The method Model::get() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
                    return self::/** @scrutinizer ignore-call */ get($type);
Loading history...
41
                }
42
                break;
43
        }
44
    }
45
46
    /**
47
     * Deletes an item.
48
     *
49
     * @param int $id
50
     *
51
     * @return bool
52
     */
53
    public function delete($id)
54
    {
55
        if (empty($id) || $id != strval(intval($id))) {
56
            return false;
57
        }
58
        $params = ['id = ?' => $id];
59
        if ($this->is_course_model) {
60
            $courseId = api_get_course_int_id();
61
            $params = ['id = ? AND c_id = ?' => [$id, $courseId]];
62
        }
63
64
        // Database table definition
65
        $result = Database::delete($this->table, $params);
66
        if (1 != $result) {
67
            return false;
68
        }
69
70
        return true;
71
    }
72
73
    /**
74
     * Displays the title + grid.
75
     */
76
    public function display()
77
    {
78
    }
79
80
    /**
81
     * Gets an element.
82
     *
83
     * @param int $id
84
     *
85
     * @return array|mixed
86
     */
87
    public function get($id)
88
    {
89
        if (empty($id)) {
90
            return [];
91
        }
92
        $params = ['id = ?' => intval($id)];
93
        if ($this->is_course_model) {
94
            $course_id = api_get_course_int_id();
95
            $params = ['id = ? AND c_id = ?' => [$id, $course_id]];
96
        }
97
        $result = Database::select(
98
            '*',
99
            $this->table,
100
            ['where' => $params],
101
            'first'
102
        );
103
104
        return $result;
105
    }
106
107
    /**
108
     * @param array $options
109
     *
110
     * @return array
111
     */
112
    public function get_all($options = null)
113
    {
114
        return Database::select('*', $this->table, $options);
115
    }
116
117
    /**
118
     * @param array $options
119
     *
120
     * @return array
121
     */
122
    public function getDataToExport($options = [])
123
    {
124
        return Database::select('name, description', $this->table, $options);
125
    }
126
127
    /**
128
     * Get the count of elements.
129
     *
130
     * @return int
131
     */
132
    public function get_count()
133
    {
134
        $row = Database::select(
135
            'count(*) as count',
136
            $this->table,
137
            ['where' => ['parent_id = ?' => '0']],
138
            'first'
139
        );
140
141
        return $row['count'];
142
    }
143
144
    /**
145
     * a little bit of javascript to display.
146
     */
147
    public function javascript()
148
    {
149
    }
150
151
    /**
152
     * Saves an element into the DB.
153
     *
154
     * @param array $params
155
     * @param bool  $show_query Whether to show the query in logs or not (passed to Database::insert())
156
     *
157
     * @return bool|int
158
     */
159
    public function save($params, $show_query = false)
160
    {
161
        $params = $this->clean_parameters($params);
162
163
        if ($this->is_course_model) {
164
            if (!isset($params['c_id']) || empty($params['c_id'])) {
165
                $params['c_id'] = api_get_course_int_id();
166
            }
167
        }
168
169
        if (!empty($this->required)) {
170
            $require_ok = true;
171
            $key_params = array_keys($params);
172
            foreach ($this->required as $field) {
173
                if (!in_array($field, $key_params)) {
174
                    $require_ok = false;
175
                }
176
            }
177
            if (!$require_ok) {
178
                return false;
179
            }
180
        }
181
182
        if (in_array('created_at', $this->columns)) {
183
            $params['created_at'] = api_get_utc_datetime();
184
        }
185
186
        if (in_array('updated_at', $this->columns)) {
187
            $params['updated_at'] = api_get_utc_datetime();
188
        }
189
190
        if (!empty($params)) {
191
            $id = Database::insert($this->table, $params, $show_query);
192
            if (is_numeric($id)) {
193
                return $id;
194
            }
195
        }
196
197
        return false;
198
    }
199
200
    /**
201
     * Updates the obj in the database. The $params['id'] must exist in order to update a record.
202
     *
203
     * @param array $params
204
     * @param bool  $showQuery
205
     *
206
     * @return bool
207
     */
208
    public function update($params, $showQuery = false)
209
    {
210
        $params = $this->clean_parameters($params);
211
212
        if ($this->is_course_model) {
213
            if (!isset($params['c_id']) || empty($params['c_id'])) {
214
                $params['c_id'] = api_get_course_int_id();
215
            }
216
        }
217
218
        //If the class has the updated_at field we update the date
219
        if (in_array('updated_at', $this->columns)) {
220
            $params['updated_at'] = api_get_utc_datetime();
221
        }
222
        //If the class has the created_at field then we remove it
223
        if (in_array('created_at', $this->columns)) {
224
            unset($params['created_at']);
225
        }
226
227
        if (!empty($params) && !empty($params['id'])) {
228
            $id = intval($params['id']);
229
            unset($params['id']); //To not overwrite the id
230
            if (is_numeric($id)) {
231
                $result = Database::update(
232
                    $this->table,
233
                    $params,
234
                    ['id = ?' => $id],
235
                    $showQuery
236
                );
237
                if ($result) {
238
                    return true;
239
                }
240
            }
241
        }
242
243
        return false;
244
    }
245
246
    /**
247
     * @param array $params
248
     *
249
     * @return array
250
     */
251
    private function clean_parameters($params)
252
    {
253
        $clean_params = [];
254
        if (!empty($params)) {
255
            foreach ($params as $key => $value) {
256
                if (in_array($key, $this->columns)) {
257
                    $clean_params[$key] = $value;
258
                }
259
            }
260
        }
261
262
        return $clean_params;
263
    }
264
}
265