ClientOptions.php 2.2 KB

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