Browse Source

Fix inserting at the end of crumbs in BreadCrumbHelper

Inserting after the last element in the crumb list should work as you
could end up in that scenario with dynamic breadcrumbs.

Fixes #16161
Mark Story 4 years ago
parent
commit
61e777e757

+ 5 - 3
src/View/Helper/BreadcrumbsHelper.php

@@ -136,8 +136,10 @@ class BreadcrumbsHelper extends Helper
      * Insert a crumb at a specific index.
      *
      * If the index already exists, the new crumb will be inserted,
-     * and the existing element will be shifted one index greater.
-     * If the index is out of bounds, it will throw an exception.
+     * before the existing element, shifting the existing element one index
+     * greater than before.
+     *
+     * If the index is out of bounds, an exception will be thrown.
      *
      * @param int $index The index to insert at.
      * @param string $title Title of the crumb.
@@ -154,7 +156,7 @@ class BreadcrumbsHelper extends Helper
      */
     public function insertAt(int $index, string $title, $url = null, array $options = [])
     {
-        if (!isset($this->crumbs[$index])) {
+        if (!isset($this->crumbs[$index]) && $index !== count($this->crumbs)) {
             throw new LogicException(sprintf("No crumb could be found at index '%s'", $index));
         }
 

+ 27 - 0
tests/TestCase/View/Helper/BreadcrumbsHelperTest.php

@@ -355,6 +355,33 @@ class BreadcrumbsHelperTest extends TestCase
     }
 
     /**
+     * Test adding crumbs after a specific one
+     */
+    public function testInsertAfterLastItem(): void
+    {
+        $this->breadcrumbs
+            ->add('Home', '/')
+            ->insertAfter('Home', 'Below Home', '/below', ['class' => 'second']);
+
+        $result = $this->breadcrumbs->getCrumbs();
+        $expected = [
+            [
+                'title' => 'Home',
+                'url' => '/',
+                'options' => [],
+            ],
+            [
+                'title' => 'Below Home',
+                'url' => '/below',
+                'options' => [
+                    'class' => 'second',
+                ],
+            ],
+        ];
+        $this->assertEquals($expected, $result);
+    }
+
+    /**
      * Tests the render method
      */
     public function testRender(): void