ArticleService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Api\ChannelApi;
  4. use App\Http\Resources\ArticleResource;
  5. use App\Models\Article;
  6. use App\Models\ArticleCollection;
  7. use App\Models\Sentence;
  8. use Illuminate\Support\Facades\Log;
  9. class ArticleService
  10. {
  11. public function getRawById(string $id)
  12. {
  13. return Article::find($id);
  14. }
  15. public function getRawByTitle(string $title)
  16. {
  17. $article = Article::where('title', $title)->first();
  18. return $article;
  19. }
  20. public function sentenceIds(string $id): ?array
  21. {
  22. $article = $this->getRawById($id);
  23. if (empty($article->content)) {
  24. return null;
  25. }
  26. $sentenceIds = $this->extractBracesContent($article->content);
  27. return $sentenceIds;
  28. }
  29. /**
  30. * 提取字符串中 {{1-2-3-4}} 格式的内容(四段数字)
  31. */
  32. public function extractBracesContent(string $text): array
  33. {
  34. preg_match_all('/\{\{\s*(\d+-\d+-\d+-\d+)\s*\}\}/', $text, $matches);
  35. return $matches[1] ?? [];
  36. }
  37. public function articlesInAnthology(string $anthologyId)
  38. {
  39. $inCollection = ArticleCollection::where('collect_id', $anthologyId)
  40. ->select('article_id')
  41. ->get()->toArray();
  42. return array_map(fn ($item) => $item['article_id'], $inCollection);
  43. }
  44. public function getArticle(string $id): array
  45. {
  46. $result = Article::where('uid', $id)->first();
  47. if (! $result) {
  48. Log::warning("没有查询到数据 id={$id}");
  49. return ['error' => "没有查询到数据 id={$id}", 'code' => 404];
  50. }
  51. return [
  52. 'data' => new ArticleResource($result),
  53. 'ok' => true,
  54. ];
  55. }
  56. public function articleChannels(string $id): ?array
  57. {
  58. $sentences = $this->sentenceIds($id);
  59. if (! $sentences) {
  60. return null;
  61. }
  62. $query = [];
  63. foreach ($sentences as $value) {
  64. $ids = explode('-', $value);
  65. $query[] = $ids;
  66. }
  67. $fields = ['book_id', 'paragraph', 'word_start', 'word_end'];
  68. $publicChannelIds = Sentence::whereIns($fields, $query)
  69. ->where('strlen', '>', 0)
  70. ->where('status', 30)
  71. ->groupBy('channel_uid')
  72. ->select('channel_uid')
  73. ->get();
  74. $channels = [];
  75. foreach ($publicChannelIds as $channel) {
  76. $channels[] = ChannelApi::getById($channel->channel_uid);
  77. }
  78. return $channels;
  79. }
  80. }