05e0268c20e90673953323f2b041f7595ac7cb5e
[yaffs-website] / web / core / modules / system / src / Tests / Menu / AssertMenuActiveTrailTrait.php
1 <?php
2
3 namespace Drupal\system\Tests\Menu;
4
5 use Drupal\Core\Url;
6
7 /**
8  * Provides test assertions for verifying the active menu trail.
9  */
10 trait AssertMenuActiveTrailTrait {
11
12   /**
13    * Assert that active trail exists in a menu tree output.
14    *
15    * @param array $tree
16    *   An associative array whose keys are link paths and whose
17    *   values are link titles (not sanitized) of an expected active trail in a
18    *   menu tree output on the page.
19    * @param bool $last_active
20    *   Whether the last link in $tree is expected to be active (TRUE)
21    *   or just to be in the active trail (FALSE).
22    */
23   protected function assertMenuActiveTrail($tree, $last_active) {
24     end($tree);
25     $active_link_path = key($tree);
26     $active_link_title = array_pop($tree);
27     $xpath = '';
28     if ($tree) {
29       $i = 0;
30       foreach ($tree as $link_path => $link_title) {
31         $part_xpath = (!$i ? '//' : '/following-sibling::ul/descendant::');
32         $part_xpath .= 'li[contains(@class, :class)]/a[contains(@href, :href) and contains(text(), :title)]';
33         $part_args = [
34           ':class' => 'menu-item--active-trail',
35           ':href' => Url::fromUri('base:' . $link_path)->toString(),
36           ':title' => $link_title,
37         ];
38         $xpath .= $this->buildXPathQuery($part_xpath, $part_args);
39         $i++;
40       }
41       $elements = $this->xpath($xpath);
42       $this->assertTrue(!empty($elements), 'Active trail to current page was found in menu tree.');
43
44       // Append prefix for active link asserted below.
45       $xpath .= '/following-sibling::ul/descendant::';
46     }
47     else {
48       $xpath .= '//';
49     }
50     $xpath_last_active = ($last_active ? 'and contains(@class, :class-active)' : '');
51     $xpath .= 'li[contains(@class, :class-trail)]/a[contains(@href, :href) ' . $xpath_last_active . 'and contains(text(), :title)]';
52     $args = [
53       ':class-trail' => 'menu-item--active-trail',
54       ':class-active' => 'is-active',
55       ':href' => Url::fromUri('base:' . $active_link_path)->toString(),
56       ':title' => $active_link_title,
57     ];
58     $elements = $this->xpath($xpath, $args);
59     $this->assertTrue(!empty($elements), format_string('Active link %title was found in menu tree, including active trail links %tree.', [
60       '%title' => $active_link_title,
61       '%tree' => implode(' ยป ', $tree),
62     ]));
63   }
64
65 }