From 53dcf72e1bfdd14944c5261c273a005cc48c5d7a Mon Sep 17 00:00:00 2001 From: Jake Hotson Date: Fri, 6 Feb 2026 01:52:01 +0000 Subject: [PATCH] [TASK] Throw exception upon invalid selector ... being passed to `Selector` via the constructor or `setSelector()` --- CHANGELOG.md | 2 ++ src/Property/Selector.php | 10 ++++++++ tests/Unit/Property/SelectorTest.php | 36 ++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e58bc83..29df562a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ Please also have a look at our ### Changed +- `Selector::setSelector()` and `Selector` constructor will now throw exception + upon provision of an invalid selectior (#1498) - Clean up extra whitespace in CSS selector (#1398) - The array keys passed to `DeclarationBlock::setSelectors()` are no longer preserved (#1407) diff --git a/src/Property/Selector.php b/src/Property/Selector.php index dcecf387..01db122e 100644 --- a/src/Property/Selector.php +++ b/src/Property/Selector.php @@ -69,6 +69,9 @@ public static function isValid(string $selector): bool return $numberOfMatches === 1; } + /** + * @throws \UnexpectedValueException if the selector is not valid + */ final public function __construct(string $selector) { $this->setSelector($selector); @@ -152,8 +155,15 @@ public function getSelector(): string return $this->selector; } + /** + * @throws \UnexpectedValueException if the selector is not valid + */ public function setSelector(string $selector): void { + if (!self::isValid($selector)) { + throw new \UnexpectedValueException("Selector `$selector` is not valid."); + } + $selector = \trim($selector); $hasAttribute = \strpos($selector, '[') !== false; diff --git a/tests/Unit/Property/SelectorTest.php b/tests/Unit/Property/SelectorTest.php index 9aa62031..1e537951 100644 --- a/tests/Unit/Property/SelectorTest.php +++ b/tests/Unit/Property/SelectorTest.php @@ -315,6 +315,42 @@ public function parseExtractsTwoCommentsFromSelector(): void self::assertSame('comment2', $result[1]->getComment()); } + /** + * @test + */ + public function canConstructObjectWithEmptyState(): void + { + $subject = new Selector(''); + + self::assertSame('', $subject->getSelector()); + } + + /** + * @test + * + * @dataProvider provideInvalidSelectors + */ + public function constructorThrowsExceptionWithInvalidSelector(string $selector): void + { + $this->expectException(\UnexpectedValueException::class); + + new Selector($selector); + } + + /** + * @test + * + * @dataProvider provideInvalidSelectors + */ + public function setSelectorThrowsExceptionWithInvalidSelector(string $selector): void + { + $this->expectException(\UnexpectedValueException::class); + + $subject = new Selector('a'); + + $subject->setSelector($selector); + } + /** * @test *