-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathParser.php
2056 lines (1788 loc) · 51 KB
/
Parser.php
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @package s9e\TextFormatter
* @copyright Copyright (c) The s9e authors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\TextFormatter;
use InvalidArgumentException;
use RuntimeException;
use s9e\TextFormatter\Parser\FilterProcessing;
use s9e\TextFormatter\Parser\Logger;
use s9e\TextFormatter\Parser\Tag;
class Parser
{
/**#@+
* Boolean rules bitfield
*/
const RULE_AUTO_CLOSE = 1 << 0;
const RULE_AUTO_REOPEN = 1 << 1;
const RULE_BREAK_PARAGRAPH = 1 << 2;
const RULE_CREATE_PARAGRAPHS = 1 << 3;
const RULE_DISABLE_AUTO_BR = 1 << 4;
const RULE_ENABLE_AUTO_BR = 1 << 5;
const RULE_IGNORE_TAGS = 1 << 6;
const RULE_IGNORE_TEXT = 1 << 7;
const RULE_IGNORE_WHITESPACE = 1 << 8;
const RULE_IS_TRANSPARENT = 1 << 9;
const RULE_PREVENT_BR = 1 << 10;
const RULE_SUSPEND_AUTO_BR = 1 << 11;
const RULE_TRIM_FIRST_LINE = 1 << 12;
/**#@-*/
/**
* Bitwise disjunction of rules related to automatic line breaks
*/
const RULES_AUTO_LINEBREAKS = self::RULE_DISABLE_AUTO_BR | self::RULE_ENABLE_AUTO_BR | self::RULE_SUSPEND_AUTO_BR;
/**
* Bitwise disjunction of rules that are inherited by subcontexts
*/
const RULES_INHERITANCE = self::RULE_ENABLE_AUTO_BR;
/**
* All the characters that are considered whitespace
*/
const WHITESPACE = " \n\t";
/**
* @var array Number of open tags for each tag name
*/
protected $cntOpen;
/**
* @var array Number of times each tag has been used
*/
protected $cntTotal;
/**
* @var array Current context
*/
protected $context;
/**
* @var integer How hard the parser has worked on fixing bad markup so far
*/
protected $currentFixingCost;
/**
* @var Tag Current tag being processed
*/
protected $currentTag;
/**
* @var bool Whether the output contains "rich" tags, IOW any tag that is not <p> or <br/>
*/
protected $isRich;
/**
* @var Logger This parser's logger
*/
protected $logger;
/**
* @var integer How hard the parser should work on fixing bad markup
*/
public $maxFixingCost = 10000;
/**
* @var array Associative array of namespace prefixes in use in document (prefixes used as key)
*/
protected $namespaces;
/**
* @var array Stack of open tags (instances of Tag)
*/
protected $openTags;
/**
* @var string This parser's output
*/
protected $output;
/**
* @var integer Position of the cursor in the original text
*/
protected $pos;
/**
* @var array Array of callbacks, using plugin names as keys
*/
protected $pluginParsers = [];
/**
* @var array Associative array of [pluginName => pluginConfig]
*/
protected $pluginsConfig;
/**
* @var array Variables registered for use in filters
*/
public $registeredVars = [];
/**
* @var array Root context, used at the root of the document
*/
protected $rootContext;
/**
* @var array Tags' config
*/
protected $tagsConfig;
/**
* @var array Tag storage
*/
protected $tagStack;
/**
* @var bool Whether the tags in the stack are sorted
*/
protected $tagStackIsSorted;
/**
* @var string Text being parsed
*/
protected $text;
/**
* @var integer Length of the text being parsed
*/
protected $textLen;
/**
* @var integer Counter incremented everytime the parser is reset. Used to as a canary to detect
* whether the parser was reset during execution
*/
protected $uid = 0;
/**
* @var integer Position before which we output text verbatim, without paragraphs or linebreaks
*/
protected $wsPos;
/**
* Constructor
*/
public function __construct(array $config)
{
$this->pluginsConfig = $config['plugins'];
$this->registeredVars = $config['registeredVars'];
$this->rootContext = $config['rootContext'];
$this->tagsConfig = $config['tags'];
$this->__wakeup();
}
/**
* Serializer
*
* Returns the properties that need to persist through serialization.
*
* NOTE: using __sleep() is preferable to implementing Serializable because it leaves the choice
* of the serializer to the user (e.g. igbinary)
*
* @return array
*/
public function __sleep()
{
return ['pluginsConfig', 'registeredVars', 'rootContext', 'tagsConfig'];
}
/**
* Unserializer
*
* @return void
*/
public function __wakeup()
{
$this->logger = new Logger;
}
/**
* Reset the parser for a new parsing
*
* @param string $text Text to be parsed
* @return void
*/
protected function reset($text)
{
// Reject invalid UTF-8
if (!preg_match('//u', $text))
{
throw new InvalidArgumentException('Invalid UTF-8 input');
}
// Normalize CR/CRLF to LF, remove characters that aren't allowed in XML
$text = preg_replace('/\\r\\n?/', "\n", $text);
$text = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]|\\xEF\\xBF[\\xBE\\xBF]/', '', $text);
// Clear the logs
$this->logger->clear();
// Initialize the rest
$this->cntOpen = [];
$this->cntTotal = [];
$this->currentFixingCost = 0;
$this->currentTag = null;
$this->isRich = false;
$this->namespaces = [];
$this->openTags = [];
$this->output = '';
$this->pos = 0;
$this->tagStack = [];
$this->tagStackIsSorted = false;
$this->text = $text;
$this->textLen = strlen($text);
$this->wsPos = 0;
// Initialize the root context
$this->context = $this->rootContext;
$this->context['inParagraph'] = false;
// Bump the UID
++$this->uid;
}
/**
* Set a tag's option
*
* This method ensures that the tag's config is a value and not a reference, to prevent
* potential side-effects. References contained *inside* the tag's config are left untouched
*
* @param string $tagName Tag's name
* @param string $optionName Option's name
* @param mixed $optionValue Option's value
* @return void
*/
protected function setTagOption($tagName, $optionName, $optionValue)
{
if (isset($this->tagsConfig[$tagName]))
{
// Copy the tag's config and remove it. That will destroy the reference
$tagConfig = $this->tagsConfig[$tagName];
unset($this->tagsConfig[$tagName]);
// Set the new value and replace the tag's config
$tagConfig[$optionName] = $optionValue;
$this->tagsConfig[$tagName] = $tagConfig;
}
}
//==========================================================================
// Public API
//==========================================================================
/**
* Disable a tag
*
* @param string $tagName Name of the tag
* @return void
*/
public function disableTag($tagName)
{
$this->setTagOption($tagName, 'isDisabled', true);
}
/**
* Enable a tag
*
* @param string $tagName Name of the tag
* @return void
*/
public function enableTag($tagName)
{
if (isset($this->tagsConfig[$tagName]))
{
unset($this->tagsConfig[$tagName]['isDisabled']);
}
}
/**
* Get this parser's Logger instance
*
* @return Logger
*/
public function getLogger()
{
return $this->logger;
}
/**
* Return the last text parsed
*
* This method returns the normalized text, which may be slightly different from the original
* text in that EOLs are normalized to LF and other control codes are stripped. This method is
* meant to be used in support of processing log entries, which contain offsets based on the
* normalized text
*
* @see Parser::reset()
*
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* Parse a text
*
* @param string $text Text to parse
* @return string XML representation
*/
public function parse($text)
{
// Reset the parser and save the uid
$this->reset($text);
$uid = $this->uid;
// Do the heavy lifting
$this->executePluginParsers();
$this->processTags();
// Finalize the document
$this->finalizeOutput();
// Check the uid in case a plugin or a filter reset the parser mid-execution
if ($this->uid !== $uid)
{
throw new RuntimeException('The parser has been reset during execution');
}
// Log a warning if the fixing cost limit was exceeded
if ($this->currentFixingCost > $this->maxFixingCost)
{
$this->logger->warn('Fixing cost limit exceeded');
}
return $this->output;
}
/**
* Change a tag's tagLimit
*
* NOTE: the default tagLimit should generally be set during configuration instead
*
* @param string $tagName The tag's name, in UPPERCASE
* @param integer $tagLimit
* @return void
*/
public function setTagLimit($tagName, $tagLimit)
{
$this->setTagOption($tagName, 'tagLimit', $tagLimit);
}
/**
* Change a tag's nestingLimit
*
* NOTE: the default nestingLimit should generally be set during configuration instead
*
* @param string $tagName The tag's name, in UPPERCASE
* @param integer $nestingLimit
* @return void
*/
public function setNestingLimit($tagName, $nestingLimit)
{
$this->setTagOption($tagName, 'nestingLimit', $nestingLimit);
}
//==========================================================================
// Output handling
//==========================================================================
/**
* Finalize the output by appending the rest of the unprocessed text and create the root node
*
* @return void
*/
protected function finalizeOutput()
{
// Output the rest of the text and close the last paragraph
$this->outputText($this->textLen, 0, true);
// Remove empty tag pairs, e.g. <I><U></U></I> as well as empty paragraphs
do
{
$this->output = preg_replace('(<([^ />]++)[^>]*></\\1>)', '', $this->output, -1, $cnt);
}
while ($cnt > 0);
// Merge consecutive <i> tags
if (strpos($this->output, '</i><i>') !== false)
{
$this->output = str_replace('</i><i>', '', $this->output);
}
// Remove illegal characters from the output to ensure it's valid XML
$this->output = preg_replace('([\\x00-\\x08\\x0B-\\x1F]|\\xEF\\xBF[\\xBE\\xBF])', '', $this->output);
// Encode Unicode characters that are outside of the BMP
$this->output = Utils::encodeUnicodeSupplementaryCharacters($this->output);
// Use a <r> root if the text is rich, or <t> for plain text (including <p></p> and <br/>)
$tagName = ($this->isRich) ? 'r' : 't';
// Prepare the root node with all the namespace declarations
$tmp = '<' . $tagName;
foreach (array_keys($this->namespaces) as $prefix)
{
$tmp .= ' xmlns:' . $prefix . '="urn:s9e:TextFormatter:' . $prefix . '"';
}
$this->output = $tmp . '>' . $this->output . '</' . $tagName . '>';
}
/**
* Append a tag to the output
*
* @param Tag $tag Tag to append
* @return void
*/
protected function outputTag(Tag $tag)
{
$this->isRich = true;
$tagName = $tag->getName();
$tagPos = $tag->getPos();
$tagLen = $tag->getLen();
$tagFlags = $tag->getFlags();
if ($tagFlags & self::RULE_IGNORE_WHITESPACE)
{
$skipBefore = 1;
$skipAfter = ($tag->isEndTag()) ? 2 : 1;
}
else
{
$skipBefore = $skipAfter = 0;
}
// Current paragraph must end before the tag if:
// - the tag is a start (or self-closing) tag and it breaks paragraphs, or
// - the tag is an end tag (but not self-closing)
$closeParagraph = (!$tag->isStartTag() || ($tagFlags & self::RULE_BREAK_PARAGRAPH));
// Let the cursor catch up with this tag's position
$this->outputText($tagPos, $skipBefore, $closeParagraph);
// Capture the text consumed by the tag
$tagText = ($tagLen)
? htmlspecialchars(substr($this->text, $tagPos, $tagLen), ENT_NOQUOTES, 'UTF-8')
: '';
// Output current tag
if ($tag->isStartTag())
{
// Handle paragraphs before opening the tag
if (!($tagFlags & self::RULE_BREAK_PARAGRAPH))
{
$this->outputParagraphStart($tagPos);
}
// Record this tag's namespace, if applicable
$colonPos = strpos($tagName, ':');
if ($colonPos)
{
$this->namespaces[substr($tagName, 0, $colonPos)] = 0;
}
// Open the start tag and add its attributes, but don't close the tag
$this->output .= '<' . $tagName;
// We output the attributes in lexical order. Helps canonicalizing the output and could
// prove useful someday
$attributes = $tag->getAttributes();
ksort($attributes);
foreach ($attributes as $attrName => $attrValue)
{
$this->output .= ' ' . $attrName . '="' . str_replace("\n", ' ', htmlspecialchars($attrValue, ENT_COMPAT, 'UTF-8')) . '"';
}
if ($tag->isSelfClosingTag())
{
if ($tagLen)
{
$this->output .= '>' . $tagText . '</' . $tagName . '>';
}
else
{
$this->output .= '/>';
}
}
elseif ($tagLen)
{
$this->output .= '><s>' . $tagText . '</s>';
}
else
{
$this->output .= '>';
}
}
else
{
if ($tagLen)
{
$this->output .= '<e>' . $tagText . '</e>';
}
$this->output .= '</' . $tagName . '>';
}
// Move the cursor past the tag
$this->pos = $tagPos + $tagLen;
// Skip newlines (no other whitespace) after this tag
$this->wsPos = $this->pos;
while ($skipAfter && $this->wsPos < $this->textLen && $this->text[$this->wsPos] === "\n")
{
// Decrement the number of lines to skip
--$skipAfter;
// Move the cursor past the newline
++$this->wsPos;
}
}
/**
* Output the text between the cursor's position (included) and given position (not included)
*
* @param integer $catchupPos Position we're catching up to
* @param integer $maxLines Maximum number of lines to ignore at the end of the text
* @param bool $closeParagraph Whether to close the paragraph at the end, if applicable
* @return void
*/
protected function outputText($catchupPos, $maxLines, $closeParagraph)
{
if ($closeParagraph)
{
if (!($this->context['flags'] & self::RULE_CREATE_PARAGRAPHS))
{
$closeParagraph = false;
}
else
{
// Ignore any number of lines at the end if we're closing a paragraph
$maxLines = -1;
}
}
if ($this->pos >= $catchupPos)
{
// We're already there, close the paragraph if applicable and return
if ($closeParagraph)
{
$this->outputParagraphEnd();
}
return;
}
// Skip over previously identified whitespace if applicable
if ($this->wsPos > $this->pos)
{
$skipPos = min($catchupPos, $this->wsPos);
$this->output .= substr($this->text, $this->pos, $skipPos - $this->pos);
$this->pos = $skipPos;
if ($this->pos >= $catchupPos)
{
// Skipped everything. Close the paragraph if applicable and return
if ($closeParagraph)
{
$this->outputParagraphEnd();
}
return;
}
}
// Test whether we're even supposed to output anything
if ($this->context['flags'] & self::RULE_IGNORE_TEXT)
{
$catchupLen = $catchupPos - $this->pos;
$catchupText = substr($this->text, $this->pos, $catchupLen);
// If the catchup text is not entirely composed of whitespace, we put it inside ignore
// tags
if (strspn($catchupText, " \n\t") < $catchupLen)
{
$catchupText = '<i>' . htmlspecialchars($catchupText, ENT_NOQUOTES, 'UTF-8') . '</i>';
}
$this->output .= $catchupText;
$this->pos = $catchupPos;
if ($closeParagraph)
{
$this->outputParagraphEnd();
}
return;
}
// Compute the amount of text to ignore at the end of the output
$ignorePos = $catchupPos;
$ignoreLen = 0;
// Ignore as many lines (including whitespace) as specified
while ($maxLines && --$ignorePos >= $this->pos)
{
$c = $this->text[$ignorePos];
if (strpos(self::WHITESPACE, $c) === false)
{
break;
}
if ($c === "\n")
{
--$maxLines;
}
++$ignoreLen;
}
// Adjust $catchupPos to ignore the text at the end
$catchupPos -= $ignoreLen;
// Break down the text in paragraphs if applicable
if ($this->context['flags'] & self::RULE_CREATE_PARAGRAPHS)
{
if (!$this->context['inParagraph'])
{
$this->outputWhitespace($catchupPos);
if ($catchupPos > $this->pos)
{
$this->outputParagraphStart($catchupPos);
}
}
// Look for a paragraph break in this text
$pbPos = strpos($this->text, "\n\n", $this->pos);
while ($pbPos !== false && $pbPos < $catchupPos)
{
$this->outputText($pbPos, 0, true);
$this->outputParagraphStart($catchupPos);
$pbPos = strpos($this->text, "\n\n", $this->pos);
}
}
// Capture, escape and output the text
if ($catchupPos > $this->pos)
{
$catchupText = htmlspecialchars(
substr($this->text, $this->pos, $catchupPos - $this->pos),
ENT_NOQUOTES,
'UTF-8'
);
// Format line breaks if applicable
if (($this->context['flags'] & self::RULES_AUTO_LINEBREAKS) === self::RULE_ENABLE_AUTO_BR)
{
$catchupText = str_replace("\n", "<br/>\n", $catchupText);
}
$this->output .= $catchupText;
}
// Close the paragraph if applicable
if ($closeParagraph)
{
$this->outputParagraphEnd();
}
// Add the ignored text if applicable
if ($ignoreLen)
{
$this->output .= substr($this->text, $catchupPos, $ignoreLen);
}
// Move the cursor past the text
$this->pos = $catchupPos + $ignoreLen;
}
/**
* Output a linebreak tag
*
* @param Tag $tag
* @return void
*/
protected function outputBrTag(Tag $tag)
{
$this->outputText($tag->getPos(), 0, false);
$this->output .= '<br/>';
}
/**
* Output an ignore tag
*
* @param Tag $tag
* @return void
*/
protected function outputIgnoreTag(Tag $tag)
{
$tagPos = $tag->getPos();
$tagLen = $tag->getLen();
// Capture the text to ignore
$ignoreText = substr($this->text, $tagPos, $tagLen);
// Catch up with the tag's position then output the tag
$this->outputText($tagPos, 0, false);
$this->output .= '<i>' . htmlspecialchars($ignoreText, ENT_NOQUOTES, 'UTF-8') . '</i>';
$this->isRich = true;
// Move the cursor past this tag
$this->pos = $tagPos + $tagLen;
}
/**
* Start a paragraph between current position and given position, if applicable
*
* @param integer $maxPos Rightmost position at which the paragraph can be opened
* @return void
*/
protected function outputParagraphStart($maxPos)
{
// Do nothing if we're already in a paragraph, or if we don't use paragraphs
if ($this->context['inParagraph']
|| !($this->context['flags'] & self::RULE_CREATE_PARAGRAPHS))
{
return;
}
// Output the whitespace between $this->pos and $maxPos if applicable
$this->outputWhitespace($maxPos);
// Open the paragraph, but only if it's not at the very end of the text
if ($this->pos < $this->textLen)
{
$this->output .= '<p>';
$this->context['inParagraph'] = true;
}
}
/**
* Close current paragraph at current position if applicable
*
* @return void
*/
protected function outputParagraphEnd()
{
// Do nothing if we're not in a paragraph
if (!$this->context['inParagraph'])
{
return;
}
$this->output .= '</p>';
$this->context['inParagraph'] = false;
}
/**
* Output the content of a verbatim tag
*
* @param Tag $tag
* @return void
*/
protected function outputVerbatim(Tag $tag)
{
$flags = $this->context['flags'];
$this->context['flags'] = $tag->getFlags();
$this->outputText($this->currentTag->getPos() + $this->currentTag->getLen(), 0, false);
$this->context['flags'] = $flags;
}
/**
* Skip as much whitespace after current position as possible
*
* @param integer $maxPos Rightmost character to be skipped
* @return void
*/
protected function outputWhitespace($maxPos)
{
if ($maxPos > $this->pos)
{
$spn = strspn($this->text, self::WHITESPACE, $this->pos, $maxPos - $this->pos);
if ($spn)
{
$this->output .= substr($this->text, $this->pos, $spn);
$this->pos += $spn;
}
}
}
//==========================================================================
// Plugins handling
//==========================================================================
/**
* Disable a plugin
*
* @param string $pluginName Name of the plugin
* @return void
*/
public function disablePlugin($pluginName)
{
if (isset($this->pluginsConfig[$pluginName]))
{
// Copy the plugin's config to remove the reference
$pluginConfig = $this->pluginsConfig[$pluginName];
unset($this->pluginsConfig[$pluginName]);
// Update the value and replace the plugin's config
$pluginConfig['isDisabled'] = true;
$this->pluginsConfig[$pluginName] = $pluginConfig;
}
}
/**
* Enable a plugin
*
* @param string $pluginName Name of the plugin
* @return void
*/
public function enablePlugin($pluginName)
{
if (isset($this->pluginsConfig[$pluginName]))
{
$this->pluginsConfig[$pluginName]['isDisabled'] = false;
}
}
/**
* Execute given plugin
*
* @param string $pluginName Plugin's name
* @return void
*/
protected function executePluginParser($pluginName)
{
$pluginConfig = $this->pluginsConfig[$pluginName];
if (isset($pluginConfig['quickMatch']) && strpos($this->text, $pluginConfig['quickMatch']) === false)
{
return;
}
$matches = [];
if (isset($pluginConfig['regexp'], $pluginConfig['regexpLimit']))
{
$matches = $this->getMatches($pluginConfig['regexp'], $pluginConfig['regexpLimit']);
if (empty($matches))
{
return;
}
}
// Execute the plugin's parser, which will add tags via $this->addStartTag() and others
call_user_func($this->getPluginParser($pluginName), $this->text, $matches);
}
/**
* Execute all the plugins
*
* @return void
*/
protected function executePluginParsers()
{
foreach ($this->pluginsConfig as $pluginName => $pluginConfig)
{
if (empty($pluginConfig['isDisabled']))
{
$this->executePluginParser($pluginName);
}
}
}
/**
* Execute given regexp and returns as many matches as given limit
*
* @param string $regexp
* @param integer $limit
* @return array
*/
protected function getMatches($regexp, $limit)
{
$cnt = preg_match_all($regexp, $this->text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
if ($cnt > $limit)
{
$matches = array_slice($matches, 0, $limit);
}
return $matches;
}
/**
* Get the cached callback for given plugin's parser
*
* @param string $pluginName Plugin's name
* @return callable
*/
protected function getPluginParser($pluginName)
{
// Cache a new instance of this plugin's parser if there isn't one already
if (!isset($this->pluginParsers[$pluginName]))
{
$pluginConfig = $this->pluginsConfig[$pluginName];
$className = (isset($pluginConfig['className']))
? $pluginConfig['className']
: 's9e\\TextFormatter\\Plugins\\' . $pluginName . '\\Parser';
// Register the parser as a callback
$this->pluginParsers[$pluginName] = [new $className($this, $pluginConfig), 'parse'];
}
return $this->pluginParsers[$pluginName];
}
/**
* Register a parser
*
* Can be used to add a new parser with no plugin config, or pre-generate a parser for an
* existing plugin
*
* @param string $pluginName
* @param callable $parser
* @param string $regexp
* @param integer $limit
* @return void
*/
public function registerParser($pluginName, $parser, $regexp = null, $limit = PHP_INT_MAX)
{
if (!is_callable($parser))
{
throw new InvalidArgumentException('Argument 1 passed to ' . __METHOD__ . ' must be a valid callback');
}
// Create an empty config for this plugin to ensure it is executed
if (!isset($this->pluginsConfig[$pluginName]))
{
$this->pluginsConfig[$pluginName] = [];
}
if (isset($regexp))
{
$this->pluginsConfig[$pluginName]['regexp'] = $regexp;
$this->pluginsConfig[$pluginName]['regexpLimit'] = $limit;
}
$this->pluginParsers[$pluginName] = $parser;
}
//==========================================================================
// Rules handling
//==========================================================================
/**
* Apply closeAncestor rules associated with given tag
*
* @param Tag $tag Tag
* @return bool Whether a new tag has been added
*/
protected function closeAncestor(Tag $tag)
{
if (!empty($this->openTags))
{
$tagName = $tag->getName();
$tagConfig = $this->tagsConfig[$tagName];
if (!empty($tagConfig['rules']['closeAncestor']))
{
$i = count($this->openTags);
while (--$i >= 0)
{
$ancestor = $this->openTags[$i];