ChannelDirectory.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Models\Channel;
  4. use Illuminate\Support\Str;
  5. /**
  6. * 渲染期间用到的 channel 的基本信息(uid、名字、类型、语言、拥有者),攒够一批再查。
  7. */
  8. final class ChannelDirectory
  9. {
  10. /** @var array<string, Channel|null> */
  11. private array $channels = [];
  12. /** @var array<string, true> */
  13. private array $pending = [];
  14. /**
  15. * @param list<string> $uids
  16. */
  17. public function request(array $uids): void
  18. {
  19. foreach ($uids as $uid) {
  20. if (Str::isUuid($uid) && ! array_key_exists($uid, $this->channels)) {
  21. $this->pending[$uid] = true;
  22. }
  23. }
  24. }
  25. public function get(?string $uid): ?Channel
  26. {
  27. if ($uid === null || ! Str::isUuid($uid)) {
  28. return null;
  29. }
  30. if (! array_key_exists($uid, $this->channels)) {
  31. $this->pending[$uid] = true;
  32. }
  33. $this->flush();
  34. return $this->channels[$uid] ?? null;
  35. }
  36. private function flush(): void
  37. {
  38. if ($this->pending === []) {
  39. return;
  40. }
  41. $uids = array_keys($this->pending);
  42. $this->pending = [];
  43. $found = Channel::whereIn('uid', $uids)
  44. ->get(['uid', 'name', 'type', 'lang', 'owner_uid'])
  45. ->keyBy(fn (Channel $channel) => (string) $channel->uid);
  46. foreach ($uids as $uid) {
  47. $this->channels[$uid] = $found->get($uid);
  48. }
  49. }
  50. }