]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/EntityHtmlDescription.php
Merge pull request #5913 from BookStackApp/slug_history
[bookstack] / app / Entities / Tools / EntityHtmlDescription.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Util\HtmlContentFilter;
9
10 class EntityHtmlDescription
11 {
12     protected string $html = '';
13     protected string $plain = '';
14
15     public function __construct(
16         protected Book|Chapter|Bookshelf $entity,
17     ) {
18         $this->html = $this->entity->description_html ?? '';
19         $this->plain = $this->entity->description ?? '';
20     }
21
22     /**
23      * Update the description from HTML code.
24      * Optionally takes plaintext to use for the model also.
25      */
26     public function set(string $html, string|null $plaintext = null): void
27     {
28         $this->html = $html;
29         $this->entity->description_html = $this->html;
30
31         if ($plaintext !== null) {
32             $this->plain = $plaintext;
33             $this->entity->description = $this->plain;
34         }
35
36         if (empty($html) && !empty($plaintext)) {
37             $this->html = $this->getHtml();
38             $this->entity->description_html = $this->html;
39         }
40     }
41
42     /**
43      * Get the description as HTML.
44      * Optionally returns the raw HTML if requested.
45      */
46     public function getHtml(bool $raw = false): string
47     {
48         $html = $this->html ?: '<p>' . nl2br(e($this->plain)) . '</p>';
49         if ($raw) {
50             return $html;
51         }
52
53         return HtmlContentFilter::removeScriptsFromHtmlString($html);
54     }
55
56     public function getPlain(): string
57     {
58         return $this->plain;
59     }
60 }