SearchPaliWbwResource.php 2.1 KB

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