Skip to content

Selector validation #162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jul 13, 2019
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions lib/Sabberworm/CSS/CSSList/CSSList.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,18 @@ private static function parseListItem(ParserState $oParserState, CSSList $oList)
}
return $oAtRule;
} else if ($oParserState->comes('}')) {
$oParserState->consume('}');
if ($bIsRoot) {
if ($oParserState->getSettings()->bLenientParsing) {
while ($oParserState->comes('}')) $oParserState->consume('}');
return DeclarationBlock::parse($oParserState);
if (!$oParserState->getSettings()->bLenientParsing) {
throw new UnexpectedTokenException('CSS selector', '}', 'identifier', $oParserState->currentLine());
} else {
if ($bIsRoot) {
if ($oParserState->getSettings()->bLenientParsing) {
return DeclarationBlock::parse($oParserState);
} else {
throw new SourceException("Unopened {", $oParserState->currentLine());
}
} else {
throw new SourceException("Unopened {", $oParserState->currentLine());
return null;
}
} else {
return null;
}
} else {
return DeclarationBlock::parse($oParserState);
Expand Down Expand Up @@ -123,6 +125,9 @@ private static function parseAtRule(ParserState $oParserState) {
$oResult->setVendorKeyFrame($sIdentifier);
$oResult->setAnimationName(trim($oParserState->consumeUntil('{', false, true)));
CSSList::parseList($oParserState, $oResult);
if ($oParserState->comes('}')) {
$oParserState->consume('}');
}
return $oResult;
} else if ($sIdentifier === 'namespace') {
$sPrefix = null;
Expand Down Expand Up @@ -162,6 +167,9 @@ private static function parseAtRule(ParserState $oParserState) {
} else {
$oAtRule = new AtRuleBlockList($sIdentifier, $sArgs, $iIdentifierLineNum);
CSSList::parseList($oParserState, $oAtRule);
if ($oParserState->comes('}')) {
$oParserState->consume('}');
}
}
return $oAtRule;
}
Expand Down
13 changes: 13 additions & 0 deletions lib/Sabberworm/CSS/Property/Selector.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Sabberworm\CSS\Property;

use Sabberworm\CSS\Parsing\UnexpectedTokenException;

/**
* Class representing a single CSS selector. Selectors have to be split by the comma prior to being passed into this class.
*/
Expand Down Expand Up @@ -35,10 +37,21 @@ class Selector {
))
/ix';

const SELECTOR_VALIDATION_RX = '/
^((?:[a-zA-Z0-9\x{00A0}-\x{FFFF}_\^\$\|\*\=\"\'\~\[\]\(\)\-\s\.:#\+\>]*(?:\\\\.)?(?:\'.*?\')?(?:\".*?\")?)*|\s*?[\+-]?\d+\%\s*)$
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This regex is too complicated to understand. If it can’t be simplified, maybe a regex isn’t the right tool for the job. But since the end goal for selectors still is a complete parser (which will make the regex obsolete), I’ll allow it for now. But maybe you could split the regex to multiple lines using concatenation and comment each line so we better understand what it does.

Also, some of the escapes are unnecessary. Inside character classes [], you only need to escape ] and - (in some cases) (and maybe [ to be symmetrical), but ^, $, |, *, =, ", ~, +, (, ) can be left literal (' was already literal since \' is a string escape, not a regex escape).

/ux';

private $sSelector;
private $iSpecificity;

public static function isValid($sSelector) {
return preg_match(self::SELECTOR_VALIDATION_RX, $sSelector);
}

public function __construct($sSelector, $bCalculateSpecificity = false) {
if (!Selector::isValid($sSelector)) {
throw new UnexpectedTokenException("Selector did not match '" . self::SELECTOR_VALIDATION_RX . "'.", $sSelector, "custom");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m not sure it is the job of the Selector class to validate its input. I think it’s the job of the selector parsing logic (i.e. DeclarationBlock::parse) to do that.

}
$this->setSelector($sSelector);
if ($bCalculateSpecificity) {
$this->getSpecificity();
Expand Down
29 changes: 28 additions & 1 deletion lib/Sabberworm/CSS/RuleSet/DeclarationBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Sabberworm\CSS\Parsing\ParserState;
use Sabberworm\CSS\Parsing\OutputException;
use Sabberworm\CSS\Parsing\UnexpectedTokenException;
use Sabberworm\CSS\Property\Selector;
use Sabberworm\CSS\Rule\Rule;
use Sabberworm\CSS\Value\RuleValueList;
Expand All @@ -28,7 +29,33 @@ public function __construct($iLineNo = 0) {
public static function parse(ParserState $oParserState) {
$aComments = array();
$oResult = new DeclarationBlock($oParserState->currentLine());
$oResult->setSelector($oParserState->consumeUntil('{', false, true, $aComments));
try {
$aSelectorParts = array();
$sStringWrapperChar = false;
do {
$aSelectorParts[] = $oParserState->consume(1) . $oParserState->consumeUntil(array('{', '}', '\'', '"'), false, false, $aComments);
if ( in_array($oParserState->peek(), array('\'', '"')) && substr(end($aSelectorParts), -1) != "\\" ) {
if ( $sStringWrapperChar === false ) {
$sStringWrapperChar = $oParserState->peek();
} else if ($sStringWrapperChar == $oParserState->peek()) {
$sStringWrapperChar = false;
}
}
} while (!in_array($oParserState->peek(), array('{', '}')) || $sStringWrapperChar !== false);
$oResult->setSelector(implode('', $aSelectorParts));
if ($oParserState->comes('{')) {
$oParserState->consume(1);
}
} catch (UnexpectedTokenException $e) {
if($oParserState->getSettings()->bLenientParsing) {
if(!$oParserState->comes('}')) {
$oParserState->consumeUntil('}', false, true);
}
return false;
} else {
throw $e;
}
}
$oResult->setComments($aComments);
RuleSet::parseRuleSet($oParserState, $oResult);
return $oResult;
Expand Down
43 changes: 42 additions & 1 deletion tests/Sabberworm/CSS/ParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,47 @@ function testUnmatchedBracesInFile() {
$this->assertSame($sExpected, $oDoc->render());
}

function testInvalidSelectorsInFile() {
$oDoc = $this->parsedStructureForFile('invalid-selectors', Settings::create()->withMultibyteSupport(true));
$sExpected = '@keyframes mymove {from {top: 0px;}}
#test {color: white;background: green;}
#test {display: block;background: white;color: black;}';
$this->assertSame($sExpected, $oDoc->render());

$oDoc = $this->parsedStructureForFile('invalid-selectors-2', Settings::create()->withMultibyteSupport(true));
$sExpected = '@media only screen and (max-width: 1215px) {.breadcrumb {padding-left: 10px;}
.super-menu > li:first-of-type {border-left-width: 0;}
.super-menu > li:last-of-type {border-right-width: 0;}
html[dir="rtl"] .super-menu > li:first-of-type {border-left-width: 1px;border-right-width: 0;}
html[dir="rtl"] .super-menu > li:last-of-type {border-left-width: 0;}}
body {background-color: red;}';
$this->assertSame($sExpected, $oDoc->render());
}

function testSelectorEscapesInFile() {
$oDoc = $this->parsedStructureForFile('selector-escapes', Settings::create()->withMultibyteSupport(true));
$sExpected = '#\# {color: red;}
.col-sm-1\/5 {width: 20%;}';
$this->assertSame($sExpected, $oDoc->render());

$oDoc = $this->parsedStructureForFile('invalid-selectors-2', Settings::create()->withMultibyteSupport(true));
$sExpected = '@media only screen and (max-width: 1215px) {.breadcrumb {padding-left: 10px;}
.super-menu > li:first-of-type {border-left-width: 0;}
.super-menu > li:last-of-type {border-right-width: 0;}
html[dir="rtl"] .super-menu > li:first-of-type {border-left-width: 1px;border-right-width: 0;}
html[dir="rtl"] .super-menu > li:last-of-type {border-left-width: 0;}}
body {background-color: red;}';
$this->assertSame($sExpected, $oDoc->render());
}

function testSelectorIgnoresInFile() {
$oDoc = $this->parsedStructureForFile('selector-ignores', Settings::create()->withMultibyteSupport(true));
$sExpected = '.some[selectors-may=\'contain-a-{\'] {}
.this-selector .valid {width: 100px;}
@media only screen and (min-width: 200px) {.test {prop: val;}}';
$this->assertSame($sExpected, $oDoc->render());
}

/**
* @expectedException Sabberworm\CSS\Parsing\UnexpectedTokenException
*/
Expand Down Expand Up @@ -501,7 +542,7 @@ function testCharsetFailure2() {
* @expectedException \Sabberworm\CSS\Parsing\SourceException
*/
function testUnopenedClosingBracketFailure() {
$this->parsedStructureForFile('unopened-close-brackets', Settings::create()->withLenientParsing(false));
$this->parsedStructureForFile('-unopened-close-brackets', Settings::create()->withLenientParsing(false));
}

/**
Expand Down
33 changes: 33 additions & 0 deletions tests/files/invalid-selectors-2.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
@media only screen and (max-width: 1215px) {
.breadcrumb{
padding-left:10px;
}
.super-menu > li:first-of-type{
border-left-width:0;
}
.super-menu > li:last-of-type{
border-right-width:0;
}
html[dir="rtl"] .super-menu > li:first-of-type{
border-left-width:1px;
border-right-width:0;
}
html[dir="rtl"] .super-menu > li:last-of-type{
border-left-width:0;
}
html[dir="rtl"] .super-menu.menu-floated > li:first-of-type
border-right-width:0;
}
}


.super-menu.menu-floated{
border-right-width:1px;
border-left-width:1px;
border-color:rgb(90, 66, 66);
border-style:dotted;
}

body {
background-color: red;
}
24 changes: 24 additions & 0 deletions tests/files/invalid-selectors.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@keyframes mymove {
from { top: 0px; }
}

#test {
color: white;
background: green;
}

body
background: black;
}

#test {
display: block;
background: red;
color: white;
}
#test {
display: block;
background: white;
color: black;
}

7 changes: 7 additions & 0 deletions tests/files/selector-escapes.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#\# {
color: red;
}

.col-sm-1\/5 {
width: 20%;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
.some[selectors-may='contain-a-{'] {


}

.this-selector /* should remain-} */ .valid {
width:100px;
}

@media only screen and (min-width: 200px) {
.test {
prop: val;
}
}
}