SafeExecutor.php 1.6 KB

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