QuoteLoader.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Models\PaliText;
  4. /**
  5. * quote 模板:按 `book-para` 取段落的目录标题与路径,一次查完。
  6. */
  7. final class QuoteLoader extends Loader
  8. {
  9. /** @var array<string, array{0: int, 1: int}> */
  10. private array $pending = [];
  11. /** @var array<string, array{toc: string, path: mixed}|null> */
  12. private array $results = [];
  13. public function request(string $paraId): void
  14. {
  15. $parts = explode('-', $paraId);
  16. if (count($parts) < 2 || ! ctype_digit($parts[0]) || ! ctype_digit($parts[1])) {
  17. $this->results[$paraId] = null;
  18. return;
  19. }
  20. if (! array_key_exists($paraId, $this->results)) {
  21. $this->pending[$paraId] = [(int) $parts[0], (int) $parts[1]];
  22. }
  23. }
  24. /**
  25. * @return array{toc: string, path: mixed}|null
  26. */
  27. public function result(string $paraId): ?array
  28. {
  29. return $this->results[$paraId] ?? null;
  30. }
  31. public function hasPending(): bool
  32. {
  33. return $this->pending !== [];
  34. }
  35. public function load(): void
  36. {
  37. $batch = $this->pending;
  38. $this->pending = [];
  39. $rows = PaliText::query()
  40. ->where(function ($query) use ($batch) {
  41. foreach ($batch as [$book, $para]) {
  42. $query->orWhere(fn ($where) => $where->where('book', $book)->where('paragraph', $para));
  43. }
  44. })
  45. ->get(['book', 'paragraph', 'toc', 'path'])
  46. ->keyBy(fn (PaliText $row) => "{$row->book}-{$row->paragraph}");
  47. foreach ($batch as $paraId => [$book, $para]) {
  48. $row = $rows->get("{$book}-{$para}");
  49. $this->results[$paraId] = $row === null ? null : [
  50. 'toc' => (string) $row->toc,
  51. 'path' => json_decode((string) $row->path, true),
  52. ];
  53. }
  54. }
  55. }