Skip to content

Commit 8d4985a

Browse files
committed
add possibility to remove items from collections
1 parent c4b2f94 commit 8d4985a

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Collection.php

+25
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,31 @@ public function getItem($id)
183183
return array_key_exists($id, $this->ids) ? $this->ids[$id] : null;
184184
}
185185

186+
/**
187+
* Remove an item from the collection.
188+
*
189+
* @param string $id
190+
*
191+
* @return boolean
192+
*/
193+
public function removeItem($id)
194+
{
195+
if (!array_key_exists($id, $this->ids)) {
196+
return false;
197+
}
198+
199+
$item = $this->ids[$id];
200+
unset($this->ids[$id]);
201+
202+
foreach ($this->items as $k1 => $v1) {
203+
foreach ($v1 as $k2 => $v2) {
204+
if ($item === $v2) {
205+
unset($this->items[$k1][$k2]);
206+
}
207+
}
208+
}
209+
}
210+
186211
/**
187212
* Determine whether the menu collection is currently empty or not.
188213
*

tests/MenuCollectionTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,19 @@ public function testAddWithPriorities()
5050
$this->assertTrue(strpos($str, 'First Item') > strpos($str, 'Second Item'),
5151
'Second Item should come before First Item.'.PHP_EOL.$str);
5252
}
53+
54+
public function testCanRemoveItem()
55+
{
56+
$coll = $this->makeCollection();
57+
$coll->addItem('First Item', '/foo', [], 20);
58+
$coll->addItem('Second Item', '/foo', [], 10);
59+
$coll->removeItem('first-item');
60+
61+
$this->assertNull($coll->getItem('first-item'));
62+
$this->assertNotNull($coll->getItem('second-item'));
63+
64+
$str = $coll->render();
65+
$this->assertSame(false, strpos($str, 'First Item'));
66+
$this->assertNotSame(false, strpos($str, 'Second Item'));
67+
}
5368
}

0 commit comments

Comments
 (0)