CommandPipeline.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Predis;
  3. use Predis\Pipeline\IPipelineExecutor;
  4. class CommandPipeline {
  5. private $_client, $_pipelineBuffer, $_returnValues, $_running, $_executor;
  6. public function __construct(Client $client, IPipelineExecutor $executor = null) {
  7. $this->_client = $client;
  8. $this->_executor = $executor ?: new Pipeline\StandardExecutor();
  9. $this->_pipelineBuffer = array();
  10. $this->_returnValues = array();
  11. }
  12. public function __call($method, $arguments) {
  13. $command = $this->_client->createCommand($method, $arguments);
  14. $this->recordCommand($command);
  15. return $this;
  16. }
  17. private function recordCommand(ICommand $command) {
  18. $this->_pipelineBuffer[] = $command;
  19. }
  20. public function flushPipeline() {
  21. if (count($this->_pipelineBuffer) > 0) {
  22. $connection = $this->_client->getConnection();
  23. $this->_returnValues = array_merge(
  24. $this->_returnValues,
  25. $this->_executor->execute($connection, $this->_pipelineBuffer)
  26. );
  27. $this->_pipelineBuffer = array();
  28. }
  29. return $this;
  30. }
  31. private function setRunning($bool) {
  32. if ($bool === true && $this->_running === true) {
  33. throw new ClientException("This pipeline is already opened");
  34. }
  35. $this->_running = $bool;
  36. }
  37. public function execute($block = null) {
  38. if ($block && !is_callable($block)) {
  39. throw new \InvalidArgumentException('Argument passed must be a callable object');
  40. }
  41. $this->setRunning(true);
  42. $pipelineBlockException = null;
  43. try {
  44. if ($block !== null) {
  45. $block($this);
  46. }
  47. $this->flushPipeline();
  48. }
  49. catch (\Exception $exception) {
  50. $pipelineBlockException = $exception;
  51. }
  52. $this->setRunning(false);
  53. if ($pipelineBlockException !== null) {
  54. throw $pipelineBlockException;
  55. }
  56. return $this->_returnValues;
  57. }
  58. }