configuration = $configuration; } /** * Apply transformations to the provided DOM document. * * @param Document $document DOM document to apply the * transformations to. * @param ErrorCollection $errors Collection of errors that are collected * during transformation. * @return void */ public function transform(Document $document, ErrorCollection $errors) { $host = $this->calculateHost(); $referenceNode = $document->viewport; $preloadNodes = array_filter($this->collectPreloadNodes($document, $host)); foreach ($preloadNodes as $preloadNode) { $document->head->insertBefore( $preloadNode, $referenceNode instanceof DOMNode ? $referenceNode->nextSibling : null ); $referenceNode = $preloadNode; } $this->adaptForSelfHosting($document, $host, $errors); } /** * Collect all the preload nodes to be added to the
. * * @param Document $document Document to collect preload nodes for. * @param string $host Host URL to use. * @return Element[] Preload nodes. */ private function collectPreloadNodes(Document $document, $host) { $usesEsm = $this->configuration->get(RewriteAmpUrlsConfiguration::ESM_MODULES_ENABLED); $preloadNodes = []; $node = $document->head->firstChild; while ($node) { $nextSibling = $node->nextSibling; if (! $node instanceof Element) { $node = $nextSibling; continue; } $src = $node->getAttribute(Attribute::SRC); $href = $node->getAttribute(Attribute::HREF); if ($node->tagName === Tag::SCRIPT && $this->usesAmpCacheUrl($src)) { $newUrl = $this->replaceUrl($src, $host); $node->setAttribute(Attribute::SRC, $this->replaceUrl($src, $host)); if ($usesEsm) { $preloadNodes[] = $this->addEsm($document, $node); } else { $preloadNodes[] = $this->createPreload($document, $newUrl, Tag::SCRIPT); } } elseif ( $node->tagName === Tag::LINK && $node->getAttribute(Attribute::REL) === Attribute::REL_STYLESHEET && $this->usesAmpCacheUrl($href) ) { $newUrl = $this->replaceUrl($href, $host); $node->setAttribute(Attribute::HREF, $newUrl); $preloadNodes[] = $this->createPreload($document, $newUrl, Tag::STYLE); } elseif ( $node->tagName === Tag::LINK && $node->getAttribute(Attribute::REL) === Attribute::REL_PRELOAD && $this->usesAmpCacheUrl($href) ) { if ($usesEsm && $this->shouldPreload($href)) { // Only preload .mjs runtime in ESM mode. $node->parentNode->removeChild($node); } else { $node->setAttribute(Attribute::HREF, $this->replaceUrl($href, $host)); } } $node = $nextSibling; } return $preloadNodes; } /** * Check if a given URL uses the AMP Cache. * * @param string $url Url to check. * @return bool Whether the provided URL uses the AMP Cache. */ private function usesAmpCacheUrl($url) { if (! $url) { return false; } return strpos($url, Amp::CACHE_HOST) === 0; } /** * Replace URL root with provided host. * * @param string $url Url to replace. * @param string $host Host to use. * @return string Adapted URL. */ private function replaceUrl($url, $host) { return str_replace(Amp::CACHE_HOST, $host, $url); } /** * Replace