Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
barryvdh committed Jul 17, 2014
1 parent 732c9e2 commit afbaf19
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Symfony/Component/CssSelector/Node/Specificity.php
Expand Up @@ -75,4 +75,28 @@ public function getValue()
{
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;
}
}
22 changes: 22 additions & 0 deletions src/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.php
Expand Up @@ -37,4 +37,26 @@ public function getValueTestData()
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),
);
}
}

0 comments on commit afbaf19

Please sign in to comment.