PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/core/lib/Drupal/Core/Template/Attribute.php

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