]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Chapter.php
Input WYSIWYG: Added reference store & fetch handling
[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     use HasHtmlDescription;
19
20     public float $searchFactor = 1.2;
21
22     protected $fillable = ['name', 'description', 'priority'];
23     protected $hidden = ['pivot', 'deleted_at'];
24
25     /**
26      * Get the pages that this chapter contains.
27      *
28      * @return HasMany<Page>
29      */
30     public function pages(string $dir = 'ASC'): HasMany
31     {
32         return $this->hasMany(Page::class)->orderBy('priority', $dir);
33     }
34
35     /**
36      * Get the url of this chapter.
37      */
38     public function getUrl(string $path = ''): string
39     {
40         $parts = [
41             'books',
42             urlencode($this->book_slug ?? $this->book->slug),
43             'chapter',
44             urlencode($this->slug),
45             trim($path, '/'),
46         ];
47
48         return url('/' . implode('/', $parts));
49     }
50
51     /**
52      * Get the visible pages in this chapter.
53      */
54     public function getVisiblePages(): Collection
55     {
56         return $this->pages()
57         ->scopes('visible')
58         ->orderBy('draft', 'desc')
59         ->orderBy('priority', 'asc')
60         ->get();
61     }
62
63     /**
64      * Get a visible chapter by its book and page slugs.
65      * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
66      */
67     public static function getBySlugs(string $bookSlug, string $chapterSlug): self
68     {
69         return static::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
70     }
71 }