| 1 |
<?php |
| 2 |
namespace enshrined\svgSanitize; |
| 3 |
|
| 4 |
class Helper |
| 5 |
{ |
| 6 |
const XLINK_NAMESPACE_URI = 'http://www.w3.org/1999/xlink'; |
| 7 |
|
| 8 |
/** |
| 9 |
* Resolves the `href`/`xlink:href` value of an element. |
| 10 |
* |
| 11 |
* The lookup is case insensitive on purpose: `Sanitizer::cleanHrefAttributes()` |
| 12 |
* normalizes names such as `HrEf`/`xlink:HrEf` back to `href`/`xlink:href`, |
| 13 |
* so anything consuming this helper has to see those attributes as well - |
| 14 |
* otherwise a mixed-case name hides the reference from e.g. the `<use>` |
| 15 |
* reference graph, which is built before that normalization happens. |
| 16 |
* |
| 17 |
* @param \DOMElement $element |
| 18 |
* @return string|null |
| 19 |
*/ |
| 20 |
public static function getElementHref(\DOMElement $element) |
| 21 |
{ |
| 22 |
if ($element->hasAttribute('href')) { |
| 23 |
return $element->getAttribute('href'); |
| 24 |
} |
| 25 |
if ($element->hasAttributeNS(self::XLINK_NAMESPACE_URI, 'href')) { |
| 26 |
return $element->getAttributeNS(self::XLINK_NAMESPACE_URI, 'href'); |
| 27 |
} |
| 28 |
foreach ($element->attributes as $attribute) { |
| 29 |
if (!$attribute instanceof \DOMAttr |
| 30 |
|| strtolower($attribute->localName) !== 'href' |
| 31 |
) { |
| 32 |
continue; |
| 33 |
} |
| 34 |
$prefix = strtolower((string)$attribute->prefix); |
| 35 |
if ($prefix === '' || $prefix === 'xlink') { |
| 36 |
return $attribute->value; |
| 37 |
} |
| 38 |
} |
| 39 |
return null; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* @param string $href |
| 44 |
* @return string|null |
| 45 |
*/ |
| 46 |
public static function extractIdReferenceFromHref($href) |
| 47 |
{ |
| 48 |
if (!is_string($href) || strpos($href, '#') !== 0) { |
| 49 |
return null; |
| 50 |
} |
| 51 |
return substr($href, 1); |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* @param \DOMElement $needle |
| 56 |
* @param \DOMElement $haystack |
| 57 |
* @return bool |
| 58 |
*/ |
| 59 |
public static function isElementContainedIn(\DOMElement $needle, \DOMElement $haystack) |
| 60 |
{ |
| 61 |
if ($needle === $haystack) { |
| 62 |
return true; |
| 63 |
} |
| 64 |
foreach ($haystack->childNodes as $childNode) { |
| 65 |
if (!$childNode instanceof \DOMElement) { |
| 66 |
continue; |
| 67 |
} |
| 68 |
if (self::isElementContainedIn($needle, $childNode)) { |
| 69 |
return true; |
| 70 |
} |
| 71 |
} |
| 72 |
return false; |
| 73 |
} |
| 74 |
} |
| 75 |
|