SafeExecutor.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 SplQueue;
  12. use Predis\CommunicationException;
  13. use Predis\ServerException;
  14. use Predis\Connection\ConnectionInterface;
  15. /**
  16. * Implements a pipeline executor strategy that does not fail when an error is
  17. * encountered, but adds the returned error in the replies array.
  18. *
  19. * @author Daniele Alessandri <suppakilla@gmail.com>
  20. */
  21. class SafeExecutor implements PipelineExecutorInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function execute(ConnectionInterface $connection, SplQueue $commands)
  27. {
  28. $size = count($commands);
  29. $values = array();
  30. foreach ($commands as $command) {
  31. try {
  32. $connection->writeCommand($command);
  33. }
  34. catch (CommunicationException $exception) {
  35. return array_fill(0, $size, $exception);
  36. }
  37. }
  38. for ($i = 0; $i < $size; $i++) {
  39. $command = $commands->dequeue();
  40. try {
  41. $response = $connection->readResponse($command);
  42. $values[$i] = $response instanceof \Iterator ? iterator_to_array($response) : $response;
  43. }
  44. catch (CommunicationException $exception) {
  45. $toAdd = count($commands) - count($values);
  46. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  47. break;
  48. }
  49. }
  50. return $values;
  51. }
  52. }