Command.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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(Array $arguments) {
  11. $this->_arguments = $this->filterArguments($arguments);
  12. unset($this->_hash);
  13. }
  14. public function getArguments() {
  15. return $this->_arguments;
  16. }
  17. public function getArgument($index = 0) {
  18. if (isset($this->_arguments[$index]) === true) {
  19. return $this->_arguments[$index];
  20. }
  21. }
  22. protected function canBeHashed() {
  23. return isset($this->_arguments[0]);
  24. }
  25. protected function getHashablePart($key) {
  26. $start = strpos($key, '{');
  27. if ($start !== false) {
  28. $end = strpos($key, '}', $start);
  29. if ($end !== false) {
  30. $key = substr($key, ++$start, $end - $start);
  31. }
  32. }
  33. return $key;
  34. }
  35. protected function checkSameHashForKeys(Array $keys) {
  36. if (($count = count($keys)) === 0) {
  37. return false;
  38. }
  39. $currentKey = $this->getHashablePart($keys[0]);
  40. for ($i = 1; $i < $count; $i++) {
  41. $nextKey = $this->getHashablePart($keys[$i]);
  42. if ($currentKey !== $nextKey) {
  43. return false;
  44. }
  45. $currentKey = $nextKey;
  46. }
  47. return true;
  48. }
  49. public function getHash(IDistributionStrategy $distributor) {
  50. if (isset($this->_hash)) {
  51. return $this->_hash;
  52. }
  53. if ($this->canBeHashed()) {
  54. $key = $this->getHashablePart($this->_arguments[0]);
  55. $this->_hash = $distributor->generateKey($key);
  56. return $this->_hash;
  57. }
  58. return null;
  59. }
  60. public function parseResponse($data) {
  61. return $data;
  62. }
  63. public function __toString() {
  64. $reducer = function($acc, $arg) {
  65. if (strlen($arg) > 32) {
  66. $arg = substr($arg, 0, 32) . '[...]';
  67. }
  68. $acc .= " $arg";
  69. return $acc;
  70. };
  71. return array_reduce($this->getArguments(), $reducer, $this->getId());
  72. }
  73. }