ClientOptions.php 2.2 KB

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