]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/EntityDefaultTemplate.php
Merge pull request #5913 from BookStackApp/slug_history
[bookstack] / app / Entities / Tools / EntityDefaultTemplate.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Entities\Queries\PageQueries;
9
10 class EntityDefaultTemplate
11 {
12     public function __construct(
13         protected Book|Chapter $entity,
14     ) {
15     }
16
17     /**
18      * Set the default template ID for this entity.
19      */
20     public function setFromId(int $templateId): void
21     {
22         $changing = $templateId !== intval($this->entity->default_template_id);
23         if (!$changing) {
24             return;
25         }
26
27         if ($templateId === 0) {
28             $this->entity->default_template_id = null;
29             return;
30         }
31
32         $pageQueries = app()->make(PageQueries::class);
33         $templateExists = $pageQueries->visibleTemplates()
34             ->where('id', '=', $templateId)
35             ->exists();
36
37         $this->entity->default_template_id = $templateExists ? $templateId : null;
38     }
39
40     /**
41      * Get the default template for this entity (if visible).
42      */
43     public function get(): Page|null
44     {
45         if (!$this->entity->default_template_id) {
46             return null;
47         }
48
49         $pageQueries = app()->make(PageQueries::class);
50         $page = $pageQueries->visibleTemplates(true)
51             ->where('id', '=', $this->entity->default_template_id)
52             ->first();
53
54         if ($page instanceof Page) {
55             return $page;
56         }
57
58         return null;
59     }
60 }