CustomOption.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. return call_user_func($this->_validate, $value);
  25. }
  26. }
  27. public function getDefault() {
  28. if ($this->_default !== null) {
  29. return call_user_func($this->_default);
  30. }
  31. }
  32. public function __invoke($value) {
  33. return isset($value) ? $this->validate($value) : $this->getDefault();
  34. }
  35. }