SafeExecutor.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. } catch (CommunicationException $exception) {
  34. return array_fill(0, $size, $exception);
  35. }
  36. }
  37. for ($i = 0; $i < $size; $i++) {
  38. $command = $commands->dequeue();
  39. try {
  40. $response = $connection->readResponse($command);
  41. $values[$i] = $response instanceof \Iterator ? iterator_to_array($response) : $response;
  42. } catch (CommunicationException $exception) {
  43. $toAdd = count($commands) - count($values);
  44. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  45. break;
  46. }
  47. }
  48. return $values;
  49. }
  50. }