diff --git a/src/Symfony/Component/CssSelector/Node/Specificity.php b/src/Symfony/Component/CssSelector/Node/Specificity.php index 96bbd11f51..16cf9ad3d0 100644 --- a/src/Symfony/Component/CssSelector/Node/Specificity.php +++ b/src/Symfony/Component/CssSelector/Node/Specificity.php @@ -75,4 +75,28 @@ class Specificity { return $this->a * self::A_FACTOR + $this->b * self::B_FACTOR + $this->c * self::C_FACTOR; } + + /** + * Returns -1 if the object specificity is lower than the argument, + * 0 if they are equal, and 1 if the argument is lower + * + * @param Specificity $specificity + * @return int + */ + public function compare(Specificity $specificity) + { + if ($this->a !== $specificity->a) { + return $this->a > $specificity->a ? 1 : -1; + } + + if ($this->b !== $specificity->b) { + return $this->b > $specificity->b ? 1 : -1; + } + + if ($this->c !== $specificity->c) { + return $this->c > $specificity->c ? 1 : -1; + } + + return 0; + } } diff --git a/src/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.php b/src/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.php index 1f200cffe4..24b32ce4ac 100644 --- a/src/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.php +++ b/src/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.php @@ -37,4 +37,26 @@ class SpecificityTest extends \PHPUnit_Framework_TestCase array(new Specificity(4, 3, 2), 432), ); } + + /** @dataProvider getCompareTestData */ + public function testCompare(Specificity $a, Specificity $b, $result) + { + $this->assertEquals($result, $a->compare($b)); + } + + public function getCompareTestData() + { + return array( + array(new Specificity(0, 0, 0), new Specificity(0, 0, 0), 0), + array(new Specificity(0, 0, 1), new Specificity(0, 0, 1), 0), + array(new Specificity(0, 0, 2), new Specificity(0, 0, 1), 1), + array(new Specificity(0, 0, 2), new Specificity(0, 0, 3), -1), + array(new Specificity(0, 4, 0), new Specificity(0, 4, 0), 0), + array(new Specificity(0, 6, 0), new Specificity(0, 5, 11), 1), + array(new Specificity(0, 7, 0), new Specificity(0, 8, 0), -1), + array(new Specificity(9, 0, 0), new Specificity(9, 0, 0), 0), + array(new Specificity(11, 0, 0), new Specificity(10, 11, 0), 1), + array(new Specificity(12, 11, 0), new Specificity(13, 0, 0), -1), + ); + } }