ClientOptions.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. /**
  12. * Class that manages client options with filtering and conversion.
  13. *
  14. * @author Daniele Alessandri <suppakilla@gmail.com>
  15. */
  16. class ClientOptions implements IClientOptions
  17. {
  18. private $handlers;
  19. private $defined;
  20. private $options = array();
  21. /**
  22. * @param array $options Array of client options.
  23. */
  24. public function __construct(Array $options = array())
  25. {
  26. $this->handlers = $this->initialize($options);
  27. $this->defined = array_fill_keys(array_keys($options), true);
  28. }
  29. /**
  30. * Ensures that the default options are initialized.
  31. *
  32. * @return array
  33. */
  34. protected function getDefaultOptions()
  35. {
  36. return array(
  37. 'profile' => new ClientProfile(),
  38. 'connections' => new ClientConnectionFactory(),
  39. 'cluster' => new ClientCluster(),
  40. 'prefix' => new ClientPrefix(),
  41. );
  42. }
  43. /**
  44. * Initializes client options handlers.
  45. *
  46. * @param array $options List of client options values.
  47. * @return array
  48. */
  49. protected function initialize(Array $options)
  50. {
  51. $handlers = $this->getDefaultOptions();
  52. foreach ($options as $option => $value) {
  53. if (isset($handlers[$option])) {
  54. $handler = $handlers[$option];
  55. $handlers[$option] = function($options) use($handler, $value) {
  56. return $handler->filter($options, $value);
  57. };
  58. }
  59. else {
  60. $this->options[$option] = $value;
  61. }
  62. }
  63. return $handlers;
  64. }
  65. /**
  66. * Checks if the specified option is set.
  67. *
  68. * @param string $option Name of the option.
  69. * @return Boolean
  70. */
  71. public function __isset($option)
  72. {
  73. return isset($this->defined[$option]);
  74. }
  75. /**
  76. * Returns the value of the specified option.
  77. *
  78. * @param string $option Name of the option.
  79. * @return mixed
  80. */
  81. public function __get($option)
  82. {
  83. if (isset($this->options[$option])) {
  84. return $this->options[$option];
  85. }
  86. if (isset($this->handlers[$option])) {
  87. $handler = $this->handlers[$option];
  88. $value = $handler instanceof IOption ? $handler->getDefault($this) : $handler($this);
  89. $this->options[$option] = $value;
  90. return $value;
  91. }
  92. }
  93. }