function Attribute::createAttributeValue

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Template/Attribute.php \Drupal\Core\Template\Attribute::createAttributeValue()
  2. 8.9.x core/lib/Drupal/Core/Template/Attribute.php \Drupal\Core\Template\Attribute::createAttributeValue()
  3. 10 core/lib/Drupal/Core/Template/Attribute.php \Drupal\Core\Template\Attribute::createAttributeValue()

Creates the different types of attribute values.

Parameters

string $name: The attribute name.

mixed $value: The attribute value.

Return value

\Drupal\Core\Template\AttributeValueBase An AttributeValueBase representation of the attribute's value.

2 calls to Attribute::createAttributeValue()
Attribute::merge in core/lib/Drupal/Core/Template/Attribute.php
Merges an Attribute object into the current storage.
Attribute::offsetSet in core/lib/Drupal/Core/Template/Attribute.php

File

core/lib/Drupal/Core/Template/Attribute.php, line 118

Class

Attribute
Collects, sanitizes, and renders HTML attributes.

Namespace

Drupal\Core\Template

Code

protected function createAttributeValue($name, $value) {
    // If the value is already an AttributeValueBase object,
    // return a new instance of the same class, but with the new name.
    if ($value instanceof AttributeValueBase) {
        $class = get_class($value);
        return new $class($name, $value->value());
    }
    // An array value or 'class' attribute name are forced to always be an
    // AttributeArray value for consistency.
    if ($name == 'class' && !is_array($value)) {
        // Cast the value to string in case it implements MarkupInterface.
        $value = [
            (string) $value,
        ];
    }
    if (is_array($value)) {
        // Cast the value to an array if the value was passed in as a string.
        // @todo Decide to fix all the broken instances of class as a string
        // in core or cast them.
        $value = new AttributeArray($name, $value);
    }
    elseif (is_bool($value)) {
        $value = new AttributeBoolean($name, $value);
    }
    elseif ($value instanceof MarkupInterface) {
        // Attributes are not supposed to display HTML markup, so we just convert
        // the value to plain text.
        $value = PlainTextOutput::renderFromHtml($value);
        $value = new AttributeString($name, $value);
    }
    elseif (!is_object($value)) {
        $value = new AttributeString($name, $value);
    }
    return $value;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.