You are here

protected function FilterHtml::filterElementAttributes in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/filter/src/Plugin/Filter/FilterHtml.php \Drupal\filter\Plugin\Filter\FilterHtml::filterElementAttributes()
  2. 10 core/modules/filter/src/Plugin/Filter/FilterHtml.php \Drupal\filter\Plugin\Filter\FilterHtml::filterElementAttributes()

Filters attributes on an element according to a list of allowed values.

Parameters

\DOMElement $element: The element to be processed.

array $allowed_attributes: The list of allowed attributes as an array of names and values.

1 call to FilterHtml::filterElementAttributes()
FilterHtml::filterAttributes in core/modules/filter/src/Plugin/Filter/FilterHtml.php
Provides filtering of tag attributes into accepted HTML.

File

core/modules/filter/src/Plugin/Filter/FilterHtml.php, line 159

Class

FilterHtml
Provides a filter to limit allowed HTML tags.

Namespace

Drupal\filter\Plugin\Filter

Code

protected function filterElementAttributes(\DOMElement $element, array $allowed_attributes) {
  $modified_attributes = [];
  foreach ($element->attributes as $name => $attribute) {

    // Remove attributes not in the list of allowed attributes.
    $allowed_value = $this
      ->findAllowedValue($allowed_attributes, $name);
    if (empty($allowed_value)) {
      $modified_attributes[$name] = FALSE;
    }
    elseif ($allowed_value !== TRUE) {

      // Check the list of allowed attribute values.
      $attribute_values = preg_split('/\\s+/', $attribute->value, -1, PREG_SPLIT_NO_EMPTY);
      $modified_attributes[$name] = [];
      foreach ($attribute_values as $value) {
        if ($this
          ->findAllowedValue($allowed_value, $value)) {
          $modified_attributes[$name][] = $value;
        }
      }
    }
  }

  // If the $allowed_value was TRUE for an attribute name, it does not
  // appear in this array so the value on the DOM element is left unchanged.
  foreach ($modified_attributes as $name => $values) {
    if ($values) {
      $element
        ->setAttribute($name, implode(' ', $values));
    }
    else {
      $element
        ->removeAttribute($name);
    }
  }
}