Skip to content

Commit 268f57c

Browse files
committed
Test the exception message.
Also make it more useful. And add additional test data to fully exercise the code.
1 parent e7a4387 commit 268f57c

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

src/RuleSet/DeclarationBlock.php

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,22 @@ public function setSelectors($selectors, ?CSSList $list = null): void
101101
} else {
102102
// A string of comma-separated selectors requires parsing.
103103
// Parse as if it's the opening part of a rule.
104-
$parserState = new ParserState($selectors . '{', Settings::create());
105-
$selectorsToSet = self::parseSelectors($parserState);
106-
$parserState->consume('{'); // throw exception if this is not next
107-
if (!$parserState->isEnd()) {
108-
throw new UnexpectedTokenException('EOF', $parserState->peek(5));
104+
try {
105+
$parserState = new ParserState($selectors . '{', Settings::create());
106+
$selectorsToSet = self::parseSelectors($parserState);
107+
$parserState->consume('{'); // throw exception if this is not next
108+
if (!$parserState->isEnd()) {
109+
throw new UnexpectedTokenException('EOF', 'more');
110+
}
111+
} catch (UnexpectedTokenException $exception) {
112+
// The exception message from parsing may refer to the faux `{` block start token,
113+
// which would be confusing.
114+
// Rethrow with a more useful message, that also includes the selector(s) string that was passed.
115+
throw new UnexpectedTokenException(
116+
'Selector(s) string is not valid.',
117+
$selectors,
118+
'custom'
119+
);
109120
}
110121
}
111122

tests/Unit/RuleSet/DeclarationBlockTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,16 +333,31 @@ public function setSelectorsSetsTwoCommaSeparatedSelectorsProvidedAsString(
333333
self::assertSame([$firstSelector, $secondSelector], self::getSelectorsAsStrings($subject));
334334
}
335335

336+
/**
337+
* Provides selectors that would be parsed without error in the context of full CSS, but are nonetheless invalid.
338+
*
339+
* @return array<non-empty-string, array{0: non-empty-string}>
340+
*/
341+
public static function provideInvalidStandaloneSelector(): array
342+
{
343+
return [
344+
'rogue `{`' => ['a { b'],
345+
'rogue `}`' => ['a } b'],
346+
];
347+
}
348+
336349
/**
337350
* @test
338351
*
339352
* @param non-empty-string $selector
340353
*
341354
* @dataProvider provideInvalidSelector
355+
* @dataProvider provideInvalidStandaloneSelector
342356
*/
343357
public function setSelectorsThrowsExceptionWithInvalidSelector(string $selector): void
344358
{
345359
$this->expectException(UnexpectedTokenException::class);
360+
$this->expectExceptionMessageMatches('/^Selector\\(s\\) string is not valid. /');
346361

347362
$subject = new DeclarationBlock();
348363

0 commit comments

Comments
 (0)