-
Notifications
You must be signed in to change notification settings - Fork 11
/
ScrubberService.php
77 lines (64 loc) · 2.48 KB
/
ScrubberService.php
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace YorCreative\Scrubber\Services;
use Carbon\Carbon;
use Monolog\LogRecord;
use YorCreative\Scrubber\Interfaces\RegexCollectionInterface;
use YorCreative\Scrubber\Repositories\RegexRepository;
use YorCreative\Scrubber\SecretManager\Secret;
class ScrubberService
{
public static function encodeRecord($record): string
{
if (is_array($record)) {
return json_encode($record);
} else {
return $record;
}
}
public static function decodeRecord($scrubbedContent): mixed
{
if (! is_array($scrubbedContent)) {
$scrubbedContent = json_decode($scrubbedContent, true);
}
// set datetime back to DateTimeInterface for papertrail specifically.
if (isset($scrubbedContent['datetime'])) {
$datetime = match (true) {
is_array($scrubbedContent['datetime']) => $scrubbedContent['datetime']['date'],
$scrubbedContent instanceof LogRecord => Carbon::instance($scrubbedContent['datetime']),
default => Carbon::parse($scrubbedContent['datetime'])
};
$scrubbedContent['datetime'] = $datetime;
}
return $scrubbedContent;
}
public static function autoSanitize(string &$jsonContent): void
{
app(RegexRepository::class)->getRegexCollection()->each(function (RegexCollectionInterface $regexClass) use (&$jsonContent) {
$pattern = $regexClass->isSecret()
? Secret::decrypt($regexClass->getPattern())
: $regexClass->getPattern();
if (method_exists($regexClass, 'getReplacementValue')) {
// Check if getReplacementValue() exists on the regex class and if it does, use it.
$replace = $regexClass->getReplacementValue();
} else {
// Otherwise, use the default replacement pattern.
$replace = config('scrubber.redaction');
}
self::patternChecker($pattern, $jsonContent, $replace);
});
}
protected static function patternChecker(string $regexPattern, string &$jsonContent, string $replace): void
{
$hits = 0;
$jsonContent = RegexRepository::checkAndSanitize($regexPattern, $replace, $jsonContent, $hits);
/**
* @todo
* add detection reporting
*
**/
}
public static function getRegexRepository(): RegexRepository
{
return app()->get(RegexRepository::class);
}
}