Command.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 getArguments() {
  16. return $this->_arguments;
  17. }
  18. public function getArgument($index = 0) {
  19. if (isset($this->_arguments[$index]) === true) {
  20. return $this->_arguments[$index];
  21. }
  22. }
  23. protected function canBeHashed() {
  24. return isset($this->_arguments[0]);
  25. }
  26. protected function checkSameHashForKeys(Array $keys) {
  27. if (($count = count($keys)) === 0) {
  28. return false;
  29. }
  30. $currentKey = Helpers::getKeyHashablePart($keys[0]);
  31. for ($i = 1; $i < $count; $i++) {
  32. $nextKey = Helpers::getKeyHashablePart($keys[$i]);
  33. if ($currentKey !== $nextKey) {
  34. return false;
  35. }
  36. $currentKey = $nextKey;
  37. }
  38. return true;
  39. }
  40. public function getHash(INodeKeyGenerator $distributor) {
  41. if (isset($this->_hash)) {
  42. return $this->_hash;
  43. }
  44. if ($this->canBeHashed()) {
  45. $key = Helpers::getKeyHashablePart($this->_arguments[0]);
  46. $this->_hash = $distributor->generateKey($key);
  47. return $this->_hash;
  48. }
  49. return null;
  50. }
  51. public function parseResponse($data) {
  52. return $data;
  53. }
  54. protected function toStringArgumentReducer($accumulator, $argument) {
  55. if (strlen($argument) > 32) {
  56. $argument = substr($argument, 0, 32) . '[...]';
  57. }
  58. $accumulator .= " $argument";
  59. return $accumulator;
  60. }
  61. public function __toString() {
  62. return array_reduce(
  63. $this->getArguments(),
  64. array($this, 'toStringArgumentReducer'),
  65. $this->getId()
  66. );
  67. }
  68. }