Command.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Predis;
  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. public function getHash(IDistributionStrategy $distributor) {
  11. if (isset($this->_hash)) {
  12. return $this->_hash;
  13. }
  14. if (isset($this->_arguments[0])) {
  15. // TODO: should we throw an exception if the command does not
  16. // support sharding?
  17. $key = $this->_arguments[0];
  18. $start = strpos($key, '{');
  19. if ($start !== false) {
  20. $end = strpos($key, '}', $start);
  21. if ($end !== false) {
  22. $key = substr($key, ++$start, $end - $start);
  23. }
  24. }
  25. $this->_hash = $distributor->generateKey($key);
  26. return $this->_hash;
  27. }
  28. return null;
  29. }
  30. protected function filterArguments(Array $arguments) {
  31. return $arguments;
  32. }
  33. public function setArguments(/* arguments */) {
  34. $this->_arguments = $this->filterArguments(func_get_args());
  35. unset($this->_hash);
  36. }
  37. public function setArgumentsArray(Array $arguments) {
  38. $this->_arguments = $this->filterArguments($arguments);
  39. unset($this->_hash);
  40. }
  41. public function getArguments() {
  42. return $this->_arguments;
  43. }
  44. public function getArgument($index = 0) {
  45. if (isset($this->_arguments[$index]) === true) {
  46. return $this->_arguments[$index];
  47. }
  48. }
  49. public function parseResponse($data) {
  50. return $data;
  51. }
  52. public function __toString() {
  53. $reducer = function($acc, $arg) {
  54. if (strlen($arg) > 32) {
  55. $arg = substr($arg, 0, 32) . '[...]';
  56. }
  57. $acc .= " $arg";
  58. return $acc;
  59. };
  60. return array_reduce($this->getArguments(), $reducer, $this->getCommandId());
  61. }
  62. }