Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
attributes.php
1<?php
2
4
6use CUtil;
7
11final class Attributes
12{
17 private array $attributes = [];
18
29 public function set(string $name, $value): self
30 {
31 $this->attributes[$name] = $value;
32
33 return $this;
34 }
35
46 public function setData(string $name, $value): self
47 {
48 $this->set('data-' . $name, $value);
49
50 return $this;
51 }
52
60 public function get(string $name)
61 {
62 return $this->attributes[$name] ?? null;
63 }
64
72 public function remove(string $name)
73 {
74 try
75 {
76 return $this->get($name);
77 }
78 finally
79 {
80 unset($this->attributes[$name]);
81 }
82 }
83
89 public function __toString()
90 {
91 $result = '';
92
93 if (!empty($this->attributes))
94 {
95 $result = ' ';
96 foreach ($this->attributes as $name => $value)
97 {
98 if (!isset($value))
99 {
100 continue;
101 }
102
103 $escapedName = HtmlFilter::encode($name);
104
105 $isDataAttribute = stripos($name, 'data-') === 0;
106 if ($isDataAttribute)
107 {
108 if (is_array($value))
109 {
110 $escapedValue = '(' . HtmlFilter::encode(CUtil::PhpToJSObject($value)) . ')';
111 }
112 elseif (is_bool($value))
113 {
114 $escapedValue = $value ? 'true' : 'false';
115 }
116 else
117 {
118 $escapedValue = HtmlFilter::encode((string)$value);
119 }
120 }
121 else
122 {
123 $escapedValue = HtmlFilter::encode((string)$value);
124 }
125
126 $result .= $escapedName . '="' . $escapedValue . '"';
127 }
128
129 $result .= ' ';
130 }
131
132 return $result;
133 }
134}
setData(string $name, $value)
static encode($string, $flags=ENT_COMPAT, $doubleEncode=true)