-
-
Notifications
You must be signed in to change notification settings - Fork 506
/
Menu.php
611 lines (533 loc) · 17.6 KB
/
Menu.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
116
117
118
119
120
121
122
123
124
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
<?php
namespace Timber;
use Timber\Factory\MenuItemFactory;
use WP_Term;
/**
* Class Menu
*
* @api
*/
class Menu extends CoreEntity
{
/**
* The underlying WordPress Core object.
*
* @since 2.0.0
*
* @var \WP_Term|null
*/
protected ?WP_Term $wp_object;
public $object_type = 'term';
/**
* @api
* @var integer The depth of the menu we are rendering
*/
public $depth;
/**
* @api
* @var array|null Array of `Timber\Menu` objects you can to iterate through.
*/
public $items = null;
/**
* @api
* @var int The ID of the menu, corresponding to the wp_terms table.
*/
public $id;
/**
* @api
* @var int The ID of the menu, corresponding to the wp_terms table.
*/
public $ID;
/**
* @api
* @var int The ID of the menu, corresponding to the wp_terms table.
*/
public $term_id;
/**
* @api
* @var string The name of the menu (ex: `Main Navigation`).
*/
public $name;
/**
* @api
* @var string The name of the menu (ex: `Main Navigation`).
*/
public $title;
/**
* Menu args.
*
* @api
* @since 1.9.6
* @var object An object of menu args.
*/
public $args;
/**
* @var MenuItem the current menu item
*/
private $_current_item;
/**
* @api
* @var array The unfiltered args sent forward via the user in the __construct
*/
public $raw_args;
/**
* Theme Location.
*
* @api
* @since 1.9.6
* @var string The theme location of the menu, if available.
*/
public $theme_location = null;
/**
* @internal
* @param \WP_Term $wp_term the vanilla WP term object to build from
* @param array $args Optional. Right now, only the `depth` is
* supported which says how many levels of hierarchy should be
* included in the menu. Default `0`, which is all levels.
* @return \Timber\Menu
*/
public static function build(?WP_Term $menu, $args = []): ?self
{
/**
* Default arguments from wp_nav_menu() function.
*
* @see wp_nav_menu()
*/
$defaults = [
'menu' => '',
'container' => 'div',
'container_class' => '',
'container_id' => '',
'container_aria_label' => '',
'menu_class' => 'menu',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'item_spacing' => 'preserve',
'depth' => 0,
'walker' => '',
'theme_location' => '',
];
$args = wp_parse_args($args, $defaults);
if (!in_array($args['item_spacing'], ['preserve', 'discard'], true)) {
// Invalid value, fall back to default.
$args['item_spacing'] = $defaults['item_spacing'];
}
/**
* @see wp_nav_menu()
*/
$args = apply_filters('wp_nav_menu_args', $args);
$args = (object) $args;
/**
* Since Timber doesn't use HTML here, try to unserialize the maybe cached menu object
*
* @see wp_nav_menu()
*/
$nav_menu = apply_filters('pre_wp_nav_menu', null, $args);
if (null !== $nav_menu) {
try {
$nav_menu = unserialize($nav_menu);
if ($nav_menu instanceof Menu) {
return $nav_menu;
}
} catch (\Throwable $e) {
}
}
/**
* No valid menu term provided.
*
* In earlier versions, Timber returned a pages menu if no menu was found. Now, it returns
* null. If you still need the pages menu, you can use Timber\Timber::get_pages_menu().
*
* @see \Timber\Timber::get_pages_menu()
*/
if (!$menu) {
return null;
}
// Skip the menu term guessing part, we already have our menu term
$menu_items = wp_get_nav_menu_items($menu->term_id, [
'update_post_term_cache' => false,
]);
_wp_menu_item_classes_by_context($menu_items);
$sorted_menu_items = [];
$menu_items_with_children = [];
foreach ((array) $menu_items as $menu_item) {
$sorted_menu_items[$menu_item->menu_order] = $menu_item;
if ($menu_item->menu_item_parent) {
$menu_items_with_children[$menu_item->menu_item_parent] = true;
}
}
// Add the menu-item-has-children class where applicable.
if ($menu_items_with_children) {
foreach ($sorted_menu_items as &$menu_item) {
if (isset($menu_items_with_children[$menu_item->ID])) {
$menu_item->classes[] = 'menu-item-has-children';
}
}
}
unset($menu_items, $menu_item);
/**
* @see wp_nav_menu()
*/
$sorted_menu_items = apply_filters('wp_nav_menu_objects', $sorted_menu_items, $args);
/**
* Filters the sorted list of menu item objects before creating the Menu object.
*
* @since 2.0.0
* @example
* ```
* add_filter( 'timber/menu/item_objects', function ( $items ) {
* return array_map(function ($item) {
* if ( is_object( $item ) && ! ( $item instanceof \WP_Post ) ) {
* return new \WP_Post( get_object_vars( $item ) );
* }
*
* return $item;
* }, $items);
* } );
* ```
*
* @param array<mixed> $item
* @param WP_Term $menu
*/
$sorted_menu_items = apply_filters('timber/menu/item_objects', $sorted_menu_items, $menu);
// Create Menu object
$nav_menu = new static($menu, (array) $args);
$nav_menu->sorted_menu_items = $sorted_menu_items;
// Convert items into MenuItem objects
$sorted_menu_items = $nav_menu->convert_menu_items($sorted_menu_items);
$sorted_menu_items = $nav_menu->order_children($sorted_menu_items);
$sorted_menu_items = $nav_menu->strip_to_depth_limit($sorted_menu_items);
$nav_menu->items = $sorted_menu_items;
unset($sorted_menu_items);
/**
* Since Timber doesn't use HTML, serialize the menu object to provide a cacheable string
*
* @see wp_nav_menu()
*/
$_nav_menu = apply_filters('wp_nav_menu', serialize($nav_menu), $args);
return $nav_menu;
}
/**
* Initialize a menu.
*
* @api
*
* @param int|string $slug A menu slug, the term ID of the menu, the full name from the admin
* menu, the slug of the registered location or nothing. Passing
* nothing is good if you only have one menu. Timber will grab what
* it finds.
* @param array $args Optional. Right now, only the `depth` is
* supported which says how many levels of hierarchy should be
* included in the menu. Default `0`, which is all levels.
*/
protected function __construct(?WP_term $term, array $args)
{
// For future enhancements?
$this->raw_args = $args;
$this->args = (object) $args;
$this->depth = (int) $this->args->depth;
if (!$term) {
return;
}
// Set theme location if available
$locations = array_flip(array_filter(get_nav_menu_locations(), fn ($location) => is_string($location) || is_int($location)));
$this->theme_location = $locations[$term->term_id] ?? null;
if ($this->theme_location) {
$this->args->theme_location = $this->theme_location;
}
$this->import($term);
$this->ID = $this->term_id;
$this->id = $this->term_id;
$this->wp_object = $term;
$this->title = $this->name;
}
/**
* Gets the underlying WordPress Core object.
*
* @since 2.0.0
*
* @return WP_Term|null
*/
public function wp_object(): ?WP_Term
{
return $this->wp_object;
}
/**
* Convert menu items into MenuItem objects
*
* @param array $items
* @return MenuItem[]
*/
protected function convert_menu_items(array $menu_items): array
{
$menu_item_factory = new MenuItemFactory();
return array_map(function ($item) use ($menu_item_factory): MenuItem {
return $menu_item_factory->from($item, $this);
}, $menu_items);
}
/**
* Find a parent menu item in a set of menu items.
*
* @api
* @param array $menu_items An array of menu items.
* @param int $parent_id The parent ID to look for.
* @return \Timber\MenuItem|null A menu item. False if no parent was found.
*/
public function find_parent_item_in_menu(array $menu_items, int $parent_id): ?MenuItem
{
foreach ($menu_items as $item) {
if ($item->ID === $parent_id) {
return $item;
}
}
return null;
}
/**
* @internal
* @param array $items
* @return MenuItem[]
*/
protected function order_children(array $items): array
{
$items_by_id = [];
$menu_items = [];
foreach ($items as $item) {
// Index each item by its ID
$items_by_id[$item->ID] = $item;
}
// Walk through our indexed items and assign them to their parents as applicable
foreach ($items_by_id as $item) {
if (!empty($item->menu_item_parent) && isset($items_by_id[$item->menu_item_parent])) {
// This one is a child item, add it to its parent
$items_by_id[$item->menu_item_parent]->add_child($item);
} else {
// This is a top-level item, add it as such
$menu_items[] = $item;
}
}
return $menu_items;
}
/**
* @internal
* @param array $menu_items
*/
protected function strip_to_depth_limit(array $menu_items, int $current = 1): array
{
$depth = (int) $this->depth; // Confirms still int.
if ($depth <= 0) {
return $menu_items;
}
foreach ($menu_items as &$current_item) {
if ($current === $depth) {
$current_item->remove_class('menu-item-has-children');
$current_item->children = false;
continue;
}
$current_item->children = $this->strip_to_depth_limit($current_item->children, $current + 1);
}
return $menu_items;
}
/**
* Gets a menu meta value.
*
* @api
* @deprecated 2.0.0, use `{{ menu.meta('field_name') }}` instead.
* @see \Timber\Menu::meta()
*
* @param string $field_name The field name for which you want to get the value.
* @return mixed The meta field value.
*/
public function get_field($field_name = null)
{
Helper::deprecated(
"{{ menu.get_field('field_name') }}",
"{{ menu.meta('field_name') }}",
'2.0.0'
);
return $this->meta($field_name);
}
/**
* Get menu items.
*
* Instead of using this function, you can use the `$items` property directly to get the items
* for a menu.
*
* @api
* @example
* ```twig
* {% for item in menu.get_items %}
* <a href="{{ item.link }}">{{ item.title }}</a>
* {% endfor %}
* ```
* @return array Array of `Timber\MenuItem` objects. Empty array if no items could be found.
*/
public function get_items()
{
if (is_array($this->items)) {
return $this->items;
}
return [];
}
/**
* Get the current MenuItem based on the WP context
*
* @see _wp_menu_item_classes_by_context()
* @example
* Say you want to render the sub-tree of the main menu that corresponds
* to the menu item for the current page, such as in a context-aware sidebar:
* ```twig
* <div class="sidebar">
* <a href="{{ menu.current_item.link }}">
* {{ menu.current_item.title }}
* </a>
* <ul>
* {% for child in menu.current_item.children %}
* <li>
* <a href="{{ child.link }}">{{ child.title }}</a>
* </li>
* {% endfor %}
* </ul>
* </div>
* ```
* @param int $depth the maximum depth to traverse the menu tree to find the
* current item. Defaults to null, meaning no maximum. 1-based, meaning the
* top level is 1.
* @return MenuItem the current `Timber\MenuItem` object, i.e. the menu item
* corresponding to the current post.
*/
public function current_item($depth = null)
{
if (false === $this->_current_item) {
// I TOLD YOU BEFORE.
return false;
}
if (empty($this->items)) {
$this->_current_item = false;
return $this->_current_item;
}
if (!isset($this->_current_item)) {
$current = $this->traverse_items_for_current(
$this->items,
$depth
);
if (is_null($depth)) {
$this->_current_item = $current;
} else {
return $current;
}
}
return $this->_current_item;
}
/**
* Alias for current_top_level_item(1).
*
* @return MenuItem the current top-level `Timber\MenuItem` object.
*/
public function current_top_level_item()
{
return $this->current_item(1);
}
/**
* Traverse an array of MenuItems in search of the current item.
*
* @internal
* @param array $items the items to traverse.
*/
private function traverse_items_for_current($items, $depth)
{
$current = false;
$currentDepth = 1;
$i = 0;
while (isset($items[$i])) {
$item = $items[$i];
if ($item->current) {
// cache this item for subsequent calls.
$current = $item;
// stop looking.
break;
} elseif ($item->current_item_ancestor) {
// we found an ancestor,
// but keep looking for a more precise match.
$current = $item;
if ($currentDepth === $depth) {
// we're at max traversal depth.
return $current;
}
// we're in the right subtree, so go deeper.
if ($item->children()) {
// reset the counter, since we're at a new level.
$items = $item->children();
$i = 0;
$currentDepth++;
continue;
}
}
$i++;
}
return $current;
}
public function __toString()
{
static $menu_id_slugs = [];
$args = $this->args;
$items = '';
$nav_menu = '';
$show_container = false;
if ($args->container) {
/**
* Filters the list of HTML tags that are valid for use as menu containers.
*
* @since 3.0.0
*
* @param string[] $tags The acceptable HTML tags for use as menu containers.
* Default is array containing 'div' and 'nav'.
*/
$allowed_tags = apply_filters('wp_nav_menu_container_allowedtags', ['div', 'nav']);
if (is_string($args->container) && in_array($args->container, $allowed_tags, true)) {
$show_container = true;
$class = $args->container_class ? ' class="' . esc_attr($args->container_class) . '"' : ' class="menu-' . $this->slug . '-container"';
$id = $args->container_id ? ' id="' . esc_attr($args->container_id) . '"' : '';
$aria_label = ('nav' === $args->container && $args->container_aria_label) ? ' aria-label="' . esc_attr($args->container_aria_label) . '"' : '';
$nav_menu .= '<' . $args->container . $id . $class . $aria_label . '>';
}
}
$items .= walk_nav_menu_tree($this->sorted_menu_items, $args->depth, $args);
// Attributes.
if (!empty($args->menu_id)) {
$wrap_id = $args->menu_id;
} else {
$wrap_id = 'menu-' . $this->slug;
while (in_array($wrap_id, $menu_id_slugs, true)) {
if (preg_match('#-(\d+)$#', $wrap_id, $matches)) {
$wrap_id = preg_replace('#-(\d+)$#', '-' . ++$matches[1], $wrap_id);
} else {
$wrap_id = $wrap_id . '-1';
}
}
}
$menu_id_slugs[] = $wrap_id;
$wrap_class = $args->menu_class ? $args->menu_class : '';
$nav_menu .= sprintf($args->items_wrap, esc_attr($wrap_id), esc_attr($wrap_class), $items);
if ($show_container) {
$nav_menu .= '</' . $args->container . '>';
}
return $nav_menu;
}
/**
* Checks whether the current user can edit the menu.
*
* @api
* @since 2.0.0
* @return bool
*/
public function can_edit(): bool
{
return current_user_can('edit_theme_options');
}
}