Command.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. public function __toString() {
  55. $reducer = function($acc, $arg) {
  56. if (strlen($arg) > 32) {
  57. $arg = substr($arg, 0, 32) . '[...]';
  58. }
  59. $acc .= " $arg";
  60. return $acc;
  61. };
  62. return array_reduce($this->getArguments(), $reducer, $this->getId());
  63. }
  64. }