Config.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace Overtrue\Socialite;
  3. use ArrayAccess;
  4. use InvalidArgumentException;
  5. class Config implements ArrayAccess, \JsonSerializable
  6. {
  7. /**
  8. * @var array
  9. */
  10. protected array $config;
  11. /**
  12. * @param array $config
  13. */
  14. public function __construct(array $config)
  15. {
  16. $this->config = $config;
  17. }
  18. /**
  19. * @param string $key
  20. * @param mixed $default
  21. *
  22. * @return mixed
  23. */
  24. public function get(string $key, $default = null)
  25. {
  26. $config = $this->config;
  27. if (is_null($key)) {
  28. return $config;
  29. }
  30. if (isset($config[$key])) {
  31. return $config[$key];
  32. }
  33. foreach (explode('.', $key) as $segment) {
  34. if (!is_array($config) || !array_key_exists($segment, $config)) {
  35. return $default;
  36. }
  37. $config = $config[$segment];
  38. }
  39. return $config;
  40. }
  41. /**
  42. * @param string $key
  43. * @param mixed $value
  44. *
  45. * @return array
  46. */
  47. public function set(string $key, $value)
  48. {
  49. if (is_null($key)) {
  50. throw new InvalidArgumentException('Invalid config key.');
  51. }
  52. $keys = explode('.', $key);
  53. $config = &$this->config;
  54. while (count($keys) > 1) {
  55. $key = array_shift($keys);
  56. if (!isset($config[$key]) || !is_array($config[$key])) {
  57. $config[$key] = [];
  58. }
  59. $config = &$config[$key];
  60. }
  61. $config[array_shift($keys)] = $value;
  62. return $config;
  63. }
  64. /**
  65. * @param string $key
  66. *
  67. * @return bool
  68. */
  69. public function has(string $key): bool
  70. {
  71. return (bool) $this->get($key);
  72. }
  73. public function offsetExists($offset)
  74. {
  75. return array_key_exists($offset, $this->config);
  76. }
  77. public function offsetGet($offset)
  78. {
  79. return $this->get($offset);
  80. }
  81. public function offsetSet($offset, $value)
  82. {
  83. $this->set($offset, $value);
  84. }
  85. public function offsetUnset($offset)
  86. {
  87. $this->set($offset, null);
  88. }
  89. public function jsonSerialize()
  90. {
  91. return $this->config;
  92. }
  93. public function __toString()
  94. {
  95. return \json_encode($this, \JSON_UNESCAPED_UNICODE);
  96. }
  97. }