HistoryIterator::valid()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
3
namespace itertools;
4
5
use IteratorIterator;
6
7
8
/**
9
 * An iterator that keeps track of the elements it iterates. It differs from
10
 * the CachingIterator in the standard PHP library because this implementations
11
 * allows the history size to be specified.
12
 *
13
 * Example:
14
 *     $range = new HistoryIterator(new ArrayIterator(range(1, 10)));
15
 *     foreach($range as $i) {
16
 *         if($range->hasPrev()) {
17
 *             echo $i, $range->prev(), "\n";
18
 *         }
19
 *     }
20
 */
21
class HistoryIterator extends IteratorIterator
22
{
23
	protected $history;
24
	protected $maxHistorySize;
25
	protected $hasStoredCurrent;
26
27
	public function __construct($innerIterator, $maxHistorySize = 1)
28
	{
29
		parent::__construct(IterUtil::asIterator($innerIterator));
30
		$this->history = new Queue();
31
		$this->maxHistorySize = $maxHistorySize;
32
		$this->hasStoredCurrent = false;
33
	}
34
35
	public function next()
36
	{
37
		parent::next();
38
		$this->hasStoredCurrent = false;
39
	}
40
41
	public function valid()
42
	{
43
		if(!parent::valid()) {
44
			return false;
45
		}
46
		if($this->hasStoredCurrent) {
47
			return true;
48
		}
49
		$this->addToHistory(parent::current());
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (current() instead of valid()). Are you sure this is correct? If so, you might want to change this to $this->current().

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...
50
		$this->hasStoredCurrent = true;
51
		return true;
52
	}
53
54
	public function current()
55
	{
56
		return $this->history->bottom();
57
	}
58
59
	public function prev($n = 1)
60
	{
61
		return $this->history->offsetGet($n);
62
	}
63
64
	public function hasPrev($n = 1)
65
	{
66
		return $this->history->count() > $n;
67
	}
68
69
	public function rewind()
70
	{
71
		parent::rewind();
72
		$this->keepLastEntries(0);
73
		$this->hasStoredCurrent = false;
74
	}
75
76
	protected function addToHistory($value)
77
	{
78
		$this->history->unshift($value);
79
		$this->keepLastEntries($this->maxHistorySize + 1);
80
	}
81
82
	protected function keepLastEntries($count)
83
	{
84
		while($this->history->count() > $count) {
85
			$this->history->pop();
86
		}
87
	}
88
}
89
90