1: <?php
2:
3: namespace Guzzle\Service\Resource;
4:
5: use Guzzle\Common\AbstractHasDispatcher;
6: use Guzzle\Batch\BatchBuilder;
7: use Guzzle\Batch\BatchSizeDivisor;
8: use Guzzle\Batch\BatchClosureTransfer;
9:
10: 11: 12:
13: class ResourceIteratorApplyBatched extends AbstractHasDispatcher
14: {
15: 16: 17:
18: protected $callback;
19:
20: 21: 22:
23: protected $iterator;
24:
25: 26: 27:
28: protected $batches = 0;
29:
30: 31: 32:
33: protected $iterated = 0;
34:
35: 36: 37:
38: public static function getAllEvents()
39: {
40: return array(
41:
42: 'iterator_batch.before_batch',
43:
44: 'iterator_batch.after_batch',
45:
46: 'iterator_batch.created_batch'
47: );
48: }
49:
50: 51: 52: 53: 54: 55: 56:
57: public function __construct(ResourceIteratorInterface $iterator, $callback)
58: {
59: $this->iterator = $iterator;
60: $this->callback = $callback;
61: }
62:
63: 64: 65: 66: 67: 68: 69:
70: public function apply($perBatch = 50)
71: {
72: $this->iterated = $this->batches = $batches = 0;
73: $that = $this;
74: $it = $this->iterator;
75: $callback = $this->callback;
76:
77: $batch = BatchBuilder::factory()
78: ->createBatchesWith(new BatchSizeDivisor($perBatch))
79: ->transferWith(new BatchClosureTransfer(function (array $batch) use ($that, $callback, &$batches, $it) {
80: $batches++;
81: $that->dispatch('iterator_batch.before_batch', array('iterator' => $it, 'batch' => $batch));
82: call_user_func_array($callback, array($it, $batch));
83: $that->dispatch('iterator_batch.after_batch', array('iterator' => $it, 'batch' => $batch));
84: }))
85: ->autoFlushAt($perBatch)
86: ->build();
87:
88: $this->dispatch('iterator_batch.created_batch', array('batch' => $batch));
89:
90: foreach ($this->iterator as $resource) {
91: $this->iterated++;
92: $batch->add($resource);
93: }
94:
95: $batch->flush();
96: $this->batches = $batches;
97:
98: return $this->iterated;
99: }
100:
101: 102: 103: 104: 105:
106: public function getBatchCount()
107: {
108: return $this->batches;
109: }
110:
111: 112: 113: 114: 115:
116: public function getIteratedCount()
117: {
118: return $this->iterated;
119: }
120: }
121: