Context.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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\Utils;
  12. use Hyperf\Engine\Coroutine as Co;
  13. /**
  14. * @deprecated v3.0 please use `hyperf/context` instead.
  15. */
  16. class Context
  17. {
  18. protected static $nonCoContext = [];
  19. public static function set(string $id, $value)
  20. {
  21. if (Coroutine::inCoroutine()) {
  22. Co::getContextFor()[$id] = $value;
  23. } else {
  24. static::$nonCoContext[$id] = $value;
  25. }
  26. return $value;
  27. }
  28. public static function get(string $id, $default = null, $coroutineId = null)
  29. {
  30. if (Coroutine::inCoroutine()) {
  31. return Co::getContextFor($coroutineId)[$id] ?? $default;
  32. }
  33. return static::$nonCoContext[$id] ?? $default;
  34. }
  35. public static function has(string $id, $coroutineId = null)
  36. {
  37. if (Coroutine::inCoroutine()) {
  38. return isset(Co::getContextFor($coroutineId)[$id]);
  39. }
  40. return isset(static::$nonCoContext[$id]);
  41. }
  42. /**
  43. * Release the context when you are not in coroutine environment.
  44. */
  45. public static function destroy(string $id)
  46. {
  47. unset(static::$nonCoContext[$id]);
  48. }
  49. /**
  50. * Copy the context from a coroutine to current coroutine.
  51. */
  52. public static function copy(int $fromCoroutineId, array $keys = []): void
  53. {
  54. $from = Co::getContextFor($fromCoroutineId);
  55. if ($from === null) {
  56. return;
  57. }
  58. $current = Co::getContextFor();
  59. $current->exchangeArray($keys ? Arr::only($from->getArrayCopy(), $keys) : $from->getArrayCopy());
  60. }
  61. /**
  62. * Retrieve the value and override it by closure.
  63. */
  64. public static function override(string $id, \Closure $closure)
  65. {
  66. $value = null;
  67. if (self::has($id)) {
  68. $value = self::get($id);
  69. }
  70. $value = $closure($value);
  71. self::set($id, $value);
  72. return $value;
  73. }
  74. /**
  75. * Retrieve the value and store it if not exists.
  76. * @param mixed $value
  77. */
  78. public static function getOrSet(string $id, $value)
  79. {
  80. if (! self::has($id)) {
  81. return self::set($id, value($value));
  82. }
  83. return self::get($id);
  84. }
  85. public static function getContainer()
  86. {
  87. if (Coroutine::inCoroutine()) {
  88. return Co::getContextFor();
  89. }
  90. return static::$nonCoContext;
  91. }
  92. }