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 $chapter = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
60 if ($chapter === null) abort(404);
65 * Create a new chapter from request input.
69 public function newFromInput($input)
71 return $this->chapter->fill($input);
75 * Destroy a chapter and its relations by providing its slug.
76 * @param Chapter $chapter
78 public function destroy(Chapter $chapter)
80 if (count($chapter->pages) > 0) {
81 foreach ($chapter->pages as $page) {
82 $page->chapter_id = 0;
86 Activity::removeEntity($chapter);
87 $chapter->views()->delete();
92 * Check if a chapter's slug exists.
95 * @param bool|false $currentId
98 public function doesSlugExist($slug, $bookId, $currentId = false)
100 $query = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId);
102 $query = $query->where('id', '!=', $currentId);
104 return $query->count() > 0;
108 * Finds a suitable slug for the provided name.
109 * Checks database to prevent duplicate slugs.
112 * @param bool|false $currentId
115 public function findSuitableSlug($name, $bookId, $currentId = false)
117 $slug = Str::slug($name);
118 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
119 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
125 * Get chapters by the given search term.
127 * @param array $whereTerms
130 public function getBySearch($term, $whereTerms = [])
132 $terms = explode(' ', preg_quote(trim($term)));
133 $chapters = $this->chapter->fullTextSearch(['name', 'description'], $terms, $whereTerms);
134 $words = join('|', $terms);
135 foreach ($chapters as $chapter) {
137 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $chapter->getExcerpt(100));
138 $chapter->searchSnippet = $result;
144 * Changes the book relation of this chapter.
146 * @param Chapter $chapter
149 public function changeBook($bookId, Chapter $chapter)
151 $chapter->book_id = $bookId;
152 foreach ($chapter->activity as $activity) {
153 $activity->book_id = $bookId;
156 $chapter->slug = $this->findSuitableSlug($chapter->name, $bookId, $chapter->id);