Utility::truncateHtml()   F
last analyzed

Complexity

Conditions 19
Paths 194

Size

Total Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
nc 194
nop 5
dl 0
loc 91
rs 3.7333
c 0
b 0
f 0

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 namespace Xoopsmodules\randomquote;
2
3
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
*/
12
/**
13
 * Module: randomquote
14
 *
15
 * @category        Module
16
 * @package         randomquote
17
 * @author          XOOPS Development Team <[email protected]> - <https://xoops.org>
18
 * @copyright       {@link https://xoops.org/ XOOPS Project}
19
 * @license         GPL 2.0 or later
20
 * @link            https://xoops.org/
21
 * @since           1.0.0
22
 */
23
24
use Xmf\Request;
25
use Xoopsmodules\randomquote;
26
use Xoopsmodules\randomquote\common;
27
28
/**
29
 * Class Utility
30
 */
31
class Utility
32
{
33
34
    use common\VersionChecks; //checkVerXoops, checkVerPhp Traits
35
36
    use common\ServerStats; // getServerStats Trait
37
38
    use common\FilesManagement; // Files Management Trait
39
40
    //--------------- Custom module methods -----------------------------
41
42
    /**
43
     * @param $text
44
     * @param $form_sort
45
     * @return string
46
     */
47
    public static function selectSorting($text, $form_sort)
48
    {
49
        global $start, $order, $file_cat, $sort, $xoopsModule;
50
51
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
$select_view is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
        $moduleDirName = basename(dirname(__DIR__));
53
54
        //        if (false !== ($helper = Xmf\Module\Helper::getHelper($moduleDirName))) {
55
        //        } else {
56
        //            $helper = Xmf\Module\Helper::getHelper('system');
57
        //        }
58
        $helper = randomquote\Helper::getInstance();
59
60
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getModule()->getInfo('modicons16');
61
62
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
63
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
64
        if ($form_sort == $sort) {
65
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
66
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
67
        } else {
68
            $sel1 = 'asc.png';
69
            $sel2 = 'desc.png';
70
        }
71
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc" /><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
72
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc" /><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
73
        $select_view .= '</form>';
74
75
        return $select_view;
76
    }
77
78
    /***************Blocks***************/
79
    /**
80
     * @param array $cats
81
     * @return string
82
     */
83
    public static function block_addCatSelect($cats)
84
    {
85
        $cat_sql = '';
86
        if (is_array($cats)) {
87
            $cat_sql = '(' . current($cats);
88
            array_shift($cats);
89
            foreach ($cats as $cat) {
90
                $cat_sql .= ',' . $cat;
91
            }
92
            $cat_sql .= ')';
93
        }
94
95
        return $cat_sql;
96
    }
97
98
    /**
99
     * @param $content
100
     */
101 View Code Duplication
    public static function meta_keywords($content)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        global $xoopsTpl, $xoTheme;
104
        $myts    = \MyTextSanitizer::getInstance();
105
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
106
        if (null !== $xoTheme && is_object($xoTheme)) {
107
            $xoTheme->addMeta('meta', 'keywords', strip_tags($content));
108
        } else {    // Compatibility for old Xoops versions
109
            $xoopsTpl->assign('xoops_meta_keywords', strip_tags($content));
110
        }
111
    }
112
113
    /**
114
     * @param $content
115
     */
116 View Code Duplication
    public static function meta_description($content)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
    {
118
        global $xoopsTpl, $xoTheme;
119
        $myts    = \MyTextSanitizer::getInstance();
120
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
121
        if (null !== $xoTheme && is_object($xoTheme)) {
122
            $xoTheme->addMeta('meta', 'description', strip_tags($content));
123
        } else {    // Compatibility for old Xoops versions
124
            $xoopsTpl->assign('xoops_meta_description', strip_tags($content));
125
        }
126
    }
127
128
    /**
129
     * @param $tableName
130
     * @param $columnName
131
     *
132
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be null|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
133
     */
134
    public static function enumerate($tableName, $columnName)
135
    {
136
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
137
138
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
139
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
140
        //    || exit ($GLOBALS['xoopsDB']->error());
141
142
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
143
        $result = $GLOBALS['xoopsDB']->query($sql);
144
        if (!$result) {
145
            exit ($GLOBALS['xoopsDB']->error());
146
        }
147
148
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
149
        $enumList = explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, -6)));
150
        return $enumList;
151
    }
152
153
    /**
154
     * @param array|string $tableName
155
     * @param int          $id_field
156
     * @param int          $id
157
     *
158
     * @return mixed
159
     */
160
    public static function cloneRecord($tableName, $id_field, $id)
161
    {
162
        $new_id = false;
163
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
164
        // copy content of the record you wish to clone 
165
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query("SELECT * FROM $table WHERE $id_field='$id' "), MYSQLI_ASSOC) or exit('Could not select record');
166
        // set the auto-incremented id's value to blank.
167
        unset($tempTable[$id_field]);
168
        // insert cloned copy of the original  record 
169
        $result = $GLOBALS['xoopsDB']->queryF("INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')") or exit ($GLOBALS['xoopsDB']->error());
170
171
        if ($result) {
172
            // Return the new id
173
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
174
        }
175
        return $new_id;
176
    }
177
178
    /**
179
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
180
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
181
     * www.cakephp.org
182
     *
183
     * @param string  $text         String to truncate.
184
     * @param integer $length       Length of returned string, including ellipsis.
185
     * @param string  $ending       Ending to be appended to the trimmed string.
186
     * @param boolean $exact        If false, $text will not be cut mid-word
187
     * @param boolean $considerHtml If true, HTML tags would be handled correctly
188
     *
189
     * @return string Trimmed string.
190
     */
191
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
192
    {
193
        if ($considerHtml) {
194
            // if the plain text is shorter than the maximum length, return the whole text
195
            if (strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
196
                return $text;
197
            }
198
            // splits all html-tags to scanable lines
199
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
200
            $total_length = strlen($ending);
201
            $open_tags    = [];
202
            $truncate     = '';
203
            foreach ($lines as $line_matchings) {
0 ignored issues
show
Bug introduced by
The expression $lines of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
204
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
205
                if (!empty($line_matchings[1])) {
206
                    // if it's an "empty element" with or without xhtml-conform closing slash
207
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
208
                        // do nothing
209
                        // if tag is a closing tag
210
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
211
                        // delete tag from $open_tags list
212
                        $pos = array_search($tag_matchings[1], $open_tags);
213
                        if (false !== $pos) {
214
                            unset($open_tags[$pos]);
215
                        }
216
                        // if tag is an opening tag
217
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
218
                        // add tag to the beginning of $open_tags list
219
                        array_unshift($open_tags, strtolower($tag_matchings[1]));
220
                    }
221
                    // add html-tag to $truncate'd text
222
                    $truncate .= $line_matchings[1];
223
                }
224
                // calculate the length of the plain text part of the line; handle entities as one character
225
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
226
                if ($total_length + $content_length > $length) {
227
                    // the number of characters which are left
228
                    $left            = $length - $total_length;
229
                    $entities_length = 0;
230
                    // search for html entities
231
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
232
                        // calculate the real length of all entities in the legal range
233
                        foreach ($entities[0] as $entity) {
234
                            if ($entity[1] + 1 - $entities_length <= $left) {
235
                                $left--;
236
                                $entities_length += strlen($entity[0]);
237
                            } else {
238
                                // no more characters left
239
                                break;
240
                            }
241
                        }
242
                    }
243
                    $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
244
                    // maximum lenght is reached, so get off the loop
245
                    break;
246
                } else {
247
                    $truncate     .= $line_matchings[2];
248
                    $total_length += $content_length;
249
                }
250
                // if the maximum length is reached, get off the loop
251
                if ($total_length >= $length) {
252
                    break;
253
                }
254
            }
255
        } else {
256
            if (strlen($text) <= $length) {
257
                return $text;
258
            } else {
259
                $truncate = substr($text, 0, $length - strlen($ending));
260
            }
261
        }
262
        // if the words shouldn't be cut in the middle...
263
        if (!$exact) {
264
            // ...search the last occurance of a space...
265
            $spacepos = strrpos($truncate, ' ');
266
            if (isset($spacepos)) {
267
                // ...and cut the text in this position
268
                $truncate = substr($truncate, 0, $spacepos);
269
            }
270
        }
271
        // add the defined ending to the text
272
        $truncate .= $ending;
273
        if ($considerHtml) {
274
            // close all unclosed html-tags
275
            foreach ($open_tags as $tag) {
0 ignored issues
show
Bug introduced by
The variable $open_tags does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
276
                $truncate .= '</' . $tag . '>';
277
            }
278
        }
279
280
        return $truncate;
281
    }
282
}
283