ClientOptions.php 2.2 KB

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