feature #10699 [DomCrawler] Added support for slicing nodes (Berat Doğan, beratdogan)
This PR was squashed before being merged into the 2.6-dev branch (closes #10699).
Discussion
----------
[DomCrawler] Added support for slicing nodes
| Q | A
| ------------- | ---
| Bug fix? | no
| New feature? | yes
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets |
| License | MIT
There are no easy way to slice nodes in specific range. I created a method using \LimitIterator. Works fine for me.
An example using is:
```php
$crawler->filter('h1')->slice(5, 10)->each(function ($node, $i) {
return $node->text();
});
Commits
-------
1181bdc
[DomCrawler] Added support for slicing nodes
This commit is contained in:
commit
4b7e7ad271
13
src/Symfony/Component/DomCrawler/Crawler.php
Normal file → Executable file
13
src/Symfony/Component/DomCrawler/Crawler.php
Normal file → Executable file
@ -341,6 +341,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.
|
||||
*
|
||||
|
10
src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
Normal file → Executable file
10
src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
Normal file → Executable file
@ -313,6 +313,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');
|
||||
|
Reference in New Issue
Block a user