Total Complexity | 49 |
Total Lines | 392 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
Complex classes like SysUtility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SysUtility, and based on these observations, apply Extract Interface, too.
1 | <?php declare(strict_types=1); |
||
34 | class SysUtility |
||
35 | { |
||
36 | use VersionChecks; |
||
|
|||
37 | |||
38 | //checkVerXoops, checkVerPhp Traits |
||
39 | |||
40 | use ServerStats; |
||
41 | |||
42 | // getServerStats Trait |
||
43 | |||
44 | use FilesManagement; |
||
45 | |||
46 | // Files Management Trait |
||
47 | // use ModuleStats; // ModuleStats Trait |
||
48 | |||
49 | //--------------- Common module methods ----------------------------- |
||
50 | |||
51 | /** |
||
52 | * Access the only instance of this class |
||
53 | */ |
||
54 | public static function getInstance(): self |
||
55 | { |
||
56 | static $instance; |
||
57 | if (null === $instance) { |
||
58 | $instance = new static(); |
||
59 | } |
||
60 | |||
61 | return $instance; |
||
62 | } |
||
63 | |||
64 | public static function selectSorting(string $text, string $form_sort): string |
||
65 | { |
||
66 | global $start, $order, $sort; |
||
67 | |||
68 | $selectView = ''; |
||
69 | $helper = Helper::getInstance(); |
||
70 | |||
71 | //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16'); |
||
72 | $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16')); |
||
73 | |||
74 | $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>'; |
||
75 | //$sorts = $sort == 'asc' ? 'desc' : 'asc'; |
||
76 | if ($form_sort == $sort) { |
||
77 | $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png'; |
||
78 | $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png'; |
||
79 | } else { |
||
80 | $sel1 = 'asc.png'; |
||
81 | $sel2 = 'desc.png'; |
||
82 | } |
||
83 | $selectView .= ' <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>'; |
||
84 | $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>'; |
||
85 | $selectView .= '</form>'; |
||
86 | |||
87 | return $selectView; |
||
88 | } |
||
89 | |||
90 | /***************Blocks***************/ |
||
91 | public static function blockAddCatSelect(array $cats): string |
||
92 | { |
||
93 | $catSql = ''; |
||
94 | if (!empty($cats)) { |
||
95 | $catSql = '(' . \current($cats); |
||
96 | \array_shift($cats); |
||
97 | // foreach ($cats as $cat) { |
||
98 | // $catSql .= ',' . $cat; |
||
99 | // } |
||
100 | $catSql .= \implode(',', $cats); |
||
101 | $catSql .= ')'; |
||
102 | } |
||
103 | |||
104 | return $catSql; |
||
105 | } |
||
106 | |||
107 | public static function metaKeywords(string $content): void |
||
108 | { |
||
109 | global $xoopsTpl, $xoTheme; |
||
110 | $myts = \MyTextSanitizer::getInstance(); |
||
111 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
112 | if (\is_object($xoTheme)) { |
||
113 | $xoTheme->addMeta('meta', 'keywords', \strip_tags($content)); |
||
114 | } else { // Compatibility for old Xoops versions |
||
115 | $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content)); |
||
116 | } |
||
117 | } |
||
118 | |||
119 | public static function metaDescription(string $content): void |
||
120 | { |
||
121 | global $xoopsTpl, $xoTheme; |
||
122 | $myts = \MyTextSanitizer::getInstance(); |
||
123 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
124 | if (\is_object($xoTheme)) { |
||
125 | $xoTheme->addMeta('meta', 'description', \strip_tags($content)); |
||
126 | } else { // Compatibility for old Xoops versions |
||
127 | $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content)); |
||
128 | } |
||
129 | } |
||
130 | |||
131 | public static function enumerate(string $tableName, string $columnName): ?array |
||
132 | { |
||
133 | $table = $GLOBALS['xoopsDB']->prefix($tableName); |
||
134 | |||
135 | // $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS |
||
136 | // WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'") |
||
137 | // || exit ($GLOBALS['xoopsDB']->error()); |
||
138 | |||
139 | $sql = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"'; |
||
140 | $result = $GLOBALS['xoopsDB']->query($sql); |
||
141 | if (!$result instanceof \mysqli_result) { |
||
142 | // \trigger_error($GLOBALS['xoopsDB']->error()); |
||
143 | $logger = \XoopsLogger::getInstance(); |
||
144 | $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__); |
||
145 | |||
146 | return null; |
||
147 | } |
||
148 | |||
149 | $row = $GLOBALS['xoopsDB']->fetchBoth($result); |
||
150 | $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6))); |
||
151 | |||
152 | return $enumList; |
||
153 | } |
||
154 | |||
155 | /** |
||
156 | * Clone a record in a dB |
||
157 | * |
||
158 | * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false |
||
159 | * |
||
160 | * @param string $tableName name of dB table (without prefix) |
||
161 | * @param string $idField name of field (column) in dB table |
||
162 | * @param int $id item id to clone |
||
163 | */ |
||
164 | public static function cloneRecord(string $tableName, string $idField, int $id): ?int |
||
206 | } |
||
207 | |||
208 | /** |
||
209 | * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags |
||
210 | * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags |
||
211 | * www.cakephp.org |
||
212 | * |
||
213 | * @TODO: Refactor to consider HTML5 & void (self-closing) elements |
||
214 | * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php |
||
215 | * |
||
216 | * @param string $text String to truncate. |
||
217 | * @param int|null $length Length of returned string, including ellipsis. |
||
218 | * @param string $ending Ending to be appended to the trimmed string. |
||
219 | * @param bool $exact If false, $text will not be cut mid-word |
||
220 | * @param bool $considerHtml If true, HTML tags would be handled correctly |
||
221 | * |
||
222 | * @return string Trimmed string. |
||
223 | */ |
||
224 | public static function truncateHtml( |
||
225 | string $text, |
||
226 | ?int $length = 100, |
||
227 | string $ending = '...', |
||
228 | bool $exact = false, |
||
229 | bool $considerHtml = true |
||
230 | ): string { |
||
231 | $openTags = []; |
||
232 | if ($considerHtml) { |
||
233 | // if the plain text is shorter than the maximum length, return the whole text |
||
234 | if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) { |
||
235 | return $text; |
||
236 | } |
||
237 | // splits all html-tags to scanable lines |
||
238 | \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER); |
||
239 | $totalLength = \mb_strlen($ending); |
||
240 | //$openTags = []; |
||
241 | $truncate = ''; |
||
242 | foreach ($lines as $lineMatchings) { |
||
243 | // if there is any html-tag in this line, handle it and add it (uncounted) to the output |
||
244 | if (!empty($lineMatchings[1])) { |
||
245 | // if it's an "empty element" with or without xhtml-conform closing slash |
||
246 | if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) { |
||
247 | // do nothing |
||
248 | // if tag is a closing tag |
||
249 | } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) { |
||
250 | // delete tag from $openTags list |
||
251 | $pos = \array_search($tagMatchings[1], $openTags, true); |
||
252 | if (false !== $pos) { |
||
253 | unset($openTags[$pos]); |
||
254 | } |
||
255 | // if tag is an opening tag |
||
256 | } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) { |
||
257 | // add tag to the beginning of $openTags list |
||
258 | \array_unshift($openTags, \mb_strtolower($tagMatchings[1])); |
||
259 | } |
||
260 | // add html-tag to $truncate'd text |
||
261 | $truncate .= $lineMatchings[1]; |
||
262 | } |
||
263 | // calculate the length of the plain text part of the line; handle entities as one character |
||
264 | $contentLength = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2])); |
||
265 | if ($totalLength + $contentLength > $length) { |
||
266 | // the number of characters which are left |
||
267 | $left = $length - $totalLength; |
||
268 | $entitiesLength = 0; |
||
269 | // search for html entities |
||
270 | if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) { |
||
271 | // calculate the real length of all entities in the legal range |
||
272 | foreach ($entities[0] as $entity) { |
||
273 | if ($left >= $entity[1] + 1 - $entitiesLength) { |
||
274 | $left--; |
||
275 | $entitiesLength += \mb_strlen($entity[0]); |
||
276 | } else { |
||
277 | // no more characters left |
||
278 | break; |
||
279 | } |
||
280 | } |
||
281 | } |
||
282 | $truncate .= \mb_substr($lineMatchings[2], 0, $left + $entitiesLength); |
||
283 | // maximum length is reached, so get off the loop |
||
284 | break; |
||
285 | } |
||
286 | $truncate .= $lineMatchings[2]; |
||
287 | $totalLength += $contentLength; |
||
288 | |||
289 | // if the maximum length is reached, get off the loop |
||
290 | if ($totalLength >= $length) { |
||
291 | break; |
||
292 | } |
||
293 | } |
||
294 | } else { |
||
295 | if (\mb_strlen($text) <= $length) { |
||
296 | return $text; |
||
297 | } |
||
298 | $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending)); |
||
299 | } |
||
300 | // if the words shouldn't be cut in the middle... |
||
301 | if (!$exact) { |
||
302 | // ...search the last occurance of a space... |
||
303 | $spacepos = \mb_strrpos($truncate, ' '); |
||
304 | if (false !== $spacepos) { |
||
305 | // ...and cut the text in this position |
||
306 | $truncate = \mb_substr($truncate, 0, $spacepos); |
||
307 | } |
||
308 | } |
||
309 | // add the defined ending to the text |
||
310 | $truncate .= $ending; |
||
311 | if ($considerHtml) { |
||
312 | // close all unclosed html-tags |
||
313 | foreach ($openTags as $tag) { |
||
314 | $truncate .= '</' . $tag . '>'; |
||
315 | } |
||
316 | } |
||
317 | |||
318 | return $truncate; |
||
319 | } |
||
320 | |||
321 | /** |
||
322 | * Get correct text editor based on user rights |
||
323 | * |
||
324 | * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor |
||
325 | */ |
||
326 | public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null): ?\XoopsFormTextArea |
||
360 | } |
||
361 | |||
362 | /** |
||
363 | * Check if column in dB table exists |
||
364 | * |
||
365 | * @param string $fieldname name of dB table field |
||
366 | * @param string $table name of dB table (including prefix) |
||
367 | * |
||
368 | * @return bool true if table exists |
||
369 | * @deprecated |
||
370 | */ |
||
371 | public static function fieldExists(string $fieldname, string $table): bool |
||
372 | { |
||
373 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
374 | \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},"); |
||
375 | |||
376 | $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); |
||
377 | |||
378 | return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0); |
||
379 | } |
||
380 | |||
381 | /** |
||
382 | * Function responsible for checking if a directory exists, we can also write in and create an index.html file |
||
383 | * |
||
384 | * @param string $folder The full path of the directory to check |
||
385 | */ |
||
386 | public static function prepareFolder(string $folder): void |
||
387 | { |
||
388 | try { |
||
389 | if (!@\mkdir($folder) && !\is_dir($folder)) { |
||
390 | throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder)); |
||
391 | } |
||
392 | file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>'); |
||
393 | } catch (\Throwable $e) { |
||
394 | echo 'Caught exception: ', $e->getMessage(), "\n", '<br>'; |
||
395 | } |
||
396 | } |
||
397 | |||
398 | /** |
||
399 | * Check if dB table exists |
||
400 | * |
||
401 | * @param string $tablename dB tablename with prefix |
||
402 | * @return bool true if table exists |
||
403 | */ |
||
404 | public static function tableExists(string $tablename): bool |
||
405 | { |
||
406 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
407 | \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}"); |
||
408 | $GLOBALS['xoopsLogger']->addDeprecated( |
||
409 | \basename(\dirname(__DIR__, 2)) . ' Module: ' . __FUNCTION__ . ' function is deprecated, please use Xmf\Database\Tables method(s) instead.' . " Called from {$trace[0]['file']}line {$trace[0]['line']}" |
||
410 | ); |
||
411 | $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'"); |
||
412 | |||
413 | return $GLOBALS['xoopsDB']->getRowsNum($result) > 0; |
||
414 | } |
||
415 | |||
416 | /** |
||
417 | * Add a field to a mysql table |
||
418 | * |
||
419 | * @return bool|\mysqli_result |
||
420 | */ |
||
421 | public static function addField(string $field, string $table) |
||
426 | } |
||
427 | } |
||
428 |