ClientOptions.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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;
  11. use Predis\Options\IOption;
  12. use Predis\Options\ClientPrefix;
  13. use Predis\Options\ClientProfile;
  14. use Predis\Options\ClientCluster;
  15. use Predis\Options\ClientConnectionFactory;
  16. class ClientOptions
  17. {
  18. private static $_sharedOptions;
  19. private $_handlers;
  20. private $_defined;
  21. private $_options = array();
  22. public function __construct(Array $options = array())
  23. {
  24. $this->_handlers = $this->initialize($options);
  25. $this->_defined = array_keys($options);
  26. }
  27. private static function getSharedOptions()
  28. {
  29. if (isset(self::$_sharedOptions)) {
  30. return self::$_sharedOptions;
  31. }
  32. self::$_sharedOptions = array(
  33. 'profile' => new ClientProfile(),
  34. 'connections' => new ClientConnectionFactory(),
  35. 'cluster' => new ClientCluster(),
  36. 'prefix' => new ClientPrefix(),
  37. );
  38. return self::$_sharedOptions;
  39. }
  40. public static function define($option, IOption $handler)
  41. {
  42. self::getSharedOptions();
  43. self::$_sharedOptions[$option] = $handler;
  44. }
  45. public static function undefine($option)
  46. {
  47. self::getSharedOptions();
  48. unset(self::$_sharedOptions[$option]);
  49. }
  50. private function initialize($options)
  51. {
  52. $handlers = self::getSharedOptions();
  53. foreach ($options as $option => $value) {
  54. if (isset($handlers[$option])) {
  55. $handler = $handlers[$option];
  56. $handlers[$option] = function() use($handler, $value) {
  57. return $handler->validate($value);
  58. };
  59. }
  60. }
  61. return $handlers;
  62. }
  63. public function __isset($option)
  64. {
  65. return in_array($option, $this->_defined);
  66. }
  67. public function __get($option)
  68. {
  69. if (isset($this->_options[$option])) {
  70. return $this->_options[$option];
  71. }
  72. if (isset($this->_handlers[$option])) {
  73. $handler = $this->_handlers[$option];
  74. $value = $handler instanceof IOption ? $handler->getDefault() : $handler();
  75. $this->_options[$option] = $value;
  76. return $value;
  77. }
  78. }
  79. }