1 <?php namespace BookStack\Repos;
5 use Illuminate\Support\Str;
14 * ChapterRepo constructor.
17 public function __construct(Chapter $chapter)
19 $this->chapter = $chapter;
23 * Check if an id exists.
27 public function idExists($id)
29 return $this->chapter->where('id', '=', $id)->count() > 0;
33 * Get a chapter by a specific id.
37 public function getById($id)
39 return $this->chapter->findOrFail($id);
44 * @return \Illuminate\Database\Eloquent\Collection|static[]
46 public function getAll()
48 return $this->chapter->all();
52 * Get a chapter that has the given slug within the given book.
57 public function getBySlug($slug, $bookId)
59 return $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
63 * Create a new chapter from request input.
67 public function newFromInput($input)
69 return $this->chapter->fill($input);
73 * Destroy a chapter and its relations by providing its slug.
74 * @param Chapter $chapter
76 public function destroy(Chapter $chapter)
78 if (count($chapter->pages) > 0) {
79 foreach ($chapter->pages as $page) {
80 $page->chapter_id = 0;
84 Activity::removeEntity($chapter);
85 $chapter->views()->delete();
90 * Check if a chapter's slug exists.
93 * @param bool|false $currentId
96 public function doesSlugExist($slug, $bookId, $currentId = false)
98 $query = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId);
100 $query = $query->where('id', '!=', $currentId);
102 return $query->count() > 0;
106 * Finds a suitable slug for the provided name.
107 * Checks database to prevent duplicate slugs.
110 * @param bool|false $currentId
113 public function findSuitableSlug($name, $bookId, $currentId = false)
115 $slug = Str::slug($name);
116 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
117 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
123 * Get chapters by the given search term.
125 * @param array $whereTerms
128 public function getBySearch($term, $whereTerms = [])
130 $terms = explode(' ', preg_quote(trim($term)));
131 $chapters = $this->chapter->fullTextSearch(['name', 'description'], $terms, $whereTerms);
132 $words = join('|', $terms);
133 foreach ($chapters as $chapter) {
135 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $chapter->getExcerpt(100));
136 $chapter->searchSnippet = $result;
142 * Changes the book relation of this chapter.
144 * @param Chapter $chapter
147 public function changeBook($bookId, Chapter $chapter)
149 $chapter->book_id = $bookId;
150 foreach ($chapter->activity as $activity) {
151 $activity->book_id = $bookId;
154 $chapter->slug = $this->findSuitableSlug($chapter->name, $bookId, $chapter->id);