Skip to content

Commit e017680

Browse files
committed
feat: added forEach method for NodeLists
1 parent 3460135 commit e017680

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

docs/phpmd.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ layout: home
1313
## Design
1414

1515

16-
Fri Nov 28 18:29:15 CET 2025
16+
Fri Nov 28 18:57:10 CET 2025

src/Delegator/NodeListDelegator.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Html\Delegator;
46

57
use AllowDynamicProperties;
@@ -144,4 +146,15 @@ final public function count(): int
144146
{
145147
return $this->delegated->length;
146148
}
149+
150+
/**
151+
* Applies callback to each item in the node list.
152+
* @param callable $callback function($element, $index, $list)
153+
*/
154+
public function forEach(callable $callback): void
155+
{
156+
foreach ($this as $i => $item) {
157+
$callback($item, $i, $this);
158+
}
159+
}
147160
}

tests/Delegator/NodeListDelegatorTest.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@
3939
$element = $document->createElement('div', 'example content');
4040
$document->appendChild($element);
4141
$item = $delegator->item(0);
42-
expect($item instanceof NodeDelegator || strpos(get_class($item), 'Html\\Element\\') === 0)->toBeTrue();
42+
expect($item instanceof NodeDelegator || strpos(get_class($item), 'Html\\Element\\') === 0)
43+
->toBeTrue();
4344
});
4445

4546
test('item count', function () {
@@ -76,3 +77,21 @@
7677
expect(iterator_to_array($delegator->getIterator()))
7778
->toHaveCount(0);
7879
});
80+
81+
test('forEach applies callback to all elements', function () {
82+
$document = HTMLDocumentDelegator::createEmpty();
83+
$a1 = $document->createElement('a');
84+
$a2 = $document->createElement('a');
85+
$document->appendChild($a1);
86+
$document->appendChild($a2);
87+
$list = new NodeListDelegator($document->documentElement->getElementsByTagName('a'));
88+
$list->forEach(function ($element, $i) {
89+
$element->setAttribute('data-tracking-id', 'id-' . $i);
90+
});
91+
$ids = [];
92+
foreach ($list as $i => $el) {
93+
$ids[] = $el->getAttribute('data-tracking-id');
94+
}
95+
expect($ids)
96+
->toBe(['id-0', 'id-1']);
97+
});

0 commit comments

Comments
 (0)