CustomOption.php 1.2 KB

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