AtRule.php
4 years ago
CSSNamespace.php
4 years ago
Charset.php
2 years ago
Import.php
2 years ago
KeyframeSelector.php
4 years ago
Selector.php
4 years ago
index.php
3 years ago
Selector.php
80 lines
| 1 | <?php |
| 2 | namespace MailPoetVendor\Sabberworm\CSS\Property; |
| 3 | if (!defined('ABSPATH')) exit; |
| 4 | class Selector |
| 5 | { |
| 6 | const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX = '/ |
| 7 | (\\.[\\w]+) # classes |
| 8 | | |
| 9 | \\[(\\w+) # attributes |
| 10 | | |
| 11 | (\\:( # pseudo classes |
| 12 | link|visited|active |
| 13 | |hover|focus |
| 14 | |lang |
| 15 | |target |
| 16 | |enabled|disabled|checked|indeterminate |
| 17 | |root |
| 18 | |nth-child|nth-last-child|nth-of-type|nth-last-of-type |
| 19 | |first-child|last-child|first-of-type|last-of-type |
| 20 | |only-child|only-of-type |
| 21 | |empty|contains |
| 22 | )) |
| 23 | /ix'; |
| 24 | const ELEMENTS_AND_PSEUDO_ELEMENTS_RX = '/ |
| 25 | ((^|[\\s\\+\\>\\~]+)[\\w]+ # elements |
| 26 | | |
| 27 | \\:{1,2}( # pseudo-elements |
| 28 | after|before|first-letter|first-line|selection |
| 29 | )) |
| 30 | /ix'; |
| 31 | const SELECTOR_VALIDATION_RX = '/ |
| 32 | ^( |
| 33 | (?: |
| 34 | [a-zA-Z0-9\\x{00A0}-\\x{FFFF}_^$|*="\'~\\[\\]()\\-\\s\\.:#+>]* # any sequence of valid unescaped characters |
| 35 | (?:\\\\.)? # a single escaped character |
| 36 | (?:([\'"]).*?(?<!\\\\)\\2)? # a quoted text like [id="example"] |
| 37 | )* |
| 38 | )$ |
| 39 | /ux'; |
| 40 | private $sSelector; |
| 41 | private $iSpecificity; |
| 42 | public static function isValid($sSelector) |
| 43 | { |
| 44 | return \preg_match(static::SELECTOR_VALIDATION_RX, $sSelector); |
| 45 | } |
| 46 | public function __construct($sSelector, $bCalculateSpecificity = \false) |
| 47 | { |
| 48 | $this->setSelector($sSelector); |
| 49 | if ($bCalculateSpecificity) { |
| 50 | $this->getSpecificity(); |
| 51 | } |
| 52 | } |
| 53 | public function getSelector() |
| 54 | { |
| 55 | return $this->sSelector; |
| 56 | } |
| 57 | public function setSelector($sSelector) |
| 58 | { |
| 59 | $this->sSelector = \trim($sSelector); |
| 60 | $this->iSpecificity = null; |
| 61 | } |
| 62 | public function __toString() |
| 63 | { |
| 64 | return $this->getSelector(); |
| 65 | } |
| 66 | public function getSpecificity() |
| 67 | { |
| 68 | if ($this->iSpecificity === null) { |
| 69 | $a = 0; |
| 70 | /// @todo should exclude \# as well as "#" |
| 71 | $aMatches = null; |
| 72 | $b = \substr_count($this->sSelector, '#'); |
| 73 | $c = \preg_match_all(self::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX, $this->sSelector, $aMatches); |
| 74 | $d = \preg_match_all(self::ELEMENTS_AND_PSEUDO_ELEMENTS_RX, $this->sSelector, $aMatches); |
| 75 | $this->iSpecificity = $a * 1000 + $b * 100 + $c * 10 + $d; |
| 76 | } |
| 77 | return $this->iSpecificity; |
| 78 | } |
| 79 | } |
| 80 |