SearchPaliWbwResource.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Models\PageNumber;
  4. use App\Models\PaliText;
  5. use Illuminate\Contracts\Support\Arrayable;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Http\Resources\Json\JsonResource;
  8. class SearchPaliWbwResource extends JsonResource
  9. {
  10. /**
  11. * Transform the resource into an array.
  12. *
  13. * @param Request $request
  14. * @return array|Arrayable|\JsonSerializable
  15. */
  16. public function toArray($request)
  17. {
  18. $data = [
  19. 'book' => $this->book,
  20. 'paragraph' => $this->paragraph,
  21. ];
  22. if (isset($this->rank)) {
  23. $data['rank'] = $this->rank;
  24. }
  25. $paliText = PaliText::where('book', $this->book)
  26. ->where('paragraph', $this->paragraph)
  27. ->first();
  28. if ($paliText) {
  29. $data['path'] = json_decode($paliText->path);
  30. if ($paliText->level < 100) {
  31. $data['paliTitle'] = $paliText->toc;
  32. $book = $this->book;
  33. $para = $this->paragraph;
  34. $data['link'] = config('app.url')."/library/tipitaka/{$book}-{$para}/read";
  35. } else {
  36. $data['paliTitle'] = PaliText::where('book', $this->book)
  37. ->where('paragraph', $paliText->parent)
  38. ->value('toc');
  39. $book = end($data['path'])['book'];
  40. $para = end($data['path'])['paragraph'];
  41. $data['link'] = config('app.url')."/library/tipitaka/{$book}-{$para}/read#{$this->paragraph}";
  42. }
  43. $keyWords = explode(',', $request->input('key'));
  44. $keyWordsUpper = $keyWords;
  45. foreach ($keyWords as $key => $word) {
  46. if (mb_substr($word, -3, null, 'UTF-8') === 'nti') {
  47. $keyWordsUpper[] = mb_substr($word, 0, mb_strlen($word, 'UTF-8') - 3, 'UTF-8');
  48. } elseif (mb_substr($word, -3, null, 'UTF-8') === 'ti') {
  49. $keyWordsUpper[] = mb_substr($word, 0, mb_strlen($word, 'UTF-8') - 2, 'UTF-8');
  50. }
  51. }
  52. foreach ($keyWords as $key => $word) {
  53. $keyWordsUpper[] = mb_strtoupper(mb_substr($word, 0, 1, 'UTF-8'), 'UTF-8').mb_substr($word, 1, null, 'UTF-8');
  54. }
  55. $keyReplace = [];
  56. foreach ($keyWordsUpper as $key => $word) {
  57. $keyReplace[] = "<span class='hl'>{$word}</span>";
  58. }
  59. $data['highlight'] = str_replace($keyWordsUpper, $keyReplace, $paliText->html);
  60. }
  61. $pageNumbers = PageNumber::where('book', $this->book)
  62. ->where('paragraph', $this->paragraph)
  63. ->orderBy('wid')
  64. ->get()
  65. ->unique('type')
  66. ->map(fn ($pageNumber) => [
  67. 'type' => $pageNumber->type,
  68. 'page' => $pageNumber->page,
  69. ])
  70. ->values()
  71. ->all();
  72. if ($pageNumbers !== []) {
  73. $data['ref'] = $pageNumbers;
  74. }
  75. return $data;
  76. }
  77. }