CustomOption.php 1.2 KB

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