Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
19 / 19 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
AllowedCssInSpanSanitizer | |
100.00% |
19 / 19 |
|
100.00% |
3 / 3 |
7 | |
100.00% |
1 / 1 |
getSupportedElements | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getSupportedAttributes | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
sanitizeAttribute | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
5 |
1 | <?php |
2 | namespace Apie\CommonValueObjects\Bridge\Symfony; |
3 | |
4 | use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; |
5 | use Symfony\Component\HtmlSanitizer\Visitor\AttributeSanitizer\AttributeSanitizerInterface; |
6 | |
7 | final class AllowedCssInSpanSanitizer implements AttributeSanitizerInterface |
8 | { |
9 | private const ALLOWED_CSS = [ |
10 | '/text-decoration-line\s*:\s*underline\s*(;|$)/i' => 'text-decoration-line:underline;', |
11 | '/text-decoration-line\s*:\s*line-through\s*(;|$)/i' => 'text-decoration-line:line-through;', |
12 | '/font-weight\s*:\s*bold\s*(;|$)/i' => 'font-weight:bold;', |
13 | '/font-style\s*:\s*italic\s*(;|$)/i' => 'font-style:italic;', |
14 | '/font-size\s*:\s*x-small\s*(;|$)/i' => 'font-size:x-small;', |
15 | '/font-size\s*:\s*small\s*(;|$)/i' => 'font-size:small;', |
16 | '/font-size\s*:\s*medium\s*(;|$)/i' => 'font-size:medium;', |
17 | '/font-size\s*:\s*large\s*(;|$)/i' => 'font-size:large;', |
18 | '/font-size\s*:\s*x-large\s*(;|$)/i' => 'font-size:x-large;', |
19 | '/font-size\s*:\s*xx-large\s*(;|$)/i' => 'font-size:xx-large;', |
20 | '/font-size\s*:\s*xxx-large\s*(;|$)/i' => 'font-size:xxx-large;', |
21 | ]; |
22 | |
23 | /** |
24 | * @return list<string> |
25 | */ |
26 | public function getSupportedElements(): array |
27 | { |
28 | return ['span']; |
29 | } |
30 | |
31 | /** |
32 | * @return list<string> |
33 | */ |
34 | public function getSupportedAttributes(): array |
35 | { |
36 | return ['style']; |
37 | } |
38 | |
39 | /** |
40 | * Returns the sanitized value of a given attribute for the given element. |
41 | */ |
42 | public function sanitizeAttribute(string $element, string $attribute, string $value, HtmlSanitizerConfig $config): ?string |
43 | { |
44 | $newValue = ''; |
45 | $found = true; |
46 | while ($found) { |
47 | $found = false; |
48 | $value = preg_replace_callback( |
49 | '/(;|^)\s*(?<color>(background-|)color\s*:[^;]*(;|$))/i', |
50 | function (array $matches) use (&$newValue, &$found): string { |
51 | $newValue .= $matches['color']; |
52 | $found = true; |
53 | return ''; |
54 | }, |
55 | $value |
56 | ); |
57 | } |
58 | foreach (self::ALLOWED_CSS as $regex => $css) { |
59 | if (preg_match($regex, $value)) { |
60 | $newValue .= $css; |
61 | } |
62 | } |
63 | |
64 | return $newValue ? rtrim($newValue, ';') : null; |
65 | } |
66 | } |