ArticleService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Article;
  4. use App\Models\ArticleCollection;
  5. use App\Models\Sentence;
  6. use App\Http\Resources\ArticleResource;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Http\Api\ChannelApi;
  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. * 提取字符串中 {{ }} 之间的内容
  31. *
  32. * @param string $text
  33. * @return array
  34. */
  35. public function extractBracesContent(string $text): array
  36. {
  37. preg_match_all('/\{\{\s*(.*?)\s*\}\}/', $text, $matches);
  38. return $matches[1] ?? [];
  39. }
  40. public function articlesInAnthology($anthologyId)
  41. {
  42. $inCollection = ArticleCollection::where('collect_id', $anthologyId)
  43. ->select('article_id')
  44. ->get()->toArray();
  45. return array_map(fn($item) => $item['article_id'], $inCollection);
  46. }
  47. public function getArticle(string $id): array
  48. {
  49. $result = Article::where('uid', $id)->first();
  50. if (!$result) {
  51. Log::warning("没有查询到数据 id={$id}");
  52. return ['error' => "没有查询到数据 id={$id}", 'code' => 404];
  53. }
  54. return [
  55. 'data' => new ArticleResource($result),
  56. 'ok' => true
  57. ];
  58. }
  59. public function articleChannels(string $id): array
  60. {
  61. $sentences = $this->sentenceIds($id);
  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 $id) {
  76. $channels = ChannelApi::getById($id);
  77. }
  78. return $channels;
  79. }
  80. }