CustomOption.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\Option;
  11. /**
  12. * Implements a generic class used to dynamically define a client option.
  13. *
  14. * @author Daniele Alessandri <suppakilla@gmail.com>
  15. */
  16. class CustomOption implements OptionInterface
  17. {
  18. private $filter;
  19. private $default;
  20. /**
  21. * @param array $options List of options
  22. */
  23. public function __construct(Array $options = array())
  24. {
  25. $this->filter = $this->ensureCallable($options, 'filter');
  26. $this->default = $this->ensureCallable($options, 'default');
  27. }
  28. /**
  29. * Checks if the specified value in the options array is a callable object.
  30. *
  31. * @param array $options Array of options
  32. * @param string $key Target option.
  33. */
  34. private function ensureCallable($options, $key)
  35. {
  36. if (!isset($options[$key])) {
  37. return;
  38. }
  39. if (is_callable($callable = $options[$key])) {
  40. return $callable;
  41. }
  42. throw new \InvalidArgumentException("The parameter $key must be callable");
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function filter(ClientOptionsInterface $options, $value)
  48. {
  49. if (isset($value)) {
  50. if ($this->filter === null) {
  51. return $value;
  52. }
  53. return call_user_func($this->filter, $options, $value);
  54. }
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function getDefault(ClientOptionsInterface $options)
  60. {
  61. if (!isset($this->default)) {
  62. return;
  63. }
  64. return call_user_func($this->default, $options);
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function __invoke(ClientOptionsInterface $options, $value)
  70. {
  71. if (isset($value)) {
  72. return $this->filter($options, $value);
  73. }
  74. return $this->getDefault($options);
  75. }
  76. }