Utility::getRssFeedAsHtml()   F
last analyzed

Complexity

Conditions 17
Paths 552

Size

Total Lines 90
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 58
c 0
b 0
f 0
nc 552
nop 7
dl 0
loc 90
rs 1.6722

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
declare(strict_types=1);
4
5
namespace XoopsModules\Rssfit;
6
7
/*
8
 Utility Class Definition
9
10
 You may not change or alter any portion of this comment or credits of
11
 supporting developers from this source code or any supporting source code
12
 which is considered copyrighted (c) material of the original comment or credit
13
 authors.
14
15
 This program is distributed in the hope that it will be useful, but
16
 WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18
 */
19
/**
20
 * Module:  xSitemap
21
 *
22
 * @package      \module\xsitemap\class
23
 * @license      http://www.fsf.org/copyleft/gpl.html GNU public license
24
 * @copyright    https://xoops.org 2001-2017 &copy; XOOPS Project
25
 * @author       ZySpec <[email protected]>
26
 * @author       Mamba <[email protected]>
27
 * @since        File available since version 1.54
28
 */
29
30
//require_once  \dirname(__DIR__) . '/include/common.php';
31
32
use XoopsModules\Rssfit\Constants;
33
34
/**
35
 * Class Utility
36
 */
37
class Utility extends Common\SysUtility
38
{
39
    //--------------- Custom module methods -----------------------------
40
41
    public static function sortTimestamp(array $a, array $b): int
42
    {
43
        if ($a['timestamp'] == $b['timestamp']) {
44
            return 0;
45
        }
46
47
        return ($a['timestamp'] > $b['timestamp']) ? -1 : 1;
48
    }
49
50
    public static function genSpecMoreInfo(string $spec, FeedHandler $feedHandler): string
51
    {
52
        return static::rssfGenAnchor($feedHandler->specUrl($spec), \_AM_RSSFIT_EDIT_CHANNEL_QMARK, 'spec', \_AM_RSSFIT_EDIT_CHANNEL_MOREINFO);
53
    }
54
55
    public static function rssfGenAnchor(?string $url = null, string $text = '', string $target = '', string $title = '', string $class = '', string $id = ''): string
56
    {
57
        if (null !== $url) {
58
            $ret = '<a href="' . $url . '"';
59
            $ret .= !empty($target) ? ' target="' . $target . '"' : '';
60
            $ret .= !empty($class) ? ' class="' . $class . '"' : '';
61
            $ret .= !empty($id) ? ' id="' . $id . '"' : '';
62
            $ret .= !empty($title) ? ' title="' . $title . '"' : '';
63
            $ret .= '>' . $text . '</a>';
64
65
            return $ret;
66
        }
67
68
        return $text;
69
    }
70
71
    // Check http://www.systutorials.com/136102/a-php-function-for-fetching-rss-feed-and-outputing-feed-items-as-html/ for description
72
73
    // RSS to HTML
74
    /*
75
        $tiem_cnt: max number of feed items to be displayed
76
        $max_words: max number of words (not real words, HTML words)
77
        if <= 0: no limitation, if > 0 display at most $max_words words
78
     */
79
    public static function getRssFeedAsHtml(string $feed_url, int $maxItemCount = 10, bool $show_date = true, bool $show_description = true, int $max_words = 0, int $cache_timeout = 7200, string $cache_prefix = XOOPS_VAR_PATH . '/caches/xoops_cache/rss2html-'): string
80
    {
81
        $result = '';
82
        // get feeds and parse items
83
        $rss       = new \DOMDocument();
84
        $cacheFile = $cache_prefix . \md5($feed_url);
85
        // load from file or load content
86
        if ($cache_timeout > 0
87
            && \is_file($cacheFile)
88
            && (\filemtime($cacheFile) + $cache_timeout > \time())) {
89
            $rss->load($cacheFile);
90
        } else {
91
            $rss->load($feed_url);
92
            /*
93
            // if load() doesn't work, you might try this
94
            $ch = curl_init($feed_url);
95
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
96
            $content = curl_exec($ch);
97
            curl_close($ch);
98
            $rss->loadXML($content);
99
            */
100
            if ($cache_timeout > 0) {
101
                $rss->save($cacheFile);
102
            }
103
        }
104
        $feed = [];
105
        foreach ($rss->getElementsByTagName('item') as $node) {
106
            if (null !== $node) {
107
                $item    = [
108
                    'title'   => $node->getElementsByTagName('title')->item(0)->nodeValue,
109
                    'desc'    => $node->getElementsByTagName('description')->item(0)->nodeValue,
110
                    'content' => $node->getElementsByTagName('description')->item(0)->nodeValue,
111
                    'link'    => $node->getElementsByTagName('link')->item(0)->nodeValue,
112
                    'date'    => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
113
                ];
114
                $content = $node->getElementsByTagName('encoded'); // <content:encoded>
115
                if ($content->length > 0) {
116
                    $item['content'] = $content->item(0)->nodeValue;
117
                }
118
                $feed[] = $item;
119
            }
120
        }
121
        // real good count
122
        if ($maxItemCount > \count($feed)) {
123
            $maxItemCount = \count($feed);
124
        }
125
        $result .= '<ul class="feed-lists">';
126
        for ($x = 0; $x < $maxItemCount; $x++) {
127
            $title  = \str_replace(' & ', ' &amp; ', $feed[$x]['title']);
128
            $link   = $feed[$x]['link'];
129
            $result .= '<li class="feed-item">';
130
            $result .= '<div class="feed-title"><strong><a href="' . $link . '" title="' . $title . '">' . $title . '</a></strong></div>';
131
            if ($show_date) {
132
                $date   = \date('l F d, Y', (int)\strtotime($feed[$x]['date']));
133
                $result .= '<small class="feed-date"><em>Posted on ' . $date . '</em></small>';
134
            }
135
            if ($show_description) {
136
                $description = $feed[$x]['desc'];
137
                $content     = $feed[$x]['content'];
138
                // find the img
139
                $hasImage = \preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $content, $image);
140
                // no html tags
141
                $description = \strip_tags((string)\preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/s', '$1$3', $description), '');
142
                // whether cut by number of words
143
                if ($max_words > 0) {
144
                    $arr = \explode(' ', $description);
145
                    if ($max_words < \count($arr)) {
146
                        $description = '';
147
                        $wordsCount  = 0;
148
                        foreach ($arr as $w) {
149
                            $description .= $w . ' ';
150
                            ++$wordsCount;
151
                            if ($wordsCount == $max_words) {
152
                                break;
153
                            }
154
                        }
155
                        $description .= ' ...';
156
                    }
157
                }
158
                // add img if it exists
159
                if (1 == $hasImage) {
160
                    $description = '<img class="feed-item-image" src="' . $image['src'] . '" />' . $description;
161
                }
162
                $result .= '<div class="feed-description">' . $description;
163
                $result .= ' <a href="' . $link . '" title="' . $title . '">Continue Reading &raquo;</a>' . '</div>';
164
            }
165
            $result .= '</li>';
166
        }
167
        $result .= '</ul>';
168
        return $result;
169
    }
170
171
    public static function outputRssFeed(string $feed_url, int $maxItemCount = 10, bool $show_date = true, bool $show_description = true, int $max_words = 0): void
172
    {
173
        echo self::getRssFeedAsHtml($feed_url, $maxItemCount, $show_date, $show_description, $max_words);
174
    }
175
}
176