MetadataCacheCollector.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. class MetadataCacheCollector
  13. {
  14. public function __construct(protected array $collectors)
  15. {
  16. }
  17. public function addCollector(string $collector)
  18. {
  19. $this->collectors = array_unique(array_merge(
  20. $this->collectors,
  21. [$collector]
  22. ));
  23. }
  24. public function clear()
  25. {
  26. $this->collectors = [];
  27. }
  28. public function serialize(): string
  29. {
  30. $metadata = [];
  31. foreach ($this->collectors as $collector) {
  32. if (is_string($collector) && method_exists($collector, 'serialize')) {
  33. $metadata[$collector] = $collector::serialize();
  34. }
  35. }
  36. return json_encode($metadata);
  37. }
  38. public function unserialize($serialized): void
  39. {
  40. $metadatas = json_decode($serialized, true) ?? [];
  41. $collectors = [];
  42. foreach ($metadatas as $collector => $metadata) {
  43. if (method_exists($collector, 'deserialize')) {
  44. $collector::deserialize($metadata);
  45. $collectors[] = $collector;
  46. }
  47. }
  48. $this->collectors = $collectors;
  49. }
  50. }