diff --git a/autoloader.php b/autoloader.php index 1ae88be64..1b4e63169 100644 --- a/autoloader.php +++ b/autoloader.php @@ -3,6 +3,9 @@ // SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue // SPDX-License-Identifier: BSD-3-Clause +// Polyfill PHP 8.4+ `Dom\` classes +require_once __DIR__ . '/compat/dom.php'; + /** * PSR-4 implementation for SimplePie. * diff --git a/compat/dom-polyfill.php b/compat/dom-polyfill.php new file mode 100644 index 000000000..7323f9bc5 --- /dev/null +++ b/compat/dom-polyfill.php @@ -0,0 +1,313 @@ += 80300) { + // The polyfilled classes that cannot use `registerNodeClass()` + // (aliasing internal classes requires PHP 8.3+): + class_alias(\DOMComment::class, 'Dom\Comment', false); + class_alias(\DOMDocument::class, 'Dom\Document', false); + class_alias(\DOMNode::class, 'Dom\Node', false); + class_alias(\DOMNodeList::class, 'Dom\NodeList', false); + class_alias(\DOMText::class, 'Dom\Text', false); + } + + /** + * Optional PHP 8.4+ CSS selector API, requiring `GT\CssXPath` library. + */ + trait CssSelectors + { + private function cssXPath(): ?XPath + { + /** @var \DOMDocument|null $document */ + $document = $this->ownerDocument ?? $this; + return $document instanceof \DOMDocument ? new XPath($document) : null; + } + + /** + * Translates a CSS selector to an XPath expression. + * + * @param string $selectors CSS selector + * @param string $prefix e.g. `.//` to search descendants of the context node + * @throws \DOMException if the CSS selector cannot be translated + */ + private function cssToXPath(string $selectors, string $prefix): string + { + if (!class_exists(\GT\CssXPath\Translator::class)) { + // https://github.com/PhpGt/CssXPath + throw new \DOMException('CSS selectors are not available: missing the `GT\CssXPath` package'); + } + try { + return (new \GT\CssXPath\Translator($selectors, $prefix))->asXPath(); + } catch (\Throwable $e) { + throw new \DOMException('Invalid CSS selector: ' . $selectors, 0, $e); + } + } + + /** + * Returns the first descendant element matching the CSS selector, or null. + * + * @return \Dom\Element|null + */ + public function querySelector(string $selectors) + { + $result = $this->querySelectorAll($selectors); + return $result->length === 0 ? null : $result->item(0); + } + + /** + * Returns the descendant elements matching the CSS selector. + * + * @return \Dom\NodeList<\Dom\Element> + * @throws \DOMException if the CSS selector cannot be translated + */ + public function querySelectorAll(string $selectors) + { + $xpath = $this->cssXPath(); + if ($xpath === null) { + // No owner document (e.g. a detached node): empty result + return $this->getElementsByTagName('_'); + } + try { + return $xpath->query($this->cssToXPath($selectors, './/'), $this); + } catch (\Throwable $e) { + throw $e instanceof \DOMException ? $e : new \DOMException('Invalid CSS selector: ' . $selectors, 0, $e); + } + } + + /** + * Whether this element matches the given CSS selector. + * + * @throws \DOMException if the CSS selector cannot be translated + */ + public function matches(string $selectors): bool + { + $xpath = $this->cssXPath(); + if ($xpath === null) { + return false; + } + try { + $result = $xpath->query($this->cssToXPath($selectors, 'descendant-or-self::')); + } catch (\Throwable $e) { + throw $e instanceof \DOMException ? $e : new \DOMException('Invalid CSS selector: ' . $selectors, 0, $e); + } + for ($i = 0; $i < $result->length; $i++) { + $candidate = $result->item($i); + if ($candidate !== null && $candidate->isSameNode($this)) { + return true; + } + } + return false; + } + } + + /** + * Equivalent of native `Dom\Element` (PHP 8.4+), + * registered as the element class of `HTMLDocument` and `XMLDocument` below. + */ + final class Element extends \DOMElement + { + use CssSelectors; + + /** + * Native `Dom\Element::getAttribute()` return null when the attribute is missing + * @return string|null + */ + #[\ReturnTypeWillChange] + public function getAttribute($qualifiedName) + { + return $this->hasAttribute($qualifiedName) ? parent::getAttribute($qualifiedName) : null; + } + } + + /** + * Maps `\Dom\HTMLDocument::createFromString()` onto `\DOMDocument::loadHTML()`. + */ + final class HTMLDocument extends \DOMDocument + { + use CssSelectors; + + public function __construct() + { + parent::__construct(); + $this->registerNodeClass(\DOMElement::class, Element::class); + } + + /** + * @return static + */ + public static function createFromString(string $source, ?int $options = null, ?string $overrideEncoding = null) + { + $document = new self(); + $options = ($options ?? 0) | LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_HTML_NODEFDTD; + + // If the source itself declares an encoding, let the parser honour it, otherwise UTF-8. + $injectEncoding = $source !== '' && strncmp($source, "\xEF\xBB\xBF", 3) !== 0 + && !preg_match('#<(?:meta|\?xml)[^>]*?(?:charset|encoding)\\s*=#i', $source); + if ($injectEncoding) { + $source = '' . $source; + } + + try { + // `HTML_NO_DEFAULT_NS` is unknown to the legacy `loadHTML()` + /** @var \DOMDocument $document */ + $document->loadHTML($source, $options & ~HTML_NO_DEFAULT_NS); + } catch (\ValueError $e) { + // the native API silently creates an empty document. + } + + if ($injectEncoding) { + // Remove the injected declaration, which would otherwise be serialised + foreach ($document->childNodes as $child) { + if ($child instanceof \DOMProcessingInstruction && $child->target === 'xml') { + $document->removeChild($child); + break; + } + } + } + + return $document; + } + + /** + * Normalise to `attr=""` for parity. + * It also emits end tags for void elements (e.g. ``). + * + * Returns `''` instead of `false` in case of error, for parity with the + * native `Dom\HTMLDocument::saveHTML()`, which always returns a string. + */ + public function saveHTML(?\DOMNode $node = null): string + { + if ($node === null && in_array(strtolower($this->encoding ?? 'utf-8'), ['utf-8', 'utf8'], true)) { + // For a whole document, the legacy serialiser only knows the charset from ``, + // and otherwise writes non-ASCII characters as HTML entities, also inside `