SysUtility::truncateHtml()   F
last analyzed

Complexity

Conditions 19
Paths 194

Size

Total Lines 89
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

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

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\Groupmanager\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
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
20
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
21
 * @author       ZySpec <[email protected]>
22
 * @author       Mamba <[email protected]>
23
 */
24
25
use XoopsModules\Groupmanager\{
26
    Helper
27
};
28
29
/**
30
 * Class SysUtility
31
 */
32
class SysUtility
33
{
34
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Groupmanager\Common\VersionChecks requires some properties which are not provided by XoopsModules\Groupmanager\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
     * @param string $text         String to truncate.
52
     * @param int    $length       Length of returned string, including ellipsis.
53
     * @param string $ending       Ending to be appended to the trimmed string.
54
     * @param bool   $exact        If false, $text will not be cut mid-word
55
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
56
     *
57
     * @return string Trimmed string.
58
     */
59
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
60
    {
61
        if ($considerHtml) {
62
            // if the plain text is shorter than the maximum length, return the whole text
63
            if (mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
64
                return $text;
65
            }
66
            // splits all html-tags to scanable lines
67
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
68
            $total_length = mb_strlen($ending);
69
            $open_tags    = [];
70
            $truncate     = '';
71
            foreach ($lines as $line_matchings) {
72
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
73
                if (!empty($line_matchings[1])) {
74
                    // if it's an "empty element" with or without xhtml-conform closing slash
75
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
76
                        // do nothing
77
                        // if tag is a closing tag
78
                    } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
79
                        // delete tag from $open_tags list
80
                        $pos = \array_search($tag_matchings[1], $open_tags, true);
81
                        if (false !== $pos) {
82
                            unset($open_tags[$pos]);
83
                        }
84
                        // if tag is an opening tag
85
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
86
                        // add tag to the beginning of $open_tags list
87
                        \array_unshift($open_tags, mb_strtolower($tag_matchings[1]));
88
                    }
89
                    // add html-tag to $truncate'd text
90
                    $truncate .= $line_matchings[1];
91
                }
92
                // calculate the length of the plain text part of the line; handle entities as one character
93
                $content_length = mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
94
                if ($total_length + $content_length > $length) {
95
                    // the number of characters which are left
96
                    $left            = $length - $total_length;
97
                    $entities_length = 0;
98
                    // search for html entities
99
                    if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, \PREG_OFFSET_CAPTURE)) {
100
                        // calculate the real length of all entities in the legal range
101
                        foreach ($entities[0] as $entity) {
102
                            if ($left >= $entity[1] + 1 - $entities_length) {
103
                                $left--;
104
                                $entities_length += mb_strlen($entity[0]);
105
                            } else {
106
                                // no more characters left
107
                                break;
108
                            }
109
                        }
110
                    }
111
                    $truncate .= mb_substr($line_matchings[2], 0, $left + $entities_length);
112
                    // maximum lenght is reached, so get off the loop
113
                    break;
114
                }
115
                $truncate     .= $line_matchings[2];
116
                $total_length += $content_length;
117
118
                // if the maximum length is reached, get off the loop
119
                if ($total_length >= $length) {
120
                    break;
121
                }
122
            }
123
        } else {
124
            if (mb_strlen($text) <= $length) {
125
                return $text;
126
            }
127
            $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
128
        }
129
        // if the words shouldn't be cut in the middle...
130
        if (!$exact) {
131
            // ...search the last occurance of a space...
132
            $spacepos = mb_strrpos($truncate, ' ');
133
            if (isset($spacepos)) {
134
                // ...and cut the text in this position
135
                $truncate = mb_substr($truncate, 0, $spacepos);
136
            }
137
        }
138
        // add the defined ending to the text
139
        $truncate .= $ending;
140
        if ($considerHtml) {
141
            // close all unclosed html-tags
142
            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...
143
                $truncate .= '</' . $tag . '>';
144
            }
145
        }
146
147
        return $truncate;
148
    }
149
150
    /**
151
     * @param \Xmf\Module\Helper $helper
152
     * @param array|null         $options
153
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
154
     */
155
    public static function getEditor($helper = null, $options = null)
156
    {
157
        /** @var Helper $helper */
158
        if (null === $options) {
159
            $options           = [];
160
            $options['name']   = 'Editor';
161
            $options['value']  = 'Editor';
162
            $options['rows']   = 10;
163
            $options['cols']   = '100%';
164
            $options['width']  = '100%';
165
            $options['height'] = '400px';
166
        }
167
168
        if (null === $helper) {
169
            $helper = Helper::getInstance();
170
        }
171
172
        $isAdmin = $helper->isUserAdmin();
173
174
        if (\class_exists('XoopsFormEditor')) {
175
            if ($isAdmin) {
176
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea');
177
            } else {
178
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea');
179
            }
180
        } else {
181
            $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

181
            $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

181
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
182
        }
183
184
        //        $form->addElement($descEditor);
185
186
        return $descEditor;
187
    }
188
189
    /**
190
     * @param $fieldname
191
     * @param $table
192
     *
193
     * @return bool
194
     */
195
    public static function fieldExists($fieldname, $table)
196
    {
197
        global $xoopsDB;
198
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
199
200
        return ($xoopsDB->getRowsNum($result) > 0);
201
    }
202
203
    /**
204
     * @param array|string $tableName
205
     * @param int          $id_field
206
     * @param int          $id
207
     *
208
     * @return mixed
209
     */
210
    public static function cloneRecord($tableName, $id_field, $id)
211
    {
212
        $new_id = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $new_id is dead and can be removed.
Loading history...
213
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
214
        // copy content of the record you wish to clone 
215
        $sql       = "SELECT * FROM $table WHERE $id_field='$id' ";
216
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query($sql), \MYSQLI_ASSOC);
217
        if (!$tempTable) {
218
            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...
219
        }
220
        // set the auto-incremented id's value to blank.
221
        unset($tempTable[$id_field]);
222
        // insert cloned copy of the original  record 
223
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", \array_values($tempTable)) . "')";
224
        $result = $GLOBALS['xoopsDB']->queryF($sql);
225
        if (!$result) {
226
            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...
227
        }
228
        // Return the new id
229
        $new_id = $GLOBALS['xoopsDB']->getInsertId();
230
231
        return $new_id;
232
    }
233
234
    /**
235
     * @param string $tablename
236
     *
237
     * @return bool
238
     */
239
    public static function tableExists($tablename)
240
    {
241
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
242
243
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0) ? true : false;
244
    }
245
}
246