Open Monograph Press  3.3.0
BatchCommandTransfer.php
1 <?php
2 
3 namespace Guzzle\Batch;
4 
10 
16 {
18  protected $batchSize;
19 
23  public function __construct($batchSize = 50)
24  {
25  $this->batchSize = $batchSize;
26  }
27 
32  public function createBatches(\SplQueue $queue)
33  {
34  $groups = new \SplObjectStorage();
35  foreach ($queue as $item) {
36  if (!$item instanceof CommandInterface) {
37  throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface');
38  }
39  $client = $item->getClient();
40  if (!$groups->contains($client)) {
41  $groups->attach($client, new \ArrayObject(array($item)));
42  } else {
43  $groups[$client]->append($item);
44  }
45  }
46 
47  $batches = array();
48  foreach ($groups as $batch) {
49  $batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize));
50  }
51 
52  return $batches;
53  }
54 
55  public function transfer(array $batch)
56  {
57  if (empty($batch)) {
58  return;
59  }
60 
61  // Get the client of the first found command
62  $client = reset($batch)->getClient();
63 
64  // Keep a list of all commands with invalid clients
65  $invalid = array_filter($batch, function ($command) use ($client) {
66  return $command->getClient() !== $client;
67  });
68 
69  if (!empty($invalid)) {
70  throw new InconsistentClientTransferException($invalid);
71  }
72 
73  $client->execute($batch);
74  }
75 }
Guzzle\Batch
Definition: AbstractBatchDecorator.php:3
Guzzle\Batch\BatchTransferInterface
Definition: BatchTransferInterface.php:8
Guzzle\Service\Exception\InconsistentClientTransferException
Definition: InconsistentClientTransferException.php:10
Guzzle\Batch\BatchCommandTransfer\$batchSize
$batchSize
Definition: BatchCommandTransfer.php:21
Guzzle\Batch\BatchCommandTransfer\transfer
transfer(array $batch)
Definition: BatchCommandTransfer.php:58
Guzzle\Service\Command\CommandInterface
Definition: CommandInterface.php:17
Guzzle\Common\Exception\InvalidArgumentException
Definition: lib/vendor/guzzle/guzzle/src/Guzzle/Common/Exception/InvalidArgumentException.php:5
Guzzle\Batch\BatchCommandTransfer\createBatches
createBatches(\SplQueue $queue)
Definition: BatchCommandTransfer.php:35
Guzzle\Batch\BatchCommandTransfer
Definition: BatchCommandTransfer.php:15
Guzzle\Batch\BatchDivisorInterface
Definition: BatchDivisorInterface.php:8
Guzzle\Batch\BatchCommandTransfer\__construct
__construct($batchSize=50)
Definition: BatchCommandTransfer.php:26