]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Chapter.php
Merge branch 'development' into bugfix/fix-being-unable-to-clear-filters
[bookstack] / app / Entities / Models / Chapter.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use Illuminate\Database\Eloquent\Factories\HasFactory;
6 use Illuminate\Database\Eloquent\Relations\HasMany;
7 use Illuminate\Support\Collection;
8
9 /**
10  * Class Chapter.
11  *
12  * @property Collection<Page> $pages
13  * @property string           $description
14  */
15 class Chapter extends BookChild
16 {
17     use HasFactory;
18
19     public $searchFactor = 1.2;
20
21     protected $fillable = ['name', 'description', 'priority'];
22     protected $hidden = ['pivot', 'deleted_at'];
23
24     /**
25      * Get the pages that this chapter contains.
26      *
27      * @return HasMany<Page>
28      */
29     public function pages(string $dir = 'ASC'): HasMany
30     {
31         return $this->hasMany(Page::class)->orderBy('priority', $dir);
32     }
33
34     /**
35      * Get the url of this chapter.
36      */
37     public function getUrl(string $path = ''): string
38     {
39         $parts = [
40             'books',
41             urlencode($this->book_slug ?? $this->book->slug),
42             'chapter',
43             urlencode($this->slug),
44             trim($path, '/'),
45         ];
46
47         return url('/' . implode('/', $parts));
48     }
49
50     /**
51      * Get the visible pages in this chapter.
52      */
53     public function getVisiblePages(): Collection
54     {
55         return $this->pages()
56         ->scopes('visible')
57         ->orderBy('draft', 'desc')
58         ->orderBy('priority', 'asc')
59         ->get();
60     }
61
62     /**
63      * Get a visible chapter by its book and page slugs.
64      * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
65      */
66     public static function getBySlugs(string $bookSlug, string $chapterSlug): self
67     {
68         return static::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
69     }
70 }