Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions src/Property/Selector/SpecificityCalculator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

declare(strict_types=1);

namespace Sabberworm\CSS\Property\Selector;

/**
* Utility class to calculate the specificity of a CSS selector.
*
* The results are cached to avoid recalculating the specificity of the same selector multiple times.
*/
final class SpecificityCalculator
{
/**
* regexp for specificity calculations
*
* @var non-empty-string
*/
private const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX = '/
(\\.[\\w]+) # classes
|
\\[(\\w+) # attributes
|
(\\:( # pseudo classes
link|visited|active
|hover|focus
|lang
|target
|enabled|disabled|checked|indeterminate
|root
|nth-child|nth-last-child|nth-of-type|nth-last-of-type
|first-child|last-child|first-of-type|last-of-type
|only-child|only-of-type
|empty|contains
))
/ix';

/**
* regexp for specificity calculations
*
* @var non-empty-string
*/
private const ELEMENTS_AND_PSEUDO_ELEMENTS_RX = '/
((^|[\\s\\+\\>\\~]+)[\\w]+ # elements
|
\\:{1,2}( # pseudo-elements
after|before|first-letter|first-line|selection
))
/ix';

/**
* @var array<string, int<0, max>>
*/
private static $cache = [];

/**
* Calculates the specificity of the given CSS selector.
*
* @return int<0, max>
*
* @internal
*/
public static function calculate(string $selector): int
{
if (!isset(self::$cache[$selector])) {
$a = 0;
/// @todo should exclude \# as well as "#"
$aMatches = null;
$b = \substr_count($selector, '#');
$c = \preg_match_all(self::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX, $selector, $aMatches);
$d = \preg_match_all(self::ELEMENTS_AND_PSEUDO_ELEMENTS_RX, $selector, $aMatches);
self::$cache[$selector] = ($a * 1000) + ($b * 100) + ($c * 10) + $d;
}

return self::$cache[$selector];
}

/**
* Clears the cache in order to lower memory usage.
*/
public static function clearCache(): void
{
self::$cache = [];
}
}
94 changes: 94 additions & 0 deletions tests/Unit/Property/Selector/SpecificityCalculatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

declare(strict_types=1);

namespace Sabberworm\CSS\Tests\Unit\Property\Selector;

use PHPUnit\Framework\TestCase;
use Sabberworm\CSS\Property\Selector\SpecificityCalculator;

/**
* @covers \Sabberworm\CSS\Property\Selector\SpecificityCalculator
*/
final class SpecificityCalculatorTest extends TestCase
{
protected function tearDown(): void
{
SpecificityCalculator::clearCache();
}

/**
* @return array<string, array{0: non-empty-string, 1: int<0, max>}>
*/
public static function provideSelectorsAndSpecificities(): array
{
return [
'element' => ['a', 1],
'element and descendant with pseudo-selector' => ['ol li::before', 3],
'class' => ['.highlighted', 10],
'element with class' => ['li.green', 11],
'class with pseudo-selector' => ['.help:hover', 20],
'ID' => ['#file', 100],
'ID and descendant class' => ['#test .help', 110],
];
}

/**
* @test
*
* @param non-empty-string $selector
* @param int<0, max> $expectedSpecificity
*
* @dataProvider provideSelectorsAndSpecificities
*/
public function calculateReturnsSpecificityForProvidedSelector(
string $selector,
int $expectedSpecificity
): void {
self::assertSame($expectedSpecificity, SpecificityCalculator::calculate($selector));
}

/**
* @test
*
* @param non-empty-string $selector
* @param int<0, max> $expectedSpecificity
*
* @dataProvider provideSelectorsAndSpecificities
*/
public function calculateAfterClearingCacheReturnsSpecificityForProvidedSelector(
string $selector,
int $expectedSpecificity
): void {
SpecificityCalculator::clearCache();

self::assertSame($expectedSpecificity, SpecificityCalculator::calculate($selector));
}

/**
* @test
*/
public function calculateCalledTwoTimesReturnsSameSpecificityForProvidedSelector(): void
{
$selector = '#test .help';

$firstResult = SpecificityCalculator::calculate($selector);
$secondResult = SpecificityCalculator::calculate($selector);

self::assertSame($firstResult, $secondResult);
}

/**
* @test
*/
public function calculateCalledReturnsSameSpecificityForProvidedSelectorBeforeAndAfterClearingCache(): void
{
$selector = '#test .help';

$firstResult = SpecificityCalculator::calculate($selector);
SpecificityCalculator::clearCache();
$secondResult = SpecificityCalculator::calculate($selector);

self::assertSame($firstResult, $secondResult);
}
}