View source
<?php
namespace Drupal\Tests\menu_link_content\Kernel;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\Routing\Route;
class MenuLinkContentDeriverTest extends KernelTestBase {
protected static $modules = [
'menu_link_content',
'link',
'system',
'menu_link_content_dynamic_route',
'user',
];
protected function setUp() : void {
parent::setUp();
$this
->installEntitySchema('user');
$this
->installEntitySchema('menu_link_content');
}
public function testRediscover() {
\Drupal::state()
->set('menu_link_content_dynamic_route.routes', [
'route_name_1' => new Route('/example-path'),
]);
\Drupal::service('router.builder')
->rebuild();
$parent = MenuLinkContent::create([
'title' => '<script>alert("Welcome to the discovered jungle!")</script>',
'link' => [
[
'uri' => 'internal:/example-path',
],
],
'menu_name' => 'tools',
]);
$parent
->save();
$menu_tree = \Drupal::menuTree()
->load('tools', new MenuTreeParameters());
$this
->assertCount(1, $menu_tree);
$tree_element = reset($menu_tree);
$this
->assertEquals('route_name_1', $tree_element->link
->getRouteName());
\Drupal::state()
->set('menu_link_content_dynamic_route.routes', [
'route_name_2' => new Route('/example-path'),
]);
\Drupal::service('router.builder')
->rebuild();
$menu_tree = \Drupal::menuTree()
->load('tools', new MenuTreeParameters());
$this
->assertCount(1, $menu_tree);
$tree_element = reset($menu_tree);
$this
->assertEquals('route_name_2', $tree_element->link
->getRouteName());
$title = $tree_element->link
->getTitle();
$this
->assertNotInstanceOf(TranslatableMarkup::class, $title);
$this
->assertSame('<script>alert("Welcome to the discovered jungle!")</script>', $title);
\Drupal::state()
->set('menu_link_content_dynamic_route.routes', [
'route_name_1' => new Route('/example-path'),
'route_name_2' => new Route('/example-path/child'),
]);
$child = MenuLinkContent::create([
'title' => 'Child',
'link' => [
[
'uri' => 'entity:/example-path/child',
],
],
'menu_name' => 'tools',
'parent' => 'menu_link_content:' . $parent
->uuid(),
]);
$child
->save();
$parent
->set('link', [
[
'uri' => 'entity:/example-path',
],
]);
$parent
->save();
$menu_tree = \Drupal::menuTree()
->load('tools', new MenuTreeParameters());
$this
->assertCount(1, $menu_tree);
$tree_element = reset($menu_tree);
$this
->assertTrue($tree_element->hasChildren);
$this
->assertCount(1, $tree_element->subtree);
$child
->set('link', [
[
'uri' => 'internal:/example-path/child',
],
]);
$child
->save();
\Drupal::service('plugin.manager.menu.link')
->rebuild();
$menu_tree = \Drupal::menuTree()
->load('tools', new MenuTreeParameters());
$this
->assertCount(1, $menu_tree);
$tree_element = reset($menu_tree);
$this
->assertTrue($tree_element->hasChildren);
$this
->assertCount(1, $tree_element->subtree);
}
}