1<?php
2
3namespace Drupal\Tests\block\Functional;
4
5use Drupal\Component\Utility\Html;
6use Drupal\Tests\BrowserTestBase;
7
8/**
9 * Tests blocks are being rendered in order by weight.
10 *
11 * @group block
12 */
13class BlockRenderOrderTest extends BrowserTestBase {
14
15  /**
16   * Modules to install.
17   *
18   * @var array
19   */
20  protected static $modules = ['node', 'block'];
21
22  /**
23   * {@inheritdoc}
24   */
25  protected $defaultTheme = 'stark';
26
27  protected function setUp(): void {
28    parent::setUp();
29    // Create a test user.
30    $end_user = $this->drupalCreateUser([
31      'access content',
32    ]);
33    $this->drupalLogin($end_user);
34  }
35
36  /**
37   * Tests the render order of the blocks.
38   */
39  public function testBlockRenderOrder() {
40    // Enable test blocks and place them in the same region.
41    $region = 'header';
42    $test_blocks = [
43      'stark_powered' => [
44        'weight' => '-3',
45        'id' => 'stark_powered',
46        'label' => 'Test block A',
47      ],
48      'stark_by' => [
49        'weight' => '3',
50        'id' => 'stark_by',
51        'label' => 'Test block C',
52      ],
53      'stark_drupal' => [
54        'weight' => '3',
55        'id' => 'stark_drupal',
56        'label' => 'Test block B',
57      ],
58    ];
59
60    // Place the test blocks.
61    foreach ($test_blocks as $test_block) {
62      $this->drupalPlaceBlock('system_powered_by_block', [
63        'label' => $test_block['label'],
64        'region' => $region,
65        'weight' => $test_block['weight'],
66        'id' => $test_block['id'],
67      ]);
68    }
69
70    $this->drupalGet('');
71    $test_content = $this->getSession()->getPage()->getContent();
72
73    $controller = $this->container->get('entity_type.manager')->getStorage('block');
74    foreach ($controller->loadMultiple() as $return_block) {
75      $id = $return_block->id();
76      if ($return_block_weight = $return_block->getWeight()) {
77        $this->assertSame((int) $test_blocks[$id]['weight'], $return_block_weight, 'Block weight is set as "' . $return_block_weight . '" for ' . $id . ' block.');
78        $position[$id] = strpos($test_content, Html::getClass('block-' . $test_blocks[$id]['id']));
79      }
80    }
81    // Verify that blocks with different weight are rendered in the correct
82    // order.
83    $this->assertLessThan($position['stark_by'], $position['stark_powered']);
84    // Verify that blocks with identical weight are rendered in alphabetical
85    // order.
86    $this->assertLessThan($position['stark_by'], $position['stark_drupal']);
87  }
88
89}
90