SafeExecutor.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\CommunicationException;
  13. use Predis\Network\IConnection;
  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 IPipelineExecutor
  21. {
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function execute(IConnection $connection, &$commands)
  26. {
  27. $sizeofPipe = count($commands);
  28. $values = array();
  29. foreach ($commands as $command) {
  30. try {
  31. $connection->writeCommand($command);
  32. }
  33. catch (CommunicationException $exception) {
  34. return array_fill(0, $sizeofPipe, $exception);
  35. }
  36. }
  37. for ($i = 0; $i < $sizeofPipe; $i++) {
  38. $command = $commands[$i];
  39. unset($commands[$i]);
  40. try {
  41. $response = $connection->readResponse($command);
  42. $values[] = $response instanceof \Iterator ? iterator_to_array($response) : $response;
  43. }
  44. catch (ServerException $exception) {
  45. $values[] = $exception->toResponseError();
  46. }
  47. catch (CommunicationException $exception) {
  48. $toAdd = count($commands) - count($values);
  49. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  50. break;
  51. }
  52. }
  53. return $values;
  54. }
  55. }