Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403]

   1  <?php
   2  
   3  namespace Sabberworm\CSS\Property;
   4  
   5  /**
   6   * Class representing a single CSS selector. Selectors have to be split by the comma prior to being passed into this class.
   7   */
   8  class Selector {
   9  
  10  	 //Regexes for specificity calculations
  11  	 const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX = '/
  12  	 (\.[\w]+)                   # classes
  13  	 |
  14  	 \[(\w+)                     # attributes
  15  	 |
  16  	 (\:(                        # pseudo classes
  17  	 	 link|visited|active
  18  	 	 |hover|focus
  19  	 	 |lang
  20  	 	 |target
  21  	 	 |enabled|disabled|checked|indeterminate
  22  	 	 |root
  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
  26  	 	 |empty|contains
  27  	 ))
  28  	 /ix';
  29  
  30  	 const ELEMENTS_AND_PSEUDO_ELEMENTS_RX = '/
  31  	 ((^|[\s\+\>\~]+)[\w]+   # elements
  32  	 |
  33  	 \:{1,2}(                # pseudo-elements
  34  	 	 after|before|first-letter|first-line|selection
  35  	 ))
  36  	 /ix';
  37  
  38  	 private $sSelector;
  39  	 private $iSpecificity;
  40  
  41  	public function __construct($sSelector, $bCalculateSpecificity = false) {
  42  	 	 $this->setSelector($sSelector);
  43  	 	 if ($bCalculateSpecificity) {
  44  	 	 	 $this->getSpecificity();
  45  	 	 }
  46  	 }
  47  
  48  	public function getSelector() {
  49  	 	 return $this->sSelector;
  50  	 }
  51  
  52  	public function setSelector($sSelector) {
  53  	 	 $this->sSelector = trim($sSelector);
  54  	 	 $this->iSpecificity = null;
  55  	 }
  56  
  57  	public function __toString() {
  58  	 	 return $this->getSelector();
  59  	 }
  60  
  61  	public function getSpecificity() {
  62  	 	 if ($this->iSpecificity === null) {
  63  	 	 	 $a = 0;
  64  	 	 	 /// @todo should exclude \# as well as "#"
  65  	 	 	 $aMatches = null;
  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;
  70  	 	 }
  71  	 	 return $this->iSpecificity;
  72  	 }
  73  
  74  }