PipelineContext.php 2.1 KB

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