Helpers.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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;
  11. use Predis\Network\IConnection;
  12. use Predis\Network\IConnectionCluster;
  13. /**
  14. * Defines a few helper methods.
  15. *
  16. * @author Daniele Alessandri <suppakilla@gmail.com>
  17. */
  18. class Helpers
  19. {
  20. /**
  21. * Checks if the specified connection represents a cluster.
  22. *
  23. * @param IConnection $connection Connection object.
  24. * @return Boolean
  25. */
  26. public static function isCluster(IConnection $connection)
  27. {
  28. return $connection instanceof IConnectionCluster;
  29. }
  30. /**
  31. * Offers a generic and reusable method to handle exceptions generated by
  32. * a connection object.
  33. *
  34. * @param CommunicationException $exception Exception.
  35. */
  36. public static function onCommunicationException(CommunicationException $exception)
  37. {
  38. if ($exception->shouldResetConnection()) {
  39. $connection = $exception->getConnection();
  40. if ($connection->isConnected()) {
  41. $connection->disconnect();
  42. }
  43. }
  44. throw $exception;
  45. }
  46. /**
  47. * Normalizes the arguments array passed to a Redis command.
  48. *
  49. * @param array $arguments Arguments for a command.
  50. * @return array
  51. */
  52. public static function filterArrayArguments(Array $arguments)
  53. {
  54. if (count($arguments) === 1 && is_array($arguments[0])) {
  55. return $arguments[0];
  56. }
  57. return $arguments;
  58. }
  59. /**
  60. * Normalizes the arguments array passed to a variadic Redis command.
  61. *
  62. * @param array $arguments Arguments for a command.
  63. * @return array
  64. */
  65. public static function filterVariadicValues(Array $arguments)
  66. {
  67. if (count($arguments) === 2 && is_array($arguments[1])) {
  68. return array_merge(array($arguments[0]), $arguments[1]);
  69. }
  70. return $arguments;
  71. }
  72. /**
  73. * Returns only the hashable part of a key (delimited by "{...}"), or the
  74. * whole key if a key tag is not found in the string.
  75. *
  76. * @param string $key A key.
  77. * @return string
  78. */
  79. public static function extractKeyTag($key)
  80. {
  81. $start = strpos($key, '{');
  82. if ($start !== false) {
  83. $end = strpos($key, '}', $start);
  84. if ($end !== false) {
  85. $key = substr($key, ++$start, $end - $start);
  86. }
  87. }
  88. return $key;
  89. }
  90. }