AlbumsHandler   C
last analyzed

Complexity

Total Complexity 56

Size/Duplication

Total Lines 268
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 127
c 1
b 0
f 0
dl 0
loc 268
rs 5.5199
wmc 56

9 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 12 5
A getURL() 0 39 5
A getTop() 0 13 2
A filterFields() 0 3 1
B getFilterCriteria() 0 24 11
A getObjects() 0 26 1
A __construct() 0 3 1
A getFilterForm() 0 8 2
F insert() 0 78 28

How to fix   Complexity   

Complex Class

Complex classes like AlbumsHandler 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 AlbumsHandler, and based on these observations, apply Extract Interface, too.

1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Songlist;
4
5
use Criteria;
6
use CriteriaCompo;
7
use XoopsDatabase;
8
use XoopsObject;
9
use XoopsPersistableObjectHandler;
10
11
require_once \dirname(__DIR__) . '/include/songlist.object.php';
12
// require_once \dirname(__DIR__) . '/include/songlist.form.php';
13
use  XoopsModules\Songlist\Form\FormController;
14
15
/**
16
 * Class AlbumsHandler
17
 */
18
class AlbumsHandler extends XoopsPersistableObjectHandler
19
{
20
    /**
21
     * AlbumsHandler constructor.
22
     * @param \XoopsDatabase $db
23
     */
24
    public function __construct(XoopsDatabase $db)
25
    {
26
        parent::__construct($db, 'songlist_albums', Albums::class, 'abid', 'title');
27
    }
28
29
    /**
30
     * @return array
31
     */
32
    public function filterFields(): array
33
    {
34
        return ['abid', 'cid', 'aids', 'sids', 'title', 'image', 'path', 'artists', 'songs', 'hits', 'rank', 'votes', 'created', 'updated'];
35
    }
36
37
    /**
38
     * @param $filter
39
     * @return \CriteriaCompo
40
     */
41
    public function getFilterCriteria($filter): CriteriaCompo
42
    {
43
        $parts    = \explode('|', $filter);
44
        $criteria = new CriteriaCompo();
45
        foreach ($parts as $part) {
46
            $var = \explode(',', $part);
47
            if (!empty($var[1]) && !\is_numeric($var[0])) {
48
                $object = $this->create();
49
                if (\XOBJ_DTYPE_TXTBOX == $object->vars[$var[0]]['data_type']
50
                    || \XOBJ_DTYPE_TXTAREA == $object->vars[$var[0]]['data_type']) {
51
                    $criteria->add(new Criteria('`' . $var[0] . '`', '%' . $var[1] . '%', ($var[2] ?? 'LIKE')));
52
                } elseif (in_array($object->vars[$var[0]]['data_type'], [XOBJ_DTYPE_INT, XOBJ_DTYPE_DECIMAL, XOBJ_DTYPE_FLOAT])) {
53
                    $criteria->add(new Criteria('`' . $var[0] . '`', $var[1], ($var[2] ?? '=')));
54
                } elseif (\XOBJ_DTYPE_ENUM == $object->vars[$var[0]]['data_type']) {
55
                    $criteria->add(new Criteria('`' . $var[0] . '`', $var[1], ($var[2] ?? '=')));
56
                } elseif (\XOBJ_DTYPE_ARRAY == $object->vars[$var[0]]['data_type']) {
57
                    $criteria->add(new Criteria('`' . $var[0] . '`', '%"' . $var[1] . '";%', ($var[2] ?? 'LIKE')));
58
                }
59
            } elseif (!empty($var[1]) && \is_numeric($var[0])) {
60
                $criteria->add(new Criteria($var[0], $var[1]));
61
            }
62
        }
63
64
        return $criteria;
65
    }
66
67
    /**
68
     * @param        $filter
69
     * @param        $field
70
     * @param string $sort
71
     * @param string $op
72
     * @param string $fct
73
     * @return string
74
     */
75
    public function getFilterForm($filter, $field, $sort = 'created', $op = 'dashboard', $fct = 'list'): string
76
    {
77
        $ele = Utility::getFilterElement($filter, $field, $sort, $op, $fct);
78
        if (\is_object($ele)) {
79
            return $ele->render();
80
        }
81
82
        return '&nbsp;';
83
    }
84
85
    /**
86
     * @param bool $force
87
     * @param null $object
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $object is correct as it would always require null to be passed?
Loading history...
88
     * @return bool|mixed
89
     */
90
    public function insert(XoopsObject $obj, $force = true, $object = null)
91
    {
92
        if ($obj->isNew()) {
93
            $new = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $new is dead and can be removed.
Loading history...
94
            $old = $this->create();
95
            $obj->setVar('created', \time());
96
        } else {
97
            $new = false;
98
            $old = $this->get($obj->getVar('abid'));
99
            $obj->setVar('updated', \time());
100
        }
101
102
        $artistsHandler  = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Artists');
103
        $genreHandler    = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Genre');
104
        $voiceHandler    = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Voice');
105
        $categoryHandler = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Category');
106
107
        if ($object instanceof Songs) {
108
            if (true === $obj->vars['cid']['changed']) {
109
                if ($obj->vars['cid']['value'] != $old->vars['cid']['value']) {
110
                    $category = $categoryHandler->get($obj->vars['cid']['value']);
111
                    if (\is_object($category)) {
112
                        $category->setVar('albums', $category->getVar('albums') + 1);
113
                        $categoryHandler->insert($category, true, $obj);
0 ignored issues
show
Unused Code introduced by
The call to XoopsModules\Songlist\CategoryHandler::insert() has too many arguments starting with $obj. ( Ignorable by Annotation )

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

113
                        $categoryHandler->/** @scrutinizer ignore-call */ 
114
                                          insert($category, true, $obj);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
114
                        if (!$old->isNew() && $old->vars['cid']['value'] > 0) {
115
                            $category = $categoryHandler->get($old->vars['cid']['value']);
116
                            if (\is_object($category)) {
117
                                $category->setVar('albums', $category->getVar('albums') - 1);
118
                                $categoryHandler->insert($category, true, $obj);
119
                            }
120
                        }
121
                    }
122
                }
123
            }
124
125
            if (is_array($obj->vars['aids']['value']) && 0 != \count($obj->vars['aids']['value']) && true === $obj->vars['aids']['changed']) {
126
                foreach ($obj->vars['aids']['value'] as $aid) {
127
                    if (!\is_array($aid, $old->getVar('aids')) && 0 != $aid) {
0 ignored issues
show
Unused Code introduced by
The call to is_array() has too many arguments starting with $old->getVar('aids'). ( Ignorable by Annotation )

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

127
                    if (!/** @scrutinizer ignore-call */ \is_array($aid, $old->getVar('aids')) && 0 != $aid) {

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
128
                        $artists = $artistsHandler->get($aid);
129
                        if (\is_object($artists)) {
130
                            $artists->setVar('albums', $artists->getVar('albums') + 1);
131
                            $artistsHandler->insert($artists, true, $obj);
132
                        }
133
                    }
134
                }
135
                if (!$old->isNew()) {
136
                    foreach ($old->getVar('aids') as $aid) {
137
                        if (!\is_array($aid, $obj->vars['aids']['value']) && 0 != $aid) {
138
                            $artists = $artistsHandler->get($aid);
139
                            if (\is_object($artists)) {
140
                                $artists->setVar('albums', $artists->getVar('albums') - 1);
141
                                $artistsHandler->insert($artists, true, $obj);
142
                            }
143
                        }
144
                    }
145
                }
146
            }
147
148
            if (0 != $object->vars['gid']['value']??'' && true === $object->vars['gid']['changed']??'') {
149
                $genre = $genreHandler->get($object->vars['gid']['value']);
150
                if (\is_object($genre)) {
151
                    $genre->setVar('albums', $genre->getVar('albums') + 1);
152
                    $genreHandler->insert($genre, true, $obj);
0 ignored issues
show
Unused Code introduced by
The call to XoopsModules\Songlist\GenreHandler::insert() has too many arguments starting with $obj. ( Ignorable by Annotation )

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

152
                    $genreHandler->/** @scrutinizer ignore-call */ 
153
                                   insert($genre, true, $obj);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
153
                }
154
            }
155
            if (0 != $object->vars['vid']['value']??'' && true === $object->vars['vid']['changed']??'') {
156
                $voice = $voiceHandler->get($object->vars['vid']['value']);
157
                if (\is_object($voice)) {
158
                    $voice->setVar('albums', $voice->getVar('albums') + 1);
159
                    $voiceHandler->insert($voice, true, $obj);
0 ignored issues
show
Unused Code introduced by
The call to XoopsModules\Songlist\VoiceHandler::insert() has too many arguments starting with $obj. ( Ignorable by Annotation )

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

159
                    $voiceHandler->/** @scrutinizer ignore-call */ 
160
                                   insert($voice, true, $obj);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
160
                }
161
            }
162
        }
163
        if ('' == $obj->getVar('title')) {
164
            return false;
165
        }
166
167
        return parent::insert($obj, $force);
168
    }
169
170
    public $_objects = ['object' => [], 'array' => []];
171
172
    /**
173
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
174
     * @param null $fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
175
     * @return \XoopsObject
176
     */
177
    public function get($id = null, $fields = null)//get($id, $fields = '*')
178
    {
179
        $fields = $fields ?: '*';
0 ignored issues
show
introduced by
$fields is of type null, thus it always evaluated to false.
Loading history...
180
        if (!isset($this->_objects['object'][$id])) {
181
            $this->_objects['object'][$id] = parent::get($id, $fields);
0 ignored issues
show
Bug introduced by
$fields of type string is incompatible with the type array expected by parameter $fields of XoopsPersistableObjectHandler::get(). ( Ignorable by Annotation )

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

181
            $this->_objects['object'][$id] = parent::get($id, /** @scrutinizer ignore-type */ $fields);
Loading history...
182
            if (!isset($GLOBALS['songlistAdmin']) && \is_object($this->_objects['object'][$id])) {
183
                $sql = 'UPDATE `' . $this->table . '` set hits=hits+1 where `' . $this->keyName . '` = ' . $this->_objects['object'][$id]->getVar($this->keyName);
184
                $GLOBALS['xoopsDB']->queryF($sql);
185
            }
186
        }
187
188
        return $this->_objects['object'][$id];
189
    }
190
191
    /**
192
     * @param \CriteriaElement|\CriteriaCompo $criteria
193
     * @param bool $id_as_key
194
     * @param bool $as_object
195
     * @return array
196
     */
197
    public function &getObjects($criteria = null, $id_as_key = false, $as_object = true): array
198
    {
199
        $ret = parent::getObjects($criteria, $id_as_key, $as_object);
200
201
        /* if (!isset($GLOBALS['songlistAdmin'])) {
202
            $id = [];
203
            foreach($ret as $data) {
204
                if ($as_object==true) {
205
                    if (!in_array($data->getVar($this->keyName), array_keys($this->_objects['object']))) {
206
                        $this->_objects['object'][$data->getVar($this->keyName)] = $data;
207
                        $id[$data->getVar($this->keyName)] = $data->getVar($this->keyName);
208
                    }
209
                } else {
210
                    if (!in_array($data[$this->keyName], array_keys($this->_objects['array']))) {
211
                        $this->_objects['array'][$data[$this->keyName]] = $data;
212
                        $id[$data[$this->keyName]] = $data[$this->keyName];;
213
                    }
214
                }
215
            }
216
        }
217
        if (!isset($GLOBALS['songlistAdmin'])&&count($id)>0) {
218
            $sql = 'UPDATE `'.$this->table.'` set hits=hits+1 where `'.$this->keyName.'` IN ('.implode(',', $id).')';
219
            $GLOBALS['xoopsDB']->queryF($sql);
220
        }*/
221
222
        return $ret;
223
    }
224
225
    /**
226
     * @return string
227
     */
228
    public function getURL(): string
229
    {
230
        global $file, $op, $fct, $id, $value, $gid, $vid, $cid, $start, $limit;
231
        if ($GLOBALS['songlistModuleConfig']['htaccess']) {
232
            if (0 != $cid) {
233
                $artistHandler = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Artists');
234
                $artist        = $artistHandler->get($cid);
235
                if (\is_object($artist) && !$artist->isNew()) {
236
                    return XOOPS_URL
237
                           . '/'
238
                           . $GLOBALS['songlistModuleConfig']['baseofurl']
239
                           . '/'
240
                           . $file
241
                           . '/'
242
                           . \urlencode(\str_replace([' ', \chr(9)], '-', $artist->getVar('name')))
243
                           . '/'
244
                           . $start
245
                           . '-'
246
                           . $id
247
                           . '-'
248
                           . $op
249
                           . '-'
250
                           . $fct
251
                           . '-'
252
                           . $gid
253
                           . '-'
254
                           . $cid
255
                           . '/'
256
                           . \urlencode($value)
257
                           . $GLOBALS['songlistModuleConfig']['endofurl'];
258
                }
259
260
                return XOOPS_URL . '/' . $GLOBALS['songlistModuleConfig']['baseofurl'] . '/' . $file . '/' . $start . '-' . $id . '-' . $op . '-' . $fct . '-' . $gid . '-' . $cid . '/' . \urlencode($value) . $GLOBALS['songlistModuleConfig']['endofurl'];
261
            }
262
263
            return XOOPS_URL . '/' . $GLOBALS['songlistModuleConfig']['baseofurl'] . '/' . $file . '/' . $start . '-' . $id . '-' . $op . '-' . $fct . '-' . $gid . '-' . $cid . '/' . \urlencode($value) . $GLOBALS['songlistModuleConfig']['endofurl'];
264
        }
265
266
        return XOOPS_URL . '/modules/songlist/' . $file . '.php?op=' . $op . '&fct=' . $fct . '&id=' . $id . '&value=' . \urlencode($value ?? '') . '&gid=' . $gid . '&vid=' . $vid . '&cid=' . $cid . '&start=' . $start;
267
    }
268
269
    /**
270
     * @param int $limit
271
     * @return array
272
     */
273
    public function getTop($limit = 1): array
274
    {
275
        $sql     = 'SELECT * FROM `' . $this->table . '` WHERE `rank`>=0 ORDER BY (`rank`/`votes`) DESC LIMIT ' . $limit;
276
        $results = $GLOBALS['xoopsDB']->queryF($sql);
277
        $ret     = [];
278
        $i       = 0;
279
        while (false !== ($row = $GLOBALS['xoopsDB']->fetchArray($results))) {
280
            $ret[$i] = $this->create();
281
            $ret[$i]->assignVars($row);
282
            ++$i;
283
        }
284
285
        return $ret;
286
    }
287
}
288