Skip to content

Instantly share code, notes, and snippets.

@AlexeyKosov
Created November 9, 2016 10:27
Show Gist options
  • Save AlexeyKosov/6aad332bcfd614f92933146a344c89eb to your computer and use it in GitHub Desktop.
Save AlexeyKosov/6aad332bcfd614f92933146a344c89eb to your computer and use it in GitHub Desktop.
Symfony Crawler closest()
<?php
/**
* @param Crawler $crawler
* @param string $cssSelector
* @return Crawler
*/
function closest(Crawler $crawler, $cssSelector)
{
$xpath = (new CssSelectorConverter())->toXPath($cssSelector, './');
$closest = null;
for (
$domNode = $crawler->getNode(0);
$domNode !== null && $domNode->nodeType === XML_ELEMENT_NODE;
$domNode = $domNode->parentNode
) {
$subcrawler = new Crawler($domNode);
$subcrawlerFiltered = $subcrawler->filterXPath($xpath);
if (count($subcrawlerFiltered) > 0) {
$closest = $subcrawlerFiltered;
break;
}
}
if ($closest === null) {
$closest = new Crawler();
}
return $closest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment