| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Sabberworm\CSS\Property\Selector; |
| 6 |
|
| 7 |
use function Safe\preg_match_all; |
| 8 |
|
| 9 |
/** |
| 10 |
* Utility class to calculate the specificity of a CSS selector. |
| 11 |
* |
| 12 |
* The results are cached to avoid recalculating the specificity of the same selector multiple times. |
| 13 |
*/ |
| 14 |
final class SpecificityCalculator |
| 15 |
{ |
| 16 |
/** |
| 17 |
* regexp for specificity calculations |
| 18 |
*/ |
| 19 |
private const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX = '/ |
| 20 |
(\\.[\\w]+) # classes |
| 21 |
| |
| 22 |
\\[(\\w+) # attributes |
| 23 |
| |
| 24 |
(\\:( # pseudo classes |
| 25 |
link|visited|active |
| 26 |
|hover|focus |
| 27 |
|lang |
| 28 |
|target |
| 29 |
|enabled|disabled|checked|indeterminate |
| 30 |
|root |
| 31 |
|nth-child|nth-last-child|nth-of-type|nth-last-of-type |
| 32 |
|first-child|last-child|first-of-type|last-of-type |
| 33 |
|only-child|only-of-type |
| 34 |
|empty|contains |
| 35 |
)) |
| 36 |
/ix'; |
| 37 |
|
| 38 |
/** |
| 39 |
* regexp for specificity calculations |
| 40 |
*/ |
| 41 |
private const ELEMENTS_AND_PSEUDO_ELEMENTS_RX = '/ |
| 42 |
((^|[\\s\\+\\>\\~]+)[\\w]+ # elements |
| 43 |
| |
| 44 |
\\:{1,2}( # pseudo-elements |
| 45 |
after|before|first-letter|first-line|selection |
| 46 |
)) |
| 47 |
/ix'; |
| 48 |
|
| 49 |
/** |
| 50 |
* @var array<string, int<0, max>> |
| 51 |
*/ |
| 52 |
private static $cache = []; |
| 53 |
|
| 54 |
/** |
| 55 |
* Calculates the specificity of the given CSS selector. |
| 56 |
* |
| 57 |
* @return int<0, max> |
| 58 |
* |
| 59 |
* @internal |
| 60 |
*/ |
| 61 |
public static function calculate(string $selector): int |
| 62 |
{ |
| 63 |
if (!isset(self::$cache[$selector])) { |
| 64 |
$a = 0; |
| 65 |
/// @todo should exclude \# as well as "#" |
| 66 |
$matches = null; |
| 67 |
$b = \substr_count($selector, '#'); |
| 68 |
$c = preg_match_all(self::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX, $selector, $matches); |
| 69 |
$d = preg_match_all(self::ELEMENTS_AND_PSEUDO_ELEMENTS_RX, $selector, $matches); |
| 70 |
self::$cache[$selector] = ($a * 1000) + ($b * 100) + ($c * 10) + $d; |
| 71 |
} |
| 72 |
|
| 73 |
return self::$cache[$selector]; |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Clears the cache in order to lower memory usage. |
| 78 |
*/ |
| 79 |
public static function clearCache(): void |
| 80 |
{ |
| 81 |
self::$cache = []; |
| 82 |
} |
| 83 |
} |