1: <?php
2:
3: namespace Guzzle\Batch;
4:
5: use Guzzle\Batch\BatchTransferInterface;
6: use Guzzle\Batch\BatchDivisorInterface;
7: use Guzzle\Common\Exception\InvalidArgumentException;
8: use Guzzle\Service\Command\CommandInterface;
9: use Guzzle\Service\Exception\InconsistentClientTransferException;
10:
11: 12: 13: 14:
15: class BatchCommandTransfer implements BatchTransferInterface, BatchDivisorInterface
16: {
17: 18: 19:
20: protected $batchSize;
21:
22: 23: 24: 25: 26:
27: public function __construct($batchSize = 50)
28: {
29: $this->batchSize = $batchSize;
30: }
31:
32: 33: 34: 35: 36:
37: public function createBatches(\SplQueue $queue)
38: {
39: $groups = new \SplObjectStorage();
40: foreach ($queue as $item) {
41: if (!$item instanceof CommandInterface) {
42: throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface');
43: }
44: $client = $item->getClient();
45: if (!$groups->contains($client)) {
46: $groups->attach($client, new \ArrayObject(array($item)));
47: } else {
48: $groups[$client]->append($item);
49: }
50: }
51:
52: $batches = array();
53: foreach ($groups as $batch) {
54: $batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize));
55: }
56:
57: return $batches;
58: }
59:
60: 61: 62:
63: public function transfer(array $batch)
64: {
65: if (empty($batch)) {
66: return;
67: }
68:
69:
70: $client = reset($batch)->getClient();
71:
72:
73: $invalid = array_filter($batch, function ($command) use ($client) {
74: return $command->getClient() !== $client;
75: });
76:
77: if (!empty($invalid)) {
78: throw new InconsistentClientTransferException($invalid);
79: }
80:
81: $client->execute($batch);
82: }
83: }
84: