Context.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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\Rpc;
  12. use Hyperf\Collection\Arr;
  13. use Hyperf\Context\Context as ContextUtil;
  14. class Context
  15. {
  16. public function getData(): array
  17. {
  18. return ContextUtil::get($this->getContextKey(), []);
  19. }
  20. public function setData(array $data): void
  21. {
  22. ContextUtil::set($this->getContextKey(), $data);
  23. }
  24. public function get($key, $default = null)
  25. {
  26. return Arr::get($this->getData(), $key, $default);
  27. }
  28. public function set($key, $value): void
  29. {
  30. $data = $this->getData();
  31. $data[$key] = $value;
  32. ContextUtil::set($this->getContextKey(), $data);
  33. }
  34. public function clear(): void
  35. {
  36. ContextUtil::set($this->getContextKey(), []);
  37. }
  38. protected function getContextKey(): string
  39. {
  40. return static::class . '::DATA';
  41. }
  42. }