SearchPaliWbwResource.php 2.5 KB

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