1 | <?php |
||
14 | class WhiteSpaceRemovalSubscriber implements EventSubscriberInterface |
||
15 | { |
||
16 | |||
17 | protected $allowedTags = array(); |
||
18 | |||
19 | protected $allowedNamespaces = array(); |
||
20 | |||
21 | 23 | public function __construct(array $allowedTags = array(), array $allowedNamespaces = array()) |
|
26 | |||
27 | 18 | public static function getSubscribedEvents() |
|
33 | |||
34 | 23 | private function performXpathQuery(\DOMXPath $xp, $query, \DOMNode $ref) |
|
42 | |||
43 | 23 | public function removeWhitespace(TemplateEvent $event) |
|
44 | { |
||
45 | 23 | $doc = $event->getTemplate()->getDocument(); |
|
46 | |||
47 | 23 | $xp = new \DOMXPath($doc); |
|
48 | 23 | $xp->registerNamespace("t", Twital::NS); |
|
49 | |||
50 | 23 | foreach ($this->performXpathQuery($xp, "//text()[ancestor::*[@t:trans or @t:trans-n]]", $doc) as $text) { |
|
51 | 12 | if ($this->isAllowedNode($text->parentNode)) { |
|
52 | 5 | $text->data = preg_replace('/\s+/', ' ', $text->data); |
|
53 | |||
54 | 5 | if ($text->parentNode->childNodes->length === 1) { |
|
55 | 5 | $trimmed = trim($text->data); |
|
56 | 5 | if (!strlen($trimmed) && strlen($text->data)) { |
|
57 | 1 | $trimmed = " "; |
|
58 | } |
||
59 | 5 | $text->data = $trimmed; |
|
60 | 2 | } elseif ($text->parentNode->hasAttributeNs(Twital::NS, 'trans') || $text->parentNode->hasAttributeNs(Twital::NS, 'trans-n')) { |
|
61 | 2 | if ($text->parentNode->firstChild === $text) { |
|
62 | 2 | $text->data = ltrim($text->data); |
|
63 | 2 | } elseif ($text->parentNode->lastChild === $text) { |
|
64 | 12 | $text->data = rtrim($text->data); |
|
65 | } |
||
66 | } |
||
67 | } |
||
68 | } |
||
69 | 23 | } |
|
70 | |||
71 | 12 | private function isAllowedNode(\DOMElement $element) |
|
84 | } |
||
85 |
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.