/
Batch.php
59 lines (47 loc) · 1.42 KB
/
Batch.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
<?php
/**
* Created by PhpStorm.
* User: sam
* Date: 5/29/15
* Time: 5:46 PM
*/
class Batch {
protected $callback;
protected $defaultCategory;
public $batchSize;
public $commitCount = 0;
protected $data = [];
public function __construct(Closure $callback, $batchSize = 5000, $defaultCategory = 'default') {
$this->callback = $callback;
$this->batchSize = $batchSize;
$this->defaultCategory = $defaultCategory;
}
public function add($elements, $category = null) {
if (!empty($elements) && is_scalar(reset($elements))) {
$elements = [$elements];
}
if (!isset($category)) {
$category = $this->defaultCategory;
}
foreach($elements as $element) {
$this->data[$category][] = ($element instanceof \CActiveRecord) ? $element->attributes : $element;
if (count($this->data[$category]) > $this->batchSize) {
$this->commitCategory($category);
}
}
}
public function commitCategory($category) {
$callback = $this->callback;
$callback($this->data[$category], $category);
$this->commitCount++;
unset($this->data[$category]);
}
public function commit() {
foreach($this->data as $key => $items) {
$this->commitCategory($key);
}
}
public function __destruct() {
$this->commit();
}
}