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