| Conditions | 12 |
| Paths | 38 |
| Total Lines | 45 |
| Code Lines | 33 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
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:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 67 | public static function htmlTruncateByWords(string $html, int $length = 0, string $ending = '...'): string |
||
| 68 | { |
||
| 69 | if (!$length) { |
||
| 70 | $length = Config::main('listview_max_textlength'); |
||
| 71 | } |
||
| 72 | if (\strlen(strip_tags($html)) <= $length) { |
||
| 73 | return $html; |
||
| 74 | } |
||
| 75 | $totalLength = \mb_strlen($ending); |
||
| 76 | $openTagsLength = 0; |
||
| 77 | $openTags = []; |
||
| 78 | preg_match_all('/(<.+?>)?([^<>]*)/s', $html, $tags, PREG_SET_ORDER); |
||
| 79 | $html = ''; |
||
| 80 | foreach ($tags as $tag) { |
||
| 81 | $tagLength = \mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $tag[2])); |
||
| 82 | if (($totalLength + $tagLength + $openTagsLength) >= $length) { |
||
| 83 | if (empty($html)) { |
||
| 84 | preg_match('/^<\s*([^\s>!]+).*?>$/s', $tag[1], $tagName); |
||
| 85 | $openTags[] = $tagName[1]; |
||
| 86 | $html = $tag[1] . self::textTruncate($tag[2], $length - 3, false); |
||
| 87 | } |
||
| 88 | break; |
||
| 89 | } |
||
| 90 | if (!empty($tag[1])) { |
||
| 91 | if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $tag[1])) { |
||
| 92 | // if tag is a closing tag |
||
| 93 | } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $tag[1], $tagName)) { |
||
| 94 | $pos = array_search(strtolower($tagName[1]), $openTags); |
||
| 95 | if (false !== $pos) { |
||
| 96 | unset($openTags[$pos]); |
||
| 97 | $openTagsLength -= \mb_strlen("</{$tagName[1]}>"); |
||
| 98 | } |
||
| 99 | } elseif (preg_match('/^<\s*([^\s>!]+).*?>$/s', $tag[1], $tagName)) { |
||
| 100 | array_unshift($openTags, strtolower($tagName[1])); |
||
| 101 | $openTagsLength += \mb_strlen("</{$tagName[1]}>"); |
||
| 102 | } |
||
| 103 | } |
||
| 104 | $html .= $tag[0]; |
||
| 105 | $totalLength += $tagLength; |
||
| 106 | } |
||
| 107 | $html .= $ending; |
||
| 108 | if ($openTags) { |
||
| 109 | $html .= '</' . implode('></', $openTags) . '>'; |
||
| 110 | } |
||
| 111 | return $html; |
||
| 112 | } |
||
| 191 |