You are here

public function ElementTest::testChildren in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 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 58
Contains \Drupal\Tests\Core\Render\ElementTest.

Class

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

Namespace

Drupal\Tests\Core\Render

Code

public function testChildren() {
  $element = array(
    'child2' => array(
      '#weight' => 10,
    ),
    'child1' => array(
      '#weight' => 0,
    ),
    'child3' => array(
      '#weight' => 20,
    ),
    '#property' => 'property',
  );
  $expected = array(
    '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 = array(
    'child2',
    'child1',
    'child3',
  );
  $this
    ->assertSame($expected, Element::children($element_copy, TRUE));

  // Test with weight sorting, #sorted property should be added.
  $expected = array(
    '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 = array(
    'child2' => array(),
    'child1' => array(),
    'child3' => array(),
    '#property' => 'property',
  );
  $expected = array(
    '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 = array(
    'child5' => array(
      '#weight' => 10,
    ),
    'child3' => array(
      '#weight' => -10,
    ),
    'child1' => array(),
    'child4' => array(
      '#weight' => 10,
    ),
    'child2' => array(),
  );
  $expected = array(
    'child3',
    'child1',
    'child2',
    'child5',
    'child4',
  );
  $this
    ->assertSame($expected, Element::children($element_mixed_weight, TRUE));
}