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 class.
10 //Regexes for specificity calculations
11 const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX
= '/
21 |enabled|disabled|checked|indeterminate
23 |nth-child|nth-last-child|nth-of-type|nth-last-of-type
24 |first-child|last-child|first-of-type|last-of-type
25 |only-child|only-of-type
30 const ELEMENTS_AND_PSEUDO_ELEMENTS_RX
= '/
31 ((^|[\s\+\>\~]+)[\w]+ # elements
33 \:{1,2}( # pseudo-elements
34 after|before|first-letter|first-line|selection
39 private $iSpecificity;
41 public function __construct($sSelector, $bCalculateSpecificity = false) {
42 $this->setSelector($sSelector);
43 if ($bCalculateSpecificity) {
44 $this->getSpecificity();
48 public function getSelector() {
49 return $this->sSelector
;
52 public function setSelector($sSelector) {
53 $this->sSelector
= trim($sSelector);
54 $this->iSpecificity
= null;
57 public function __toString() {
58 return $this->getSelector();
61 public function getSpecificity() {
62 if ($this->iSpecificity
=== null) {
64 /// @todo should exclude \# as well as "#"
66 $b = substr_count($this->sSelector
, '#');
67 $c = preg_match_all(self
::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX
, $this->sSelector
, $aMatches);
68 $d = preg_match_all(self
::ELEMENTS_AND_PSEUDO_ELEMENTS_RX
, $this->sSelector
, $aMatches);
69 $this->iSpecificity
= ($a * 1000) +
($b * 100) +
($c * 10) +
$d;
71 return $this->iSpecificity
;