-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringHelper.php
More file actions
46 lines (42 loc) · 1.34 KB
/
StringHelper.php
File metadata and controls
46 lines (42 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
namespace WebmanTech\Logger\Helper;
/**
* @internal
*/
final class StringHelper
{
public static function limit(string $value, int $limit): string
{
return (strlen($value) > $limit) ? (substr($value, 0, $limit) . '...') : $value;
}
/**
* 遮蔽敏感字段
* @param array<int, string> $sensitiveKeys
*/
public static function maskSensitiveFields(string $content, array $sensitiveKeys, string $replacement = '***'): string
{
foreach ($sensitiveKeys as $key) {
if (!str_contains($content, $key)) {
continue;
}
if (str_starts_with($content, '{')) {
$quotedKey = preg_quote($key, '/');
$content = (string)preg_replace(
'/"(' . $quotedKey . ')"\s*:\s*".*?"/im',
'"$1":"' . $replacement . '"',
$content
);
} elseif (str_contains($content, '=')) {
$quotedKey = preg_quote($key, '/');
$content = (string)preg_replace(
'/(' . $quotedKey . ')=.+?(&|$)/im',
'$1=' . $replacement . '$2',
$content
);
} else {
$content = "[Contain Sensitive {$key}]";
}
}
return $content;
}
}