Context.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Context;
  12. use Hyperf\Engine\Coroutine;
  13. class Context
  14. {
  15. protected static $nonCoContext = [];
  16. public static function set(string $id, $value)
  17. {
  18. if (Coroutine::id() > 0) {
  19. Coroutine::getContextFor()[$id] = $value;
  20. } else {
  21. static::$nonCoContext[$id] = $value;
  22. }
  23. return $value;
  24. }
  25. public static function get(string $id, $default = null, $coroutineId = null)
  26. {
  27. if (Coroutine::id() > 0) {
  28. return Coroutine::getContextFor($coroutineId)[$id] ?? $default;
  29. }
  30. return static::$nonCoContext[$id] ?? $default;
  31. }
  32. public static function has(string $id, $coroutineId = null)
  33. {
  34. if (Coroutine::id() > 0) {
  35. return isset(Coroutine::getContextFor($coroutineId)[$id]);
  36. }
  37. return isset(static::$nonCoContext[$id]);
  38. }
  39. /**
  40. * Release the context when you are not in coroutine environment.
  41. */
  42. public static function destroy(string $id)
  43. {
  44. unset(static::$nonCoContext[$id]);
  45. }
  46. /**
  47. * Copy the context from a coroutine to current coroutine.
  48. * This method will delete the origin values in current coroutine.
  49. */
  50. public static function copy(int $fromCoroutineId, array $keys = []): void
  51. {
  52. $from = Coroutine::getContextFor($fromCoroutineId);
  53. if ($from === null) {
  54. return;
  55. }
  56. $current = Coroutine::getContextFor();
  57. if ($keys) {
  58. $map = array_intersect_key($from->getArrayCopy(), array_flip($keys));
  59. } else {
  60. $map = $from->getArrayCopy();
  61. }
  62. $current->exchangeArray($map);
  63. }
  64. /**
  65. * Retrieve the value and override it by closure.
  66. */
  67. public static function override(string $id, \Closure $closure)
  68. {
  69. $value = null;
  70. if (self::has($id)) {
  71. $value = self::get($id);
  72. }
  73. $value = $closure($value);
  74. self::set($id, $value);
  75. return $value;
  76. }
  77. /**
  78. * Retrieve the value and store it if not exists.
  79. * @param mixed $value
  80. */
  81. public static function getOrSet(string $id, $value)
  82. {
  83. if (! self::has($id)) {
  84. return self::set($id, value($value));
  85. }
  86. return self::get($id);
  87. }
  88. public static function getContainer()
  89. {
  90. if (Coroutine::id() > 0) {
  91. return Coroutine::getContextFor();
  92. }
  93. return static::$nonCoContext;
  94. }
  95. }