|
1
|
|
|
<?php |
|
2
|
|
|
namespace Goetas\Twital\EventSubscriber; |
|
3
|
|
|
|
|
4
|
|
|
use Goetas\Twital\EventDispatcher\CompilerEvents; |
|
5
|
|
|
use Goetas\Twital\EventDispatcher\SourceEvent; |
|
6
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* |
|
10
|
|
|
* @author Asmir Mustafic <[email protected]> |
|
11
|
|
|
* |
|
12
|
|
|
*/ |
|
13
|
|
|
class CustomNamespaceRawSubscriber implements EventSubscriberInterface |
|
14
|
|
|
{ |
|
15
|
|
|
protected $customNamespaces = array(); |
|
16
|
|
|
|
|
17
|
487 |
|
public function __construct(array $customNamespaces) |
|
18
|
|
|
{ |
|
19
|
487 |
|
$this->customNamespaces = $customNamespaces; |
|
20
|
487 |
|
} |
|
21
|
|
|
|
|
22
|
487 |
|
public static function getSubscribedEvents() |
|
23
|
|
|
{ |
|
24
|
|
|
return array( |
|
25
|
487 |
|
CompilerEvents::PRE_LOAD => 'addCustomNamespace', |
|
26
|
487 |
|
CompilerEvents::POST_DUMP => 'removeCustomNamespaces', |
|
27
|
487 |
|
); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
486 |
|
public function addCustomNamespace(SourceEvent $event) |
|
31
|
|
|
{ |
|
32
|
486 |
|
$xml = $event->getTemplate(); |
|
33
|
486 |
|
$mch = null; |
|
34
|
486 |
|
if (preg_match('~<(([a-z0-9\-_]+):)?([a-z0-9\-_]+)~i', $xml, $mch, PREG_OFFSET_CAPTURE)) { |
|
35
|
483 |
|
$addPos = $mch[0][1] + strlen($mch[0][0]); |
|
36
|
483 |
|
foreach ($this->customNamespaces as $prefix => $ns) { |
|
37
|
483 |
|
if (!preg_match('/\sxmlns:([a-z0-9\-]+)="' . preg_quote($ns, '/') . '"/', $xml) && !preg_match('/\sxmlns:([a-z0-9\-]+)=".*?"/', $xml)) { |
|
38
|
481 |
|
$xml = substr_replace($xml, ' xmlns:' . $prefix . '="' . $ns . '"', $addPos, 0); |
|
39
|
481 |
|
} |
|
40
|
483 |
|
} |
|
41
|
|
|
|
|
42
|
483 |
|
$event->setTemplate($xml); |
|
43
|
483 |
|
} |
|
44
|
486 |
|
} |
|
45
|
|
|
|
|
46
|
484 |
|
public function removeCustomNamespaces(SourceEvent $event) |
|
47
|
|
|
{ |
|
48
|
484 |
|
$template = $event->getTemplate(); |
|
49
|
484 |
|
foreach ($this->customNamespaces as $prefix => $ns) { |
|
50
|
484 |
|
$template = preg_replace('#<(.*) xmlns:' . $prefix . '="' . $ns . '"(.*)>#mi', "<\\1\\2>", $template); |
|
51
|
484 |
|
} |
|
52
|
484 |
|
$event->setTemplate($template); |
|
53
|
484 |
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|