Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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 <colinodell@gmail.com>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
 
17
namespace League\CommonMark\Environment;
18
 
19
use League\CommonMark\Delimiter\DelimiterParser;
20
use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection;
21
use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface;
22
use League\CommonMark\Event\DocumentParsedEvent;
23
use League\CommonMark\Event\ListenerData;
24
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
25
use League\CommonMark\Extension\ConfigurableExtensionInterface;
26
use League\CommonMark\Extension\ExtensionInterface;
27
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
28
use League\CommonMark\Normalizer\SlugNormalizer;
29
use League\CommonMark\Normalizer\TextNormalizerInterface;
30
use League\CommonMark\Normalizer\UniqueSlugNormalizer;
31
use League\CommonMark\Normalizer\UniqueSlugNormalizerInterface;
32
use League\CommonMark\Parser\Block\BlockStartParserInterface;
33
use League\CommonMark\Parser\Block\SkipLinesStartingWithLettersParser;
34
use League\CommonMark\Parser\Inline\InlineParserInterface;
35
use League\CommonMark\Renderer\NodeRendererInterface;
36
use League\CommonMark\Util\HtmlFilter;
37
use League\CommonMark\Util\PrioritizedList;
38
use League\Config\Configuration;
39
use League\Config\ConfigurationAwareInterface;
40
use League\Config\ConfigurationInterface;
41
use Nette\Schema\Expect;
42
use Psr\EventDispatcher\EventDispatcherInterface;
43
use Psr\EventDispatcher\ListenerProviderInterface;
44
use Psr\EventDispatcher\StoppableEventInterface;
45
 
46
final class Environment implements EnvironmentInterface, EnvironmentBuilderInterface, ListenerProviderInterface
47
{
48
    /**
49
     * @var ExtensionInterface[]
50
     *
51
     * @psalm-readonly-allow-private-mutation
52
     */
53
    private array $extensions = [];
54
 
55
    /**
56
     * @var ExtensionInterface[]
57
     *
58
     * @psalm-readonly-allow-private-mutation
59
     */
60
    private array $uninitializedExtensions = [];
61
 
62
    /** @psalm-readonly-allow-private-mutation */
63
    private bool $extensionsInitialized = false;
64
 
65
    /**
66
     * @var PrioritizedList<BlockStartParserInterface>
67
     *
68
     * @psalm-readonly
69
     */
70
    private PrioritizedList $blockStartParsers;
71
 
72
    /**
73
     * @var PrioritizedList<InlineParserInterface>
74
     *
75
     * @psalm-readonly
76
     */
77
    private PrioritizedList $inlineParsers;
78
 
79
    /** @psalm-readonly */
80
    private DelimiterProcessorCollection $delimiterProcessors;
81
 
82
    /**
83
     * @var array<string, PrioritizedList<NodeRendererInterface>>
84
     *
85
     * @psalm-readonly-allow-private-mutation
86
     */
87
    private array $renderersByClass = [];
88
 
89
    /**
90
     * @var PrioritizedList<ListenerData>
91
     *
92
     * @psalm-readonly-allow-private-mutation
93
     */
94
    private PrioritizedList $listenerData;
95
 
96
    private ?EventDispatcherInterface $eventDispatcher = null;
97
 
98
    /** @psalm-readonly */
99
    private Configuration $config;
100
 
101
    private ?TextNormalizerInterface $slugNormalizer = null;
102
 
103
    /**
104
     * @param array<string, mixed> $config
105
     */
106
    public function __construct(array $config = [])
107
    {
108
        $this->config = self::createDefaultConfiguration();
109
        $this->config->merge($config);
110
 
111
        $this->blockStartParsers   = new PrioritizedList();
112
        $this->inlineParsers       = new PrioritizedList();
113
        $this->listenerData        = new PrioritizedList();
114
        $this->delimiterProcessors = new DelimiterProcessorCollection();
115
 
116
        // Performance optimization: always include a block "parser" that aborts parsing if a line starts with a letter
117
        // and is therefore unlikely to match any lines as a block start.
118
        $this->addBlockStartParser(new SkipLinesStartingWithLettersParser(), 249);
119
    }
120
 
121
    public function getConfiguration(): ConfigurationInterface
122
    {
123
        return $this->config->reader();
124
    }
125
 
126
    /**
127
     * @deprecated Environment::mergeConfig() is deprecated since league/commonmark v2.0 and will be removed in v3.0. Configuration should be set when instantiating the environment instead.
128
     *
129
     * @param array<string, mixed> $config
130
     */
131
    public function mergeConfig(array $config): void
132
    {
133
        @\trigger_error('Environment::mergeConfig() is deprecated since league/commonmark v2.0 and will be removed in v3.0. Configuration should be set when instantiating the environment instead.', \E_USER_DEPRECATED);
134
 
135
        $this->assertUninitialized('Failed to modify configuration.');
136
 
137
        $this->config->merge($config);
138
    }
139
 
140
    public function addBlockStartParser(BlockStartParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface
141
    {
142
        $this->assertUninitialized('Failed to add block start parser.');
143
 
144
        $this->blockStartParsers->add($parser, $priority);
145
        $this->injectEnvironmentAndConfigurationIfNeeded($parser);
146
 
147
        return $this;
148
    }
149
 
150
    public function addInlineParser(InlineParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface
151
    {
152
        $this->assertUninitialized('Failed to add inline parser.');
153
 
154
        $this->inlineParsers->add($parser, $priority);
155
        $this->injectEnvironmentAndConfigurationIfNeeded($parser);
156
 
157
        return $this;
158
    }
159
 
160
    public function addDelimiterProcessor(DelimiterProcessorInterface $processor): EnvironmentBuilderInterface
161
    {
162
        $this->assertUninitialized('Failed to add delimiter processor.');
163
        $this->delimiterProcessors->add($processor);
164
        $this->injectEnvironmentAndConfigurationIfNeeded($processor);
165
 
166
        return $this;
167
    }
168
 
169
    public function addRenderer(string $nodeClass, NodeRendererInterface $renderer, int $priority = 0): EnvironmentBuilderInterface
170
    {
171
        $this->assertUninitialized('Failed to add renderer.');
172
 
173
        if (! isset($this->renderersByClass[$nodeClass])) {
174
            $this->renderersByClass[$nodeClass] = new PrioritizedList();
175
        }
176
 
177
        $this->renderersByClass[$nodeClass]->add($renderer, $priority);
178
        $this->injectEnvironmentAndConfigurationIfNeeded($renderer);
179
 
180
        return $this;
181
    }
182
 
183
    /**
184
     * {@inheritDoc}
185
     */
186
    public function getBlockStartParsers(): iterable
187
    {
188
        if (! $this->extensionsInitialized) {
189
            $this->initializeExtensions();
190
        }
191
 
192
        return $this->blockStartParsers->getIterator();
193
    }
194
 
195
    public function getDelimiterProcessors(): DelimiterProcessorCollection
196
    {
197
        if (! $this->extensionsInitialized) {
198
            $this->initializeExtensions();
199
        }
200
 
201
        return $this->delimiterProcessors;
202
    }
203
 
204
    /**
205
     * {@inheritDoc}
206
     */
207
    public function getRenderersForClass(string $nodeClass): iterable
208
    {
209
        if (! $this->extensionsInitialized) {
210
            $this->initializeExtensions();
211
        }
212
 
213
        // If renderers are defined for this specific class, return them immediately
214
        if (isset($this->renderersByClass[$nodeClass])) {
215
            return $this->renderersByClass[$nodeClass];
216
        }
217
 
218
        /** @psalm-suppress TypeDoesNotContainType -- Bug: https://github.com/vimeo/psalm/issues/3332 */
219
        while (\class_exists($parent ??= $nodeClass) && $parent = \get_parent_class($parent)) {
220
            if (! isset($this->renderersByClass[$parent])) {
221
                continue;
222
            }
223
 
224
            // "Cache" this result to avoid future loops
225
            return $this->renderersByClass[$nodeClass] = $this->renderersByClass[$parent];
226
        }
227
 
228
        return [];
229
    }
230
 
231
    /**
232
     * {@inheritDoc}
233
     */
234
    public function getExtensions(): iterable
235
    {
236
        return $this->extensions;
237
    }
238
 
239
    /**
240
     * Add a single extension
241
     *
242
     * @return $this
243
     */
244
    public function addExtension(ExtensionInterface $extension): EnvironmentBuilderInterface
245
    {
246
        $this->assertUninitialized('Failed to add extension.');
247
 
248
        $this->extensions[]              = $extension;
249
        $this->uninitializedExtensions[] = $extension;
250
 
251
        if ($extension instanceof ConfigurableExtensionInterface) {
252
            $extension->configureSchema($this->config);
253
        }
254
 
255
        return $this;
256
    }
257
 
258
    private function initializeExtensions(): void
259
    {
260
        // Initialize the slug normalizer
261
        $this->getSlugNormalizer();
262
 
263
        // Ask all extensions to register their components
264
        while (\count($this->uninitializedExtensions) > 0) {
265
            foreach ($this->uninitializedExtensions as $i => $extension) {
266
                $extension->register($this);
267
                unset($this->uninitializedExtensions[$i]);
268
            }
269
        }
270
 
271
        $this->extensionsInitialized = true;
272
 
273
        // Create the special delimiter parser if any processors were registered
274
        if ($this->delimiterProcessors->count() > 0) {
275
            $this->inlineParsers->add(new DelimiterParser($this->delimiterProcessors), PHP_INT_MIN);
276
        }
277
    }
278
 
279
    private function injectEnvironmentAndConfigurationIfNeeded(object $object): void
280
    {
281
        if ($object instanceof EnvironmentAwareInterface) {
282
            $object->setEnvironment($this);
283
        }
284
 
285
        if ($object instanceof ConfigurationAwareInterface) {
286
            $object->setConfiguration($this->config->reader());
287
        }
288
    }
289
 
290
    /**
291
     * @deprecated Instantiate the environment and add the extension yourself
292
     *
293
     * @param array<string, mixed> $config
294
     */
295
    public static function createCommonMarkEnvironment(array $config = []): Environment
296
    {
297
        $environment = new self($config);
298
        $environment->addExtension(new CommonMarkCoreExtension());
299
 
300
        return $environment;
301
    }
302
 
303
    /**
304
     * @deprecated Instantiate the environment and add the extension yourself
305
     *
306
     * @param array<string, mixed> $config
307
     */
308
    public static function createGFMEnvironment(array $config = []): Environment
309
    {
310
        $environment = new self($config);
311
        $environment->addExtension(new CommonMarkCoreExtension());
312
        $environment->addExtension(new GithubFlavoredMarkdownExtension());
313
 
314
        return $environment;
315
    }
316
 
317
    public function addEventListener(string $eventClass, callable $listener, int $priority = 0): EnvironmentBuilderInterface
318
    {
319
        $this->assertUninitialized('Failed to add event listener.');
320
 
321
        $this->listenerData->add(new ListenerData($eventClass, $listener), $priority);
322
 
323
        if (\is_object($listener)) {
324
            $this->injectEnvironmentAndConfigurationIfNeeded($listener);
325
        } elseif (\is_array($listener) && \is_object($listener[0])) {
326
            $this->injectEnvironmentAndConfigurationIfNeeded($listener[0]);
327
        }
328
 
329
        return $this;
330
    }
331
 
332
    public function dispatch(object $event): object
333
    {
334
        if (! $this->extensionsInitialized) {
335
            $this->initializeExtensions();
336
        }
337
 
338
        if ($this->eventDispatcher !== null) {
339
            return $this->eventDispatcher->dispatch($event);
340
        }
341
 
342
        foreach ($this->getListenersForEvent($event) as $listener) {
343
            if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
344
                return $event;
345
            }
346
 
347
            $listener($event);
348
        }
349
 
350
        return $event;
351
    }
352
 
353
    public function setEventDispatcher(EventDispatcherInterface $dispatcher): void
354
    {
355
        $this->eventDispatcher = $dispatcher;
356
    }
357
 
358
    /**
359
     * {@inheritDoc}
360
     *
361
     * @return iterable<callable>
362
     */
363
    public function getListenersForEvent(object $event): iterable
364
    {
365
        foreach ($this->listenerData as $listenerData) {
366
            \assert($listenerData instanceof ListenerData);
367
 
368
            /** @psalm-suppress ArgumentTypeCoercion */
369
            if (! \is_a($event, $listenerData->getEvent())) {
370
                continue;
371
            }
372
 
373
            yield function (object $event) use ($listenerData) {
374
                if (! $this->extensionsInitialized) {
375
                    $this->initializeExtensions();
376
                }
377
 
378
                return \call_user_func($listenerData->getListener(), $event);
379
            };
380
        }
381
    }
382
 
383
    /**
384
     * @return iterable<InlineParserInterface>
385
     */
386
    public function getInlineParsers(): iterable
387
    {
388
        if (! $this->extensionsInitialized) {
389
            $this->initializeExtensions();
390
        }
391
 
392
        return $this->inlineParsers->getIterator();
393
    }
394
 
395
    public function getSlugNormalizer(): TextNormalizerInterface
396
    {
397
        if ($this->slugNormalizer === null) {
398
            $normalizer = $this->config->get('slug_normalizer/instance');
399
            \assert($normalizer instanceof TextNormalizerInterface);
400
            $this->injectEnvironmentAndConfigurationIfNeeded($normalizer);
401
 
402
            if ($this->config->get('slug_normalizer/unique') !== UniqueSlugNormalizerInterface::DISABLED && ! $normalizer instanceof UniqueSlugNormalizer) {
403
                $normalizer = new UniqueSlugNormalizer($normalizer);
404
            }
405
 
406
            if ($normalizer instanceof UniqueSlugNormalizer) {
407
                if ($this->config->get('slug_normalizer/unique') === UniqueSlugNormalizerInterface::PER_DOCUMENT) {
408
                    $this->addEventListener(DocumentParsedEvent::class, [$normalizer, 'clearHistory'], -1000);
409
                }
410
            }
411
 
412
            $this->slugNormalizer = $normalizer;
413
        }
414
 
415
        return $this->slugNormalizer;
416
    }
417
 
418
    /**
419
     * @throws \RuntimeException
420
     */
421
    private function assertUninitialized(string $message): void
422
    {
423
        if ($this->extensionsInitialized) {
424
            throw new \RuntimeException($message . ' Extensions have already been initialized.');
425
        }
426
    }
427
 
428
    public static function createDefaultConfiguration(): Configuration
429
    {
430
        return new Configuration([
431
            'html_input' => Expect::anyOf(HtmlFilter::STRIP, HtmlFilter::ALLOW, HtmlFilter::ESCAPE)->default(HtmlFilter::ALLOW),
432
            'allow_unsafe_links' => Expect::bool(true),
433
            'max_nesting_level' => Expect::type('int')->default(PHP_INT_MAX),
434
            'renderer' => Expect::structure([
435
                'block_separator' => Expect::string("\n"),
436
                'inner_separator' => Expect::string("\n"),
437
                'soft_break' => Expect::string("\n"),
438
            ]),
439
            'slug_normalizer' => Expect::structure([
440
                'instance' => Expect::type(TextNormalizerInterface::class)->default(new SlugNormalizer()),
441
                'max_length' => Expect::int()->min(0)->default(255),
442
                'unique' => Expect::anyOf(UniqueSlugNormalizerInterface::DISABLED, UniqueSlugNormalizerInterface::PER_ENVIRONMENT, UniqueSlugNormalizerInterface::PER_DOCUMENT)->default(UniqueSlugNormalizerInterface::PER_DOCUMENT),
443
            ]),
444
        ]);
445
    }
446
}