Passed
Push — master ( e3d02e...b8a1dc )
by Michael
03:24 queued 12s
created

HeadlineRenderer::renderFeed()   C

Complexity

Conditions 16
Paths 83

Size

Total Lines 69
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 52
c 0
b 0
f 0
dl 0
loc 69
rs 5.5666
cc 16
nc 83
nop 1

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
namespace XoopsModules\Xoopsheadline;
4
5
/*
6
 * You may not change or alter any portion of this comment or credits
7
 * of supporting developers from this source code or any supporting source code
8
 * which is considered copyrighted (c) material of the original comment or credit authors.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
15
use think\console\command\Help;
0 ignored issues
show
Bug introduced by
The type think\console\command\Help was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
/**
18
 * @copyright    XOOPS Project https://xoops.org/
19
 * @license      GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
20
 * @package
21
 * @since
22
 * @author       XOOPS Development Team, Kazumi Ono (AKA onokazu)
23
 */
24
25
26
require_once XOOPS_ROOT_PATH . '/class/template.php';
27
28
$helper = Helper::getInstance();
29
$helper->loadLanguage('main');
30
31
/**
32
 * Class HeadlineRenderer
33
 */
34
class HeadlineRenderer
35
{
36
    // holds reference to xoopsheadline class object
37
    protected $headline;
38
    protected $tpl;
39
    protected $feed;
40
    protected $block;
41
    protected $errors = [];
42
    // RSS2 SAX parser
43
    protected $parser;
44
45
    /**
46
     * HeadlineRenderer constructor.
47
     * @param $headline
48
     */
49
    public function __construct(&$headline)
50
    {
51
        $this->hl  = &$headline;
0 ignored issues
show
Bug Best Practice introduced by
The property hl does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
52
        $this->tpl = new \XoopsTpl();
53
    }
54
55
    /**
56
     * @return bool
57
     */
58
    public function updateCache()
59
    {
60
        $helper = Helper::getInstance();
61
        /**
62
         * Update cache - first try using fopen and then cURL
63
         */
64
        $retval = false;
65
        if (!$fp = @\fopen($this->hl->getVar('headline_rssurl'), 'r')) {
66
            // failed open using fopen, now try cURL
67
            $ch = \curl_init($this->hl->getVar('headline_rssurl'));
68
            if (\curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true)) {
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, 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

68
            if (\curl_setopt(/** @scrutinizer ignore-type */ $ch, \CURLOPT_RETURNTRANSFER, true)) {
Loading history...
69
                if (!$data = \curl_exec($ch)) {
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, 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

69
                if (!$data = \curl_exec(/** @scrutinizer ignore-type */ $ch)) {
Loading history...
70
                    \curl_close($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, 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

70
                    \curl_close(/** @scrutinizer ignore-type */ $ch);
Loading history...
71
                    $errmsg = \sprintf(\_MD_HEADLINES_NOTOPEN, $this->hl->getVar('headline_rssurl'));
72
                    $this->_setErrors($errmsg);
73
                } else {
74
                    \curl_close($ch);
75
                    $this->hl->setVar('headline_xml', $this->convertToUtf8($data));
76
                    $this->hl->setVar('headline_updated', \time());
77
                    $headlineHandler = $helper->getHandler('Headline');
78
                    $retval          = $headlineHandler->insert($this->hl);
79
                }
80
            } else {
81
                $this->_setErrors(\_MD_HEADLINES_BADOPT);
82
            }
83
        } else {  // successfully openned file using fopen
84
            $data = '';
85
            while (!\feof($fp)) {
86
                $data .= \fgets($fp, 4096);
87
            }
88
            \fclose($fp);
89
            $this->hl->setVar('headline_xml', $this->convertToUtf8($data));
90
            $this->hl->setVar('headline_updated', \time());
91
            $headlineHandler = $helper->getHandler('Headline');
92
            $retval          = $headlineHandler->insert($this->hl);
93
        }
94
95
        return $retval;
96
    }
97
98
    /**
99
     * @param bool $force_update
100
     * @return bool
101
     */
102
    public function renderFeed($force_update = false)
103
    {
104
        $retval = false;
105
        if ($force_update || $this->hl->cacheExpired()) {
106
            if (!$this->updateCache()) {
107
                return $retval;
108
            }
109
        }
110
        if ($this->_parse()) {
111
            $this->tpl->clear_all_assign();
112
            $this->tpl->assign('xoops_url', XOOPS_URL);
113
            $channel_data = $this->parser->getChannelData();
114
            \array_walk($channel_data, [$this, 'convertFromUtf8']);
115
            $this->tpl->assign_by_ref('channel', $channel_data);
116
            if (1 == $this->hl->getVar('headline_mainimg')) {
117
                $image_data = $this->parser->getImageData();
118
                \array_walk($image_data, [$this, 'convertFromUtf8']);
119
                $max_width  = 256;
120
                $max_height = 92;
121
                if (!isset($image_data['height']) || !isset($image_data['width'])) {
122
                    $image_size = @\getimagesize($image_data['url']);
123
                    if ($image_size) {
124
                        $image_data['width']  = $image_size[0];
125
                        $image_data['height'] = $image_size[1];
126
                    }
127
                }
128
                if (\array_key_exists('height', $image_data) && \array_key_exists('width', $image_data)
129
                    && ($image_data['width'] > 0)) {
130
                    $width_ratio  = $image_data['width'] / $max_width;
131
                    $height_ratio = $image_data['height'] / $max_height;
132
                    $scale        = \max($width_ratio, $height_ratio);
133
                    if ($scale > 1) {
134
                        $image_data['width']  = (int)($image_data['width'] / $scale);
135
                        $image_data['height'] = (int)($image_data['height'] / $scale);
136
                    }
137
                }
138
                $this->tpl->assign_by_ref('image', $image_data);
139
            }
140
            if (1 == $this->hl->getVar('headline_mainfull')) {
141
                $this->tpl->assign('show_full', true);
142
            } else {
143
                $this->tpl->assign('show_full', false);
144
            }
145
            $items = $this->parser->getItems();
146
            $count = \count($items);
147
            $max   = ($count > $this->hl->getVar('headline_mainmax')) ? $this->hl->getVar('headline_mainmax') : $count;
148
            for ($i = 0; $i < $max; ++$i) {
149
                \array_walk($items[$i], [$this, 'convertFromUtf8']);
150
                $this->tpl->append_by_ref('items', $items[$i]);
151
            }
152
            $this->tpl->assign(
153
                [
154
                    'lang_lastbuild'   => \_MD_HEADLINES_LASTBUILD,
155
                    'lang_language'    => \_MD_HEADLINES_LANGUAGE,
156
                    'lang_description' => \_MD_HEADLINES_DESCRIPTION,
157
                    'lang_webmaster'   => \_MD_HEADLINES_WEBMASTER,
158
                    'lang_category'    => \_MD_HEADLINES_CATEGORY,
159
                    'lang_generator'   => \_MD_HEADLINES_GENERATOR,
160
                    'lang_title'       => \_MD_HEADLINES_TITLE,
161
                    'lang_pubdate'     => \_MD_HEADLINES_PUBDATE,
162
                    //                                   'lang_description2' => _MD_HEADLINES_DESCRIPTION2,
163
                    'lang_more'        => _MORE,
164
                ]
165
            );
166
            $this->feed = $this->tpl->fetch('db:xoopsheadline_feed.tpl');
167
            $retval     = true;
168
        }
169
170
        return $retval;
171
    }
172
173
    /**
174
     * @param bool $force_update
175
     * @return bool
176
     */
177
    public function renderBlock($force_update = false)
178
    {
179
        $retval = false;
180
        if ($force_update || $this->hl->cacheExpired()) {
181
            if (!$this->updateCache()) {
182
                return $retval;
183
            }
184
        }
185
        if ($this->_parse()) {
186
            $this->tpl->clear_all_assign();
187
            $this->tpl->assign('xoops_url', XOOPS_URL);
188
            $channel_data = $this->parser->getChannelData();
189
            \array_walk($channel_data, [$this, 'convertFromUtf8']);
190
            $this->tpl->assign_by_ref('channel', $channel_data);
191
            if (1 == $this->hl->getVar('headline_blockimg')) {
192
                $image_data = $this->parser->getImageData();
193
                \array_walk($image_data, [$this, 'convertFromUtf8']);
194
                $this->tpl->assign_by_ref('image', $image_data);
195
            }
196
            $items = $this->parser->getItems();
197
            $count = \count($items);
198
            $max   = ($count > $this->hl->getVar('headline_blockmax')) ? $this->hl->getVar('headline_blockmax') : $count;
199
            for ($i = 0; $i < $max; ++$i) {
200
                \array_walk($items[$i], [$this, 'convertFromUtf8']);
201
                $this->tpl->append_by_ref('items', $items[$i]);
202
            }
203
            $this->tpl->assign(
204
                [
205
                    'site_name' => $this->hl->getVar('headline_name'),
206
                    'site_url'  => $this->hl->getVar('headline_url'),
207
                    'site_id'   => $this->hl->getVar('headline_id'),
208
                ]
209
            );
210
            $this->block = $this->tpl->fetch('file:' . XOOPS_ROOT_PATH . '/modules/xoopsheadline/templates/blocks/headline_block.tpl');
211
            $retval      = true;
212
        }
213
214
        return $retval;
215
    }
216
217
    /**
218
     * @return bool
219
     */
220
    protected function &_parse()
221
    {
222
        $retval = true;
223
        if (!isset($this->parser)) {
224
            require_once XOOPS_ROOT_PATH . '/class/xml/rss/xmlrss2parser.php';
225
            $temp         = $this->hl->getVar('headline_xml');
226
            $this->parser = new \XoopsXmlRss2Parser($temp);
227
            switch ($this->hl->getVar('headline_encoding')) {
228
                case 'utf-8':
229
                    $this->parser->useUtfEncoding();
230
                    break;
231
                case 'us-ascii':
232
                    $this->parser->useAsciiEncoding();
233
                    break;
234
                default:
235
                    $this->parser->useIsoEncoding();
236
                    break;
237
            }
238
            $result = $this->parser->parse();
239
            if (!$result) {
240
                $this->_setErrors($this->parser->getErrors(false));
241
                unset($this->parser);
242
                $retval = false;
243
            }
244
        }
245
246
        return $retval;
247
    }
248
249
    public function &getFeed()
250
    {
251
        return $this->feed;
252
    }
253
254
    public function &getBlock()
255
    {
256
        return $this->block;
257
    }
258
259
    /**
260
     * @param $err
261
     */
262
    protected function _setErrors($err)
263
    {
264
        $this->errors[] = $err;
265
    }
266
267
    /**
268
     * @param bool $ashtml
269
     * @return array|string
270
     */
271
    public function &getErrors($ashtml = true)
272
    {
273
        if (!$ashtml) {
274
            $retval = $this->errors;
275
        } else {
276
            $retval = '';
277
            if (\count($this->errors) > 0) {
278
                foreach ($this->errors as $error) {
279
                    $retval .= $error . '<br>';
280
                }
281
            }
282
        }
283
284
        return $retval;
285
    }
286
287
    // abstract
288
    // overide this method in /language/your_language/headlinerenderer.php
289
    // this method is called by the array_walk function
290
    // return void
291
292
    /**
293
     * @param $value
294
     * @param $key
295
     */
296
    public function convertFromUtf8(&$value, $key)
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed. ( Ignorable by Annotation )

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

296
    public function convertFromUtf8(/** @scrutinizer ignore-unused */ &$value, $key)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

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

296
    public function convertFromUtf8(&$value, /** @scrutinizer ignore-unused */ $key)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
297
    {
298
    }
299
300
    // abstract
301
    // overide this method in /language/your_language/headlinerenderer.php
302
    // return string
303
304
    /**
305
     * @param $xmlfile
306
     * @return string
307
     */
308
    public function &convertToUtf8(&$xmlfile)
309
    {
310
        if ('iso-8859-1' === mb_strtolower($this->hl->getVar('headline_encoding'))) {
311
            $xmlfile = utf8_encode($xmlfile);
312
        }
313
314
        return $xmlfile;
315
    }
316
}
317