Untitled
unknown
plain_text
2 years ago
3.9 kB
12
Indexable
/**
* @param $text
* @param $contentId
* @param $output
* @return string|string[]|int|null
*/
private function replaceBrokenLink($text, $contentId, $output)
{
try {
// Load html
$doc = new \DOMDocument();
$head = '<head id="head_meta"><meta charset="UTF-8" /></head>';
@$doc->loadHTML(
$head . '<div id="container">' . $text . '</div>',
\LIBXML_HTML_NOIMPLIED
);
$updateContent = false;
// Get all links tags <a>
$linksElements = $doc->getElementsByTagName('a');
if ($linksElements->count() > 0) {
for ($i = $linksElements->length; --$i >= 0;) {
$e = $linksElements->item($i);
if (
!empty($e->getAttribute('href'))
&& str_contains($e->getAttribute('href'), $this->newHost)
&& $urlPath = parse_url($e->getAttribute('href'), \PHP_URL_PATH)
) {
// Get URL system country
$urlAliasService = $this->repository->getURLAliasService();
$locationAliases = $urlAliasService->
listLocationAliases($this->countryLocation, false, $this->languageCode) ?:
$urlAliasService->listLocationAliases($this->countryLocation, false);
if (!empty($locationAliases)) {
// Get URL system content
$urlSystemContent = $locationAliases[0]->path . $urlPath;
$urlContent = null;
try {
// Load content of url
$urlContent = $urlAliasService->lookup($urlSystemContent);
} catch (\Exception $exception) {
// link not found : remove element from DOMDocument
if (!$urlContent) {
if ($e->parentNode) {
if ($e->parentNode->nodeName == 'li') {
$liElement = $e->parentNode;
$liElement->parentNode->removeChild($liElement);
$doc->saveHTML();
$updateContent = true;
} else {
$e->parentNode->removeChild($e);
$doc->saveHTML();
$updateContent = true;
}
} else {
$e->parentNode->removeChild($e);
$doc->saveHTML();
$updateContent = true;
}
}
$output->writeln('<info>Not found link:' . $e->getAttribute('href') . '</info>');
}
}
}
}
}
if ($updateContent) {
if ($innerHTML = $this->getInnerHtml($doc->getElementById('container'))) {
// Update content by the new HTML
$this->updateContent($contentId, $innerHTML, $output);
}
} else {
$this->updateContent($contentId, $text, $output);
}
} catch (\Exception $exception) {
$output->writeln('<error>' . $exception->getMessage() . '</error>');
return Command::FAILURE;
}
}Editor is loading...