SafeClusterExecutor.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 for connection clusters that does
  16. * not fail when an error is encountered, but adds the returned error in the
  17. * replies array.
  18. *
  19. * @author Daniele Alessandri <suppakilla@gmail.com>
  20. */
  21. class SafeClusterExecutor implements IPipelineExecutor
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function execute(IConnection $connection, &$commands)
  27. {
  28. $connectionExceptions = array();
  29. $sizeofPipe = count($commands);
  30. $values = array();
  31. foreach ($commands as $command) {
  32. $cmdConnection = $connection->getConnection($command);
  33. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  34. continue;
  35. }
  36. try {
  37. $cmdConnection->writeCommand($command);
  38. }
  39. catch (CommunicationException $exception) {
  40. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  41. }
  42. }
  43. for ($i = 0; $i < $sizeofPipe; $i++) {
  44. $command = $commands[$i];
  45. unset($commands[$i]);
  46. $cmdConnection = $connection->getConnection($command);
  47. $connectionObjectHash = spl_object_hash($cmdConnection);
  48. if (isset($connectionExceptions[$connectionObjectHash])) {
  49. $values[] = $connectionExceptions[$connectionObjectHash];
  50. continue;
  51. }
  52. try {
  53. $response = $cmdConnection->readResponse($command);
  54. $values[] = $response instanceof \Iterator ? iterator_to_array($response) : $response;
  55. }
  56. catch (ServerException $exception) {
  57. $values[] = $exception->toResponseError();
  58. }
  59. catch (CommunicationException $exception) {
  60. $values[] = $exception;
  61. $connectionExceptions[$connectionObjectHash] = $exception;
  62. }
  63. }
  64. return $values;
  65. }
  66. }