| Conditions | 11 |
| Paths | 19 |
| Total Lines | 42 |
| Code Lines | 31 |
| 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 |
||
| 123 | public static function htmlTruncate(string $html, int $length = 255, string $ending = '...'): string |
||
| 124 | { |
||
| 125 | if (\strlen($html) <= $length) { |
||
| 126 | return $html; |
||
| 127 | } |
||
| 128 | $totalLength = \mb_strlen($ending); |
||
| 129 | $openTagsLength = 0; |
||
| 130 | $openTags = []; |
||
| 131 | preg_match_all('/(<.+?>)?([^<>]*)/s', $html, $tags, PREG_SET_ORDER); |
||
| 132 | $html = ''; |
||
| 133 | foreach ($tags as $tag) { |
||
| 134 | $tagLength = \mb_strlen($tag[0]); |
||
| 135 | if (($totalLength + $tagLength + $openTagsLength) >= $length) { |
||
| 136 | if (empty($html)) { |
||
| 137 | preg_match('/^<\s*([^\s>!]+).*?>$/s', $tag[1], $tagName); |
||
| 138 | $openTags[] = $tagName[1]; |
||
| 139 | $html = $tag[1] . self::textTruncate($tag[2], $length - 3, false); |
||
| 140 | } |
||
| 141 | break; |
||
| 142 | } |
||
| 143 | if (!empty($tag[1])) { |
||
| 144 | if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $tag[1])) { |
||
| 145 | // if tag is a closing tag |
||
| 146 | } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $tag[1], $tagName)) { |
||
| 147 | $pos = array_search(strtolower($tagName[1]), $openTags); |
||
| 148 | if (false !== $pos) { |
||
| 149 | unset($openTags[$pos]); |
||
| 150 | $openTagsLength -= \mb_strlen("</{$tagName[1]}>"); |
||
| 151 | } |
||
| 152 | } elseif (preg_match('/^<\s*([^\s>!]+).*?>$/s', $tag[1], $tagName)) { |
||
| 153 | array_unshift($openTags, strtolower($tagName[1])); |
||
| 154 | $openTagsLength += \mb_strlen("</{$tagName[1]}>"); |
||
| 155 | } |
||
| 156 | } |
||
| 157 | $html .= $tag[0]; |
||
| 158 | $totalLength += $tagLength; |
||
| 159 | } |
||
| 160 | $html .= $ending; |
||
| 161 | if ($openTags) { |
||
| 162 | $html .= '</' . implode('></', $openTags) . '>'; |
||
| 163 | } |
||
| 164 | return $html; |
||
| 165 | } |
||
| 191 |