]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Chapter.php
API: Added comment-read endpoint, added api docs section descriptions
[bookstack] / app / Entities / Models / Chapter.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\Entities\Tools\EntityDefaultTemplate;
6 use Illuminate\Database\Eloquent\Factories\HasFactory;
7 use Illuminate\Database\Eloquent\Relations\HasMany;
8 use Illuminate\Support\Collection;
9
10 /**
11  * @property Collection<Page> $pages
12  * @property ?int             $default_template_id
13  * @property string           $description
14  * @property string           $description_html
15  */
16 class Chapter extends BookChild implements HasDescriptionInterface, HasDefaultTemplateInterface
17 {
18     use HasFactory;
19     use ContainerTrait;
20
21     public float $searchFactor = 1.2;
22     protected $hidden = ['pivot', 'deleted_at', 'description_html', 'sort_rule_id', 'image_id', 'entity_id', 'entity_type', 'chapter_id'];
23     protected $fillable = ['name', 'priority'];
24
25     /**
26      * Get the pages that this chapter contains.
27      *
28      * @return HasMany<Page, $this>
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      * @return Collection<Page>
54      */
55     public function getVisiblePages(): Collection
56     {
57         return $this->pages()
58         ->scopes('visible')
59         ->orderBy('draft', 'desc')
60         ->orderBy('priority', 'asc')
61         ->get();
62     }
63
64     public function defaultTemplate(): EntityDefaultTemplate
65     {
66         return new EntityDefaultTemplate($this);
67     }
68 }