Completed
Push — master ( 662027...11e3e9 )
by William
7s
created

WP_Bootstrap_Navwalker   C

Complexity

Total Complexity 74

Size/Duplication

Total Lines 524
Duplicated Lines 2.67 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 74
lcom 1
cbo 0
dl 14
loc 524
rs 5.5244
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
B start_lvl() 7 39 5
F start_el() 7 201 27
A display_element() 0 9 3
D fallback() 0 43 10
C seporate_linkmods_and_icons_from_classes() 0 27 7
B get_linkmod_type() 0 18 6
C update_atts_for_linkmod_type() 0 24 8
A wrap_for_screen_reader() 0 6 2
A linkmod_element_open() 0 12 3
A linkmod_element_close() 0 12 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like WP_Bootstrap_Navwalker often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WP_Bootstrap_Navwalker, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * WP Bootstrap Navwalker
4
 *
5
 * @package WP-Bootstrap-Navwalker
6
 */
7
8
/*
9
 * Class Name: WP_Bootstrap_Navwalker
10
 * Plugin Name: WP Bootstrap Navwalker
11
 * Plugin URI:  https://github.com/wp-bootstrap/wp-bootstrap-navwalker
12
 * Description: A custom WordPress nav walker class to implement the Bootstrap 4 navigation style in a custom theme using the WordPress built in menu manager.
13
 * Author: Edward McIntyre - @twittem, WP Bootstrap, William Patton - @pattonwebz
14
 * Version: 4.0.2
15
 * Author URI: https://github.com/wp-bootstrap
16
 * GitHub Plugin URI: https://github.com/wp-bootstrap/wp-bootstrap-navwalker
17
 * GitHub Branch: master
18
 * License: GPL-3.0+
19
 * License URI: http://www.gnu.org/licenses/gpl-3.0.txt
20
*/
21
22
/* Check if Class Exists. */
23
if ( ! class_exists( 'WP_Bootstrap_Navwalker' ) ) {
24
	/**
25
	 * WP_Bootstrap_Navwalker class.
26
	 *
27
	 * @extends Walker_Nav_Menu
28
	 */
29
	class WP_Bootstrap_Navwalker extends Walker_Nav_Menu {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
30
31
		/**
32
		 * Starts the list before the elements are added.
33
		 *
34
		 * @since WP 3.0.0
35
		 *
36
		 * @see Walker_Nav_Menu::start_lvl()
37
		 *
38
		 * @param string   $output Used to append additional content (passed by reference).
39
		 * @param int      $depth  Depth of menu item. Used for padding.
40
		 * @param stdClass $args   An object of wp_nav_menu() arguments.
41
		 */
42
		public function start_lvl( &$output, $depth = 0, $args = array() ) {
43 View Code Duplication
			if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
44
				$t = '';
45
				$n = '';
46
			} else {
47
				$t = "\t";
48
				$n = "\n";
49
			}
50
			$indent = str_repeat( $t, $depth );
51
			// Default class to add to the file.
52
			$classes = array( 'dropdown-menu' );
53
			/**
54
			 * Filters the CSS class(es) applied to a menu list element.
55
			 *
56
			 * @since WP 4.8.0
57
			 *
58
			 * @param array    $classes The CSS classes that are applied to the menu `<ul>` element.
59
			 * @param stdClass $args    An object of `wp_nav_menu()` arguments.
60
			 * @param int      $depth   Depth of menu item. Used for padding.
61
			 */
62
			$class_names = join( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );
63
			$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
64
			/**
65
			 * The `.dropdown-menu` container needs to have a labelledby
66
			 * attribute which points to it's trigger link.
67
			 *
68
			 * Form a string for the labelledby attribute from the the latest
69
			 * link with an id that was added to the $output.
70
			 */
71
			$labelledby = '';
0 ignored issues
show
Unused Code introduced by
$labelledby is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
72
			// find all links with an id in the output.
73
			preg_match_all( '/(<a.*?id=\"|\')(.*?)\"|\'.*?>/im', $output, $matches );
74
			// with pointer at end of array check if we got an ID match.
75
			if ( end( $matches[2] ) ) {
76
				// build a string to use as aria-labelledby.
77
				$lablledby = 'aria-labelledby="' . end( $matches[2] ) . '"';
78
			}
79
			$output .= "{$n}{$indent}<ul$class_names $lablledby role=\"menu\">{$n}";
0 ignored issues
show
Bug introduced by
The variable $lablledby does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
80
		}
81
82
		/**
83
		 * Starts the element output.
84
		 *
85
		 * @since WP 3.0.0
86
		 * @since WP 4.4.0 The {@see 'nav_menu_item_args'} filter was added.
87
		 *
88
		 * @see Walker_Nav_Menu::start_el()
89
		 *
90
		 * @param string   $output Used to append additional content (passed by reference).
91
		 * @param WP_Post  $item   Menu item data object.
92
		 * @param int      $depth  Depth of menu item. Used for padding.
93
		 * @param stdClass $args   An object of wp_nav_menu() arguments.
94
		 * @param int      $id     Current item ID.
95
		 */
96
		public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
97 View Code Duplication
			if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
				$t = '';
99
				$n = '';
0 ignored issues
show
Unused Code introduced by
$n is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
100
			} else {
101
				$t = "\t";
102
				$n = "\n";
0 ignored issues
show
Unused Code introduced by
$n is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
103
			}
104
			$indent = ( $depth ) ? str_repeat( $t, $depth ) : '';
105
106
			$classes = empty( $item->classes ) ? array() : (array) $item->classes;
107
108
			// Initialize some holder variables to store specially handled item
109
			// wrappers and icons.
110
			$linkmod_classes = array();
111
			$icon_classes    = array();
112
113
			/**
114
			 * Get an updated $classes array without linkmod or icon classes.
115
			 *
116
			 * NOTE: linkmod and icon class arrays are passed by reference and
117
			 * are maybe modified before being used later in this function.
118
			 */
119
			$classes = self::seporate_linkmods_and_icons_from_classes( $classes, $linkmod_classes, $icon_classes, $depth );
120
121
			// Join any icon classes plucked from $classes into a string.
122
			$icon_class_string = join( ' ', $icon_classes );
123
124
			/**
125
			 * Filters the arguments for a single nav menu item.
126
			 *
127
			 *  WP 4.4.0
128
			 *
129
			 * @param stdClass $args  An object of wp_nav_menu() arguments.
130
			 * @param WP_Post  $item  Menu item data object.
131
			 * @param int      $depth Depth of menu item. Used for padding.
132
			 */
133
			$args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );
134
135
			// Add .dropdown or .active classes where they are needed.
136
			if ( $args->has_children ) {
137
				$classes[] = 'dropdown';
138
			}
139
			if ( in_array( 'current-menu-item', $classes, true ) || in_array( 'current-menu-parent', $classes, true ) ) {
140
				$classes[] = 'active';
141
			}
142
143
			// Add some additional default classes to the item.
144
			$classes[] = 'menu-item-' . $item->ID;
145
			$classes[] = 'nav-item';
146
147
			// Allow filtering the classes.
148
			$classes = apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth );
149
150
			// Form a string of classes in format: class="class_names".
151
			$class_names = join( ' ', $classes );
152
			$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
153
154
			/**
155
			 * Filters the ID applied to a menu item's list item element.
156
			 *
157
			 * @since WP 3.0.1
158
			 * @since WP 4.1.0 The `$depth` parameter was added.
159
			 *
160
			 * @param string   $menu_id The ID that is applied to the menu item's `<li>` element.
161
			 * @param WP_Post  $item    The current menu item.
162
			 * @param stdClass $args    An object of wp_nav_menu() arguments.
163
			 * @param int      $depth   Depth of menu item. Used for padding.
164
			 */
165
			$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth );
166
			$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
167
168
			$output .= $indent . '<li itemscope="itemscope" itemtype="https://www.schema.org/SiteNavigationElement"' . $id . $class_names . '>';
169
170
			// initialize array for holding the $atts for the link item.
171
			$atts = array();
172
173
			// Set title from item to the $atts array - if title is empty then
174
			// default to item title.
175
			if ( empty( $item->attr_title ) ) {
176
				$atts['title'] = ! empty( $item->title ) ? strip_tags( $item->title ) : '';
177
			} else {
178
				$atts['title'] = $item->attr_title;
179
			}
180
181
			$atts['target'] = ! empty( $item->target ) ? $item->target : '';
182
			$atts['rel']    = ! empty( $item->xfn ) ? $item->xfn : '';
183
			// If item has_children add atts to <a>.
184
			if ( $args->has_children && 0 === $depth && $args->depth > 1 ) {
185
				$atts['href']          = '#';
186
				$atts['data-toggle']   = 'dropdown';
187
				$atts['aria-haspopup'] = 'true';
188
				$atts['aria-expanded'] = 'false';
189
				$atts['class']         = 'dropdown-toggle nav-link';
190
				$atts['id']            = 'menu-item-dropdown-' . $item->ID;
191
			} else {
192
				$atts['href'] = ! empty( $item->url ) ? $item->url : '#';
193
				// Items in dropdowns use .dropdown-item instead of .nav-link.
194
				if ( $depth > 0 ) {
195
					$atts['class'] = 'dropdown-item';
196
				} else {
197
					$atts['class'] = 'nav-link';
198
				}
199
			}
200
201
			// update atts of this item based on any custom linkmod classes.
202
			$atts = self::update_atts_for_linkmod_type( $atts, $linkmod_classes );
203
			// Allow filtering of the $atts array before using it.
204
			$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
205
206
			// Build a string of html containing all the atts for the item.
207
			$attributes = '';
208
			foreach ( $atts as $attr => $value ) {
209
				if ( ! empty( $value ) ) {
210
					$value       = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
211
					$attributes .= ' ' . $attr . '="' . $value . '"';
212
				}
213
			}
214
215
			/**
216
			 * Set a typeflag to easily test if this is a linkmod or not.
217
			 */
218
			$linkmod_type = self::get_linkmod_type( $linkmod_classes );
219
220
			/**
221
			 * START appending the internal item contents to the output.
222
			 */
223
			$item_output = $args->before;
224
225
			/**
226
			 * This is the start of the internal nav item. Depending on what
227
			 * kind of linkmod we have we may need different wrapper elements.
228
			 */
229
			if ( '' !== $linkmod_type ) {
230
				// is linkmod, output the required element opener.
231
				$item_output .= self::linkmod_element_open( $linkmod_type, $attributes );
232
			} else {
233
				// With no link mod type set this must be a standard <a> tag.
234
				$item_output .= '<a' . $attributes . '>';
235
			}
236
237
			/**
238
			 * Initiate empty icon var, then if we have a string containing any
239
			 * icon classes form the icon markup with an <i> element. This is
240
			 * output inside of the item before the $title (the link text).
241
			 */
242
			$icon_html = '';
243
			if ( ! empty( $icon_class_string ) ) {
244
				// append an <i> with the icon classes to what is output before links.
245
				$icon_html = '<i class="' . esc_attr( $icon_class_string ) . '" aria-hidden="true"></i> ';
246
			}
247
248
			/** This filter is documented in wp-includes/post-template.php */
249
			$title = apply_filters( 'the_title', $item->title, $item->ID );
250
251
			/**
252
			 * Filters a menu item's title.
253
			 *
254
			 * @since WP 4.4.0
255
			 *
256
			 * @param string   $title The menu item's title.
257
			 * @param WP_Post  $item  The current menu item.
258
			 * @param stdClass $args  An object of wp_nav_menu() arguments.
259
			 * @param int      $depth Depth of menu item. Used for padding.
260
			 */
261
			$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );
262
263
			/**
264
			 * If the .sr-only class was set apply to the nav items text only.
265
			 */
266
			if ( in_array( 'sr-only', $linkmod_classes, true ) ) {
267
				$title         = self::wrap_for_screen_reader( $title );
268
				$keys_to_unset = array_keys( $linkmod_classes, 'sr-only' );
269
				foreach ( $keys_to_unset as $k ) {
270
					unset( $linkmod_classes[ $k ] );
271
				}
272
			}
273
274
			// Put the item contents into $output.
275
			$item_output .= $args->link_before . $icon_html . $title . $args->link_after;
276
277
			/**
278
			 * This is the end of the internal nav item. We need to close the
279
			 * correct element depending on the type of link or link mod.
280
			 */
281
			if ( '' !== $linkmod_type ) {
282
				// is linkmod, output the required element opener.
283
				$item_output .= self::linkmod_element_close( $linkmod_type, $attributes );
284
			} else {
285
				// With no link mod type set this must be a standard <a> tag.
286
				$item_output .= '</a>';
287
			}
288
289
			$item_output .= $args->after;
290
			/**
291
			 * END appending the internal item contents to the output.
292
			 */
293
294
			$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
295
296
		}
297
298
		/**
299
		 * Traverse elements to create list from elements.
300
		 *
301
		 * Display one element if the element doesn't have any children otherwise,
302
		 * display the element and its children. Will only traverse up to the max
303
		 * depth and no ignore elements under that depth. It is possible to set the
304
		 * max depth to include all depths, see walk() method.
305
		 *
306
		 * This method should not be called directly, use the walk() method instead.
307
		 *
308
		 * @since WP 2.5.0
309
		 *
310
		 * @see Walker::start_lvl()
311
		 *
312
		 * @param object $element           Data object.
313
		 * @param array  $children_elements List of elements to continue traversing (passed by reference).
314
		 * @param int    $max_depth         Max depth to traverse.
315
		 * @param int    $depth             Depth of current element.
316
		 * @param array  $args              An array of arguments.
317
		 * @param string $output            Used to append additional content (passed by reference).
318
		 */
319
		public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
320
			if ( ! $element ) {
321
				return; }
322
			$id_field = $this->db_fields['id'];
323
			// Display this element.
324
			if ( is_object( $args[0] ) ) {
325
				$args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] ); }
326
			parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
327
		}
328
329
		/**
330
		 * Menu Fallback
331
		 * =============
332
		 * If this function is assigned to the wp_nav_menu's fallback_cb variable
333
		 * and a menu has not been assigned to the theme location in the WordPress
334
		 * menu manager the function with display nothing to a non-logged in user,
335
		 * and will add a link to the WordPress menu manager if logged in as an admin.
336
		 *
337
		 * @param array $args passed from the wp_nav_menu function.
338
		 */
339
		public static function fallback( $args ) {
340
			if ( current_user_can( 'edit_theme_options' ) ) {
341
342
				/* Get Arguments. */
343
				$container       = $args['container'];
344
				$container_id    = $args['container_id'];
345
				$container_class = $args['container_class'];
346
				$menu_class      = $args['menu_class'];
347
				$menu_id         = $args['menu_id'];
348
349
				// initialize var to store fallback html.
350
				$fallback_output = '';
351
352
				if ( $container ) {
353
					$fallback_output .= '<' . esc_attr( $container );
354
					if ( $container_id ) {
355
						$fallback_output .= ' id="' . esc_attr( $container_id ) . '"';
356
					}
357
					if ( $container_class ) {
358
						$fallback_output .= ' class="' . esc_attr( $container_class ) . '"';
359
					}
360
					$fallback_output .= '>';
361
				}
362
				$fallback_output .= '<ul';
363
				if ( $menu_id ) {
364
					$fallback_output .= ' id="' . esc_attr( $menu_id ) . '"'; }
365
				if ( $menu_class ) {
366
					$fallback_output .= ' class="' . esc_attr( $menu_class ) . '"'; }
367
				$fallback_output .= '>';
368
				$fallback_output .= '<li><a href="' . esc_url( admin_url( 'nav-menus.php' ) ) . '" title="' . esc_attr__( 'Add a menu', 'wp-bootstrap-navwalker' ) . '">' . esc_html__( 'Add a menu', 'wp-bootstrap-navwalker' ) . '</a></li>';
369
				$fallback_output .= '</ul>';
370
				if ( $container ) {
371
					$fallback_output .= '</' . esc_attr( $container ) . '>';
372
				}
373
374
				// if $args has 'echo' key and it's true echo, otherwise return.
375
				if ( array_key_exists( 'echo', $args ) && $args['echo'] ) {
376
					echo $fallback_output; // WPCS: XSS OK.
377
				} else {
378
					return $fallback_output;
379
				}
380
			}
381
		}
382
383
		/**
384
		 * Find any custom linkmod or icon classes and store in their holder
385
		 * arrays then remove them from the main classes array.
386
		 *
387
		 * Supported linkmods: .disabled, .dropdown-header, .dropdown-divider, .sr-only
388
		 * Supported iconsets: Font Awesome 4/5, Glypicons
389
		 *
390
		 * NOTE: This accepts the linkmod and icon arrays by reference.
391
		 *
392
		 * @since 4.0.0
393
		 *
394
		 * @param array   $classes         an array of classes currently assigned to the item.
395
		 * @param array   $linkmod_classes an array to hold linkmod classes.
396
		 * @param array   $icon_classes    an array to hold icon classes.
397
		 * @param integer $depth           an integer holding current depth level.
398
		 *
399
		 * @return array  $classes         a maybe modified array of classnames.
400
		 */
401
		private function seporate_linkmods_and_icons_from_classes( $classes, &$linkmod_classes, &$icon_classes, $depth ) {
402
			// Loop through $classes array to find linkmod or icon classes.
403
			foreach ( $classes as $key => $class ) {
404
				// If any special classes are found, store the class in it's
405
				// holder array and and unset the item from $classes.
406
				if ( preg_match( '/^disabled|^sr-only/i', $class ) ) {
407
					// Test for .disabled or .sr-only classes.
408
					$linkmod_classes[] = $class;
409
					unset( $classes[ $key ] );
410
				} elseif ( preg_match( '/^dropdown-header|^dropdown-divider/i', $class ) && $depth > 0 ) {
411
					// Test for .dropdown-header or .dropdown-divider and a
412
					// depth greater than 0 - IE inside a dropdown.
413
					$linkmod_classes[] = $class;
414
					unset( $classes[ $key ] );
415
				} elseif ( preg_match( '/^fa-(\S*)?|^fa(s|r|l|b)?(\s?)?$/i', $class ) ) {
416
					// Font Awesome.
417
					$icon_classes[] = $class;
418
					unset( $classes[ $key ] );
419
				} elseif ( preg_match( '/^glyphicon-(\S*)?|^glyphicon(\s?)$/i', $class ) ) {
420
					// Glyphicons.
421
					$icon_classes[] = $class;
422
					unset( $classes[ $key ] );
423
				}
424
			}
425
426
			return $classes;
427
		}
428
429
		/**
430
		 * Return a string containing a linkmod type and update $atts array
431
		 * accordingly depending on the decided.
432
		 *
433
		 * @since 4.0.0
434
		 *
435
		 * @param array $linkmod_classes array of any link modifier classes.
436
		 *
437
		 * @return string                empty for default, a linkmod type string otherwise.
438
		 */
439
		private function get_linkmod_type( $linkmod_classes = array() ) {
440
			$linkmod_type = '';
441
			// Loop through array of linkmod classes to handle their $atts.
442
			if ( ! empty( $linkmod_classes ) ) {
443
				foreach ( $linkmod_classes as $link_class ) {
444
					if ( ! empty( $link_class ) ) {
445
446
						// check for special class types and set a flag for them.
447
						if ( 'dropdown-header' === $link_class ) {
448
							$linkmod_type = 'dropdown-header';
449
						} elseif ( 'dropdown-divider' === $link_class ) {
450
							$linkmod_type = 'dropdown-divider';
451
						}
452
					}
453
				}
454
			}
455
			return $linkmod_type;
456
		}
457
458
		/**
459
		 * Update the attributes of a nav item depending on the limkmod classes.
460
		 *
461
		 * @since 4.0.0
462
		 *
463
		 * @param array $atts            array of atts for the current link in nav item.
464
		 * @param array $linkmod_classes an array of classes that modify link or nav item behaviors or displays.
465
		 *
466
		 * @return array                 maybe updated array of attributes for item.
467
		 */
468
		private function update_atts_for_linkmod_type( $atts = array(), $linkmod_classes = array() ) {
469
			if ( ! empty( $linkmod_classes ) ) {
470
				foreach ( $linkmod_classes as $link_class ) {
471
					if ( ! empty( $link_class ) ) {
472
						// update $atts with a space and the extra classname...
473
						// so long as it's not a sr-only class.
474
						if ( 'sr-only' !== $link_class ) {
475
							$atts['class'] .= ' ' . esc_attr( $link_class );
476
						}
477
						// check for special class types we need additional handling for.
478
						if ( 'disabled' === $link_class ) {
479
							// Convert link to '#' and unset open targets.
480
							$atts['href'] = '#';
481
							unset( $atts['target'] );
482
						} elseif ( 'dropdown-header' === $link_class || 'dropdown-divider' === $link_class ) {
483
							// Store a type flag and unset href and target.
484
							unset( $atts['href'] );
485
							unset( $atts['target'] );
486
						}
487
					}
488
				}
489
			}
490
			return $atts;
491
		}
492
493
		/**
494
		 * Wraps the passed text in a screen reader only class.
495
		 *
496
		 * @since 4.0.0
497
		 *
498
		 * @param string $text the string of text to be wrapped in a screen reader class.
499
		 * @return string      the string wrapped in a span with the class.
500
		 */
501
		private function wrap_for_screen_reader( $text = '' ) {
502
			if ( $text ) {
503
				$text = '<span class="sr-only">' . $text . '</span>';
504
			}
505
			return $text;
506
		}
507
508
		/**
509
		 * Returns the correct opening element and attributes for a linkmod.
510
		 *
511
		 * @since 4.0.0
512
		 *
513
		 * @param string $linkmod_type a sting containing a linkmod type flag.
514
		 * @param string $attributes   a string of attributes to add to the element.
515
		 *
516
		 * @return string              a string with the openign tag for the element with attribibutes added.
517
		 */
518
		private function linkmod_element_open( $linkmod_type, $attributes = '' ) {
519
			$output = '';
520
			if ( 'dropdown-header' === $linkmod_type ) {
521
				// For a header use a span with the .h6 class instead of a real
522
				// header tag so that it doesn't confuse screen readers.
523
				$output .= '<span class="dropdown-header h6"' . $attributes . '>';
524
			} elseif ( 'dropdown-divider' === $linkmod_type ) {
525
				// this is a divider.
526
				$output .= '<div class="dropdown-divider"' . $attributes . '>';
527
			}
528
			return $output;
529
		}
530
531
		/**
532
		 * Return the correct closing tag for the linkmod element.
533
		 *
534
		 * @since 4.0.0
535
		 *
536
		 * @param string $linkmod_type a string containing a special linkmod type.
537
		 *
538
		 * @return string              a string with the closing tag for this linkmod type.
539
		 */
540
		private function linkmod_element_close( $linkmod_type ) {
541
			$output = '';
542
			if ( 'dropdown-header' === $linkmod_type ) {
543
				// For a header use a span with the .h6 class instead of a real
544
				// header tag so that it doesn't confuse screen readers.
545
				$output .= '</span>';
546
			} elseif ( 'dropdown-divider' === $linkmod_type ) {
547
				// this is a divider.
548
				$output .= '</div>';
549
			}
550
			return $output;
551
		}
552
	}
553
}
554