截流自动化的商城平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Env.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Songshenzong\Support;
  3. use Closure;
  4. /**
  5. * Class Env
  6. *
  7. * @package Songshenzong\Support
  8. */
  9. class Env
  10. {
  11. /**
  12. * Gets the value of an environment variable.
  13. *
  14. * @param string $key
  15. * @param mixed $default
  16. *
  17. * @return mixed
  18. */
  19. public static function env($key, $default = null)
  20. {
  21. $value = getenv($key);
  22. if ($value === false) {
  23. return self::value($default);
  24. }
  25. if (self::envSubstr($value)) {
  26. return substr($value, 1, -1);
  27. }
  28. return self::envConversion($value);
  29. }
  30. /**
  31. * @param string $key
  32. *
  33. * @return bool|mixed
  34. */
  35. public static function envNotEmpty($key)
  36. {
  37. $value = self::env($key, false);
  38. if ($value) {
  39. return $value;
  40. }
  41. return false;
  42. }
  43. /**
  44. * Return the default value of the given value.
  45. *
  46. * @param mixed $value
  47. *
  48. * @return mixed
  49. */
  50. public static function value($value)
  51. {
  52. return $value instanceof Closure ? $value() : $value;
  53. }
  54. /**
  55. * @param $value
  56. *
  57. * @return bool
  58. */
  59. public static function envSubstr($value)
  60. {
  61. return ($valueLength = strlen($value)) > 1
  62. && strpos($value, '"') === 0
  63. && $value[$valueLength - 1] === '"';
  64. }
  65. /**
  66. * @param $value
  67. *
  68. * @return bool|string|null
  69. */
  70. public static function envConversion($value)
  71. {
  72. $key = strtolower($value);
  73. if ($key === 'null' || $key === '(null)') {
  74. return null;
  75. }
  76. $list = [
  77. 'true' => true,
  78. '(true)' => true,
  79. 'false' => false,
  80. '(false)' => false,
  81. 'empty' => '',
  82. '(empty)' => '',
  83. ];
  84. return isset($list[$key]) ? $list[$key] : $value;
  85. }
  86. }