CustomOption.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\Options;
  11. /**
  12. * Implements a generic class used to dinamically define a client option.
  13. *
  14. * @author Daniele Alessandri <suppakilla@gmail.com>
  15. */
  16. class CustomOption implements IOption
  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. $callable = $options[$key];
  40. if (is_callable($callable)) {
  41. return $callable;
  42. }
  43. throw new \InvalidArgumentException("The parameter $key must be callable");
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function filter(IClientOptions $options, $value)
  49. {
  50. if (isset($value)) {
  51. if ($this->filter === null) {
  52. return $value;
  53. }
  54. $validator = $this->filter;
  55. return $validator($options, $value);
  56. }
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function getDefault(IClientOptions $options)
  62. {
  63. if (!isset($this->default)) {
  64. return;
  65. }
  66. $default = $this->default;
  67. return $default($options);
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. public function __invoke(IClientOptions $options, $value)
  73. {
  74. if (isset($value)) {
  75. return $this->filter($options, $value);
  76. }
  77. return $this->getDefault($options);
  78. }
  79. }