1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui\HtmlTemplate;
6:
7: use Atk4\Core\WarnDynamicPropertyTrait;
8: use Atk4\Ui\Exception;
9:
10: class Value
11: {
12: use WarnDynamicPropertyTrait;
13:
14: private string $value = '';
15:
16: private bool $isEncoded = false;
17:
18: private function encodeValueToHtml(string $value): string
19: {
20: return htmlspecialchars($value, \ENT_HTML5 | \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
21: }
22:
23: /**
24: * @return $this
25: */
26: public function set(string $value): self
27: {
28: if (\PHP_MAJOR_VERSION === 7 || (\PHP_MAJOR_VERSION === 8 && \PHP_MAJOR_VERSION <= 1) // @phpstan-ignore-line
29: ? !preg_match('~~u', $value) // much faster in PHP 8.1 and lower
30: : !mb_check_encoding($value, 'UTF-8')
31: ) {
32: throw new Exception('Value is not valid UTF-8');
33: }
34:
35: $this->isEncoded = false;
36: $this->value = $value;
37:
38: return $this;
39: }
40:
41: /**
42: * @return $this
43: */
44: public function dangerouslySetHtml(string $value): self
45: {
46: $this->set($value);
47: $this->isEncoded = true;
48:
49: return $this;
50: }
51:
52: public function isEncoded(): bool
53: {
54: return $this->isEncoded;
55: }
56:
57: public function getUnencoded(): string
58: {
59: if ($this->isEncoded) {
60: throw new Exception('Unencoded value is not available');
61: }
62:
63: return $this->value;
64: }
65:
66: public function getHtml(): string
67: {
68: return $this->isEncoded
69: ? $this->value
70: : $this->encodeValueToHtml($this->value);
71: }
72: }
73: