Open Journal Systems  3.3.0
Batch.php
1 <?php
2 
3 namespace Guzzle\Batch;
4 
6 
15 class Batch implements BatchInterface
16 {
18  protected $queue;
19 
21  protected $dividedBatches;
22 
24  protected $transferStrategy;
25 
27  protected $divisionStrategy;
28 
34  {
35  $this->transferStrategy = $transferStrategy;
36  $this->divisionStrategy = $divisionStrategy;
37  $this->queue = new \SplQueue();
38  $this->queue->setIteratorMode(\SplQueue::IT_MODE_DELETE);
39  $this->dividedBatches = array();
40  }
41 
42  public function add($item)
43  {
44  $this->queue->enqueue($item);
45 
46  return $this;
47  }
48 
49  public function flush()
50  {
51  $this->createBatches();
52 
53  $items = array();
54  foreach ($this->dividedBatches as $batchIndex => $dividedBatch) {
55  while ($dividedBatch->valid()) {
56  $batch = $dividedBatch->current();
57  $dividedBatch->next();
58  try {
59  $this->transferStrategy->transfer($batch);
60  $items = array_merge($items, $batch);
61  } catch (\Exception $e) {
62  throw new BatchTransferException($batch, $items, $e, $this->transferStrategy, $this->divisionStrategy);
63  }
64  }
65  // Keep the divided batch down to a minimum in case of a later exception
66  unset($this->dividedBatches[$batchIndex]);
67  }
68 
69  return $items;
70  }
71 
72  public function isEmpty()
73  {
74  return count($this->queue) == 0 && count($this->dividedBatches) == 0;
75  }
76 
80  protected function createBatches()
81  {
82  if (count($this->queue)) {
83  if ($batches = $this->divisionStrategy->createBatches($this->queue)) {
84  // Convert arrays into iterators
85  if (is_array($batches)) {
86  $batches = new \ArrayIterator($batches);
87  }
88  $this->dividedBatches[] = $batches;
89  }
90  }
91  }
92 }
Guzzle\Batch
Definition: AbstractBatchDecorator.php:3
Guzzle\Batch\Batch\__construct
__construct(BatchTransferInterface $transferStrategy, BatchDivisorInterface $divisionStrategy)
Definition: Batch.php:45
Guzzle\Batch\BatchTransferInterface
Definition: BatchTransferInterface.php:8
Guzzle\Batch\Batch\$transferStrategy
$transferStrategy
Definition: Batch.php:33
Guzzle\Batch\Batch\add
add($item)
Definition: Batch.php:54
Guzzle\Batch\Batch\flush
flush()
Definition: Batch.php:61
Guzzle\Batch\Batch\$dividedBatches
$dividedBatches
Definition: Batch.php:27
Guzzle\Batch\BatchInterface
Definition: BatchInterface.php:8
Guzzle\Batch\Batch\createBatches
createBatches()
Definition: Batch.php:92
Seboettg\Collection\count
count()
Definition: ArrayListTrait.php:253
Guzzle\Batch\Batch\$queue
$queue
Definition: Batch.php:21
Guzzle\Batch\Batch\$divisionStrategy
$divisionStrategy
Definition: Batch.php:39
Guzzle\Batch\Exception\BatchTransferException
Definition: BatchTransferException.php:12
Guzzle\Batch\BatchDivisorInterface
Definition: BatchDivisorInterface.php:8
Guzzle\Batch\Batch\isEmpty
isEmpty()
Definition: Batch.php:84
Guzzle\Batch\Batch
Definition: Batch.php:15