Command.php 2.4 KB

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