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