-
Notifications
You must be signed in to change notification settings - Fork 52
/
BatchJob.php
101 lines (81 loc) · 2.24 KB
/
BatchJob.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
<?php
/*
* This file is part of Spork, an OpenSky project.
*
* (c) OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spork\Batch;
use Spork\Batch\Strategy\ChunkStrategy;
use Spork\Batch\Strategy\StrategyInterface;
use Spork\Exception\UnexpectedTypeException;
use Spork\ProcessManager;
class BatchJob
{
private $manager;
private $data;
private $strategy;
private $name;
private $callback;
public function __construct(ProcessManager $manager, $data = null, StrategyInterface $strategy = null)
{
$this->manager = $manager;
$this->data = $data;
$this->strategy = $strategy ?: new ChunkStrategy();
$this->name = '<anonymous>';
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function setStrategy(StrategyInterface $strategy)
{
$this->strategy = $strategy;
return $this;
}
public function setData($data)
{
$this->data = $data;
return $this;
}
public function setCallback($callback)
{
if (!is_callable($callback)) {
throw new UnexpectedTypeException($callback, 'callable');
}
$this->callback = $callback;
return $this;
}
public function execute($callback = null)
{
if (null !== $callback) {
$this->setCallback($callback);
}
return $this->manager->fork($this)->setName($this->name.' batch');
}
/**
* Runs in a child process.
*
* @see execute()
*/
public function __invoke()
{
$forks = array();
foreach ($this->strategy->createBatches($this->data) as $index => $batch) {
$forks[] = $this->manager
->fork($this->strategy->createRunner($batch, $this->callback))
->setName(sprintf('%s batch #%d', $this->name, $index))
;
}
// block until all forks have exited
$this->manager->wait();
$results = array();
foreach ($forks as $fork) {
$results = array_merge($results, $fork->getResult());
}
return $results;
}
}