Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
RichText
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
5 / 5
9
100.00% covered (success)
100.00%
1 / 1
 __toString
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doc
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 raw
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 json
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 excerpt
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Value;
6
7use Cosray\Markup;
8use Cosray\Richtext\Envelope;
9use Cosray\Richtext\OwnerResolver;
10use Cosray\Richtext\Renderer;
11use Cosray\Util\Html as HtmlUtil;
12use Override;
13
14class RichText extends Text
15{
16    #[Override]
17    public function __toString(): string
18    {
19        return $this->raw();
20    }
21
22    /**
23     * The locale-resolved structured document, or null for empty
24     * values.
25     *
26     * @return ?array<string, mixed>
27     */
28    public function doc(): ?array
29    {
30        if (!Envelope::isStructured($this->data)) {
31            return null;
32        }
33
34        $doc = $this->value();
35
36        return is_array($doc) ? $doc : null;
37    }
38
39    /**
40     * The rendered HTML, escaped by construction. Values without the
41     * format envelope (unmigrated legacy HTML) render empty — the
42     * HTML-to-JSON migration ships with the code that requires it.
43     */
44    #[Override]
45    public function raw(): string
46    {
47        if (isset($this->value)) {
48            return $this->value;
49        }
50
51        $doc = $this->doc();
52
53        if ($doc === null) {
54            return $this->value = '';
55        }
56
57        return $this->value = new Renderer(new OwnerResolver($this->owner))->render($doc);
58    }
59
60    /** @return array{html: string} */
61    #[Override]
62    public function json(): array
63    {
64        return ['html' => $this->raw()];
65    }
66
67    public function excerpt(
68        int $words = 30,
69        string $allowedTags = '',
70    ): Markup {
71        return new Markup(HtmlUtil::excerpt($this->raw(), $words, $allowedTags));
72    }
73}