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 canBeHashed() {
  8. return isset($this->_arguments[0]);
  9. }
  10. protected function getHashablePart($key) {
  11. $start = strpos($key, '{');
  12. if ($start !== false) {
  13. $end = strpos($key, '}', $start);
  14. if ($end !== false) {
  15. $key = substr($key, ++$start, $end - $start);
  16. }
  17. }
  18. return $key;
  19. }
  20. protected function checkSameHashForKeys(Array $keys) {
  21. if (($count = count($keys)) === 0) {
  22. return false;
  23. }
  24. $currentKey = $this->getHashablePart($keys[0]);
  25. for ($i = 1; $i < $count; $i++) {
  26. $nextKey = $this->getHashablePart($keys[$i]);
  27. if ($currentKey !== $nextKey) {
  28. return false;
  29. }
  30. $currentKey = $nextKey;
  31. }
  32. return true;
  33. }
  34. public function getHash(IDistributionStrategy $distributor) {
  35. if (isset($this->_hash)) {
  36. return $this->_hash;
  37. }
  38. if ($this->canBeHashed()) {
  39. $key = $this->getHashablePart($this->_arguments[0]);
  40. $this->_hash = $distributor->generateKey($key);
  41. return $this->_hash;
  42. }
  43. return null;
  44. }
  45. protected function filterArguments(Array $arguments) {
  46. return $arguments;
  47. }
  48. public function setArguments(/* arguments */) {
  49. $this->_arguments = $this->filterArguments(func_get_args());
  50. unset($this->_hash);
  51. }
  52. public function setArgumentsArray(Array $arguments) {
  53. $this->_arguments = $this->filterArguments($arguments);
  54. unset($this->_hash);
  55. }
  56. public function getArguments() {
  57. return $this->_arguments;
  58. }
  59. public function getArgument($index = 0) {
  60. if (isset($this->_arguments[$index]) === true) {
  61. return $this->_arguments[$index];
  62. }
  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. }