3 namespace Sabberworm\CSS\Property
;
6 * Class representing a single CSS selector. Selectors have to be split by the comma prior to being passed into this
12 * regexp for specificity calculations
16 const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX
= '/
26 |enabled|disabled|checked|indeterminate
28 |nth-child|nth-last-child|nth-of-type|nth-last-of-type
29 |first-child|last-child|first-of-type|last-of-type
30 |only-child|only-of-type
36 * regexp for specificity calculations
40 const ELEMENTS_AND_PSEUDO_ELEMENTS_RX
= '/
41 ((^|[\s\+\>\~]+)[\w]+ # elements
43 \:{1,2}( # pseudo-elements
44 after|before|first-letter|first-line|selection
49 * regexp for specificity calculations
53 const SELECTOR_VALIDATION_RX
= '/
56 [a-zA-Z0-9\x{00A0}-\x{FFFF}_^$|*="\'~\[\]()\-\s\.:#+>]* # any sequence of valid unescaped characters
57 (?:\\\\.)? # a single escaped character
58 (?:([\'"]).*?(?<!\\\\)\2)? # a quoted text like [id="example"]
71 private $iSpecificity;
74 * @param string $sSelector
78 public static function isValid($sSelector)
80 return preg_match(static::SELECTOR_VALIDATION_RX
, $sSelector);
84 * @param string $sSelector
85 * @param bool $bCalculateSpecificity
87 public function __construct($sSelector, $bCalculateSpecificity = false)
89 $this->setSelector($sSelector);
90 if ($bCalculateSpecificity) {
91 $this->getSpecificity();
98 public function getSelector()
100 return $this->sSelector
;
104 * @param string $sSelector
108 public function setSelector($sSelector)
110 $this->sSelector
= trim($sSelector);
111 $this->iSpecificity
= null;
117 public function __toString()
119 return $this->getSelector();
125 public function getSpecificity()
127 if ($this->iSpecificity
=== null) {
129 /// @todo should exclude \# as well as "#"
131 $b = substr_count($this->sSelector
, '#');
132 $c = preg_match_all(self
::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX
, $this->sSelector
, $aMatches);
133 $d = preg_match_all(self
::ELEMENTS_AND_PSEUDO_ELEMENTS_RX
, $this->sSelector
, $aMatches);
134 $this->iSpecificity
= ($a * 1000) +
($b * 100) +
($c * 10) +
$d;
136 return $this->iSpecificity
;