FlushingBatch.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Guzzle\Batch;
  3. /**
  4. * BatchInterface decorator used to add automatic flushing of the queue when the size of the queue reaches a threshold.
  5. */
  6. class FlushingBatch extends AbstractBatchDecorator
  7. {
  8. /** @var int The threshold for which to automatically flush */
  9. protected $threshold;
  10. /** @var int Current number of items known to be in the queue */
  11. protected $currentTotal = 0;
  12. /**
  13. * @param BatchInterface $decoratedBatch BatchInterface that is being decorated
  14. * @param int $threshold Flush when the number in queue matches the threshold
  15. */
  16. public function __construct(BatchInterface $decoratedBatch, $threshold)
  17. {
  18. $this->threshold = $threshold;
  19. parent::__construct($decoratedBatch);
  20. }
  21. /**
  22. * Set the auto-flush threshold
  23. *
  24. * @param int $threshold The auto-flush threshold
  25. *
  26. * @return FlushingBatch
  27. */
  28. public function setThreshold($threshold)
  29. {
  30. $this->threshold = $threshold;
  31. return $this;
  32. }
  33. /**
  34. * Get the auto-flush threshold
  35. *
  36. * @return int
  37. */
  38. public function getThreshold()
  39. {
  40. return $this->threshold;
  41. }
  42. public function add($item)
  43. {
  44. $this->decoratedBatch->add($item);
  45. if (++$this->currentTotal >= $this->threshold) {
  46. $this->currentTotal = 0;
  47. $this->decoratedBatch->flush();
  48. }
  49. return $this;
  50. }
  51. }