-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathProcessor.php
More file actions
275 lines (237 loc) · 9.06 KB
/
Processor.php
File metadata and controls
275 lines (237 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?php
namespace Thunder\Shortcode\Processor;
use Thunder\Shortcode\Event\ReplaceShortcodesEvent;
use Thunder\Shortcode\Event\FilterShortcodesEvent;
use Thunder\Shortcode\Event\RewriteReplacementsEvent;
use Thunder\Shortcode\EventContainer\EventContainerInterface;
use Thunder\Shortcode\Events;
use Thunder\Shortcode\HandlerContainer\HandlerContainerInterface as Handlers;
use Thunder\Shortcode\Parser\ParserInterface;
use Thunder\Shortcode\Shortcode\ReplacedShortcode;
use Thunder\Shortcode\Shortcode\ParsedShortcodeInterface;
use Thunder\Shortcode\Shortcode\ProcessedShortcode;
use Thunder\Shortcode\Shortcode\ShortcodeInterface;
/**
* @author Tomasz Kowalczyk <tomasz@kowalczyk.cc>
*/
final class Processor implements ProcessorInterface
{
/** @var Handlers */
private $handlers;
/** @var ParserInterface */
private $parser;
/** @var EventContainerInterface|null */
private $eventContainer;
/** @var int|null */
private $recursionDepth; // infinite recursion
/** @var int|null */
private $maxIterations = 1; // one iteration
/** @var bool */
private $autoProcessContent = true; // automatically process shortcode content
public function __construct(ParserInterface $parser, Handlers $handlers)
{
$this->parser = $parser;
$this->handlers = $handlers;
}
/**
* Entry point for shortcode processing. Implements iterative algorithm for
* both limited and unlimited number of iterations.
*
* @param string $text Text to process
*
* @return string
*/
public function process($text)
{
$iterations = $this->maxIterations === null ? 1 : $this->maxIterations;
$context = new ProcessorContext();
$context->processor = $this;
while ($iterations--) {
$context->iterationNumber++;
$newText = $this->processIteration($text, $context, null);
if ($newText === $text) {
break;
}
$text = $newText;
$iterations += $this->maxIterations === null ? 1 : 0;
}
return $text;
}
/**
* @param string $name
* @param object $event
*
* @return object
*/
private function dispatchEvent($name, $event)
{
if(null === $this->eventContainer) {
return $event;
}
$handlers = $this->eventContainer->getListeners($name);
foreach($handlers as $handler) {
$handler($event);
}
return $event;
}
/**
* @param string $text
*
* @return string
*/
private function processIteration($text, ProcessorContext $context, ProcessedShortcode $parent = null)
{
if (null !== $this->recursionDepth && $context->recursionLevel > $this->recursionDepth) {
return $text;
}
$context->parent = $parent;
$context->text = $text;
$filterEvent = new FilterShortcodesEvent($this->parser->parse($text), $parent);
$this->dispatchEvent(Events::FILTER_SHORTCODES, $filterEvent);
$shortcodes = $filterEvent->getShortcodes();
$replaces = array();
$baseOffset = $parent && $shortcodes
? (int)mb_strpos($parent->getShortcodeText(), $shortcodes[0]->getText(), 0, 'utf-8') - $shortcodes[0]->getOffset() + $parent->getOffset()
: 0;
foreach ($shortcodes as $shortcode) {
$name = $shortcode->getName();
$hasNamePosition = array_key_exists($name, $context->namePosition);
$context->baseOffset = $baseOffset + $shortcode->getOffset();
$context->position++;
$context->namePosition[$name] = $hasNamePosition ? $context->namePosition[$name] + 1 : 1;
$context->shortcodeText = $shortcode->getText();
$context->offset = $shortcode->getOffset();
$context->shortcode = $shortcode;
$context->textContent = (string)$shortcode->getContent();
$handler = $this->handlers->get($name);
$replace = $this->processHandler($shortcode, $context, $handler);
$replaces[] = new ReplacedShortcode($shortcode, $replace);
}
$rewriteEvent = new RewriteReplacementsEvent($replaces);
$this->dispatchEvent(Events::REWRITE_REPLACEMENTS, $rewriteEvent);
$replaces = $rewriteEvent->getRewritten();
$applyEvent = new ReplaceShortcodesEvent($text, $replaces, $parent);
$this->dispatchEvent(Events::REPLACE_SHORTCODES, $applyEvent);
return $applyEvent->hasResult() ? (string)$applyEvent->getResult() : $this->applyReplaces($text, $replaces);
}
/**
* @param string $text
* @param ReplacedShortcode[] $replaces
*
* @return string
*/
private function applyReplaces($text, array $replaces)
{
foreach(array_reverse($replaces) as $s) {
$offset = $s->getOffset();
$length = mb_strlen($s->getText(), 'utf-8');
$textLength = mb_strlen($text, 'utf-8');
$text = mb_substr($text, 0, $offset, 'utf-8').$s->getReplacement().mb_substr($text, $offset + $length, $textLength, 'utf-8');
}
return $text;
}
/**
* @psalm-param (callable(ShortcodeInterface):string)|null $handler
* @return string
*/
private function processHandler(ParsedShortcodeInterface $parsed, ProcessorContext $context, $handler)
{
$processed = ProcessedShortcode::createFromContext(clone $context);
$content = $this->processRecursion($processed, $context);
$processed = $processed->withContent($content);
if($handler) {
return $handler($processed);
}
$state = $parsed->getText();
$length = (int)mb_strlen($processed->getTextContent(), 'utf-8');
$offset = (int)mb_strrpos($state, $processed->getTextContent(), 0, 'utf-8');
return mb_substr($state, 0, $offset, 'utf-8').(string)$processed->getContent().mb_substr($state, $offset + $length, mb_strlen($state, 'utf-8'), 'utf-8');
}
/** @return string|null */
private function processRecursion(ProcessedShortcode $shortcode, ProcessorContext $context)
{
$content = $shortcode->getContent();
if ($this->autoProcessContent && null !== $content) {
$context->recursionLevel++;
// this is safe from using max iterations value because it's manipulated in process() method
$content = $this->processIteration($content, clone $context, $shortcode);
$context->recursionLevel--;
return $content;
}
return $content;
}
/**
* Container for event handlers used in this processor.
*
* @param EventContainerInterface $eventContainer
*
* @return self
*/
public function withEventContainer(EventContainerInterface $eventContainer)
{
$self = clone $this;
$self->eventContainer = $eventContainer;
return $self;
}
/**
* Recursion depth level, null means infinite, any integer greater than or
* equal to zero sets value (number of recursion levels). Zero disables
* recursion. Defaults to null.
*
* @param int|null $depth
*
* @return self
*/
public function withRecursionDepth($depth)
{
/** @psalm-suppress DocblockTypeContradiction */
if (null !== $depth && !(is_int($depth) && $depth >= 0)) {
$msg = 'Recursion depth must be null (infinite) or integer >= 0!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->recursionDepth = $depth;
return $self;
}
/**
* Maximum number of iterations, null means infinite, any integer greater
* than zero sets value. Zero is invalid because there must be at least one
* iteration. Defaults to 1. Loop breaks if result of two consequent
* iterations shows no change in processed text.
*
* @param int|null $iterations
*
* @return self
*/
public function withMaxIterations($iterations)
{
/** @psalm-suppress DocblockTypeContradiction */
if (null !== $iterations && !(is_int($iterations) && $iterations > 0)) {
$msg = 'Maximum number of iterations must be null (infinite) or integer > 0!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->maxIterations = $iterations;
return $self;
}
/**
* Whether shortcode content will be automatically processed and handler
* already receives shortcode with processed content. If false, every
* shortcode handler needs to process content on its own. Default true.
*
* @param bool $flag True if enabled (default), false otherwise
*
* @return self
*/
public function withAutoProcessContent($flag)
{
/** @psalm-suppress DocblockTypeContradiction */
if (!is_bool($flag)) {
$msg = 'Auto processing flag must be a boolean value!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->autoProcessContent = (bool)$flag;
return $self;
}
}