Link.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View\Element\Html;
  7. /**
  8. * HTML anchor element block
  9. *
  10. * @method string getLabel()
  11. * @method string getPath()
  12. * @method string getTitle()
  13. *
  14. * @api
  15. * @since 100.0.2
  16. */
  17. class Link extends \Magento\Framework\View\Element\Template
  18. {
  19. /**
  20. * @var array
  21. */
  22. protected $allowedAttributes = [
  23. 'href',
  24. 'title',
  25. 'charset',
  26. 'name',
  27. 'target',
  28. 'hreflang',
  29. 'rel',
  30. 'rev',
  31. 'accesskey',
  32. 'shape',
  33. 'coords',
  34. 'tabindex',
  35. 'onfocus',
  36. 'onblur', // %attrs
  37. 'id',
  38. 'class',
  39. 'style', // %coreattrs
  40. 'lang',
  41. 'dir', // %i18n
  42. 'onclick',
  43. 'ondblclick',
  44. 'onmousedown',
  45. 'onmouseup',
  46. 'onmouseover',
  47. 'onmousemove',
  48. 'onmouseout',
  49. 'onkeypress',
  50. 'onkeydown',
  51. 'onkeyup', // %events
  52. ];
  53. /**
  54. * Prepare link attributes as serialized and formatted string
  55. *
  56. * @return string
  57. */
  58. public function getLinkAttributes()
  59. {
  60. $attributes = [];
  61. foreach ($this->allowedAttributes as $attribute) {
  62. $value = $this->getDataUsingMethod($attribute);
  63. if ($value !== null) {
  64. $attributes[$attribute] = $this->escapeHtml($value);
  65. }
  66. }
  67. if (!empty($attributes)) {
  68. return $this->serialize($attributes);
  69. }
  70. return '';
  71. }
  72. /**
  73. * Serialize attributes
  74. *
  75. * @param array $attributes
  76. * @param string $valueSeparator
  77. * @param string $fieldSeparator
  78. * @param string $quote
  79. * @return string
  80. */
  81. public function serialize($attributes = [], $valueSeparator = '=', $fieldSeparator = ' ', $quote = '"')
  82. {
  83. $data = [];
  84. foreach ($attributes as $key => $value) {
  85. $data[] = $key . $valueSeparator . $quote . $value . $quote;
  86. }
  87. return implode($fieldSeparator, $data);
  88. }
  89. /**
  90. * Render block HTML
  91. *
  92. * @return string
  93. */
  94. protected function _toHtml()
  95. {
  96. if (false != $this->getTemplate()) {
  97. return parent::_toHtml();
  98. }
  99. return '<li><a ' . $this->getLinkAttributes() . ' >' . $this->escapeHtml($this->getLabel()) . '</a></li>';
  100. }
  101. /**
  102. * Get href URL
  103. *
  104. * @return string
  105. */
  106. public function getHref()
  107. {
  108. return $this->getUrl($this->getPath());
  109. }
  110. }