1 | <?php |
||
2 | |||
3 | namespace Lagdo\DbAdmin\Driver\Utils; |
||
4 | |||
5 | use function str_replace; |
||
6 | use function preg_replace; |
||
7 | use function preg_match; |
||
8 | use function htmlspecialchars; |
||
9 | |||
10 | class Str |
||
11 | { |
||
12 | /** |
||
13 | * @inheritDoc |
||
14 | */ |
||
15 | public function html($string): string |
||
16 | { |
||
17 | if(!$string) { |
||
18 | return ''; |
||
19 | } |
||
20 | $string = str_replace("\n", '<br>', $string); |
||
21 | return str_replace("\0", '�', htmlspecialchars($string, ENT_QUOTES, 'utf-8')); |
||
22 | } |
||
23 | |||
24 | /** |
||
25 | * @inheritDoc |
||
26 | */ |
||
27 | public function number(string $value): string |
||
28 | { |
||
29 | return preg_replace('~[^0-9]+~', '', $value); |
||
30 | } |
||
31 | |||
32 | /** |
||
33 | * @inheritDoc |
||
34 | */ |
||
35 | public function isUtf8(string $value): bool |
||
36 | { |
||
37 | // don't print control chars except \t\r\n |
||
38 | return (preg_match('~~u', $value) && !preg_match('~[\0-\x8\xB\xC\xE-\x1F]~', $value)); |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * Create repeat pattern for preg |
||
43 | * |
||
44 | * @param string $pattern |
||
45 | * @param int $length |
||
46 | * |
||
47 | * @return string |
||
48 | */ |
||
49 | private function repeatPattern(string $pattern, int $length): string |
||
50 | { |
||
51 | // fix for Compilation failed: number too big in {} quantifier |
||
52 | // can create {0,0} which is OK |
||
53 | $times = round($length / 65535, 0, PHP_ROUND_HALF_DOWN); |
||
54 | return str_repeat("$pattern{0,65535}", $times) . "$pattern{0," . ($length % 65535) . '}'; |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
55 | } |
||
56 | |||
57 | /** |
||
58 | * Shorten UTF-8 string |
||
59 | * |
||
60 | * @param string $string |
||
61 | * @param int $length |
||
62 | * @param string $suffix |
||
63 | * |
||
64 | * @return string |
||
65 | */ |
||
66 | public function shortenUtf8(string $string, int $length = 80, string $suffix = ''): string |
||
67 | { |
||
68 | if (!preg_match('(^(' . $this->repeatPattern("[\t\r\n -\x{10FFFF}]", $length) . ')($)?)u', $string, $match)) { |
||
69 | // ~s causes trash in $match[2] under some PHP versions, (.|\n) is slow |
||
70 | preg_match('(^(' . $this->repeatPattern("[\t\r\n -~]", $length) . ')($)?)', $string, $match); |
||
71 | } |
||
72 | return $this->html($match[1]) . $suffix . (isset($match[2]) ? '' : '<i>…</i>'); |
||
73 | } |
||
74 | } |
||
75 |