Skip to content

Commit

Permalink
Improve codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Jan 25, 2025
1 parent d9886e1 commit bace4da
Showing 1 changed file with 33 additions and 47 deletions.
80 changes: 33 additions & 47 deletions Uri.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -1843,51 +1874,6 @@ public function __unserialize(array $data): void
$this->origin = $this->setOrigin();
}

/**
* @param iterable<string, string|null|list<string>> $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.
*
Expand Down

0 comments on commit bace4da

Please sign in to comment.