BatchRequestTransfer.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Guzzle\Batch;
  3. use Guzzle\Batch\BatchTransferInterface;
  4. use Guzzle\Batch\BatchDivisorInterface;
  5. use Guzzle\Common\Exception\InvalidArgumentException;
  6. use Guzzle\Http\Message\RequestInterface;
  7. /**
  8. * Batch transfer strategy used to efficiently transfer a batch of requests.
  9. * This class is to be used with {@see Guzzle\Batch\BatchInterface}
  10. */
  11. class BatchRequestTransfer implements BatchTransferInterface, BatchDivisorInterface
  12. {
  13. /** @var int Size of each command batch */
  14. protected $batchSize;
  15. /**
  16. * Constructor used to specify how large each batch should be
  17. *
  18. * @param int $batchSize Size of each batch
  19. */
  20. public function __construct($batchSize = 50)
  21. {
  22. $this->batchSize = $batchSize;
  23. }
  24. /**
  25. * Creates batches of requests by grouping requests by their associated curl multi object.
  26. * {@inheritdoc}
  27. */
  28. public function createBatches(\SplQueue $queue)
  29. {
  30. // Create batches by client objects
  31. $groups = new \SplObjectStorage();
  32. foreach ($queue as $item) {
  33. if (!$item instanceof RequestInterface) {
  34. throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface');
  35. }
  36. $client = $item->getClient();
  37. if (!$groups->contains($client)) {
  38. $groups->attach($client, array($item));
  39. } else {
  40. $current = $groups[$client];
  41. $current[] = $item;
  42. $groups[$client] = $current;
  43. }
  44. }
  45. $batches = array();
  46. foreach ($groups as $batch) {
  47. $batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize));
  48. }
  49. return $batches;
  50. }
  51. public function transfer(array $batch)
  52. {
  53. if ($batch) {
  54. reset($batch)->getClient()->send($batch);
  55. }
  56. }
  57. }