Skip to content

Commit

Permalink
Improve codebase and simplify named constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Jan 25, 2025
1 parent 0c57d99 commit d9886e1
Showing 1 changed file with 31 additions and 21 deletions.
52 changes: 31 additions & 21 deletions Uri.php
Original file line number Diff line number Diff line change
Expand Up @@ -740,27 +740,7 @@ public static function fromMarkdownAnchor(Stringable|string $markdown, Stringabl
*/
public static function fromHtmlAnchor(Stringable|string $html, Stringable|string|null $baseUri = null): self
{
FeatureDetection::supportsDom();
$html = (string) $html;
set_error_handler(fn (int $errno, string $errstr, string $errfile, int $errline) => true);
try {
$result = true;
$exception = null;
if (class_exists(HTMLDocument::class)) {
$dom = HTMLDocument::createFromString($html);
} else {
$dom = new DOMDocument();
$result = $dom->loadHTML($html);
}
} catch (Throwable $exception) {
$result = false;
$dom = null;
}
restore_error_handler();
if (false === $result || null === $dom) {
throw $exception ?? new DOMException('The content could not be parsed as a valid HTML content.');
}

$dom = self::loadDom($html);
$element = $dom->getElementsByTagName('a')->item(0);
if (null === $element) {
throw new DOMException('No anchor element was found in the content.');
Expand All @@ -778,6 +758,36 @@ public static function fromHtmlAnchor(Stringable|string $html, Stringable|string
};
}

/**
* @throws DOMException
* @throws Throwable
*/
private static function loadDom(Stringable|string $html): DOMDocument|HTMLDocument
{
FeatureDetection::supportsDom();

$html = (string) $html;
if (class_exists(HTMLDocument::class)) {
try {
set_error_handler(fn (int $errno, string $errstr, string $errfile, int $errline) => true);

return HTMLDocument::createFromString($html);
} finally {
restore_error_handler();
}
}

set_error_handler(fn (int $errno, string $errstr, string $errfile, int $errline) => true);
$dom = new DOMDocument();
$result = $dom->loadHTML($html);
restore_error_handler();
if (false === $result) {
throw new DOMException('The content could not be parsed as a valid HTML content.');
}

return $dom;
}

/**
* Returns the environment scheme.
*/
Expand Down

0 comments on commit d9886e1

Please sign in to comment.