SliceIterator   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 57
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A key() 0 8 2
A next() 0 6 1
A valid() 0 14 4
A rewind() 0 6 1
1
<?php
2
3
namespace itertools;
4
5
use IteratorIterator;
6
7
8
/**
9
 * Iterator equivalent of [array_slice](http://be1.php.net/manual/en/function.array-slice.php).
10
 * Example:
11
 *     $lines = new SliceIterator(new FileLineIterator('file.txt'), 0, 1000); // will iterate the first 1000 lines of the file
12
 */
13
class SliceIterator extends IteratorIterator
14
{
15
	const PRESERVE_KEYS = true;
16
	const DONT_PRESERVE_KEYS = false;
17
18
	protected $offset;
19
	protected $length;
20
	protected $preserveKeys;
21
	protected $innerIterationCount;
22
	protected $outerIterationCount;
23
24
	public function __construct($iterable, $offset, $length = INF, $preserveKeys = false)
25
	{
26
		parent::__construct(IterUtil::asTraversable($iterable));
27
		$this->offset = $offset;
28
		$this->length = $length;
29
		$this->preserveKeys = $preserveKeys;
30
	}
31
32
	public function key()
33
	{
34
		if($this->preserveKeys) {
35
			return parent::key();
36
		} else {
37
			return $this->outerIterationCount;
38
		}
39
	}
40
41
	public function next()
42
	{
43
		$this->innerIterationCount += 1;
44
		$this->outerIterationCount += 1;
45
		parent::next();
46
	}
47
48
	public function valid()
49
	{
50
		while($this->innerIterationCount < $this->offset) {
51
			if(!parent::valid()) {
52
				return false;
53
			}
54
			$this->innerIterationCount += 1;
55
			parent::next();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (next() instead of valid()). Are you sure this is correct? If so, you might want to change this to $this->next().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
56
		}
57
		if($this->innerIterationCount >= $this->offset + $this->length) {
58
			return false;
59
		}
60
		return parent::valid();
61
	}
62
63
	public function rewind()
64
	{
65
		$this->innerIterationCount = 0;
66
		$this->outerIterationCount = 0;
67
		parent::rewind();
68
	}
69
}
70
71