]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
Apply fixes from StyleCI
[bookstack] / app / Entities / Models / BookChild.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use Illuminate\Database\Eloquent\Builder;
6 use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
8 /**
9  * Class BookChild.
10  *
11  * @property int  $book_id
12  * @property int  $priority
13  * @property Book $book
14  *
15  * @method Builder whereSlugs(string $bookSlug, string $childSlug)
16  */
17 abstract class BookChild extends Entity
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      */
35     public function book(): BelongsTo
36     {
37         return $this->belongsTo(Book::class)->withTrashed();
38     }
39
40     /**
41      * Change the book that this entity belongs to.
42      */
43     public function changeBook(int $newBookId): Entity
44     {
45         $this->book_id = $newBookId;
46         $this->refreshSlug();
47         $this->save();
48         $this->refresh();
49
50         // Update all child pages if a chapter
51         if ($this instanceof Chapter) {
52             foreach ($this->pages()->withTrashed()->get() as $page) {
53                 $page->changeBook($newBookId);
54             }
55         }
56
57         return $this;
58     }
59 }