You are here

public function ElementTest::testChildren in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/Tests/Core/Render/ElementTest.php \Drupal\Tests\Core\Render\ElementTest::testChildren()
  2. 9 core/tests/Drupal/Tests/Core/Render/ElementTest.php \Drupal\Tests\Core\Render\ElementTest::testChildren()

Tests the children() method.

File

core/tests/Drupal/Tests/Core/Render/ElementTest.php, line 53

Class

ElementTest
@coversDefaultClass \Drupal\Core\Render\Element @group Render

Namespace

Drupal\Tests\Core\Render

Code

public function testChildren() {
  $element = [
    'child2' => [
      '#weight' => 10,
    ],
    'child1' => [
      '#weight' => 0,
    ],
    'child3' => [
      '#weight' => 20,
    ],
    '#property' => 'property',
  ];
  $expected = [
    'child2',
    'child1',
    'child3',
  ];
  $element_copy = $element;
  $this
    ->assertSame($expected, Element::children($element_copy));

  // If #sorted is already set, no sorting should happen.
  $element_copy = $element;
  $element_copy['#sorted'] = TRUE;
  $expected = [
    'child2',
    'child1',
    'child3',
  ];
  $this
    ->assertSame($expected, Element::children($element_copy, TRUE));

  // Test with weight sorting, #sorted property should be added.
  $expected = [
    'child1',
    'child2',
    'child3',
  ];
  $element_copy = $element;
  $this
    ->assertSame($expected, Element::children($element_copy, TRUE));
  $this
    ->assertArrayHasKey('#sorted', $element_copy);
  $this
    ->assertTrue($element_copy['#sorted']);

  // The order should stay the same if no weights present.
  $element_no_weight = [
    'child2' => [],
    'child1' => [],
    'child3' => [],
    '#property' => 'property',
  ];
  $expected = [
    'child2',
    'child1',
    'child3',
  ];
  $this
    ->assertSame($expected, Element::children($element_no_weight, TRUE));

  // The order of children with same weight should be preserved.
  $element_mixed_weight = [
    'child5' => [
      '#weight' => 10,
    ],
    'child3' => [
      '#weight' => -10,
    ],
    'child1' => [],
    'child4' => [
      '#weight' => 10,
    ],
    'child2' => [],
  ];
  $expected = [
    'child3',
    'child1',
    'child2',
    'child5',
    'child4',
  ];
  $this
    ->assertSame($expected, Element::children($element_mixed_weight, TRUE));
}