CustomOption.php 1.2 KB

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