ScriptedCommand.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Command;
  11. /**
  12. * Base class used to implement an higher level abstraction for "virtual"
  13. * commands based on EVAL.
  14. *
  15. * @link http://redis.io/commands/eval
  16. * @author Daniele Alessandri <suppakilla@gmail.com>
  17. */
  18. abstract class ScriptedCommand extends ServerEvalSHA
  19. {
  20. /**
  21. * Gets the body of a Lua script.
  22. *
  23. * @return string
  24. */
  25. public abstract function getScript();
  26. /**
  27. * Specifies the number of arguments that should be considered as keys.
  28. *
  29. * The default behaviour for the base class is to return FALSE to indicate that
  30. * all the elements of the arguments array should be considered as keys, but
  31. * subclasses can enforce a static number of keys.
  32. *
  33. * @todo How about returning 1 by default to make scripted commands act like
  34. * variadic ones where the first argument is the key (KEYS[1]) and the
  35. * rest are values (ARGV)?
  36. *
  37. * @return int|Boolean
  38. */
  39. protected function getKeysCount()
  40. {
  41. return false;
  42. }
  43. /**
  44. * Returns the elements from the arguments that are identified as keys.
  45. *
  46. * @return array
  47. */
  48. public function getKeys()
  49. {
  50. return array_slice($this->getArguments(), 2, $this->getKeysCount());
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. protected function filterArguments(Array $arguments)
  56. {
  57. if (false !== $numkeys = $this->getKeysCount()) {
  58. $numkeys = $numkeys >= 0 ? $numkeys : count($arguments) + $numkeys;
  59. } else {
  60. $numkeys = count($arguments);
  61. }
  62. return array_merge(array(sha1($this->getScript()), $numkeys), $arguments);
  63. }
  64. /**
  65. * @return array
  66. */
  67. public function getEvalArguments()
  68. {
  69. $arguments = $this->getArguments();
  70. $arguments[0] = $this->getScript();
  71. return $arguments;
  72. }
  73. }