-
Notifications
You must be signed in to change notification settings - Fork 0
/
SanitizerTrait.php
111 lines (94 loc) · 2.88 KB
/
SanitizerTrait.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
namespace App\SanitizeTrait;
use App\SanitizeTrait\SanitizeFilters\SanitizeFilterInterface;
use InvalidArgumentException;
trait SanitizerTrait
{
private array $defaultFilters = [];
/**
* Add a filter to be used when there are no filters passed to sanitize().
* Throws an InvalidArgumentException if the id already exists.
*
* @param SanitizeFilterInterface $filter Filter to be added
* @param string|null $id (optional) ID for the filter to be able to remove it later.
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function addDefaultFilter(
SanitizeFilterInterface $filter,
?string $id = null
): self
{
if (!isset($id)) {
$this->defaultFilters[] = $filter;
return $this;
}
if (array_key_exists($id, $this->defaultFilters))
throw new InvalidArgumentException("Provided id already exists");
$this->defaultFilters[$id] = $filter;
return $this;
}
/**
* Remove a filter by its id. Throws an InvalidArgumentException if the id does not exist.
*
* @param string $id
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function removeDefaultFilter(string $id): self
{
if (!array_key_exists($id, $this->defaultFilters))
throw new InvalidArgumentException("Provided id is not associated with any filter");
unset($this->defaultFilters[$id]);
return $this;
}
/**
* Removes all stored filters to start from a clean slate.
*
* @return $this
*/
public function resetDefaultFilters(): self
{
$this->defaultFilters = [];
return $this;
}
/**
* Sanitize the provided string with the stored filters, or the provided filters.
*
* @param string $string
* @param SanitizeFilterInterface[]|null $filters
* @param string|null $replacementChar
* @param int|null $replacementLength
*
* @throws InvalidArgumentException
*
* @return string
*/
public function sanitize(
string $string,
?array $filters = null,
?string $replacementChar = null,
?int $replacementLength = null
): string
{
if (!isset($filters)) {
$filters = $this->defaultFilters;
}
foreach ($filters as $id => $filter) {
if (!($filter instanceof SanitizeFilterInterface))
throw new InvalidArgumentException(
sprintf(
"Expected all filters to implement SanitizeFilterInterface, but filter %s does not",
$id
)
);
}
foreach ($filters as $filter)
$string = $filter->sanitize($string, $replacementChar, $replacementLength);
return $string;
}
}