ArtistsHandler   C
last analyzed

Complexity

Total Complexity 55

Size/Duplication

Total Lines 280
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 130
c 1
b 0
f 0
dl 0
loc 280
rs 6
wmc 55

10 Methods

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

How to fix   Complexity   

Complex Class

Complex classes like ArtistsHandler 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 ArtistsHandler, 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
9
require_once \dirname(__DIR__) . '/include/songlist.object.php';
10
// require_once \dirname(__DIR__) . '/include/songlist.form.php';
11
use  XoopsModules\Songlist\Form\FormController;
12
13
/**
14
 * Class ArtistsHandler
15
 */
16
class ArtistsHandler extends \XoopsPersistableObjectHandler
17
{
18
    /**
19
     * ArtistsHandler constructor.
20
     * @param \XoopsDatabase $db
21
     */
22
    public function __construct(XoopsDatabase $db)
23
    {
24
        parent::__construct($db, 'songlist_artists', Artists::class, 'aid', 'name');
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public function filterFields(): array
31
    {
32
        return ['aid', 'cids', 'singer', 'name', 'albums', 'songs', 'hits', 'rank', 'votes', 'created', 'updated'];
33
    }
34
35
    /**
36
     * @param $filter
37
     * @return \CriteriaCompo
38
     */
39
    public function getFilterCriteria($filter): CriteriaCompo
40
    {
41
        $parts    = \explode('|', $filter);
42
        $criteria = new CriteriaCompo();
43
        foreach ($parts as $part) {
44
            $var = \explode(',', $part);
45
            if (!empty($var[1]) && !\is_numeric($var[0])) {
46
                $object = $this->create();
47
                if (\XOBJ_DTYPE_TXTBOX == $object->vars[$var[0]]['data_type']
48
                    || \XOBJ_DTYPE_TXTAREA == $object->vars[$var[0]]['data_type']) {
49
                    $criteria->add(new Criteria('`' . $var[0] . '`', '%' . $var[1] . '%', ($var[2] ?? 'LIKE')));
50
                } elseif (in_array($object->vars[$var[0]]['data_type'], [XOBJ_DTYPE_INT, XOBJ_DTYPE_DECIMAL, XOBJ_DTYPE_FLOAT])) {
51
                    $criteria->add(new Criteria('`' . $var[0] . '`', $var[1], ($var[2] ?? '=')));
52
                } elseif (\XOBJ_DTYPE_ENUM == $object->vars[$var[0]]['data_type']) {
53
                    $criteria->add(new Criteria('`' . $var[0] . '`', $var[1], ($var[2] ?? '=')));
54
                } elseif (\XOBJ_DTYPE_ARRAY == $object->vars[$var[0]]['data_type']) {
55
                    $criteria->add(new Criteria('`' . $var[0] . '`', '%"' . $var[1] . '";%', ($var[2] ?? 'LIKE')));
56
                }
57
            } elseif (!empty($var[1]) && \is_numeric($var[0])) {
58
                $criteria->add(new Criteria($var[0], $var[1]));
59
            }
60
        }
61
62
        return $criteria;
63
    }
64
65
    /**
66
     * @param        $filter
67
     * @param        $field
68
     * @param string $sort
69
     * @param string $op
70
     * @param string $fct
71
     * @return string
72
     */
73
    public function getFilterForm($filter, $field, $sort = 'created', $op = 'dashboard', $fct = 'list'): string
74
    {
75
        $ele = Utility::getFilterElement($filter, $field, $sort, $op, $fct);
76
        if (\is_object($ele)) {
77
            return $ele->render();
78
        }
79
80
        return '&nbsp;';
81
    }
82
83
    /**
84
     * @param bool $force
85
     * @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...
86
     * @return bool|mixed
87
     */
88
    public function insert(\XoopsObject $obj, $force = true, $object = null)
89
    {
90
        if ($obj->isNew()) {
91
            $new = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $new is dead and can be removed.
Loading history...
92
            $old = $this->create();
93
            $obj->setVar('created', \time());
94
        } else {
95
            $new = false;
96
            $old = $this->get($obj->getVar('aid'));
97
            $obj->setVar('updated', \time());
98
        }
99
100
        $albumsHandler   = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Albums');
101
        $songsHandler    = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Songs');
0 ignored issues
show
Unused Code introduced by
The assignment to $songsHandler is dead and can be removed.
Loading history...
102
        $genreHandler    = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Genre');
103
        $voiceHandler    = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Voice');
104
        $categoryHandler = \XoopsModules\Songlist\Helper::getInstance()->getHandler('Category');
105
106
        if ($object instanceof Songs) {
107
            if (true === $object->vars['cid']['changed']) {
108
                foreach ($obj->vars['cids']['value'] as $cid) {
109
                    if (is_array( $object->getVar('cid')) && !\in_array($cid, $object->getVar('cid'), true) && 0 != $cid) {
0 ignored issues
show
Bug introduced by
It seems like $object->getVar('cid') can also be of type boolean and null and string; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

109
                    if (is_array( $object->getVar('cid')) && !\in_array($cid, /** @scrutinizer ignore-type */ $object->getVar('cid'), true) && 0 != $cid) {
Loading history...
110
                        $obj->setVar('cids', \array_merge($obj->getVar('cids'), [$object->getVar('cid') => $object->getVar('cid')]));
0 ignored issues
show
Bug introduced by
It seems like $obj->getVar('cids') can also be of type boolean and null and string; however, parameter $arrays of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

110
                        $obj->setVar('cids', \array_merge(/** @scrutinizer ignore-type */ $obj->getVar('cids'), [$object->getVar('cid') => $object->getVar('cid')]));
Loading history...
111
                        $category = $categoryHandler->get($cid);
112
                        if (\is_object($category)) {
113
                            $category->setVar('artists', $category->getVar('artists') + 1);
114
                            $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

114
                            $categoryHandler->/** @scrutinizer ignore-call */ 
115
                                              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...
115
                        }
116
                    }
117
                }
118
                if (!$old->isNew()) {
119
                    foreach ($old->getVar('cids') as $cid) {
120
                        if (!\in_array($cid, $obj->vars['cids']['value'], true) && 0 != $cid) {
121
                            $category = $categoryHandler->get($cid);
122
                            if (\is_object($category)) {
123
                                $category->setVar('artists', $category->getVar('artists') - 1);
124
                                $categoryHandler->insert($category, true, $obj);
125
                            }
126
                        }
127
                    }
128
                }
129
            }
130
131
            if (0 != $object->vars['abid']['value'] && true === $object->vars['aids']['changed']) {
132
                $album = $albumsHandler->get($object->vars['abid']['value']);
133
                if (\is_object($album)) {
134
                    $album->setVar('artists', $album->getVar('artists') + 1);
135
                    $albumsHandler->insert($album, true, $obj);
136
                }
137
            }
138
139
            if (0 != $object->vars['gid']['value'] && true === $object->vars['gid']['changed']) {
140
                $genre = $genreHandler->get($object->vars['gid']['value']);
141
                if (\is_object($genre)) {
142
                    $genre->setVar('artists', $genre->getVar('artists') + 1);
143
                    $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

143
                    $genreHandler->/** @scrutinizer ignore-call */ 
144
                                   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...
144
                }
145
            }
146
            if (0 != $object->vars['vid']['value'] && true === $object->vars['vid']['changed']) {
147
                $voice = $voiceHandler->get($object->vars['vid']['value']);
148
                if (\is_object($voice)) {
149
                    $voice->setVar('artists', $voice->getVar('artists') + 1);
150
                    $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

150
                    $voiceHandler->/** @scrutinizer ignore-call */ 
151
                                   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...
151
                }
152
            }
153
        }
154
155
        if ('' == $obj->getVar('name')) {
156
            return false;
157
        }
158
159
        return parent::insert($obj, $force);
160
    }
161
162
    public $_objects = ['object' => [], 'array' => []];
163
164
    /**
165
     * @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...
166
     * @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...
167
     * @return \XoopsObject
168
     */
169
    public function get($id = null, $fields = null): \XoopsObject//get($id, $fields = '*')
170
    {
171
        $fields = $fields ?: '*';
0 ignored issues
show
introduced by
$fields is of type null, thus it always evaluated to false.
Loading history...
172
        if (!isset($this->_objects['object'][$id])) {
173
            $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

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