From afbaf1929a8ef83c6353f9aa172dab325e0ba12e Mon Sep 17 00:00:00 2001 From: "Barry vd. Heuvel" Date: Thu, 17 Jul 2014 09:36:46 +0200 Subject: [PATCH] Add compare method to Specificity So we can compare the specificity without using the value, so it doesn't matter if the base isn't high enough (for example, 1,0,0 should be higher then 0,11,0. Currently with using values, this wouldn't be possible (100 vs 110). --- .../CssSelector/Node/Specificity.php | 24 +++++++++++++++++++ .../Tests/Node/SpecificityTest.php | 22 +++++++++++++++++ 2 files changed, 46 insertions(+) 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), + ); + } }