SafeExecutor.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. $values[$i] = $connection->readResponse($command);
  40. } catch (CommunicationException $exception) {
  41. $toAdd = count($commands) - count($values);
  42. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  43. break;
  44. }
  45. }
  46. return $values;
  47. }
  48. }