Command.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 onPrefixKeys(Array $arguments, $prefix) {
  24. $arguments[0] = "$prefix{$arguments[0]}";
  25. return $arguments;
  26. }
  27. public function prefixKeys($prefix) {
  28. $arguments = $this->onPrefixKeys($this->_arguments, $prefix);
  29. if (isset($arguments)) {
  30. $this->_arguments = $arguments;
  31. unset($this->_hash);
  32. }
  33. }
  34. protected function canBeHashed() {
  35. return isset($this->_arguments[0]);
  36. }
  37. protected function checkSameHashForKeys(Array $keys) {
  38. if (($count = count($keys)) === 0) {
  39. return false;
  40. }
  41. $currentKey = Helpers::getKeyHashablePart($keys[0]);
  42. for ($i = 1; $i < $count; $i++) {
  43. $nextKey = Helpers::getKeyHashablePart($keys[$i]);
  44. if ($currentKey !== $nextKey) {
  45. return false;
  46. }
  47. $currentKey = $nextKey;
  48. }
  49. return true;
  50. }
  51. public function getHash(INodeKeyGenerator $distributor) {
  52. if (isset($this->_hash)) {
  53. return $this->_hash;
  54. }
  55. if ($this->canBeHashed()) {
  56. $key = Helpers::getKeyHashablePart($this->_arguments[0]);
  57. $this->_hash = $distributor->generateKey($key);
  58. return $this->_hash;
  59. }
  60. return null;
  61. }
  62. public function parseResponse($data) {
  63. return $data;
  64. }
  65. protected function toStringArgumentReducer($accumulator, $argument) {
  66. if (strlen($argument) > 32) {
  67. $argument = substr($argument, 0, 32) . '[...]';
  68. }
  69. $accumulator .= " $argument";
  70. return $accumulator;
  71. }
  72. public function __toString() {
  73. return array_reduce(
  74. $this->getArguments(),
  75. array($this, 'toStringArgumentReducer'),
  76. $this->getId()
  77. );
  78. }
  79. }