[DomCrawler] Added support for slicing nodes

This commit is contained in:
Berat Doğan 2014-04-13 13:38:36 +03:00 committed by Fabien Potencier
parent c875acf3a2
commit 1181bdc63b
2 changed files with 27 additions and 4 deletions

21
src/Symfony/Component/DomCrawler/Crawler.php Normal file → Executable file
View File

@ -107,7 +107,7 @@ class Crawler extends \SplObjectStorage
// DOM only for HTML/XML content
if (!preg_match('/(x|ht)ml/i', $type, $xmlMatches)) {
return null;
return;
}
$charset = null;
@ -294,7 +294,7 @@ class Crawler extends \SplObjectStorage
/**
* Returns a node given its position in the node list.
*
* @param integer $position The position
* @param int $position The position
*
* @return Crawler A new instance of the Crawler with the selected node, or an empty Crawler if it does not exist.
*
@ -339,6 +339,19 @@ class Crawler extends \SplObjectStorage
return $data;
}
/**
* Slices the list of nodes by $offset and $length.
*
* @param int $offset
* @param int $length
*
* @return Crawler A Crawler instance with the sliced nodes.
*/
public function slice($offset = 0, $length = -1)
{
return new static(iterator_to_array(new \LimitIterator($this, $offset, $length)), $this->uri);
}
/**
* Reduces the list of nodes by calling an anonymous function.
*
@ -806,7 +819,7 @@ class Crawler extends \SplObjectStorage
}
/**
* @param integer $position
* @param int $position
*
* @return \DOMElement|null
*/
@ -818,7 +831,7 @@ class Crawler extends \SplObjectStorage
}
}
return null;
return;
}
/**

10
src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php Normal file → Executable file
View File

@ -309,6 +309,16 @@ EOF
$this->assertEquals(array('0-One', '1-Two', '2-Three'), $data, '->each() executes an anonymous function on each node of the list');
}
public function testSlice()
{
$crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
$this->assertNotSame($crawler->slice(), $crawler, '->slice() returns a new instance of a crawler');
$this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler->slice(), '->slice() returns a new instance of a crawler');
$this->assertCount(3, $crawler->slice(), '->slice() does not slice the nodes in the list if any param is entered');
$this->assertCount(1, $crawler->slice(1, 1), '->slice() slices the nodes in the list');
}
public function testReduce()
{
$crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');