From 747c79311c9a9cc2ff765a443587ef3af82ce628 Mon Sep 17 00:00:00 2001 From: ignace nyamagana butera Date: Sat, 25 Jan 2025 20:52:43 +0100 Subject: [PATCH] Improve codebase --- uri/Uri.php | 80 ++++++++++++++++++++++------------------------------- 1 file changed, 33 insertions(+), 47 deletions(-) diff --git a/uri/Uri.php b/uri/Uri.php index eaa272a1..1629a832 100644 --- a/uri/Uri.php +++ b/uri/Uri.php @@ -1180,9 +1180,40 @@ public function toMarkdownAnchor(?string $linkTextTemplate = null): string */ public function toHtmlAnchor(?string $linkTextTemplate = null, iterable $attributes = []): string { - $content = strtr($linkTextTemplate ?? '{uri}', ['{uri}' => $this->toDisplayString()]); + FeatureDetection::supportsDom(); + + $doc = class_exists(HTMLDocument::class) ? HTMLDocument::createEmpty() : new DOMDocument(encoding:'utf-8'); + $element = $doc->createElement('a'); + $element->setAttribute('href', $this->toString()); + $element->appendChild($doc->createTextNode(strtr($linkTextTemplate ?? '{uri}', ['{uri}' => $this->toDisplayString()]))); + + foreach ($attributes as $name => $value) { + if ('href' === strtolower($name) || null === $value) { + continue; + } + + if (is_array($value)) { + $value = implode(' ', $value); + } - return self::buildHtml($this, 'a', $attributes, $content); + if (!is_string($value)) { + throw new TypeError('The attribute `'.$name.'` contains an invalid value.'); + } + + $value = trim($value); + if ('' === $value) { + continue; + } + + $element->setAttribute($name, $value); + } + + $html = $doc->saveHTML($element); + if (false === $html) { + throw new DOMException('The HTML generation failed.'); + } + + return $html; } /** @@ -1843,51 +1874,6 @@ public function __unserialize(array $data): void $this->origin = $this->setOrigin(); } - /** - * @param iterable> $attributes - * - * @throws DOMException - */ - private static function buildHtml(self $uri, string $tagName, iterable $attributes, ?string $content): string - { - FeatureDetection::supportsDom(); - - $doc = class_exists(HTMLDocument::class) ? HTMLDocument::createEmpty() : new DOMDocument(encoding:'utf-8'); - $element = $doc->createElement($tagName); - $element->setAttribute('href', $uri->toString()); - if (null !== $content) { - $element->appendChild($doc->createTextNode($content)); - } - - foreach ($attributes as $name => $value) { - if ('href' === strtolower($name) || null === $value) { - continue; - } - - if (is_array($value)) { - $value = implode(' ', $value); - } - - if (!is_string($value)) { - throw new TypeError('The attribute `'.$name.'` contains an invalid value.'); - } - - $value = trim($value); - if ('' === $value) { - continue; - } - - $element->setAttribute($name, $value); - } - - $html = $doc->saveHTML($element); - if (false === $html) { - throw new DOMException('The HTML generation failed.'); - } - - return $html; - } - /** * DEPRECATION WARNING! This method will be removed in the next major point release. *