ReferenceTemplate.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Services\Markup\Templates;
  3. use App\Models\BookTitle;
  4. use App\Services\Markup\Ir\Call;
  5. use App\Services\Markup\Render\RenderContext;
  6. /**
  7. * 参考文献:`{{ref}}`,列出本文前面句子模板引用到的巴利文献(按书名去重)。要放在文末。
  8. */
  9. final class ReferenceTemplate extends Template
  10. {
  11. protected string $component = 'reference';
  12. private const COPYRIGHT = 'CSCD V4 VRI 2008';
  13. /**
  14. * @return list<array{sn: int, title: string, copyright: string}>
  15. */
  16. private function references(RenderContext $ctx): array
  17. {
  18. if ($ctx->sentenceRefs === []) {
  19. return [];
  20. }
  21. $books = BookTitle::orderByDesc('sn')->get(['book', 'paragraph', 'title']);
  22. $seen = [];
  23. $references = [];
  24. foreach ($ctx->sentenceRefs as [$book, $para]) {
  25. foreach ($books as $title) {
  26. if ((int) $title->book !== $book || (int) $title->paragraph >= $para || isset($seen[$title->title])) {
  27. continue;
  28. }
  29. $seen[$title->title] = true;
  30. $references[] = ['sn' => count($references) + 1, 'title' => (string) $title->title, 'copyright' => self::COPYRIGHT];
  31. }
  32. }
  33. return $references;
  34. }
  35. /**
  36. * @return array<string, mixed>
  37. */
  38. public function props(Call $call, RenderContext $ctx): array
  39. {
  40. return ['pali' => $this->references($ctx)];
  41. }
  42. public function text(Call $call, RenderContext $ctx): string
  43. {
  44. $text = '';
  45. foreach ($this->references($ctx) as $reference) {
  46. $text .= '['.$reference['sn'].'] '.ucfirst($reference['title']).' '.$reference['copyright']."\n";
  47. }
  48. return $text;
  49. }
  50. public function markdown(Call $call, RenderContext $ctx): string
  51. {
  52. $markdown = '';
  53. foreach ($this->references($ctx) as $reference) {
  54. $markdown .= '['.$reference['sn'].'] **'.ucfirst($reference['title']).'** '.$reference['copyright']."\n\n";
  55. }
  56. return $markdown;
  57. }
  58. }