• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

timber / timber / 42269296138

06 Nov 2026 06:17PM UTC coverage: 90.175% (+0.01%) from 90.163%
42269296138

push

travis-ci

nlemoine
test(menu): cover a depth-limited current_item() call made before the unconstrained one

Calling current_item(2) first must not fill the cache: the following current_item() still returns the deepest current item, and a later current_item(2) still returns the depth-limited one.

4754 of 5272 relevant lines covered (90.17%)

68.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.33
/src/Menu.php
1
<?php
2

3
namespace Timber;
4

5
use Stringable;
6
use Throwable;
7
use Timber\Factory\MenuItemFactory;
8
use WP_Term;
9

10
/**
11
 * Class Menu
12
 *
13
 * @phpstan-consistent-constructor
14
 * @api
15
 */
16
class Menu extends CoreEntity implements Stringable
17
{
18
    /**
19
     * The underlying WordPress Core object.
20
     *
21
     * @since 2.0.0
22
     *
23
     * @var WP_Term|null
24
     */
25
    protected ?WP_Term $wp_object;
26

27
    public $object_type = 'term';
28

29
    /**
30
     * @api
31
     * @var integer The depth of the menu we are rendering
32
     */
33
    public $depth;
34

35
    /**
36
     * @api
37
     * @var array|null Array of `Timber\Menu` objects you can to iterate through.
38
     */
39
    public $items = null;
40

41
    /**
42
     * @api
43
     * @var int The ID of the menu, corresponding to the wp_terms table.
44
     */
45
    public $id;
46

47
    /**
48
     * @api
49
     * @var int The ID of the menu, corresponding to the wp_terms table.
50
     */
51
    public $ID;
52

53
    /**
54
     * @api
55
     * @var int The ID of the menu, corresponding to the wp_terms table.
56
     */
57
    public $term_id;
58

59
    /**
60
     * @api
61
     * @var string The name of the menu (ex: `Main Navigation`).
62
     */
63
    public $name;
64

65
    /**
66
     * Menu slug.
67
     *
68
     * @api
69
     * @var string The menu slug.
70
     */
71
    public $slug;
72

73
    /**
74
     * @api
75
     * @var string The name of the menu (ex: `Main Navigation`).
76
     */
77
    public $title;
78

79
    /**
80
     * The term's term_group.
81
     *
82
     * @var int
83
     */
84
    public $term_group;
85

86
    /**
87
     * Term Taxonomy ID.
88
     *
89
     * @var int
90
     */
91
    public $term_taxonomy_id;
92

93
    /**
94
     * The term's taxonomy name.
95
     *
96
     * @var string
97
     */
98
    public $taxonomy;
99

100
    /**
101
     * The term's description.
102
     *
103
     * @var string
104
     */
105
    public $description;
106

107
    /**
108
     * ID of a term's parent term.
109
     *
110
     * @var int
111
     */
112
    public $parent;
113

114
    /**
115
     * Cached object count for this term.
116
     *
117
     * @var int
118
     */
119
    public $count;
120

121
    /**
122
     * Stores the term object's sanitization level.
123
     *
124
     * Does not correspond to a database field.
125
     *
126
     * @var string
127
     */
128
    public $filter;
129

130
    /**
131
     * Menu args.
132
     *
133
     * @api
134
     * @since 1.9.6
135
     * @var object An object of menu args.
136
     */
137
    public $args;
138

139
    /**
140
     * @var MenuItem the current menu item
141
     */
142
    private $_current_item;
143

144
    /**
145
     * @api
146
     * @var array The unfiltered args sent forward via the user in the __construct
147
     */
148
    public $raw_args;
149

150
    /**
151
     * Theme Location.
152
     *
153
     * @api
154
     * @since 1.9.6
155
     * @var string The theme location of the menu, if available.
156
     */
157
    public $theme_location = null;
158

159
    /**
160
     * Sorted menu items.
161
     *
162
     * @var array
163
     */
164
    protected $sorted_menu_items = [];
165

166
    /**
167
     * @internal
168
     * @param WP_Term   $menu The vanilla WordPress term object to build from.
169
     * @param array      $args Optional. Right now, only the `depth` is
170
     *                            supported which says how many levels of hierarchy should be
171
     *                            included in the menu. Default `0`, which is all levels.
172
     * @return Menu
173
     */
174
    public static function build(?WP_Term $menu, $args = []): ?self
67 ✔
175
    {
176
        /**
177
         * Default arguments from wp_nav_menu() function.
178
         *
179
         * @see wp_nav_menu()
180
         */
181
        $defaults = [
67 ✔
182
            'menu' => '',
67 ✔
183
            'container' => 'div',
67 ✔
184
            'container_class' => '',
67 ✔
185
            'container_id' => '',
67 ✔
186
            'container_aria_label' => '',
67 ✔
187
            'menu_class' => 'menu',
67 ✔
188
            'menu_id' => '',
67 ✔
189
            'echo' => true,
67 ✔
190
            'fallback_cb' => 'wp_page_menu',
67 ✔
191
            'before' => '',
67 ✔
192
            'after' => '',
67 ✔
193
            'link_before' => '',
67 ✔
194
            'link_after' => '',
67 ✔
195
            'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
67 ✔
196
            'item_spacing' => 'preserve',
67 ✔
197
            'depth' => 0,
67 ✔
198
            'walker' => '',
67 ✔
199
            'theme_location' => '',
67 ✔
200
        ];
67 ✔
201

202
        $args = \wp_parse_args($args, $defaults);
67 ✔
203

204
        if (!\in_array($args['item_spacing'], ['preserve', 'discard'], true)) {
67 ✔
205
            // Invalid value, fall back to default.
206
            $args['item_spacing'] = $defaults['item_spacing'];
×
207
        }
208

209
        /**
210
         * @see wp_nav_menu()
211
         */
212
        $args = \apply_filters('wp_nav_menu_args', $args);
67 ✔
213
        $args = (object) $args;
67 ✔
214

215
        /**
216
         * Since Timber doesn't use HTML here, try to unserialize the maybe cached menu object
217
         *
218
         * @see wp_nav_menu()
219
         */
220
        $nav_menu = \apply_filters('pre_wp_nav_menu', null, $args);
67 ✔
221
        if (null !== $nav_menu) {
67 ✔
222
            try {
223
                $nav_menu = \unserialize($nav_menu);
1 ✔
224
                if ($nav_menu instanceof Menu) {
1 ✔
225
                    return $nav_menu;
1 ✔
226
                }
227
            } catch (Throwable) {
×
228
            }
229
        }
230

231
        /**
232
         * No valid menu term provided.
233
         *
234
         * In earlier versions, Timber returned a pages menu if no menu was found. Now, it returns
235
         * null. If you still need the pages menu, you can use Timber\Timber::get_pages_menu().
236
         *
237
         * @see Timber::get_pages_menu()
238
         */
239
        if (!$menu) {
67 ✔
240
            return null;
×
241
        }
242

243
        // Skip the menu term guessing part, we already have our menu term
244

245
        $menu_items = \wp_get_nav_menu_items($menu->term_id, [
67 ✔
246
            'update_post_term_cache' => false,
67 ✔
247
        ]);
67 ✔
248

249
        \_wp_menu_item_classes_by_context($menu_items);
67 ✔
250

251
        $sorted_menu_items = [];
67 ✔
252
        $menu_items_with_children = [];
67 ✔
253
        foreach ((array) $menu_items as $menu_item) {
67 ✔
254
            $sorted_menu_items[$menu_item->menu_order] = $menu_item;
58 ✔
255
            if ($menu_item->menu_item_parent) {
58 ✔
256
                $menu_items_with_children[$menu_item->menu_item_parent] = true;
41 ✔
257
            }
258
        }
259

260
        // Add the menu-item-has-children class where applicable.
261
        if ($menu_items_with_children) {
67 ✔
262
            foreach ($sorted_menu_items as &$menu_item) {
41 ✔
263
                if (isset($menu_items_with_children[$menu_item->ID])) {
41 ✔
264
                    $menu_item->classes[] = 'menu-item-has-children';
41 ✔
265
                }
266
            }
267
        }
268

269
        unset($menu_items, $menu_item);
67 ✔
270

271
        /**
272
         * @see wp_nav_menu()
273
         */
274
        $sorted_menu_items = \apply_filters('wp_nav_menu_objects', $sorted_menu_items, $args);
67 ✔
275

276
        /**
277
         * Filters the sorted list of menu item objects before creating the Menu object.
278
         *
279
         * @since 2.0.0
280
         * @example
281
         * ```
282
         * add_filter( 'timber/menu/item_objects', function ( $items ) {
283
         *     return array_map(function ($item) {
284
         *         if ( is_object( $item ) && ! ( $item instanceof \WP_Post ) ) {
285
         *             return new \WP_Post( get_object_vars( $item ) );
286
         *         }
287
         *
288
         *         return $item;
289
         *     }, $items);
290
         * } );
291
         * ```
292
         *
293
         * @param array<mixed> $item
294
         * @param WP_Term $menu
295
         */
296
        $sorted_menu_items = \apply_filters('timber/menu/item_objects', $sorted_menu_items, $menu);
67 ✔
297

298
        // Create Menu object
299
        $nav_menu = new static($menu, (array) $args);
67 ✔
300
        $nav_menu->sorted_menu_items = $sorted_menu_items;
67 ✔
301

302
        // Convert items into MenuItem objects
303
        $sorted_menu_items = $nav_menu->convert_menu_items($sorted_menu_items);
67 ✔
304
        $sorted_menu_items = $nav_menu->order_children($sorted_menu_items);
67 ✔
305
        $sorted_menu_items = $nav_menu->strip_to_depth_limit($sorted_menu_items);
67 ✔
306

307
        $nav_menu->items = $sorted_menu_items;
67 ✔
308
        unset($sorted_menu_items);
67 ✔
309

310
        /**
311
         * Since Timber doesn't use HTML, serialize the menu object to provide a cacheable string
312
         *
313
         * @see wp_nav_menu()
314
         */
315
        $_nav_menu = \apply_filters('wp_nav_menu', \serialize($nav_menu), $args);
67 ✔
316

317
        return $nav_menu;
67 ✔
318
    }
319

320
    /**
321
     * Initialize a menu.
322
     *
323
     * @api
324
     *
325
     * @param WP_Term|null $term A menu slug, the term ID of the menu, the full name from the admin
326
     *                            menu, the slug of the registered location or nothing. Passing
327
     *                            nothing is good if you only have one menu. Timber will grab what
328
     *                            it finds.
329
     * @param array $args         Optional. Right now, only the `depth` is supported which says how
330
     *                            many levels of hierarchy should be included in the menu. Default
331
     *                            `0`, which is all levels.
332
     */
333
    protected function __construct(?WP_Term $term, array $args = [])
75 ✔
334
    {
335
        // For future enhancements?
336
        $this->raw_args = $args;
75 ✔
337
        $this->args = (object) $args;
75 ✔
338

339
        if (isset($this->args->depth)) {
75 ✔
340
            $this->depth = (int) $this->args->depth;
75 ✔
341
        }
342

343
        if (!$term) {
75 ✔
344
            return;
10 ✔
345
        }
346

347
        // Set theme location if available
348
        $this->theme_location = Timber::get_menu_location($term);
67 ✔
349
        if ($this->theme_location) {
67 ✔
350
            $this->args->theme_location = $this->theme_location;
9 ✔
351
        }
352

353
        $this->import($term);
67 ✔
354
        $this->ID = $this->term_id;
67 ✔
355
        $this->id = $this->term_id;
67 ✔
356
        $this->wp_object = $term;
67 ✔
357
        $this->title = $this->name;
67 ✔
358
    }
359

360
    /**
361
     * Gets the underlying WordPress Core object.
362
     *
363
     * @since 2.0.0
364
     *
365
     * @return WP_Term|null
366
     */
367
    public function wp_object(): ?WP_Term
1 ✔
368
    {
369
        return $this->wp_object;
1 ✔
370
    }
371

372
    /**
373
     * Convert menu items into MenuItem objects
374
     *
375
     * @return MenuItem[]
376
     */
377
    protected function convert_menu_items(array $menu_items): array
73 ✔
378
    {
379
        $menu_item_factory = new MenuItemFactory();
73 ✔
380
        return \array_map(fn ($item): MenuItem => $menu_item_factory->from($item, $this), $menu_items);
73 ✔
381
    }
382

383
    /**
384
     * Find a parent menu item in a set of menu items.
385
     *
386
     * @api
387
     * @param array $menu_items An array of menu items.
388
     * @param int   $parent_id  The parent ID to look for.
389
     * @return MenuItem|null A menu item. False if no parent was found.
390
     */
391
    public function find_parent_item_in_menu(array $menu_items, int $parent_id): ?MenuItem
×
392
    {
393
        foreach ($menu_items as $item) {
×
394
            if ($item->ID === $parent_id) {
×
395
                return $item;
×
396
            }
397
        }
398
        return null;
×
399
    }
400

401
    /**
402
     * @internal
403
     * @return MenuItem[]
404
     */
405
    protected function order_children(array $items): array
73 ✔
406
    {
407
        $items_by_id = [];
73 ✔
408
        $menu_items = [];
73 ✔
409

410
        foreach ($items as $item) {
73 ✔
411
            // Index each item by its ID
412
            $items_by_id[$item->ID] = $item;
64 ✔
413
        }
414

415
        // Walk through our indexed items and assign them to their parents as applicable
416
        foreach ($items_by_id as $item) {
73 ✔
417
            if (!empty($item->menu_item_parent) && isset($items_by_id[$item->menu_item_parent])) {
64 ✔
418
                // This one is a child item, add it to its parent
419
                $items_by_id[$item->menu_item_parent]->add_child($item);
43 ✔
420
            } else {
421
                // This is a top-level item, add it as such
422
                $menu_items[] = $item;
64 ✔
423
            }
424
        }
425
        return $menu_items;
73 ✔
426
    }
427

428
    /**
429
     * @internal
430
     */
431
    protected function strip_to_depth_limit(array $menu_items, int $current = 1): array
73 ✔
432
    {
433
        $depth = (int) $this->depth; // Confirms still int.
73 ✔
434
        if ($depth <= 0) {
73 ✔
435
            return $menu_items;
70 ✔
436
        }
437

438
        foreach ($menu_items as &$current_item) {
6 ✔
439
            if ($current === $depth) {
6 ✔
440
                $current_item->remove_class('menu-item-has-children');
6 ✔
441
                $current_item->children = false;
6 ✔
442
                continue;
6 ✔
443
            }
444

445
            $current_item->children = $this->strip_to_depth_limit($current_item->children, $current + 1);
2 ✔
446
        }
447

448
        return $menu_items;
6 ✔
449
    }
450

451
    /**
452
     * Gets a menu meta value.
453
     *
454
     * @api
455
     * @deprecated 2.0.0, use `{{ menu.meta('field_name') }}` instead.
456
     * @see Menu::meta()
457
     *
458
     * @param string $field_name The field name for which you want to get the value.
459
     * @return mixed The meta field value.
460
     */
461
    public function get_field($field_name = null)
×
462
    {
463
        Helper::deprecated(
×
464
            "{{ menu.get_field('field_name') }}",
×
465
            "{{ menu.meta('field_name') }}",
×
466
            '2.0.0'
×
467
        );
×
468

469
        return $this->meta($field_name);
×
470
    }
471

472
    /**
473
     * Get menu items.
474
     *
475
     * Instead of using this function, you can use the `$items` property directly to get the items
476
     * for a menu.
477
     *
478
     * @api
479
     * @example
480
     * ```twig
481
     * {% for item in menu.get_items %}
482
     *     <a href="{{ item.link }}">{{ item.title }}</a>
483
     * {% endfor %}
484
     * ```
485
     * @return array Array of `Timber\MenuItem` objects. Empty array if no items could be found.
486
     */
487
    public function get_items()
24 ✔
488
    {
489
        if (\is_array($this->items)) {
24 ✔
490
            return $this->items;
24 ✔
491
        }
492

493
        return [];
×
494
    }
495

496
    /**
497
     * Get the current MenuItem based on the WP context
498
     *
499
     * @see _wp_menu_item_classes_by_context()
500
     * @example
501
     * Say you want to render the sub-tree of the main menu that corresponds
502
     * to the menu item for the current page, such as in a context-aware sidebar:
503
     * ```twig
504
     * <div class="sidebar">
505
     *   <a href="{{ menu.current_item.link }}">
506
     *     {{ menu.current_item.title }}
507
     *   </a>
508
     *   <ul>
509
     *     {% for child in menu.current_item.children %}
510
     *       <li>
511
     *         <a href="{{ child.link }}">{{ child.title }}</a>
512
     *       </li>
513
     *     {% endfor %}
514
     *   </ul>
515
     * </div>
516
     * ```
517
     * @param int $depth the maximum depth to traverse the menu tree to find the
518
     * current item. Defaults to null, meaning no maximum. 1-based, meaning the
519
     * top level is 1.
520
     * @return MenuItem the current `Timber\MenuItem` object, i.e. the menu item
521
     * corresponding to the current post.
522
     */
523
    public function current_item($depth = null)
11 ✔
524
    {
525
        if (false === $this->_current_item) {
11 ✔
526
            // I TOLD YOU BEFORE.
527
            return false;
1 ✔
528
        }
529

530
        if (empty($this->items)) {
11 ✔
531
            $this->_current_item = false;
1 ✔
532
            return $this->_current_item;
1 ✔
533
        }
534

535
        if (null !== $depth) {
10 ✔
536
            return $this->traverse_items_for_current($this->items, $depth);
5 ✔
537
        }
538

539
        if (!isset($this->_current_item)) {
8 ✔
540
            $this->_current_item = $this->traverse_items_for_current($this->items, null);
8 ✔
541
        }
542

543
        return $this->_current_item;
8 ✔
544
    }
545

546
    /**
547
     * Alias for current_top_level_item(1).
548
     *
549
     * @return MenuItem the current top-level `Timber\MenuItem` object.
550
     */
551
    public function current_top_level_item()
3 ✔
552
    {
553
        return $this->current_item(1);
3 ✔
554
    }
555

556
    /**
557
     * Traverse an array of MenuItems in search of the current item.
558
     *
559
     * @internal
560
     * @param array $items the items to traverse.
561
     */
562
    private function traverse_items_for_current($items, $depth)
10 ✔
563
    {
564
        $current = false;
10 ✔
565
        $currentDepth = 1;
10 ✔
566
        $i = 0;
10 ✔
567

568
        while (isset($items[$i])) {
10 ✔
569
            $item = $items[$i];
10 ✔
570

571
            if ($item->current) {
10 ✔
572
                // cache this item for subsequent calls.
573
                $current = $item;
5 ✔
574
                // stop looking.
575
                break;
5 ✔
576
            } elseif ($item->current_item_ancestor) {
10 ✔
577
                // we found an ancestor,
578
                // but keep looking for a more precise match.
579
                $current = $item;
8 ✔
580

581
                if ($currentDepth === $depth) {
8 ✔
582
                    // we're at max traversal depth.
583
                    return $current;
5 ✔
584
                }
585

586
                // we're in the right subtree, so go deeper.
587
                if ($item->children()) {
7 ✔
588
                    // reset the counter, since we're at a new level.
589
                    $items = $item->children();
5 ✔
590
                    $i = 0;
5 ✔
591
                    $currentDepth++;
5 ✔
592
                    continue;
5 ✔
593
                }
594
            }
595

596
            $i++;
7 ✔
597
        }
598

599
        return $current;
8 ✔
600
    }
601

602
    public function __toString()
1 ✔
603
    {
604
        static $menu_id_slugs = [];
1 ✔
605

606
        $args = $this->args;
1 ✔
607

608
        $items = '';
1 ✔
609
        $nav_menu = '';
1 ✔
610
        $show_container = false;
1 ✔
611

612
        if ($args->container) {
1 ✔
613
            /**
614
             * Filters the list of HTML tags that are valid for use as menu containers.
615
             *
616
             * @since 3.0.0
617
             *
618
             * @param string[] $tags The acceptable HTML tags for use as menu containers.
619
             *                       Default is array containing 'div' and 'nav'.
620
             */
621
            $allowed_tags = \apply_filters('wp_nav_menu_container_allowedtags', ['div', 'nav']);
1 ✔
622

623
            if (\is_string($args->container) && \in_array($args->container, $allowed_tags, true)) {
1 ✔
624
                $show_container = true;
1 ✔
625
                $class = $args->container_class ? ' class="' . \esc_attr($args->container_class) . '"' : ' class="menu-' . $this->slug . '-container"';
1 ✔
626
                $id = $args->container_id ? ' id="' . \esc_attr($args->container_id) . '"' : '';
1 ✔
627
                $aria_label = ('nav' === $args->container && $args->container_aria_label) ? ' aria-label="' . \esc_attr($args->container_aria_label) . '"' : '';
1 ✔
628
                $nav_menu .= '<' . $args->container . $id . $class . $aria_label . '>';
1 ✔
629
            }
630
        }
631

632
        $items .= \walk_nav_menu_tree($this->sorted_menu_items, $args->depth, $args);
1 ✔
633

634
        // Attributes.
635
        if (!empty($args->menu_id)) {
1 ✔
636
            $wrap_id = $args->menu_id;
1 ✔
637
        } else {
638
            $wrap_id = 'menu-' . $this->slug;
×
639

640
            while (\in_array($wrap_id, $menu_id_slugs, true)) {
×
641
                if (\preg_match('#-(\d+)$#', (string) $wrap_id, $matches)) {
×
642
                    $wrap_id = \preg_replace('#-(\d+)$#', '-' . ++$matches[1], (string) $wrap_id);
×
643
                } else {
644
                    $wrap_id = $wrap_id . '-1';
×
645
                }
646
            }
647
        }
648
        $menu_id_slugs[] = $wrap_id;
1 ✔
649

650
        $wrap_class = $args->menu_class ?: '';
1 ✔
651

652
        $nav_menu .= \sprintf($args->items_wrap, \esc_attr($wrap_id), \esc_attr($wrap_class), $items);
1 ✔
653
        if ($show_container) {
1 ✔
654
            $nav_menu .= '</' . $args->container . '>';
1 ✔
655
        }
656

657
        return $nav_menu;
1 ✔
658
    }
659

660
    /**
661
     * Checks whether the current user can edit the menu.
662
     *
663
     * @api
664
     * @since 2.0.0
665
     * @return bool
666
     */
667
    public function can_edit(): bool
1 ✔
668
    {
669
        return \current_user_can('edit_theme_options');
1 ✔
670
    }
671
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc