Skip to content

Commit b67aac0

Browse files
authored
[TASK] Throw exception upon invalid selector (#1498)
... being passed to `Selector` via the constructor or `setSelector()`
1 parent 600d163 commit b67aac0

3 files changed

Lines changed: 48 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ Please also have a look at our
1717

1818
### Changed
1919

20+
- `Selector::setSelector()` and `Selector` constructor will now throw exception
21+
upon provision of an invalid selectior (#1498)
2022
- Clean up extra whitespace in CSS selector (#1398)
2123
- The array keys passed to `DeclarationBlock::setSelectors()` are no longer
2224
preserved (#1407)

src/Property/Selector.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ public static function isValid(string $selector): bool
6969
return $numberOfMatches === 1;
7070
}
7171

72+
/**
73+
* @throws \UnexpectedValueException if the selector is not valid
74+
*/
7275
final public function __construct(string $selector)
7376
{
7477
$this->setSelector($selector);
@@ -152,8 +155,15 @@ public function getSelector(): string
152155
return $this->selector;
153156
}
154157

158+
/**
159+
* @throws \UnexpectedValueException if the selector is not valid
160+
*/
155161
public function setSelector(string $selector): void
156162
{
163+
if (!self::isValid($selector)) {
164+
throw new \UnexpectedValueException("Selector `$selector` is not valid.");
165+
}
166+
157167
$selector = \trim($selector);
158168

159169
$hasAttribute = \strpos($selector, '[') !== false;

tests/Unit/Property/SelectorTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,42 @@ public function parseExtractsTwoCommentsFromSelector(): void
315315
self::assertSame('comment2', $result[1]->getComment());
316316
}
317317

318+
/**
319+
* @test
320+
*/
321+
public function canConstructObjectWithEmptyState(): void
322+
{
323+
$subject = new Selector('');
324+
325+
self::assertSame('', $subject->getSelector());
326+
}
327+
328+
/**
329+
* @test
330+
*
331+
* @dataProvider provideInvalidSelectors
332+
*/
333+
public function constructorThrowsExceptionWithInvalidSelector(string $selector): void
334+
{
335+
$this->expectException(\UnexpectedValueException::class);
336+
337+
new Selector($selector);
338+
}
339+
340+
/**
341+
* @test
342+
*
343+
* @dataProvider provideInvalidSelectors
344+
*/
345+
public function setSelectorThrowsExceptionWithInvalidSelector(string $selector): void
346+
{
347+
$this->expectException(\UnexpectedValueException::class);
348+
349+
$subject = new Selector('a');
350+
351+
$subject->setSelector($selector);
352+
}
353+
318354
/**
319355
* @test
320356
*

0 commit comments

Comments
 (0)