CustomOption.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Options;
  11. class CustomOption implements IOption
  12. {
  13. private $_validate;
  14. private $_default;
  15. public function __construct(Array $options)
  16. {
  17. $this->_validate = $this->filterCallable($options, 'validate');
  18. $this->_default = $this->filterCallable($options, 'default');
  19. }
  20. private function filterCallable($options, $key)
  21. {
  22. if (!isset($options[$key])) {
  23. return;
  24. }
  25. $callable = $options[$key];
  26. if (is_callable($callable)) {
  27. return $callable;
  28. }
  29. throw new \InvalidArgumentException("The parameter $key must be callable");
  30. }
  31. public function validate($value)
  32. {
  33. if (isset($value)) {
  34. if ($this->_validate === null) {
  35. return $value;
  36. }
  37. $validator = $this->_validate;
  38. return $validator($value);
  39. }
  40. }
  41. public function getDefault()
  42. {
  43. if (!isset($this->_default)) {
  44. return;
  45. }
  46. $default = $this->_default;
  47. return $default();
  48. }
  49. public function __invoke($value)
  50. {
  51. if (isset($value)) {
  52. return $this->validate($value);
  53. }
  54. return $this->getDefault();
  55. }
  56. }