CustomOption.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Predis\Options;
  3. class CustomOption implements IOption
  4. {
  5. private $_validate;
  6. private $_default;
  7. public function __construct(Array $options)
  8. {
  9. $this->_validate = $this->filterCallable($options, 'validate');
  10. $this->_default = $this->filterCallable($options, 'default');
  11. }
  12. private function filterCallable($options, $key)
  13. {
  14. if (!isset($options[$key])) {
  15. return;
  16. }
  17. $callable = $options[$key];
  18. if (is_callable($callable)) {
  19. return $callable;
  20. }
  21. throw new \InvalidArgumentException("The parameter $key must be callable");
  22. }
  23. public function validate($value)
  24. {
  25. if (isset($value)) {
  26. if ($this->_validate === null) {
  27. return $value;
  28. }
  29. $validator = $this->_validate;
  30. return $validator($value);
  31. }
  32. }
  33. public function getDefault()
  34. {
  35. if (!isset($this->_default)) {
  36. return;
  37. }
  38. $default = $this->_default;
  39. return $default();
  40. }
  41. public function __invoke($value)
  42. {
  43. if (isset($value)) {
  44. return $this->validate($value);
  45. }
  46. return $this->getDefault();
  47. }
  48. }