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