Command.php 2.0 KB

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