ClientOptions.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. 'replication' => new ClientReplication(),
  41. 'prefix' => new ClientPrefix(),
  42. );
  43. }
  44. /**
  45. * Initializes client options handlers.
  46. *
  47. * @param array $options List of client options values.
  48. * @return array
  49. */
  50. protected function initialize(Array $options)
  51. {
  52. $handlers = $this->getDefaultOptions();
  53. foreach ($options as $option => $value) {
  54. if (isset($handlers[$option])) {
  55. $handler = $handlers[$option];
  56. $handlers[$option] = function($options) use($handler, $value) {
  57. return $handler->filter($options, $value);
  58. };
  59. }
  60. else {
  61. $this->options[$option] = $value;
  62. }
  63. }
  64. return $handlers;
  65. }
  66. /**
  67. * Checks if the specified option is set.
  68. *
  69. * @param string $option Name of the option.
  70. * @return Boolean
  71. */
  72. public function __isset($option)
  73. {
  74. return isset($this->defined[$option]);
  75. }
  76. /**
  77. * Returns the value of the specified option.
  78. *
  79. * @param string $option Name of the option.
  80. * @return mixed
  81. */
  82. public function __get($option)
  83. {
  84. if (isset($this->options[$option])) {
  85. return $this->options[$option];
  86. }
  87. if (isset($this->handlers[$option])) {
  88. $handler = $this->handlers[$option];
  89. $value = $handler instanceof IOption ? $handler->getDefault($this) : $handler($this);
  90. $this->options[$option] = $value;
  91. return $value;
  92. }
  93. }
  94. }