1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @package s9e\TextFormatter |
5
|
|
|
* @copyright Copyright (c) 2010-2019 The s9e Authors |
6
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php The MIT License |
7
|
|
|
*/ |
8
|
|
|
namespace s9e\TextFormatter\Configurator\Helpers; |
9
|
|
|
|
10
|
|
|
use InvalidArgumentException; |
11
|
|
|
use s9e\TextFormatter\Configurator\Items\Filter; |
12
|
|
|
use s9e\TextFormatter\Configurator\RecursiveParser; |
13
|
|
|
|
14
|
|
|
abstract class FilterHelper |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var RecursiveParser |
18
|
|
|
*/ |
19
|
|
|
protected static $parser; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Return the cached instance of RecursiveParser |
23
|
|
|
* |
24
|
|
|
* @return RecursiveParser |
25
|
|
|
*/ |
26
|
4 |
|
public static function getParser(): RecursiveParser |
27
|
|
|
{ |
28
|
4 |
|
if (!isset(self::$parser)) |
29
|
|
|
{ |
30
|
|
|
self::$parser = new RecursiveParser; |
31
|
|
|
self::$parser->setMatchers([new FilterSyntaxMatcher(self::$parser)]); |
32
|
|
|
} |
33
|
|
|
|
34
|
4 |
|
return self::$parser; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Test whether given filter is a default filter or is in the list of allowed filters |
39
|
|
|
* |
40
|
|
|
* @param string $filter |
41
|
|
|
* @param string[] $allowedFilters |
42
|
|
|
* @return bool |
43
|
|
|
*/ |
44
|
6 |
|
public static function isAllowed(string $filter, array $allowedFilters): bool |
45
|
|
|
{ |
46
|
6 |
|
if (substr($filter, 0, 1) === '#') |
47
|
|
|
{ |
48
|
|
|
// Default filters are always allowed |
49
|
1 |
|
return true; |
50
|
|
|
} |
51
|
5 |
|
$filter = trim(preg_replace('(^\\\\|\\(.*)s', '', $filter)); |
52
|
|
|
|
53
|
5 |
|
return in_array($filter, $allowedFilters, true); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Parse a filter definition |
58
|
|
|
* |
59
|
|
|
* @param string $filterString Filter definition such as "#number" or "strtolower($attrValue)" |
60
|
|
|
* @return array Associative array with a "filter" element and optionally a |
61
|
|
|
* "params" array |
62
|
|
|
*/ |
63
|
4 |
|
public static function parse(string $filterString): array |
64
|
|
|
{ |
65
|
4 |
|
$filterConfig = self::getParser()->parse($filterString)['value']; |
66
|
3 |
|
$filterConfig['filter'] = ltrim($filterConfig['filter'], '\\'); |
67
|
|
|
|
68
|
3 |
|
return $filterConfig; |
69
|
|
|
} |
70
|
|
|
} |