1 | <?php |
||
13 | final class RegexParser implements ParserInterface |
||
14 | { |
||
15 | /** @var SyntaxInterface */ |
||
16 | private $syntax; |
||
17 | /** @var string */ |
||
18 | private $shortcodeRegex; |
||
19 | /** @var string */ |
||
20 | private $singleShortcodeRegex; |
||
21 | /** @var string */ |
||
22 | private $parametersRegex; |
||
23 | |||
24 | 62 | public function __construct(SyntaxInterface $syntax = null) |
|
31 | |||
32 | /** |
||
33 | * @param string $text |
||
34 | * |
||
35 | * @return ParsedShortcode[] |
||
36 | */ |
||
37 | 113 | public function parse($text) |
|
38 | { |
||
39 | 113 | preg_match_all($this->shortcodeRegex, $text, $matches, PREG_OFFSET_CAPTURE); |
|
40 | |||
41 | // loop instead of array_map to pass the arguments explicitly |
||
42 | 113 | $shortcodes = array(); |
|
43 | 113 | foreach($matches[0] as $match) { |
|
44 | 103 | $offset = mb_strlen(substr($text, 0, $match[1]), 'utf-8'); |
|
45 | 103 | $shortcodes[] = $this->parseSingle($match[0], $offset); |
|
46 | 113 | } |
|
47 | |||
48 | 113 | return array_filter($shortcodes); |
|
49 | } |
||
50 | |||
51 | /** |
||
52 | * @param string $text |
||
53 | * @param int $offset |
||
54 | * |
||
55 | * @return ParsedShortcode |
||
56 | */ |
||
57 | 103 | private function parseSingle($text, $offset) |
|
71 | |||
72 | /** |
||
73 | * @param string $text |
||
74 | * |
||
75 | * @psalm-return array<string,string|null> |
||
76 | */ |
||
77 | 103 | private function parseParameters($text) |
|
78 | { |
||
79 | 103 | preg_match_all($this->parametersRegex, $text, $argsMatches); |
|
80 | |||
81 | // loop because PHP 5.3 can't handle $this properly and I want separate methods |
||
82 | 103 | $return = array(); |
|
83 | 103 | foreach ($argsMatches[1] as $item) { |
|
84 | /** @psalm-var array{0:string,1:string} $parts */ |
||
85 | 42 | $parts = explode($this->syntax->getParameterValueSeparator(), $item, 2); |
|
86 | 42 | $return[trim($parts[0])] = $this->parseValue(isset($parts[1]) ? $parts[1] : null); |
|
87 | 103 | } |
|
88 | |||
89 | 103 | return $return; |
|
90 | } |
||
91 | |||
92 | /** |
||
93 | * @param string|null $value |
||
94 | * |
||
95 | * @return string|null |
||
96 | */ |
||
97 | 42 | private function parseValue($value) |
|
101 | |||
102 | /** |
||
103 | * @param string $value |
||
104 | * |
||
105 | * @return string |
||
106 | */ |
||
107 | 46 | private function extractValue($value) |
|
113 | |||
114 | /** |
||
115 | * @param string $value |
||
116 | * |
||
117 | * @return bool |
||
118 | */ |
||
119 | 46 | private function isDelimitedValue($value) |
|
124 | } |
||
125 |