Attribute.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. namespace Drupal\Core\Template;
  3. use Drupal\Component\Render\PlainTextOutput;
  4. use Drupal\Component\Render\MarkupInterface;
  5. use Drupal\Component\Utility\NestedArray;
  6. /**
  7. * Collects, sanitizes, and renders HTML attributes.
  8. *
  9. * To use, optionally pass in an associative array of defined attributes, or
  10. * add attributes using array syntax. For example:
  11. * @code
  12. * $attributes = new Attribute(array('id' => 'socks'));
  13. * $attributes['class'] = array('black-cat', 'white-cat');
  14. * $attributes['class'][] = 'black-white-cat';
  15. * echo '<cat' . $attributes . '>';
  16. * // Produces <cat id="socks" class="black-cat white-cat black-white-cat">
  17. * @endcode
  18. *
  19. * $attributes always prints out all the attributes. For example:
  20. * @code
  21. * $attributes = new Attribute(array('id' => 'socks'));
  22. * $attributes['class'] = array('black-cat', 'white-cat');
  23. * $attributes['class'][] = 'black-white-cat';
  24. * echo '<cat class="cat ' . $attributes['class'] . '"' . $attributes . '>';
  25. * // Produces <cat class="cat black-cat white-cat black-white-cat" id="socks" class="cat black-cat white-cat black-white-cat">
  26. * @endcode
  27. *
  28. * When printing out individual attributes to customize them within a Twig
  29. * template, use the "without" filter to prevent attributes that have already
  30. * been printed from being printed again. For example:
  31. * @code
  32. * <cat class="{{ attributes.class }} my-custom-class"{{ attributes|without('class') }}>
  33. * {# Produces <cat class="cat black-cat white-cat black-white-cat my-custom-class" id="socks"> #}
  34. * @endcode
  35. *
  36. * The attribute keys and values are automatically escaped for output with
  37. * Html::escape(). No protocol filtering is applied, so when using user-entered
  38. * input as a value for an attribute that expects an URI (href, src, ...),
  39. * UrlHelper::stripDangerousProtocols() should be used to ensure dangerous
  40. * protocols (such as 'javascript:') are removed. For example:
  41. * @code
  42. * $path = 'javascript:alert("xss");';
  43. * $path = UrlHelper::stripDangerousProtocols($path);
  44. * $attributes = new Attribute(array('href' => $path));
  45. * echo '<a' . $attributes . '>';
  46. * // Produces <a href="alert(&quot;xss&quot;);">
  47. * @endcode
  48. *
  49. * The attribute values are considered plain text and are treated as such. If a
  50. * safe HTML string is detected, it is converted to plain text with
  51. * PlainTextOutput::renderFromHtml() before being escaped. For example:
  52. * @code
  53. * $value = t('Highlight the @tag tag', ['@tag' => '<em>']);
  54. * $attributes = new Attribute(['value' => $value]);
  55. * echo '<input' . $attributes . '>';
  56. * // Produces <input value="Highlight the &lt;em&gt; tag">
  57. * @endcode
  58. *
  59. * @see \Drupal\Component\Utility\Html::escape()
  60. * @see \Drupal\Component\Render\PlainTextOutput::renderFromHtml()
  61. * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
  62. */
  63. class Attribute implements \ArrayAccess, \IteratorAggregate, MarkupInterface {
  64. /**
  65. * Stores the attribute data.
  66. *
  67. * @var \Drupal\Core\Template\AttributeValueBase[]
  68. */
  69. protected $storage = [];
  70. /**
  71. * Constructs a \Drupal\Core\Template\Attribute object.
  72. *
  73. * @param array $attributes
  74. * An associative array of key-value pairs to be converted to attributes.
  75. */
  76. public function __construct($attributes = []) {
  77. foreach ($attributes as $name => $value) {
  78. $this->offsetSet($name, $value);
  79. }
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function offsetGet($name) {
  85. if (isset($this->storage[$name])) {
  86. return $this->storage[$name];
  87. }
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function offsetSet($name, $value) {
  93. $this->storage[$name] = $this->createAttributeValue($name, $value);
  94. }
  95. /**
  96. * Creates the different types of attribute values.
  97. *
  98. * @param string $name
  99. * The attribute name.
  100. * @param mixed $value
  101. * The attribute value.
  102. *
  103. * @return \Drupal\Core\Template\AttributeValueBase
  104. * An AttributeValueBase representation of the attribute's value.
  105. */
  106. protected function createAttributeValue($name, $value) {
  107. // If the value is already an AttributeValueBase object,
  108. // return a new instance of the same class, but with the new name.
  109. if ($value instanceof AttributeValueBase) {
  110. $class = get_class($value);
  111. return new $class($name, $value->value());
  112. }
  113. // An array value or 'class' attribute name are forced to always be an
  114. // AttributeArray value for consistency.
  115. if ($name == 'class' && !is_array($value)) {
  116. // Cast the value to string in case it implements MarkupInterface.
  117. $value = [(string) $value];
  118. }
  119. if (is_array($value)) {
  120. // Cast the value to an array if the value was passed in as a string.
  121. // @todo Decide to fix all the broken instances of class as a string
  122. // in core or cast them.
  123. $value = new AttributeArray($name, $value);
  124. }
  125. elseif (is_bool($value)) {
  126. $value = new AttributeBoolean($name, $value);
  127. }
  128. // As a development aid, we allow the value to be a safe string object.
  129. elseif ($value instanceof MarkupInterface) {
  130. // Attributes are not supposed to display HTML markup, so we just convert
  131. // the value to plain text.
  132. $value = PlainTextOutput::renderFromHtml($value);
  133. $value = new AttributeString($name, $value);
  134. }
  135. elseif (!is_object($value)) {
  136. $value = new AttributeString($name, $value);
  137. }
  138. return $value;
  139. }
  140. /**
  141. * {@inheritdoc}
  142. */
  143. public function offsetUnset($name) {
  144. unset($this->storage[$name]);
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function offsetExists($name) {
  150. return isset($this->storage[$name]);
  151. }
  152. /**
  153. * Adds classes or merges them on to array of existing CSS classes.
  154. *
  155. * @param string|array ...
  156. * CSS classes to add to the class attribute array.
  157. *
  158. * @return $this
  159. */
  160. public function addClass() {
  161. $args = func_get_args();
  162. if ($args) {
  163. $classes = [];
  164. foreach ($args as $arg) {
  165. // Merge the values passed in from the classes array.
  166. // The argument is cast to an array to support comma separated single
  167. // values or one or more array arguments.
  168. $classes = array_merge($classes, (array) $arg);
  169. }
  170. // Merge if there are values, just add them otherwise.
  171. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
  172. // Merge the values passed in from the class value array.
  173. $classes = array_merge($this->storage['class']->value(), $classes);
  174. $this->storage['class']->exchangeArray($classes);
  175. }
  176. else {
  177. $this->offsetSet('class', $classes);
  178. }
  179. }
  180. return $this;
  181. }
  182. /**
  183. * Sets values for an attribute key.
  184. *
  185. * @param string $attribute
  186. * Name of the attribute.
  187. * @param string|array $value
  188. * Value(s) to set for the given attribute key.
  189. *
  190. * @return $this
  191. */
  192. public function setAttribute($attribute, $value) {
  193. $this->offsetSet($attribute, $value);
  194. return $this;
  195. }
  196. /**
  197. * Checks if the storage has an attribute with the given name.
  198. *
  199. * @param string $name
  200. * The name of the attribute to check for.
  201. *
  202. * @return bool
  203. * Returns TRUE if the attribute exists, or FALSE otherwise.
  204. */
  205. public function hasAttribute($name) {
  206. return array_key_exists($name, $this->storage);
  207. }
  208. /**
  209. * Removes an attribute from an Attribute object.
  210. *
  211. * @param string|array ...
  212. * Attributes to remove from the attribute array.
  213. *
  214. * @return $this
  215. */
  216. public function removeAttribute() {
  217. $args = func_get_args();
  218. foreach ($args as $arg) {
  219. // Support arrays or multiple arguments.
  220. if (is_array($arg)) {
  221. foreach ($arg as $value) {
  222. unset($this->storage[$value]);
  223. }
  224. }
  225. else {
  226. unset($this->storage[$arg]);
  227. }
  228. }
  229. return $this;
  230. }
  231. /**
  232. * Removes argument values from array of existing CSS classes.
  233. *
  234. * @param string|array ...
  235. * CSS classes to remove from the class attribute array.
  236. *
  237. * @return $this
  238. */
  239. public function removeClass() {
  240. // With no class attribute, there is no need to remove.
  241. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
  242. $args = func_get_args();
  243. $classes = [];
  244. foreach ($args as $arg) {
  245. // Merge the values passed in from the classes array.
  246. // The argument is cast to an array to support comma separated single
  247. // values or one or more array arguments.
  248. $classes = array_merge($classes, (array) $arg);
  249. }
  250. // Remove the values passed in from the value array. Use array_values() to
  251. // ensure that the array index remains sequential.
  252. $classes = array_values(array_diff($this->storage['class']->value(), $classes));
  253. $this->storage['class']->exchangeArray($classes);
  254. }
  255. return $this;
  256. }
  257. /**
  258. * Gets the class attribute value if set.
  259. *
  260. * This method is implemented to take precedence over hasClass() for Twig 2.0.
  261. *
  262. * @return \Drupal\Core\Template\AttributeValueBase
  263. * The class attribute value if set.
  264. *
  265. * @see twig_get_attribute()
  266. */
  267. public function getClass() {
  268. return $this->offsetGet('class');
  269. }
  270. /**
  271. * Checks if the class array has the given CSS class.
  272. *
  273. * @param string $class
  274. * The CSS class to check for.
  275. *
  276. * @return bool
  277. * Returns TRUE if the class exists, or FALSE otherwise.
  278. */
  279. public function hasClass($class) {
  280. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
  281. return in_array($class, $this->storage['class']->value());
  282. }
  283. else {
  284. return FALSE;
  285. }
  286. }
  287. /**
  288. * Implements the magic __toString() method.
  289. */
  290. public function __toString() {
  291. $return = '';
  292. /** @var \Drupal\Core\Template\AttributeValueBase $value */
  293. foreach ($this->storage as $name => $value) {
  294. $rendered = $value->render();
  295. if ($rendered) {
  296. $return .= ' ' . $rendered;
  297. }
  298. }
  299. return $return;
  300. }
  301. /**
  302. * Returns all storage elements as an array.
  303. *
  304. * @return array
  305. * An associative array of attributes.
  306. */
  307. public function toArray() {
  308. $return = [];
  309. foreach ($this->storage as $name => $value) {
  310. $return[$name] = $value->value();
  311. }
  312. return $return;
  313. }
  314. /**
  315. * Implements the magic __clone() method.
  316. */
  317. public function __clone() {
  318. foreach ($this->storage as $name => $value) {
  319. $this->storage[$name] = clone $value;
  320. }
  321. }
  322. /**
  323. * {@inheritdoc}
  324. */
  325. public function getIterator() {
  326. return new \ArrayIterator($this->storage);
  327. }
  328. /**
  329. * Returns the whole array.
  330. */
  331. public function storage() {
  332. return $this->storage;
  333. }
  334. /**
  335. * Returns a representation of the object for use in JSON serialization.
  336. *
  337. * @return string
  338. * The safe string content.
  339. */
  340. public function jsonSerialize() {
  341. return (string) $this;
  342. }
  343. /**
  344. * Merges an Attribute object into the current storage.
  345. *
  346. * @param \Drupal\Core\Template\Attribute $collection
  347. * The Attribute object to merge.
  348. *
  349. * @return $this
  350. */
  351. public function merge(Attribute $collection) {
  352. $merged_attributes = NestedArray::mergeDeep($this->toArray(), $collection->toArray());
  353. foreach ($merged_attributes as $name => $value) {
  354. $this->storage[$name] = $this->createAttributeValue($name, $value);
  355. }
  356. return $this;
  357. }
  358. }