]> BookStack Code Mirror - bookstack/blob - app/Repos/ChapterRepo.php
4aba1dc1283c5e37b8ade0fa27802bb2295c1059
[bookstack] / app / Repos / ChapterRepo.php
1 <?php namespace BookStack\Repos;
2
3
4 use Illuminate\Support\Str;
5 use BookStack\Chapter;
6
7 class ChapterRepo
8 {
9
10     protected $chapter;
11
12     /**
13      * ChapterRepo constructor.
14      * @param $chapter
15      */
16     public function __construct(Chapter $chapter)
17     {
18         $this->chapter = $chapter;
19     }
20
21     public function idExists($id)
22     {
23         return $this->chapter->where('id', '=', $id)->count() > 0;
24     }
25
26     public function getById($id)
27     {
28         return $this->chapter->findOrFail($id);
29     }
30
31     public function getAll()
32     {
33         return $this->chapter->all();
34     }
35
36     public function getBySlug($slug, $bookId)
37     {
38         return $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
39     }
40
41     public function newFromInput($input)
42     {
43         return $this->chapter->fill($input);
44     }
45
46     public function destroyById($id)
47     {
48         $page = $this->getById($id);
49         $page->delete();
50     }
51
52     public function doesSlugExist($slug, $bookId, $currentId = false)
53     {
54         $query = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId);
55         if($currentId) {
56             $query = $query->where('id', '!=', $currentId);
57         }
58         return $query->count() > 0;
59     }
60
61     public function findSuitableSlug($name, $bookId, $currentId = false)
62     {
63         $slug = Str::slug($name);
64         while($this->doesSlugExist($slug, $bookId, $currentId)) {
65             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
66         }
67         return $slug;
68     }
69
70     public function getBySearch($term, $whereTerms = [])
71     {
72         $terms = explode(' ', preg_quote(trim($term)));
73         $chapters = $this->chapter->fullTextSearch(['name', 'description'], $terms, $whereTerms);
74         $words = join('|', $terms);
75         foreach ($chapters as $chapter) {
76             //highlight
77             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $chapter->getExcerpt(100));
78             $chapter->searchSnippet = $result;
79         }
80         return $chapters;
81     }
82
83     public function setBookId($bookId, Chapter $chapter)
84     {
85         $chapter->book_id = $bookId;
86         foreach($chapter->activity as $activity) {
87             $activity->book_id = $bookId;
88             $activity->save();
89         }
90         $chapter->save();
91         return $chapter;
92     }
93
94 }