Command.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace Predis\Commands;
  3. use Predis\Helpers;
  4. use Predis\Distribution\INodeKeyGenerator;
  5. abstract class Command implements ICommand
  6. {
  7. private $_hash;
  8. private $_arguments = array();
  9. protected function filterArguments(Array $arguments)
  10. {
  11. return $arguments;
  12. }
  13. public function setArguments(Array $arguments)
  14. {
  15. $this->_arguments = $this->filterArguments($arguments);
  16. unset($this->_hash);
  17. }
  18. public function setRawArguments(Array $arguments)
  19. {
  20. $this->_arguments = $arguments;
  21. unset($this->_hash);
  22. }
  23. public function getArguments()
  24. {
  25. return $this->_arguments;
  26. }
  27. public function getArgument($index = 0)
  28. {
  29. if (isset($this->_arguments[$index]) === true) {
  30. return $this->_arguments[$index];
  31. }
  32. }
  33. protected function onPrefixKeys(Array $arguments, $prefix)
  34. {
  35. $arguments[0] = "$prefix{$arguments[0]}";
  36. return $arguments;
  37. }
  38. public function prefixKeys($prefix)
  39. {
  40. $arguments = $this->onPrefixKeys($this->_arguments, $prefix);
  41. if (isset($arguments)) {
  42. $this->_arguments = $arguments;
  43. unset($this->_hash);
  44. }
  45. }
  46. protected function canBeHashed()
  47. {
  48. return isset($this->_arguments[0]);
  49. }
  50. protected function checkSameHashForKeys(Array $keys)
  51. {
  52. if (($count = count($keys)) === 0) {
  53. return false;
  54. }
  55. $currentKey = Helpers::getKeyHashablePart($keys[0]);
  56. for ($i = 1; $i < $count; $i++) {
  57. $nextKey = Helpers::getKeyHashablePart($keys[$i]);
  58. if ($currentKey !== $nextKey) {
  59. return false;
  60. }
  61. $currentKey = $nextKey;
  62. }
  63. return true;
  64. }
  65. public function getHash(INodeKeyGenerator $distributor)
  66. {
  67. if (isset($this->_hash)) {
  68. return $this->_hash;
  69. }
  70. if ($this->canBeHashed()) {
  71. $key = Helpers::getKeyHashablePart($this->_arguments[0]);
  72. $this->_hash = $distributor->generateKey($key);
  73. return $this->_hash;
  74. }
  75. return null;
  76. }
  77. public function parseResponse($data)
  78. {
  79. return $data;
  80. }
  81. protected function toStringArgumentReducer($accumulator, $argument)
  82. {
  83. if (strlen($argument) > 32) {
  84. $argument = substr($argument, 0, 32) . '[...]';
  85. }
  86. $accumulator .= " $argument";
  87. return $accumulator;
  88. }
  89. public function __toString()
  90. {
  91. return array_reduce(
  92. $this->getArguments(),
  93. array($this, 'toStringArgumentReducer'),
  94. $this->getId()
  95. );
  96. }
  97. }