You are here

public function AttributeTest::testAddClasses in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/Tests/Core/Template/AttributeTest.php \Drupal\Tests\Core\Template\AttributeTest::testAddClasses()

Tests adding class attributes with the AttributeArray helper method. @covers ::addClass

File

core/tests/Drupal/Tests/Core/Template/AttributeTest.php, line 148

Class

AttributeTest
@coversDefaultClass \Drupal\Core\Template\Attribute @group Template

Namespace

Drupal\Tests\Core\Template

Code

public function testAddClasses() {

  // Add empty Attribute object with no classes.
  $attribute = new Attribute();

  // Add no class on empty attribute.
  $attribute
    ->addClass();
  $this
    ->assertEmpty($attribute['class']);

  // Test various permutations of adding values to empty Attribute objects.
  foreach ([
    NULL,
    FALSE,
    '',
    [],
  ] as $value) {

    // Single value.
    $attribute
      ->addClass($value);
    $this
      ->assertEmpty((string) $attribute);

    // Multiple values.
    $attribute
      ->addClass($value, $value);
    $this
      ->assertEmpty((string) $attribute);

    // Single value in array.
    $attribute
      ->addClass([
      $value,
    ]);
    $this
      ->assertEmpty((string) $attribute);

    // Single value in arrays.
    $attribute
      ->addClass([
      $value,
    ], [
      $value,
    ]);
    $this
      ->assertEmpty((string) $attribute);
  }

  // Add one class on empty attribute.
  $attribute
    ->addClass('banana');
  $this
    ->assertEquals([
    'banana',
  ], $attribute['class']
    ->value());

  // Add one class.
  $attribute
    ->addClass('aa');
  $this
    ->assertEquals([
    'banana',
    'aa',
  ], $attribute['class']
    ->value());

  // Add multiple classes.
  $attribute
    ->addClass('xx', 'yy');
  $this
    ->assertEquals([
    'banana',
    'aa',
    'xx',
    'yy',
  ], $attribute['class']
    ->value());

  // Add an array of classes.
  $attribute
    ->addClass([
    'red',
    'green',
    'blue',
  ]);
  $this
    ->assertEquals([
    'banana',
    'aa',
    'xx',
    'yy',
    'red',
    'green',
    'blue',
  ], $attribute['class']
    ->value());

  // Add an array of duplicate classes.
  $attribute
    ->addClass([
    'red',
    'green',
    'blue',
  ], [
    'aa',
    'aa',
    'banana',
  ], 'yy');
  $this
    ->assertEquals('banana aa xx yy red green blue', (string) $attribute['class']);
}