+ /**
+ * Get a new priority value for a new page to be added
+ * to the given chapter.
+ * @param Chapter $chapter
+ * @return int
+ */
+ public function getNewPriority(Chapter $chapter)
+ {
+ $lastPage = $chapter->pages->last();
+ return $lastPage !== null ? $lastPage->priority + 1 : 0;
+ }
+
+ /**
+ * Get chapters by the given search term.
+ * @param string $term
+ * @param array $whereTerms
+ * @param int $count
+ * @param array $paginationAppends
+ * @return mixed
+ */
+ public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
+ {
+ $terms = $this->prepareSearchTerms($term);
+ $chapterQuery = $this->permissionService->enforceChapterRestrictions($this->chapter->fullTextSearchQuery(['name', 'description'], $terms, $whereTerms));
+ $chapterQuery = $this->addAdvancedSearchQueries($chapterQuery, $term);
+ $chapters = $chapterQuery->paginate($count)->appends($paginationAppends);
+ $words = join('|', explode(' ', preg_quote(trim($term), '/')));
+ foreach ($chapters as $chapter) {
+ //highlight
+ $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $chapter->getExcerpt(100));
+ $chapter->searchSnippet = $result;
+ }
+ return $chapters;
+ }
+
+ /**
+ * Changes the book relation of this chapter.
+ * @param $bookId
+ * @param Chapter $chapter
+ * @return Chapter
+ */
+ public function changeBook($bookId, Chapter $chapter)
+ {
+ $chapter->book_id = $bookId;
+ // Update related activity
+ foreach ($chapter->activity as $activity) {
+ $activity->book_id = $bookId;
+ $activity->save();
+ }
+ $chapter->slug = $this->findSuitableSlug($chapter->name, $bookId, $chapter->id);
+ $chapter->save();
+ // Update all child pages
+ foreach ($chapter->pages as $page) {
+ $this->pageRepo->changeBook($bookId, $page);
+ }
+ // Update permissions
+ $chapter->load('book');
+ $this->permissionService->buildJointPermissionsForEntity($chapter->book);
+
+ return $chapter;
+ }
+