-
Notifications
You must be signed in to change notification settings - Fork 0
/
BatchResult.php
115 lines (103 loc) · 2.67 KB
/
BatchResult.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
/**
* 批量获取数据
* User: 李鹏飞 <[email protected]>
* Date: 2015/12/29
* Time: 16:26
*/
class BatchResult implements \Iterator
{
public $batchSize = 100;
public $each = true;
/**
* @var callable
*/
private $_callback;
private $_key;
private $_offset;
private $_value;
private $_batch;
/**
* @inheritDoc
*/
public function __construct(callable $callback)
{
$this->_callback = $callback;
}
/**
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
* @since 5.0.0
*/
public function current()
{
return $this->_value;
}
/**
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function next()
{
if ($this->_batch === null || !$this->each || $this->each && next($this->_batch) === false) {
$this->fetchData();
reset($this->_batch);
}
if($this->each){
$this->_value = current($this->_batch);
if (key($this->_batch) !== null) {
$this->_key++;
} else {
$this->_key = null;
}
}else{
$this->_value = $this->_batch;
$this->_key = $this->_key === null ? 0 : $this->_key + 1;
}
}
/**
* 获取数据,也是这个批量数据的核心
*/
protected function fetchData(){
$this->_batch = call_user_func($this->_callback, $this->_offset, $this->batchSize);
$this->_offset += $this->batchSize;
}
/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
* @since 5.0.0
*/
public function key()
{
return $this->_key;
}
/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
* @since 5.0.0
*/
public function valid()
{
return !empty($this->_value);
}
/**
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function rewind()
{
$this->_key = 0;
$this->_value = null;
$this->_batch = null;
$this->_offset = 0;
$this->next();
}
}