SystemMenuBlockTest.php 10.8 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * Contains \Drupal\system\Tests\Block\SystemMenuBlockTest
 */

namespace Drupal\system\Tests\Block;

8 9 10 11 12 13 14 15 16
use Drupal\Core\Render\Element;
use Drupal\simpletest\KernelTestBase;
use Drupal\system\Tests\Routing\MockRouteProvider;
use Drupal\Tests\Core\Menu\MenuLinkMock;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
17 18

/**
19
 * Tests \Drupal\system\Plugin\Block\SystemMenuBlock.
20
 *
21
 * @group Block
22 23 24 25 26 27
 * @todo Expand test coverage to all SystemMenuBlock functionality, including
 *   block_menu_delete().
 *
 * @see \Drupal\system\Plugin\Derivative\SystemMenuBlock
 * @see \Drupal\system\Plugin\Block\SystemMenuBlock
 */
28
class SystemMenuBlockTest extends KernelTestBase {
29 30 31 32 33 34

  /**
   * Modules to enable.
   *
   * @var array
   */
35 36 37 38 39 40 41
  public static $modules = array(
    'system',
    'block',
    'menu_test',
    'menu_link_content',
    'field',
    'user',
42
    'link',
43
  );
44 45

  /**
46 47 48
   * The block under test.
   *
   * @var \Drupal\system\Plugin\Block\SystemMenuBlock
49
   */
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  protected $block;

  /**
   * The menu for testing.
   *
   * @var \Drupal\system\MenuInterface
   */
  protected $menu;

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTree
   */
  protected $linkTree;

  /**
   * The menu link plugin manager service.
   *
   * @var \Drupal\Core\Menu\MenuLinkManagerInterface $menuLinkManager
   */
  protected $menuLinkManager;

  /**
   * The block manager service.
   *
   * @var \Drupal\Core\block\BlockManagerInterface
   */
  protected $blockManager;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installSchema('system', 'sequences');
    $this->installEntitySchema('user');
    $this->installSchema('system', array('router'));
    $this->installEntitySchema('menu_link_content');

    $account = User::create([
      'name' => $this->randomMachineName(),
      'status' => 1,
    ]);
    $account->save();
    $this->container->get('current_user')->setAccount($account);

    $this->menuLinkManager = $this->container->get('plugin.manager.menu.link');
    $this->linkTree = $this->container->get('menu.link_tree');
    $this->blockManager = $this->container->get('plugin.manager.block');

    $routes = new RouteCollection();
    $requirements = array('_access' => 'TRUE');
    $options = array('_access_checks' => array('access_check.default'));
    $routes->add('example1', new Route('/example1', array(), $requirements, $options));
    $routes->add('example2', new Route('/example2', array(), $requirements, $options));
    $routes->add('example3', new Route('/example3', array(), $requirements, $options));
    $routes->add('example4', new Route('/example4', array(), $requirements, $options));
    $routes->add('example5', new Route('/example5', array(), $requirements, $options));
    $routes->add('example6', new Route('/example6', array(), $requirements, $options));
    $routes->add('example7', new Route('/example7', array(), $requirements, $options));
    $routes->add('example8', new Route('/example8', array(), $requirements, $options));

    $mock_route_provider = new MockRouteProvider($routes);
    $this->container->set('router.route_provider', $mock_route_provider);

116
    // Add a new custom menu.
117
    $menu_name = 'mock';
118
    $label = $this->randomMachineName(16);
119

120
    $this->menu = entity_create('menu', array(
121 122 123 124
      'id' => $menu_name,
      'label' => $label,
      'description' => 'Description text',
    ));
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    $this->menu->save();

    // This creates a tree with the following structure:
    // - 1
    // - 2
    //   - 3
    //     - 4
    // - 5
    //   - 7
    // - 6
    // - 8
    // With link 6 being the only external link.
    $links = array(
      1 => MenuLinkMock::create(array('id' => 'test.example1', 'route_name' => 'example1', 'title' => 'foo', 'parent' => '', 'weight' => 0)),
      2 => MenuLinkMock::create(array('id' => 'test.example2', 'route_name' => 'example2', 'title' => 'bar', 'parent' => '', 'route_parameters' => array('foo' => 'bar'), 'weight' => 1)),
      3 => MenuLinkMock::create(array('id' => 'test.example3', 'route_name' => 'example3', 'title' => 'baz', 'parent' => 'test.example2', 'weight' => 2)),
      4 => MenuLinkMock::create(array('id' => 'test.example4', 'route_name' => 'example4', 'title' => 'qux', 'parent' => 'test.example3', 'weight' => 3)),
      5 => MenuLinkMock::create(array('id' => 'test.example5', 'route_name' => 'example5', 'title' => 'foofoo', 'parent' => '', 'expanded' => TRUE, 'weight' => 4)),
      6 => MenuLinkMock::create(array('id' => 'test.example6', 'route_name' => '', 'url' => 'https://drupal.org/', 'title' => 'barbar', 'parent' => '', 'weight' => 5)),
      7 => MenuLinkMock::create(array('id' => 'test.example7', 'route_name' => 'example7', 'title' => 'bazbaz', 'parent' => 'test.example5', 'weight' => 6)),
      8 => MenuLinkMock::create(array('id' => 'test.example8', 'route_name' => 'example8', 'title' => 'quxqux', 'parent' => '', 'weight' => 7)),
    );
    foreach ($links as $instance) {
      $this->menuLinkManager->addDefinition($instance->getPluginId(), $instance->getPluginDefinition());
    }
  }

  /**
   * Tests calculation of a system menu block's configuration dependencies.
   */
  public function testSystemMenuBlockConfigDependencies() {
156 157

    $block = entity_create('block', array(
158
      'plugin' => 'system_menu_block:' . $this->menu->id(),
159 160 161 162 163 164 165
      'region' => 'footer',
      'id' => 'machinename',
      'theme' => 'stark',
    ));

    $dependencies = $block->calculateDependencies();
    $expected = array(
166
      'config' => array(
167
        'system.menu.' . $this->menu->id()
168 169 170 171 172 173 174 175 176 177
      ),
      'module' => array(
        'system'
      ),
      'theme' => array(
        'stark'
      ),
    );
    $this->assertIdentical($expected, $dependencies);
  }
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

  /**
   * Tests the config start level and depth.
   */
  public function testConfigLevelDepth() {
    // Helper function to generate a configured block instance.
    $place_block = function ($level, $depth) {
      return $this->blockManager->createInstance('system_menu_block:' . $this->menu->id(), array(
        'region' => 'footer',
        'id' => 'machinename',
        'theme' => 'stark',
        'level' => $level,
        'depth' => $depth,
      ));
    };

    // All the different block instances we're going to test.
    $blocks = [
      'all' => $place_block(1, 0),
      'level_1_only' => $place_block(1, 1),
      'level_2_only' => $place_block(2, 1),
      'level_3_only' => $place_block(3, 1),
      'level_1_and_beyond' => $place_block(1, 0),
      'level_2_and_beyond' => $place_block(2, 0),
      'level_3_and_beyond' => $place_block(3, 0),
    ];

    // Scenario 1: test all block instances when there's no active trail.
    $no_active_trail_expectations = [];
    $no_active_trail_expectations['all'] = [
      'test.example1' => [],
      'test.example2' => [],
      'test.example5' => [
        'test.example7' => [],
       ],
      'test.example6' => [],
      'test.example8' => [],
    ];
    $no_active_trail_expectations['level_1_only'] = [
      'test.example1' => [],
      'test.example2' => [],
      'test.example5' => [],
      'test.example6' => [],
      'test.example8' => [],
    ];
    $no_active_trail_expectations['level_2_only'] = [
      'test.example7' => [],
    ];
    $no_active_trail_expectations['level_3_only'] = [];
    $no_active_trail_expectations['level_1_and_beyond'] = $no_active_trail_expectations['all'];
    $no_active_trail_expectations['level_2_and_beyond'] = $no_active_trail_expectations['level_2_only'];
    $no_active_trail_expectations['level_3_and_beyond'] = [];
    foreach ($blocks as $id => $block) {
231 232 233
      $block_build = $block->build();
      $items = isset($block_build['#items']) ? $block_build['#items'] : [];
      $this->assertIdentical($no_active_trail_expectations[$id], $this->convertBuiltMenuToIdTree($items), format_string('Menu block %id with no active trail renders the expected tree.', ['%id' => $id]));
234 235 236 237 238 239 240 241
    }

    // Scenario 2: test all block instances when there's an active trail.
    $route = $this->container->get('router.route_provider')->getRouteByName('example3');
    $request = new Request();
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'example3');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, $route);
    $this->container->get('request_stack')->push($request);
242 243 244 245 246 247
    // \Drupal\Core\Menu\MenuActiveTrail uses the cache collector pattern, which
    // includes static caching. Since this second scenario simulates a second
    // request, we must also simulate it for the MenuActiveTrail service, by
    // clearing the cache collector's static cache.
    \Drupal::service('menu.active_trail')->clear();

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    $active_trail_expectations = [];
    $active_trail_expectations['all'] = [
      'test.example1' => [],
      'test.example2' => [
        'test.example3' => [
          'test.example4' => [],
        ]
      ],
      'test.example5' => [
        'test.example7' => [],
      ],
      'test.example6' => [],
      'test.example8' => [],
    ];
    $active_trail_expectations['level_1_only'] = [
      'test.example1' => [],
      'test.example2' => [],
      'test.example5' => [],
      'test.example6' => [],
      'test.example8' => [],
    ];
    $active_trail_expectations['level_2_only'] = [
      'test.example3' => [],
      'test.example7' => [],
    ];
    $active_trail_expectations['level_3_only'] = [
      'test.example4' => [],
    ];
    $active_trail_expectations['level_1_and_beyond'] = $active_trail_expectations['all'];
    $active_trail_expectations['level_2_and_beyond'] = [
      'test.example3' => [
        'test.example4' => [],
      ],
      'test.example7' => [],
    ];
    $active_trail_expectations['level_3_and_beyond'] = $active_trail_expectations['level_3_only'];
    foreach ($blocks as $id => $block) {
285 286 287
      $block_build = $block->build();
      $items = isset($block_build['#items']) ? $block_build['#items'] : [];
      $this->assertIdentical($active_trail_expectations[$id], $this->convertBuiltMenuToIdTree($items), format_string('Menu block %id with an active trail renders the expected tree.', ['%id' => $id]));
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    }
  }

  /**
   * Helper method to allow for easy menu link tree structure assertions.
   *
   * Converts the result of MenuLinkTree::build() in a "menu link ID tree".
   *
   * @param array $build
   *   The return value of of MenuLinkTree::build()
   *
   * @return array
   *   The "menu link ID tree" representation of the given render array.
   */
  protected function convertBuiltMenuToIdTree(array $build) {
    $level = [];
    foreach (Element::children($build) as $id) {
      $level[$id] = [];
306 307
      if (isset($build[$id]['below'])) {
        $level[$id] = $this->convertBuiltMenuToIdTree($build[$id]['below']);
308 309 310 311 312
      }
    }
    return $level;
  }

313
}