PipelineContext.php 2.1 KB

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