Passed
Push — master ( 005d4f...8b5e26 )
by Michael
06:49
created

SysUtility::truncateHtml()   F

Complexity

Conditions 19
Paths 194

Size

Total Lines 94
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 19
eloc 47
c 1
b 0
f 0
nc 194
nop 5
dl 0
loc 94
rs 3.7333

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\Pedigree\Common;
4
5
/*
6
 Utility Class Definition
7
8
 You may not change or alter any portion of this comment or credits of
9
 supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit
11
 authors.
12
13
 This program is distributed in the hope that it will be useful, but
14
 WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
 */
17
18
/**
19
 * @package      \XoopsModules\Pedigree
20
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
21
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
22
 * @author       ZySpec <[email protected]>
23
 * @author       Mamba <[email protected]>
24
 */
25
26
use XoopsFormEditor;
27
use XoopsModules\Pedigree\Helper;
28
29
/**
30
 * Class SysUtility
31
 */
32
class SysUtility
33
{
34
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Pedigree\Common\VersionChecks requires some properties which are not provided by XoopsModules\Pedigree\Common\SysUtility: $tag_name, $prerelease
Loading history...
35
36
    //checkVerXoops, checkVerPhp Traits
37
38
    use ServerStats;
39
40
    // getServerStats Trait
41
42
    use FilesManagement;
43
44
    // Files Management Trait
45
46
    /**
47
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
48
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
49
     * www.cakephp.org
50
     *
51
     * @TODO: Refactor to consider HTML5 & void (self-closing) elements
52
     * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php
53
     *
54
     * @param string $text         String to truncate.
55
     * @param int    $length       Length of returned string, including ellipsis.
56
     * @param string $ending       Ending to be appended to the trimmed string.
57
     * @param bool   $exact        If false, $text will not be cut mid-word
58
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
59
     *
60
     * @return string Trimmed string.
61
     */
62
    public static function truncateHtml(
63
        string $text,
64
        ?int $length = 100,
65
        ?string $ending = '...',
66
        ?bool $exact = false,
67
        ?bool $considerHtml = true): string
68
    {
69
        if ($considerHtml) {
70
            // if the plain text is shorter than the maximum length, return the whole text
71
            if (mb_strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
72
                return $text;
73
            }
74
            // splits all html-tags to scanable lines
75
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
76
            $total_length = mb_strlen($ending);
0 ignored issues
show
Bug introduced by
It seems like $ending can also be of type null; however, parameter $string of mb_strlen() does only seem to accept string, 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

76
            $total_length = mb_strlen(/** @scrutinizer ignore-type */ $ending);
Loading history...
77
            $open_tags    = [];
78
            $truncate     = '';
79
            foreach ($lines as $line_matchings) {
80
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
81
                if (!empty($line_matchings[1])) {
82
                    // if it's an "empty element" with or without xhtml-conform closing slash
83
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
84
                        // do nothing
85
                        // if tag is a closing tag
86
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
87
                        // delete tag from $open_tags list
88
                        $pos = array_search($tag_matchings[1], $open_tags, true);
89
                        if (false !== $pos) {
90
                            unset($open_tags[$pos]);
91
                        }
92
                        // if tag is an opening tag
93
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
94
                        // add tag to the beginning of $open_tags list
95
                        array_unshift($open_tags, mb_strtolower($tag_matchings[1]));
96
                    }
97
                    // add html-tag to $truncate'd text
98
                    $truncate .= $line_matchings[1];
99
                }
100
                // calculate the length of the plain text part of the line; handle entities as one character
101
                $content_length = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
102
                if ($total_length + $content_length > $length) {
103
                    // the number of characters which are left
104
                    $left            = $length - $total_length;
105
                    $entities_length = 0;
106
                    // search for html entities
107
                    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)) {
108
                        // calculate the real length of all entities in the legal range
109
                        foreach ($entities[0] as $entity) {
110
                            if ($left >= $entity[1] + 1 - $entities_length) {
111
                                $left--;
112
                                $entities_length += mb_strlen($entity[0]);
113
                            } else {
114
                                // no more characters left
115
                                break;
116
                            }
117
                        }
118
                    }
119
                    $truncate .= mb_substr($line_matchings[2], 0, $left + $entities_length);
120
                    // maximum length is reached, so get off the loop
121
                    break;
122
                }
123
                $truncate     .= $line_matchings[2];
124
                $total_length += $content_length;
125
126
                // if the maximum length is reached, get off the loop
127
                if ($total_length >= $length) {
128
                    break;
129
                }
130
            }
131
        } else {
132
            if (mb_strlen($text) <= $length) {
133
                return $text;
134
            }
135
            $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
136
        }
137
        // if the words shouldn't be cut in the middle...
138
        if (!$exact) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $exact of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
139
            // ...search the last occurance of a space...
140
            $spacepos = mb_strrpos($truncate, ' ');
141
            if (isset($spacepos)) {
142
                // ...and cut the text in this position
143
                $truncate = mb_substr($truncate, 0, $spacepos);
144
            }
145
        }
146
        // add the defined ending to the text
147
        $truncate .= $ending;
148
        if ($considerHtml) {
149
            // close all unclosed html-tags
150
            foreach ($open_tags as $tag) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $open_tags does not seem to be defined for all execution paths leading up to this point.
Loading history...
151
                $truncate .= '</' . $tag . '>';
152
            }
153
        }
154
155
        return $truncate;
156
    }
157
158
    /**
159
     * Get correct text editor based on user rights
160
     *
161
     * @param \Xmf\Module\Helper $helper
162
     * @param array|null         $options
163
     *
164
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
165
     */
166
    public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null)
167
    {
168
        /** @var Helper $helper */
169
        if (null === $options) {
170
            $options           = [];
171
            $options['name']   = 'Editor';
172
            $options['value']  = 'Editor';
173
            $options['rows']   = 10;
174
            $options['cols']   = '100%';
175
            $options['width']  = '100%';
176
            $options['height'] = '400px';
177
        }
178
179
        if (null === $helper) {
180
            $helper = Helper::getInstance();
181
        }
182
183
        $isAdmin = $helper->isUserAdmin();
184
185
        if (class_exists('XoopsFormEditor')) {
186
            if ($isAdmin) {
187
                $descEditor = new XoopsFormEditor(ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea');
188
            } else {
189
                $descEditor = new XoopsFormEditor(ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea');
190
            }
191
        } else {
192
            $descEditor = new \XoopsFormDhtmlTextArea(ucfirst($options['name']), $options['name'], $options['value'], '100%', '100%');
0 ignored issues
show
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $cols of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

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

192
            $descEditor = new \XoopsFormDhtmlTextArea(ucfirst($options['name']), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $rows of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

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

192
            $descEditor = new \XoopsFormDhtmlTextArea(ucfirst($options['name']), $options['name'], $options['value'], /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
193
        }
194
195
        //        $form->addElement($descEditor);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
196
197
        return $descEditor;
198
    }
199
200
    /**
201
     * Check if column in dB table exists
202
     *
203
     * @deprecated
204
     * @param string $fieldname name of dB table field
205
     * @param string $table name of dB table (including prefix)
206
     *
207
     * @return bool true if table exists
208
     */
209
    public static function fieldExists(string $fieldname, string $table): bool
210
    {
211
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
212
        trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},");
213
214
        $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
215
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0);
216
    }
217
    /**
218
     * Clone a record in a dB
219
     *
220
     * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false
221
     *
222
     * @param string $tableName name of dB table (without prefix)
223
     * @param string $idField name of field (column) in dB table
224
     * @param int    $id item id to clone
225
     *
226
     * @return mixed
227
     */
228
    public static function cloneRecord(string $tableName, string $idField, int $id)
229
    {
230
        $newId = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $newId is dead and can be removed.
Loading history...
231
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
232
        // copy content of the record you wish to clone
233
        $sql       = "SELECT * FROM $table WHERE $idField='" . (int) $id . "' ";
234
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query($sql), MYSQLI_ASSOC);
235
        if (!$tempTable) {
236
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
237
        }
238
        // set the auto-incremented id's value to blank.
239
        unset($tempTable[$idField]);
240
        // insert cloned copy of the original  record
241
        $sql    = "INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')";
242
        $result = $GLOBALS['xoopsDB']->queryF($sql);
243
        if (!$result) {
244
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
245
        }
246
        // Return the new id
247
        return $GLOBALS['xoopsDB']->getInsertId();
248
    }
249
250
    /**
251
     * Check if dB table table exists
252
     *
253
     * @param string $tablename dB tablename with prefix
254
     * @return bool true if table exists
255
     */
256
    public static function tableExists(string $tablename)
257
    {
258
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
259
260
        return (0 < $GLOBALS['xoopsDB']->getRowsNum($result));
261
    }
262
}
263