AttributeValueBase.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\Core\Template;
  3. use Drupal\Component\Utility\Html;
  4. /**
  5. * Defines the base class for an attribute type.
  6. *
  7. * @see \Drupal\Core\Template\Attribute
  8. */
  9. abstract class AttributeValueBase {
  10. /**
  11. * Renders '$name=""' if $value is an empty string.
  12. *
  13. * @see \Drupal\Core\Template\AttributeValueBase::render()
  14. */
  15. const RENDER_EMPTY_ATTRIBUTE = TRUE;
  16. /**
  17. * The value itself.
  18. *
  19. * @var mixed
  20. */
  21. protected $value;
  22. /**
  23. * The name of the value.
  24. *
  25. * @var mixed
  26. */
  27. protected $name;
  28. /**
  29. * Constructs a \Drupal\Core\Template\AttributeValueBase object.
  30. */
  31. public function __construct($name, $value) {
  32. $this->name = $name;
  33. $this->value = $value;
  34. }
  35. /**
  36. * Returns a string representation of the attribute.
  37. *
  38. * While __toString only returns the value in a string form, render()
  39. * contains the name of the attribute as well.
  40. *
  41. * @return string
  42. * The string representation of the attribute.
  43. */
  44. public function render() {
  45. $value = (string) $this;
  46. if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) {
  47. return Html::escape($this->name) . '="' . $value . '"';
  48. }
  49. }
  50. /**
  51. * Returns the raw value.
  52. */
  53. public function value() {
  54. return $this->value;
  55. }
  56. /**
  57. * Implements the magic __toString() method.
  58. */
  59. abstract public function __toString();
  60. }