MetadataCollector.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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\Di;
  12. use Hyperf\Collection\Arr;
  13. abstract class MetadataCollector implements MetadataCollectorInterface
  14. {
  15. /**
  16. * Subclass MUST override this property.
  17. */
  18. protected static array $container = [];
  19. /**
  20. * Retrieve the metadata via key.
  21. * @param null|mixed $default
  22. */
  23. public static function get(string $key, $default = null)
  24. {
  25. return Arr::get(static::$container, $key) ?? $default;
  26. }
  27. /**
  28. * Set the metadata to holder.
  29. * @param mixed $value
  30. */
  31. public static function set(string $key, $value): void
  32. {
  33. Arr::set(static::$container, $key, $value);
  34. }
  35. /**
  36. * Determine if the metadata exist.
  37. * If exist will return true, otherwise return false.
  38. */
  39. public static function has(string $key): bool
  40. {
  41. return Arr::has(static::$container, $key);
  42. }
  43. public static function clear(?string $key = null): void
  44. {
  45. if ($key) {
  46. Arr::forget(static::$container, [$key]);
  47. } else {
  48. static::$container = [];
  49. }
  50. }
  51. /**
  52. * Serialize the all metadata to a string.
  53. */
  54. public static function serialize(): string
  55. {
  56. return serialize(static::$container);
  57. }
  58. /**
  59. * Deserialize the serialized metadata and set the metadata to holder.
  60. */
  61. public static function deserialize(string $metadata): bool
  62. {
  63. static::$container = unserialize($metadata);
  64. return true;
  65. }
  66. public static function list(): array
  67. {
  68. return static::$container;
  69. }
  70. }