Debian Codegraph @

vendor/ipl/html/src/DeferredText.php

raw
1 <?php
2
3 namespace ipl\Html;
4
5 use Throwable;
6
7 /**
8 * Text node where content creation is deferred until rendering
9 *
10 * The content is created by a passed in callback which is only called when the node is going to be rendered and
11 * automatically escaped to HTML.
12 * If the created content is already escaped, see {@link setEscaped()} to indicate this.
13 *
14 * # Example Usage
15 * ```
16 * $benchmark = new Benchmark();
17 *
18 * $performance = new DeferredText(function () use ($benchmark) {
19 * return $benchmark->summary();
20 * });
21 *
22 * execute_query();
23 *
24 * $benchmark->tick('Fetched results');
25 *
26 * generate_report();
27 *
28 * $benchmark->tick('Report generated');
29 *
30 * echo $performance;
31 * ```
32 */
33 class DeferredText implements ValidHtml
34 {
35 /** @var callable will return the text that should be rendered */
36 protected $callback;
37
38 /** @var bool */
39 protected $escaped = false;
40
41 /**
42 * Create a new text node where content creation is deferred until rendering
43 *
44 * @param callable $callback Must return the content that should be rendered
45 */
46 public function __construct(callable $callback)
47 {
48 $this->callback = $callback;
49 }
50
51 /**
52 * Create a new text node where content creation is deferred until rendering
53 *
54 * @param callable $callback Must return the content that should be rendered
55 *
56 * @return static
57 */
58 public static function create(callable $callback)
59 {
60 return new static($callback);
61 }
62
63 /**
64 * Get whether the callback promises that its content is already escaped
65 *
66 * @return bool
67 */
68 public function isEscaped()
69 {
70 return $this->escaped;
71 }
72
73 /**
74 * Set whether the callback's content is already escaped
75 *
76 * @param bool $escaped
77 *
78 * @return $this
79 */
80 public function setEscaped($escaped = true)
81 {
82 $this->escaped = $escaped;
83
84 return $this;
85 }
86
87 /**
88 * Render text to HTML when treated like a string
89 *
90 * Calls {@link render()} internally in order to render the text to HTML.
91 * Exceptions will be automatically caught and returned as HTML string as well using {@link Error::render()}.
92 *
93 * @return string
94 */
95 public function __toString()
96 {
97 try {
98 return $this->render();
99 } catch (Throwable $e) {
100 return Error::render($e);
101 }
102 }
103
104 public function render()
105 {
106 $callback = $this->callback;
107
108 if ($this->escaped) {
109 return $callback();
110 } else {
111 return Html::escape($callback());
112 }
113 }
114 }