|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Webfactory\ShortcodeBundle\Handler; |
|
4
|
|
|
|
|
5
|
|
|
use Thunder\Shortcode\Event\ReplaceShortcodesEvent; |
|
6
|
|
|
use Thunder\Shortcode\Shortcode\ReplacedShortcode; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Removes <p>...</p> tags if they directly wrap a short code. |
|
10
|
|
|
* |
|
11
|
|
|
* @see https://github.com/thunderer/Shortcode/issues/40 |
|
12
|
|
|
*/ |
|
13
|
|
|
final class RemoveWrappingParagraphElementsEventHandler |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @param ReplaceShortcodesEvent $event |
|
17
|
|
|
*/ |
|
18
|
4 |
|
public function __invoke(ReplaceShortcodesEvent $event) |
|
19
|
|
|
{ |
|
20
|
|
|
/* The text still containing shortcodes */ |
|
21
|
4 |
|
$text = $event->getText(); |
|
22
|
|
|
|
|
23
|
|
|
/* The generated ReplacedShortcode instances. Each ReplacedShortcode contains the Shortcode string in the |
|
24
|
|
|
original form, it's offset and it's replacement string. */ |
|
25
|
4 |
|
$replacements = $event->getReplacements(); |
|
26
|
4 |
|
if (!$replacements) { |
|
|
|
|
|
|
27
|
4 |
|
return; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/* Do the replacements from end to back to front, so the offsets remain valid. */ |
|
31
|
2 |
|
$replacements_reversed = array_reverse($replacements); |
|
32
|
2 |
|
$result = array_reduce( |
|
33
|
2 |
|
$replacements_reversed, |
|
34
|
1 |
|
function ($state, ReplacedShortcode $r) { |
|
35
|
2 |
|
$offset = $r->getOffset(); |
|
36
|
2 |
|
$lengthOfShortcode = mb_strlen($r->getText(), 'utf-8'); |
|
37
|
2 |
|
$sourceTextBeforeShortcode = mb_substr($state, 0, $offset, 'utf-8'); |
|
38
|
2 |
|
$sourceTextAfterShortcode = mb_substr($state, $offset + $lengthOfShortcode, null, 'utf-8'); |
|
39
|
|
|
|
|
40
|
|
|
if ( |
|
41
|
2 |
|
preg_match('~(\s*<p>\s*)$~', $sourceTextBeforeShortcode, $prefixMatch) |
|
42
|
2 |
|
&& preg_match('~(^\s*</p>\s*)~', $sourceTextAfterShortcode, $postfixMatch) |
|
43
|
|
|
) { |
|
44
|
2 |
|
$sourceTextBeforeShortcode = mb_substr($state, 0, $offset - mb_strlen($prefixMatch[0], 'utf-8'), 'utf-8'); |
|
45
|
2 |
|
$sourceTextAfterShortcode = mb_substr( |
|
46
|
2 |
|
$state, |
|
47
|
2 |
|
$offset + $lengthOfShortcode + mb_strlen($postfixMatch[0], 'utf-8'), |
|
48
|
2 |
|
null, |
|
49
|
2 |
|
'utf-8' |
|
50
|
|
|
); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
2 |
|
return $sourceTextBeforeShortcode.$r->getReplacement().$sourceTextAfterShortcode; |
|
54
|
2 |
|
}, |
|
55
|
2 |
|
$text |
|
56
|
|
|
); |
|
57
|
|
|
|
|
58
|
2 |
|
$event->setResult($result); |
|
59
|
2 |
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.