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\Http\Message\RequestInterface;
9:
10: 11: 12: 13:
14: class BatchRequestTransfer implements BatchTransferInterface, BatchDivisorInterface
15: {
16: 17: 18:
19: protected $batchSize;
20:
21: 22: 23: 24: 25:
26: public function __construct($batchSize = 50)
27: {
28: $this->batchSize = $batchSize;
29: }
30:
31: 32: 33: 34: 35:
36: public function createBatches(\SplQueue $queue)
37: {
38:
39: $groups = new \SplObjectStorage();
40: foreach ($queue as $item) {
41: if (!$item instanceof RequestInterface) {
42: throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface');
43: }
44: $multi = $item->getClient()->getCurlMulti();
45: if (!$groups->contains($multi)) {
46: $groups->attach($multi, new \ArrayObject(array($item)));
47: } else {
48: $groups[$multi]->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: $multi = reset($batch)->getClient()->getCurlMulti();
70:
71:
72: foreach ($batch as $request) {
73: $multi->add($request);
74: }
75:
76: $multi->send();
77: }
78: }
79: