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