Command.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. public function getHash(IDistributionStrategy $distributor) {
  21. if (isset($this->_hash)) {
  22. return $this->_hash;
  23. }
  24. if ($this->canBeHashed()) {
  25. $key = $this->getHashablePart($this->_arguments[0]);
  26. $this->_hash = $distributor->generateKey($key);
  27. return $this->_hash;
  28. }
  29. return null;
  30. }
  31. protected function filterArguments(Array $arguments) {
  32. return $arguments;
  33. }
  34. public function setArguments(/* arguments */) {
  35. $this->_arguments = $this->filterArguments(func_get_args());
  36. unset($this->_hash);
  37. }
  38. public function setArgumentsArray(Array $arguments) {
  39. $this->_arguments = $this->filterArguments($arguments);
  40. unset($this->_hash);
  41. }
  42. public function getArguments() {
  43. return $this->_arguments;
  44. }
  45. public function getArgument($index = 0) {
  46. if (isset($this->_arguments[$index]) === true) {
  47. return $this->_arguments[$index];
  48. }
  49. }
  50. public function parseResponse($data) {
  51. return $data;
  52. }
  53. public function __toString() {
  54. $reducer = function($acc, $arg) {
  55. if (strlen($arg) > 32) {
  56. $arg = substr($arg, 0, 32) . '[...]';
  57. }
  58. $acc .= " $arg";
  59. return $acc;
  60. };
  61. return array_reduce($this->getArguments(), $reducer, $this->getId());
  62. }
  63. }