|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
namespace Sirius\Filtration\Filter; |
|
4
|
|
|
|
|
5
|
|
|
class Truncate extends AbstractFilter |
|
6
|
|
|
{ |
|
7
|
|
|
const OPTION_LIMIT = 'limit'; |
|
8
|
|
|
|
|
9
|
|
|
const OPTION_ELLIPSIS = 'ellipsis'; |
|
10
|
|
|
|
|
11
|
|
|
const OPTION_BREAK_WORDS = 'break_words'; |
|
12
|
|
|
|
|
13
|
|
|
protected $options = [ |
|
14
|
|
|
self::OPTION_LIMIT => false, |
|
15
|
|
|
self::OPTION_BREAK_WORDS => true, |
|
16
|
|
|
self::OPTION_ELLIPSIS => '...' |
|
17
|
|
|
]; |
|
18
|
|
|
|
|
19
|
9 |
|
public function filterSingle($value, string $valueIdentifier = null) |
|
20
|
|
|
{ |
|
21
|
|
|
// not a string, move along |
|
22
|
9 |
|
if (! is_string($value)) { |
|
23
|
1 |
|
return $value; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
8 |
|
if (! $this->options[self::OPTION_LIMIT] || strlen($value) <= $this->options[self::OPTION_LIMIT]) { |
|
27
|
2 |
|
return $value; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
6 |
|
$limit = (int) $this->options[self::OPTION_LIMIT]; |
|
31
|
6 |
|
$firstSpace = strpos($value, ' '); |
|
32
|
|
|
|
|
33
|
|
|
// in case word breaking is not allowed find the previous space |
|
34
|
6 |
|
if (!$this->options[self::OPTION_BREAK_WORDS]) { |
|
35
|
3 |
|
if ($firstSpace === false) { |
|
36
|
1 |
|
$limit = strlen($value); |
|
37
|
|
|
} else { |
|
38
|
2 |
|
$limit = max($firstSpace, min($limit, (int)strrpos(substr($value, 0, $limit), ' '))); |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
6 |
|
$isWordBreaker = false; |
|
|
|
|
|
|
43
|
6 |
|
if (substr($value, $limit, 1) != ' ' |
|
44
|
6 |
|
&& substr($value, $limit + 1, 1) != ' ') { |
|
45
|
2 |
|
$isWordBreaker = true; |
|
|
|
|
|
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
6 |
|
$truncated = rtrim(substr($value, 0, $limit)); |
|
49
|
|
|
|
|
50
|
6 |
|
if ($this->options[self::OPTION_ELLIPSIS] |
|
51
|
6 |
|
&& $truncated != $value) { |
|
52
|
5 |
|
$truncated .= $this->options[self::OPTION_ELLIPSIS]; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
6 |
|
return $truncated; |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVarassignment in line 1 and the$higherassignment in line 2 are dead. The first because$myVaris never used and the second because$higheris always overwritten for every possible time line.