]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
18735e56b72e74cdf08c7a774f0aadeae1bd7d4c
[bookstack] / app / Entities / Models / BookChild.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\References\ReferenceUpdater;
6 use Illuminate\Database\Eloquent\Builder;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
9 /**
10  * Class BookChild.
11  *
12  * @property int    $book_id
13  * @property int    $priority
14  * @property string $book_slug
15  * @property Book   $book
16  *
17  * @method Builder whereSlugs(string $bookSlug, string $childSlug)
18  */
19 abstract class BookChild extends Entity
20 {
21     protected static function boot()
22     {
23         parent::boot();
24
25         // Load book slugs onto these models by default during query-time
26         static::addGlobalScope('book_slug', function (Builder $builder) {
27             $builder->addSelect(['book_slug' => function ($builder) {
28                 $builder->select('slug')
29                     ->from('books')
30                     ->whereColumn('books.id', '=', 'book_id');
31             }]);
32         });
33     }
34
35     /**
36      * Scope a query to find items where the child has the given childSlug
37      * where its parent has the bookSlug.
38      */
39     public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
40     {
41         return $query->with('book')
42             ->whereHas('book', function (Builder $query) use ($bookSlug) {
43                 $query->where('slug', '=', $bookSlug);
44             })
45             ->where('slug', '=', $childSlug);
46     }
47
48     /**
49      * Get the book this page sits in.
50      */
51     public function book(): BelongsTo
52     {
53         return $this->belongsTo(Book::class)->withTrashed();
54     }
55
56     /**
57      * Change the book that this entity belongs to.
58      */
59     public function changeBook(int $newBookId): Entity
60     {
61         $oldUrl = $this->getUrl();
62         $this->book_id = $newBookId;
63         $this->refreshSlug();
64         $this->save();
65         $this->refresh();
66
67         if ($oldUrl !== $this->getUrl()) {
68             app()->make(ReferenceUpdater::class)->updateEntityReferences($this, $oldUrl);
69         }
70
71         // Update all child pages if a chapter
72         if ($this instanceof Chapter) {
73             foreach ($this->pages()->withTrashed()->get() as $page) {
74                 $page->changeBook($newBookId);
75             }
76         }
77
78         return $this;
79     }
80 }