diff --git a/CHANGELOG.md b/CHANGELOG.md index 216525f57..0a06bcef4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ Please also have a look at our ### Changed +- The array keys passed to `DeclarationBlock::setSelectors()` are no longer + preserved (#1407) + ### Deprecated ### Removed diff --git a/src/RuleSet/DeclarationBlock.php b/src/RuleSet/DeclarationBlock.php index 4d0775460..8a0f4e487 100644 --- a/src/RuleSet/DeclarationBlock.php +++ b/src/RuleSet/DeclarationBlock.php @@ -36,7 +36,7 @@ class DeclarationBlock implements CSSElement, CSSListItem, Positionable, RuleCon use Position; /** - * @var array + * @var list */ private $selectors = []; @@ -146,11 +146,13 @@ public static function parse(ParserState $parserState, ?CSSList $list = null): ? public function setSelectors($selectors, ?CSSList $list = null): void { if (\is_array($selectors)) { - $this->selectors = $selectors; + $selectorsToSet = $selectors; } else { - $this->selectors = \explode(',', $selectors); + $selectorsToSet = \explode(',', $selectors); } - foreach ($this->selectors as $key => $selector) { + + // Convert all items to a `Selector` if not already + foreach ($selectorsToSet as $key => $selector) { if (!($selector instanceof Selector)) { if ($list === null || !($list instanceof KeyFrame)) { if (!Selector::isValid($selector)) { @@ -160,7 +162,7 @@ public function setSelectors($selectors, ?CSSList $list = null): void 'custom' ); } - $this->selectors[$key] = new Selector($selector); + $selectorsToSet[$key] = new Selector($selector); } else { if (!KeyframeSelector::isValid($selector)) { throw new UnexpectedTokenException( @@ -169,10 +171,13 @@ public function setSelectors($selectors, ?CSSList $list = null): void 'custom' ); } - $this->selectors[$key] = new KeyframeSelector($selector); + $selectorsToSet[$key] = new KeyframeSelector($selector); } } } + + // Discard the keys and reindex the array + $this->selectors = \array_values($selectorsToSet); } /** @@ -195,7 +200,7 @@ public function removeSelector($selectorToRemove): bool } /** - * @return array + * @return list */ public function getSelectors(): array { diff --git a/tests/Unit/RuleSet/DeclarationBlockTest.php b/tests/Unit/RuleSet/DeclarationBlockTest.php index 4b20e9fc8..5f226846a 100644 --- a/tests/Unit/RuleSet/DeclarationBlockTest.php +++ b/tests/Unit/RuleSet/DeclarationBlockTest.php @@ -278,4 +278,19 @@ public function getRuleSetReturnsObjectWithLineNumberPassedToConstructor(?int $l self::assertSame($lineNumber, $result->getLineNumber()); } + + /** + * @test + * + * Any type of array may be passed to the method, but the resultant property should be a `list`. + */ + public function setSelectorsIgnoresKeys(): void + { + $subject = new DeclarationBlock(); + $subject->setSelectors(['Bob' => 'html', 'Mary' => 'body']); + + $result = $subject->getSelectors(); + + self::assertSame([0, 1], \array_keys($result)); + } }