Created
November 9, 2016 10:27
-
-
Save AlexeyKosov/6aad332bcfd614f92933146a344c89eb to your computer and use it in GitHub Desktop.
Symfony Crawler closest()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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