Completed
Push — master ( eb71aa...0ea014 )
by Kevin
02:20
created

string.php ➔ truncate_word()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 3
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Kevin Bond <[email protected]>
4
 */
5
namespace zenstruck\string;
6
7
/**
8
 * Replaces "&nbsp;" with a single space and converts multiple sequential spaces into a single space.
9
 *
10
 * @param string $str
11
 *
12
 * @return string
13
 */
14
function remove_whitespace($str)
15
{
16 20
    return preg_replace('/\s+/', ' ', str_replace('&nbsp;', ' ', $str));
17
}
18
19
/**
20
 * Similar to core "trim" but returns null instead of an empty string
21
 * When an array is passed, all elements get processed recursively.
22
 *
23
 * @param string|array $data
24
 * @param null|string  $character_mask
25
 *
26
 * @return array|null|string
27
 */
28
function null_trim($data, $character_mask = null)
29
{
30 13
    if (is_array($data)) {
31 3
        return array_map(
32
            function ($value) use ($character_mask) {
33 3
                return null_trim($value, $character_mask);
34 3
            },
35
            $data
36
        );
37
    }
38
39 13
    $trimmedValue = null === $character_mask ? trim($data) : trim($data, $character_mask);
40
41 13
    if ($trimmedValue === '') {
42 6
        return null;
43
    }
44
45 10
    return $trimmedValue;
46
}
47
48
/**
49
 * Truncates text to a length without breaking words.
50
 *
51
 * @param string $str
52
 * @param int    $length
53
 * @param string $suffix
54
 *
55
 * @return string
56
 */
57
function truncate_word($str, $length = 255, $suffix = '...')
58
{
59 16
    $output = remove_whitespace(trim($str));
60
61 16
    if (strlen($output) > $length) {
62 10
        $output = wordwrap($output, $length - strlen($suffix));
63 10
        $output = substr($output, 0, strpos($output, "\n"));
64 10
        $output .= $suffix;
65
    }
66
67 16
    return strlen($output) > $length ? '' : $output;
68
}
69