BatchingIterator::current()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace BatchingIterator;
6
7
use InvalidArgumentException;
8
9
/**
10
 * Iterator that batches calls for additional values.
11
 *
12
 * This is useful as a foundation for iterators over data that is
13
 * in an expensive to access location, such as a database or a web API.
14
 *
15
 * @since 1.0
16
 *
17
 * @licence GNU GPL v2+
18
 * @author Jeroen De Dauw < [email protected] >
19
 */
20
class BatchingIterator implements \Iterator {
21
22
	/**
23
	 * @var BatchingFetcher
24
	 */
25
	private $fetcher;
26
27
	/**
28
	 * @var int
29
	 */
30
	private $maxBatchSize = 10;
31
32
	/**
33
	 * @var mixed|null
34
	 */
35
	private $current = null;
36
37
	/**
38
	 * @var mixed[]
39
	 */
40
	private $currentBatch = [];
41
42
	/**
43
	 * @var int
44
	 */
45
	private $key;
46
47 12
	public function __construct( BatchingFetcher $fetcher ) {
48 12
		$this->fetcher = $fetcher;
49 12
	}
50
51
	/**
52
	 * @param int $maxBatchSize
53
	 *
54
	 * @throws InvalidArgumentException
55
	 */
56 9
	public function setMaxBatchSize( int $maxBatchSize ) {
57 9
		if ( $maxBatchSize < 1 ) {
58 3
			throw new InvalidArgumentException( '$maxBatchSize should be an int bigger than 0.' );
59
		}
60
61 6
		$this->maxBatchSize = $maxBatchSize;
62 6
	}
63
64
	/**
65
	 * Returns a value of the type returned by the BatchingFetcher,
66
	 * or null if there are no further values.
67
	 *
68
	 * @return mixed|null
69
	 */
70 7
	public function current() {
71 7
		return $this->current;
72
	}
73
74 9
	public function next() {
75 9
		$value = array_shift( $this->currentBatch );
76
77 9
		if ( $value === null ) {
78 9
			$this->nextValueFromNewBatch();
79
		}
80
		else {
81 7
			$this->current = $value;
82 7
			$this->key++;
83
		}
84 9
	}
85
86 9
	private function nextValueFromNewBatch() {
87 9
		$this->currentBatch = $this->fetcher->fetchNext( $this->maxBatchSize );
88
89 9
		if ( empty( $this->currentBatch ) ) {
90 9
			$this->current = null;
91
		}
92
		else {
93 7
			$this->next();
94
		}
95 9
	}
96
97 7
	public function key(): int {
98 7
		return $this->key;
99
	}
100
101 8
	public function valid(): bool {
102 8
		return $this->current !== null;
103
	}
104
105 9
	public function rewind() {
106 9
		$this->fetcher->rewind();
107 9
		$this->key = -1;
108 9
		$this->next();
109 9
	}
110
111
}
112