1 <?php namespace BookStack\Repos;
5 class BookRepo extends EntityRepo
8 protected $chapterRepo;
11 * BookRepo constructor.
12 * @param PageRepo $pageRepo
13 * @param ChapterRepo $chapterRepo
15 public function __construct(PageRepo $pageRepo, ChapterRepo $chapterRepo)
17 $this->pageRepo = $pageRepo;
18 $this->chapterRepo = $chapterRepo;
19 parent::__construct();
23 * Get a new book instance from request input.
27 public function createFromInput($input)
29 $book = $this->book->newInstance($input);
30 $book->slug = $this->findSuitableSlug('book', $book->name);
31 $book->created_by = user()->id;
32 $book->updated_by = user()->id;
34 $this->permissionService->buildJointPermissionsForEntity($book);
39 * Update the given book from user input.
44 public function updateFromInput(Book $book, $input)
46 if ($book->name !== $input['name']) {
47 $book->slug = $this->findSuitableSlug('book', $input['name'], $book->id);
50 $book->updated_by = user()->id;
52 $this->permissionService->buildJointPermissionsForEntity($book);
57 * Destroy the given book.
61 public function destroy(Book $book)
63 foreach ($book->pages as $page) {
64 $this->pageRepo->destroy($page);
66 foreach ($book->chapters as $chapter) {
67 $this->chapterRepo->destroy($chapter);
69 $book->views()->delete();
70 $book->permissions()->delete();
71 $this->permissionService->deleteJointPermissionsForEntity($book);
76 * Get the next child element priority.
80 public function getNewPriority($book)
82 $lastElem = $this->getChildren($book)->pop();
83 return $lastElem ? $lastElem->priority + 1 : 0;
87 * Get all child objects of a book.
88 * Returns a sorted collection of Pages and Chapters.
89 * Loads the book slug onto child elements to prevent access database access for getting the slug.
91 * @param bool $filterDrafts
94 public function getChildren(Book $book, $filterDrafts = false)
96 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts);
101 foreach ($q as $index => $rawEntity) {
102 if ($rawEntity->entity_type === 'Bookstack\\Page') {
103 $entities[$index] = $this->page->newFromBuilder($rawEntity);
104 } else if ($rawEntity->entity_type === 'Bookstack\\Chapter') {
105 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
106 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
107 $parents[$key] = $entities[$index];
108 $parents[$key]->setAttribute('pages', collect());
110 if ($entities[$index]->chapter_id === 0) $tree[] = $entities[$index];
111 $entities[$index]->book = $book;
114 foreach ($entities as $entity) {
115 if ($entity->chapter_id === 0) continue;
116 $parentKey = 'Bookstack\\Chapter:' . $entity->chapter_id;
117 $chapter = $parents[$parentKey];
118 $chapter->pages->push($entity);
121 return collect($tree);