PageHandler   B
last analyzed

Complexity

Total Complexity 45

Size/Duplication

Total Lines 317
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 138
c 0
b 0
f 0
dl 0
loc 317
rs 8.8
wmc 45

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A cleanImage() 0 18 1
B setRate() 0 21 7
B getPhpListAsArray() 0 24 7
A uploadImages() 0 25 6
A setRead() 0 7 1
A getPublished() 0 15 2
A renderAdminList() 0 11 2
A getByURL() 0 6 1
B setLikeDislike() 0 25 7
A selectPage() 0 11 2
A getUrls() 0 9 2
A insert() 0 13 3
A setOnline() 0 15 3

How to fix   Complexity   

Complex Class

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

1
<?php
2
3
namespace XoopsModules\Xooghost;
4
5
/**
6
 * Xooghost module
7
 *
8
 * You may not change or alter any portion of this comment or credits
9
 * of supporting developers from this source code or any supporting source code
10
 * which is considered copyrighted (c) material of the original comment or credit authors.
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
 *
15
 * @copyright       XOOPS Project (https://xoops.org)
16
 * @license         GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
17
 * @package         Xooghost
18
 * @since           2.6.0
19
 * @author          Laurent JEN (Aka DuGris)
20
 */
21
use Xoops\Core\Database\Connection;
22
use Xoops\Core\Request;
23
24
/**
25
 * Class XooghostPageHandler
26
 */
27
class PageHandler extends \XoopsPersistableObjectHandler
28
{
29
    private $exclude = [
30
        'backend.php',
31
        'footer.php',
32
        'header.php',
33
        'index.php',
34
        'page_comment.php',
35
        'page_like_dislike.php',
36
        'page_print.php',
37
        'page_rate.php',
38
        'qrcode.php',
39
        'xoops_version.php',
40
    ];
41
42
    /**
43
     * @param null|\Xoops\Core\Database\Connection $db
44
     */
45
    public function __construct(Connection $db = null)
46
    {
47
        parent::__construct($db, 'xooghost', Page::class, 'xooghost_id', 'xooghost_title');
48
49
        // Module
50
        $helper = \XoopsModules\Xooghost\Helper::getInstance();
51
        $this->config = $helper->loadConfig();
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The method loadConfig() does not exist on Xoops\Module\Helper\HelperAbstract. It seems like you code against a sub-type of Xoops\Module\Helper\HelperAbstract such as XoopsModules\Xooghost\Helper. ( Ignorable by Annotation )

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

51
        /** @scrutinizer ignore-call */ 
52
        $this->config = $helper->loadConfig();
Loading history...
52
        $this->rldHandler = $helper->getHandler('Rld');
0 ignored issues
show
Bug Best Practice introduced by
The property rldHandler does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
53
    }
54
55
    /**
56
     * @param $xooghostUrl
57
     *
58
     * @return mixed
59
     */
60
    public function getByURL($xooghostUrl)
61
    {
62
        $criteria = new \Criteria('xooghost_url', $xooghostUrl);
63
        $page = $this->getObjects($criteria, false, true);
64
65
        return $page[0];
66
    }
67
68
    /**
69
     * @param string $sort
70
     * @param string $order
71
     * @param int    $start
72
     * @param int    $limit
73
     *
74
     * @return array
75
     */
76
    public function getPublished($sort = 'published', $order = 'desc', $start = 0, $limit = 0)
77
    {
78
        $criteria = new \CriteriaCompo();
79
        $criteria->add(new \Criteria('xooghost_online', 1));
80
        $criteria->add(new \Criteria('xooghost_published', time(), '<='));
81
        if ('random' === $sort) {
82
            $criteria->setSort('rand()');
83
        } else {
84
            $criteria->setSort('xooghost_' . $sort);
85
        }
86
        $criteria->setOrder($order);
87
        $criteria->setStart($start);
88
        $criteria->setLimit($limit);
89
90
        return $this->getObjects($criteria, true, false);
91
    }
92
93
    /**
94
     * @return array
95
     */
96
    public function getUrls()
97
    {
98
        $ret = [];
99
        $pages = $this->getPublished();
100
        foreach ($pages as $page) {
101
            $ret[] = $page['xooghost_url'];
102
        }
103
104
        return $ret;
105
    }
106
107
    /**
108
     * @param $Xooghost_id
109
     *
110
     * @return bool
111
     */
112
    public function setOnline($Xooghost_id)
113
    {
114
        if (0 != $Xooghost_id) {
115
            $page = $this->get($Xooghost_id);
116
            if (1 == $page->getVar('xooghost_online')) {
117
                $page->setVar('xooghost_online', 0);
118
            } else {
119
                $page->setVar('xooghost_online', 1);
120
            }
121
            $this->insert($page);
0 ignored issues
show
Bug introduced by
It seems like $page can also be of type null; however, parameter $object of XoopsModules\Xooghost\PageHandler::insert() does only seem to accept Xoops\Core\Kernel\XoopsObject, 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

121
            $this->insert(/** @scrutinizer ignore-type */ $page);
Loading history...
122
123
            return true;
124
        }
125
126
        return false;
127
    }
128
129
    /**
130
     * @param $pageObj
131
     *
132
     * @return bool
133
     */
134
    public function setRead($pageObj)
135
    {
136
        $read = $pageObj->getVar('xooghost_hits') + 1;
137
        $pageObj->setVar('xooghost_hits', $read);
138
        $this->insert($pageObj);
139
140
        return true;
141
    }
142
143
    /**
144
     * @param $page_id
145
     * @param $like_dislike
146
     *
147
     * @return array|bool
148
     */
149
    public function setLikeDislike($page_id, $like_dislike)
150
    {
151
        if (0 != $page_id) {
152
            $page = $this->get($page_id);
153
            if (is_object($page) && 0 != count($page)) {
0 ignored issues
show
Bug introduced by
$page of type Xoops\Core\Kernel\XoopsObject is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

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

153
            if (is_object($page) && 0 != count(/** @scrutinizer ignore-type */ $page)) {
Loading history...
154
                $xoops = \Xoops::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $xoops is dead and can be removed.
Loading history...
155
156
                if ($ret = $this->rldHandler->setLikeDislike($page_id, $like_dislike)) {
0 ignored issues
show
Bug introduced by
The method setLikeDislike() does not exist on XoopsObjectHandler. ( Ignorable by Annotation )

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

156
                if ($ret = $this->rldHandler->/** @scrutinizer ignore-call */ setLikeDislike($page_id, $like_dislike)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
157
                    if (0 == $like_dislike) {
158
                        $xooghost_dislike = $page->getVar('xooghost_dislike') + 1;
159
                        $page->setVar('xooghost_dislike', $xooghost_dislike);
160
                    } elseif (1 == $like_dislike) {
161
                        $xooghost_like = $page->getVar('xooghost_like') + 1;
162
                        $page->setVar('xooghost_like', $xooghost_like);
163
                    }
164
                    $this->insert($page);
165
166
                    return $page->getValues();
167
                }
168
            }
169
170
            return false;
171
        }
172
173
        return false;
174
    }
175
176
    /**
177
     * @param $page_id
178
     * @param $rate
179
     *
180
     * @return bool
181
     */
182
    public function setRate($page_id, $rate)
183
    {
184
        if (0 != $page_id) {
185
            $page = $this->get($page_id);
186
            if (is_object($page) && 0 != count($page)) {
0 ignored issues
show
Bug introduced by
$page of type Xoops\Core\Kernel\XoopsObject is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

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

186
            if (is_object($page) && 0 != count(/** @scrutinizer ignore-type */ $page)) {
Loading history...
187
                $xoops = \Xoops::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $xoops is dead and can be removed.
Loading history...
188
189
                if ($ret = $this->rldHandler->setRate($page_id, $rate)) {
0 ignored issues
show
Bug introduced by
The method setRate() does not exist on XoopsObjectHandler. ( Ignorable by Annotation )

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

189
                if ($ret = $this->rldHandler->/** @scrutinizer ignore-call */ setRate($page_id, $rate)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
190
                    if (is_array($ret) && 3 == count($ret)) {
191
                        $page->setVar('xooghost_rates', $ret['average']);
192
                        $this->insert($page);
193
194
                        return $ret;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $ret returns the type array which is incompatible with the documented return type boolean.
Loading history...
195
                    }
196
                }
197
            }
198
199
            return false;
200
        }
201
202
        return false;
203
    }
204
205
    /**
206
     * @return string
207
     */
208
    public function selectPage()
209
    {
210
        $pages = $this->getPublished();
211
        $form = new \Xoops\Form\Select('', 'xooghost_url');
212
        $form->setExtra("onChange='javascript:window.location.href=this.value'");
0 ignored issues
show
Deprecated Code introduced by
The function Xoops\Form\Element::setExtra() has been deprecated: please use attributes for event scripting ( Ignorable by Annotation )

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

212
        /** @scrutinizer ignore-deprecated */ $form->setExtra("onChange='javascript:window.location.href=this.value'");

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
213
        $form->addOption('index.php', _XOO_GHOST_CHOOSE);
214
        foreach ($pages as $page) {
215
            $form->addOption($page['xooghost_link'], $page['xooghost_title']);
216
        }
217
218
        return $form->render();
219
    }
220
221
    /**
222
     * @param int $online
223
     *
224
     * @return array
225
     */
226
    public function renderAdminList($online = -1)
227
    {
228
        $criteria = new \CriteriaCompo();
229
        $criteria->setSort('xooghost_published');
230
        $criteria->setOrder('DESC');
231
        if ($online >= 0) {
232
            $criteria->add(new \Criteria('xooghost_online', $online));
233
        }
234
        $criteria->setOrder('asc');
235
236
        return $this->getObjects($criteria, true, false);
237
    }
238
239
    /**
240
     * @param \Xoops\Core\Kernel\XoopsObject $object
241
     * @param bool                           $force
242
     *
243
     * @return bool|mixed
244
     */
245
    public function insert(\Xoops\Core\Kernel\XoopsObject $object, $force = true)
246
    {
247
        $xoops = \Xoops::getInstance();
248
        if (parent::insert($object, $force)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression parent::insert($object, $force) of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
249
            $object->createPage();
0 ignored issues
show
Bug introduced by
The method createPage() does not exist on Xoops\Core\Kernel\XoopsObject. It seems like you code against a sub-type of Xoops\Core\Kernel\XoopsObject such as XoopsModules\Xooghost\Page. ( Ignorable by Annotation )

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

249
            $object->/** @scrutinizer ignore-call */ 
250
                     createPage();
Loading history...
250
            if ($object->isNew()) {
251
                return $xoops->db()->getInsertId();
252
            }
253
254
            return $object->getVar('xooghost_id');
255
        }
256
257
        return false;
258
    }
259
260
    /**
261
     * @param $image_name
262
     *
263
     * @return array
264
     */
265
    public function uploadImages($image_name)
266
    {
267
        $xoops = \Xoops::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $xoops is dead and can be removed.
Loading history...
268
        $autoload = \XoopsLoad::loadConfig('xooghost');
269
270
        $uploader = new \XoopsMediaUploader(\XoopsBaseConfig::get('uploads-path') . '/xooghost/images', $autoload['mimetypes'], $this->config['xooghost_image_size'], $this->config['xooghost_image_width'], $this->config['xooghost_image_height']);
271
272
        $ret = [];
273
        foreach (Request::getArray('xoops_upload_file', [], 'POST') as $k => $input_image) {
274
            if ('' != Request::getArray($input_image, [], 'FILES')['tmp_name'] || is_readable(Request::getArray($input_image, [], 'FILES')['tmp_name'])) {
275
                $path_parts = pathinfo(Request::getArray($input_image, [], 'FILES')['name']);
276
                $uploader->setTargetFileName($this->cleanImage(mb_strtolower($image_name . '.' . $path_parts['extension'])));
277
                if ($uploader->fetchMedia(Request::getArray('xoops_upload_file', [], 'POST')[$k])) {
278
                    if ($uploader->upload()) {
279
                        $ret[$input_image] = ['filename' => $uploader->getSavedFileName(), 'error' => false, 'message' => ''];
280
                    } else {
281
                        $ret[$input_image] = ['filename' => Request::getArray($input_image, [], 'FILES')['name'], 'error' => true, 'message' => $uploader->getErrors()];
282
                    }
283
                } else {
284
                    $ret[$input_image] = ['filename' => Request::getArray($input_image, [], 'FILES')['name'], 'error' => true, 'message' => $uploader->getErrors()];
285
                }
286
            }
287
        }
288
289
        return $ret;
290
    }
291
292
    /**
293
     * @param $filename
294
     *
295
     * @return string
296
     */
297
    public function cleanImage($filename)
298
    {
299
        $path_parts = pathinfo($filename);
300
        $string = $path_parts['filename'];
301
302
        $string = str_replace('_', md5('xooghost'), $string);
303
        $string = str_replace('-', md5('xooghost'), $string);
304
        $string = str_replace(' ', md5('xooghost'), $string);
305
306
        $string = preg_replace('~\p{P}~', '', $string);
307
        $string = htmlentities($string, ENT_NOQUOTES, \XoopsLocale::_CHARSET);
0 ignored issues
show
Bug introduced by
The constant XoopsLocale::_CHARSET was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
308
        $string = preg_replace("~\&([A-za-z])(?:uml|circ|tilde|acute|grave|cedil|ring)\;~", '$1', $string);
309
        $string = preg_replace("~\&([A-za-z]{2})(?:lig)\;~", '$1', $string); // pour les ligatures e.g. "&oelig;"
310
        $string = preg_replace("~\&[^;]+\;~", '', $string); // supprime les autres caract�res
311
312
        $string = str_replace(md5('xooghost'), '_', $string);
313
314
        return $string . '.' . $path_parts['extension'];
315
    }
316
317
    /**
318
     * @return array
319
     */
320
    public function getPhpListAsArray()
321
    {
322
        $exclude = $this->exclude;
323
        $pages = parent::getAll(null, ['xooghost_url'], false, true);
324
        foreach ($pages as $page) {
325
            $exclude[] = $page['xooghost_url'];
326
        }
327
328
        $dirname = \XoopsBaseConfig::get('root-path') . '/modules/xooghost';
329
330
        $filelist = [];
331
        if ($handle = opendir($dirname)) {
332
            while (false !== ($file = readdir($handle))) {
333
                if ((preg_match('/(\.php)$/i', $file) && !is_dir($file) && !in_array($file, $exclude, true))) {
334
                    $file = basename($file);
335
                    $filelist[$file] = $file;
336
                }
337
            }
338
            closedir($handle);
339
            asort($filelist);
340
            reset($filelist);
341
        }
342
343
        return $filelist;
344
    }
345
}
346