StandardExecutor.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Pipeline;
  11. use Predis\ServerException;
  12. use Predis\Network\IConnection;
  13. use Predis\Network\IConnectionReplication;
  14. /**
  15. * Implements the standard pipeline executor strategy used
  16. * to write a list of commands and read their replies over
  17. * a connection to Redis.
  18. *
  19. * @author Daniele Alessandri <suppakilla@gmail.com>
  20. */
  21. class StandardExecutor implements IPipelineExecutor
  22. {
  23. /**
  24. * Allows the pipeline executor to perform operations on the
  25. * connection before starting to execute the commands stored
  26. * in the pipeline.
  27. *
  28. * @param IConnection Connection instance.
  29. */
  30. protected function checkConnection(IConnection $connection)
  31. {
  32. if ($connection instanceof IConnectionReplication) {
  33. $connection->switchTo('master');
  34. }
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function execute(IConnection $connection, &$commands)
  40. {
  41. $sizeofPipe = count($commands);
  42. $values = array();
  43. $this->checkConnection($connection);
  44. foreach ($commands as $command) {
  45. $connection->writeCommand($command);
  46. }
  47. try {
  48. for ($i = 0; $i < $sizeofPipe; $i++) {
  49. $response = $connection->readResponse($commands[$i]);
  50. $values[] = $response instanceof \Iterator
  51. ? iterator_to_array($response)
  52. : $response;
  53. unset($commands[$i]);
  54. }
  55. }
  56. catch (ServerException $exception) {
  57. // Force disconnection to prevent protocol desynchronization.
  58. $connection->disconnect();
  59. throw $exception;
  60. }
  61. return $values;
  62. }
  63. }