| 1 |
<?php |
| 2 |
namespace enshrined\svgSanitize\data; |
| 3 |
|
| 4 |
class XPath extends \DOMXPath |
| 5 |
{ |
| 6 |
const DEFAULT_NAMESPACE_PREFIX = 'svg'; |
| 7 |
|
| 8 |
/** |
| 9 |
* @var string |
| 10 |
*/ |
| 11 |
protected $defaultNamespaceURI; |
| 12 |
|
| 13 |
public function __construct(\DOMDocument $doc) |
| 14 |
{ |
| 15 |
parent::__construct($doc); |
| 16 |
$this->handleDefaultNamespace(); |
| 17 |
} |
| 18 |
|
| 19 |
/** |
| 20 |
* @param string $nodeName |
| 21 |
* @return string |
| 22 |
*/ |
| 23 |
public function createNodeName($nodeName) |
| 24 |
{ |
| 25 |
if (empty($this->defaultNamespaceURI)) { |
| 26 |
return $nodeName; |
| 27 |
} |
| 28 |
return self::DEFAULT_NAMESPACE_PREFIX . ':' . $nodeName; |
| 29 |
} |
| 30 |
|
| 31 |
protected function handleDefaultNamespace() |
| 32 |
{ |
| 33 |
$rootElements = $this->getRootElements(); |
| 34 |
|
| 35 |
if (count($rootElements) !== 1) { |
| 36 |
throw new \LogicException( |
| 37 |
sprintf('Got %d svg elements, expected exactly one', count($rootElements)), |
| 38 |
1570870568 |
| 39 |
); |
| 40 |
} |
| 41 |
$this->defaultNamespaceURI = (string)$rootElements[0]->namespaceURI; |
| 42 |
|
| 43 |
if ($this->defaultNamespaceURI !== '') { |
| 44 |
$this->registerNamespace(self::DEFAULT_NAMESPACE_PREFIX, $this->defaultNamespaceURI); |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* @return \DOMElement[] |
| 50 |
*/ |
| 51 |
protected function getRootElements() |
| 52 |
{ |
| 53 |
$rootElements = []; |
| 54 |
$elements = $this->document->getElementsByTagName('svg'); |
| 55 |
/** @var \DOMElement $element */ |
| 56 |
foreach ($elements as $element) { |
| 57 |
if ($element->parentNode !== $this->document) { |
| 58 |
continue; |
| 59 |
} |
| 60 |
$rootElements[] = $element; |
| 61 |
} |
| 62 |
return $rootElements; |
| 63 |
} |
| 64 |
} |
| 65 |
|