HtmlFilter::filter()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.9666
c 1
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace League\CommonMark\Util;
15
16
/**
17
 * @psalm-immutable
18
 */
19
final class HtmlFilter
20
{
21
    // Return the entire string as-is
22
    public const ALLOW = 'allow';
23
    // Escape the entire string so any HTML/JS won't be interpreted as such
24
    public const ESCAPE = 'escape';
25
    // Return an empty string
26
    public const STRIP = 'strip';
27
28
    /**
29
     * Runs the given HTML through the given filter
30
     *
31
     * @param string $html   HTML input to be filtered
32
     * @param string $filter One of the HtmlFilter constants
33
     *
34
     * @return string Filtered HTML
35
     *
36
     * @throws \InvalidArgumentException when an invalid $filter is given
37
     *
38
     * @psalm-pure
39
     */
40 288
    public static function filter(string $html, string $filter): string
41
    {
42
        switch ($filter) {
43 288
            case self::STRIP:
44 12
                return '';
45 276
            case self::ESCAPE:
46 12
                return \htmlspecialchars($html, \ENT_NOQUOTES);
47 264
            case self::ALLOW:
48 261
                return $html;
49
            default:
50 3
                throw new \InvalidArgumentException(\sprintf('Invalid filter provided: "%s"', $filter));
51
        }
52
    }
53
}
54