Command.php 2.6 KB

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