Completed
Push — master ( 1316f3...b7872d )
by Aydin
26s queued 12s
created

StringUtil   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 42
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A wordwrap() 0 25 5
A stripAnsiEscapeSequence() 0 3 1
A length() 0 3 2
1
<?php
2
3
namespace PhpSchool\CliMenu\Util;
4
5
/**
6
 * @author Michael Woodward <[email protected]>
7
 */
8
class StringUtil
9
{
10
    /**
11
     * Minimal multi-byte wordwrap implementation
12
     * which also takes break length into consideration
13
     */
14
    public static function wordwrap(string $string, int $width, string $break = "\n") : string
15
    {
16
        return implode(
17
            $break,
18
            array_map(function (string $line) use ($width, $break) {
19
                $line = rtrim($line);
20
                if (mb_strlen($line) <= $width) {
21
                    return $line;
22
                }
23
                
24
                $words  = explode(' ', $line);
25
                $line   = '';
26
                $actual = '';
27
                foreach ($words as $word) {
28
                    if (mb_strlen($actual . $word) <= $width) {
29
                        $actual .= $word . ' ';
30
                    } else {
31
                        if ($actual !== '') {
32
                            $line .= rtrim($actual) . $break;
33
                        }
34
                        $actual = $word . ' ';
35
                    }
36
                }
37
                return $line . trim($actual);
38
            }, explode("\n", $string))
39
        );
40
    }
41
42
    public static function stripAnsiEscapeSequence(string $str) : string
43
    {
44
        return (string) preg_replace('/\x1b[^m]*m/', '', $str);
45
    }
46
47
    public static function length(string $str, bool $ignoreAnsiEscapeSequence = true) : int
48
    {
49
        return mb_strlen($ignoreAnsiEscapeSequence ? self::stripAnsiEscapeSequence($str) : $str);
50
    }
51
}
52