]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
Code cleanup, bug squashing
[bookstack] / app / Entities / Models / BookChild.php
1 <?php namespace BookStack\Entities\Models;
2
3 use BookStack\Entities\Models\Chapter;
4 use BookStack\Entities\Models\Entity;
5 use BookStack\Entities\Models\Book;
6 use Illuminate\Database\Eloquent\Builder;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
9 /**
10  * Class BookChild
11  * @property int $book_id
12  * @property int $priority
13  * @property Book $book
14  * @method Builder whereSlugs(string $bookSlug, string $childSlug)
15  */
16 abstract class BookChild extends Entity
17 {
18
19     /**
20      * Scope a query to find items where the the child has the given childSlug
21      * where its parent has the bookSlug.
22      */
23     public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
24     {
25         return $query->with('book')
26             ->whereHas('book', function (Builder $query) use ($bookSlug) {
27                 $query->where('slug', '=', $bookSlug);
28             })
29             ->where('slug', '=', $childSlug);
30     }
31
32     /**
33      * Get the book this page sits in.
34      * @return BelongsTo
35      */
36     public function book(): BelongsTo
37     {
38         return $this->belongsTo(Book::class);
39     }
40
41     /**
42      * Change the book that this entity belongs to.
43      */
44     public function changeBook(int $newBookId): Entity
45     {
46         $this->book_id = $newBookId;
47         $this->refreshSlug();
48         $this->save();
49         $this->refresh();
50
51         // Update all child pages if a chapter
52         if ($this instanceof Chapter) {
53             foreach ($this->pages as $page) {
54                 $page->changeBook($newBookId);
55             }
56         }
57
58         return $this;
59     }
60 }