Specificity.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\CssSelector\Node;
  11. /**
  12. * Represents a node specificity.
  13. *
  14. * This component is a port of the Python cssselect library,
  15. * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
  16. *
  17. * @see http://www.w3.org/TR/selectors/#specificity
  18. *
  19. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  20. *
  21. * @internal
  22. */
  23. class Specificity
  24. {
  25. const A_FACTOR = 100;
  26. const B_FACTOR = 10;
  27. const C_FACTOR = 1;
  28. private $a;
  29. private $b;
  30. private $c;
  31. /**
  32. * @param int $a
  33. * @param int $b
  34. * @param int $c
  35. */
  36. public function __construct($a, $b, $c)
  37. {
  38. $this->a = $a;
  39. $this->b = $b;
  40. $this->c = $c;
  41. }
  42. /**
  43. * @return self
  44. */
  45. public function plus(self $specificity)
  46. {
  47. return new self($this->a + $specificity->a, $this->b + $specificity->b, $this->c + $specificity->c);
  48. }
  49. /**
  50. * Returns global specificity value.
  51. *
  52. * @return int
  53. */
  54. public function getValue()
  55. {
  56. return $this->a * self::A_FACTOR + $this->b * self::B_FACTOR + $this->c * self::C_FACTOR;
  57. }
  58. /**
  59. * Returns -1 if the object specificity is lower than the argument,
  60. * 0 if they are equal, and 1 if the argument is lower.
  61. *
  62. * @return int
  63. */
  64. public function compareTo(self $specificity)
  65. {
  66. if ($this->a !== $specificity->a) {
  67. return $this->a > $specificity->a ? 1 : -1;
  68. }
  69. if ($this->b !== $specificity->b) {
  70. return $this->b > $specificity->b ? 1 : -1;
  71. }
  72. if ($this->c !== $specificity->c) {
  73. return $this->c > $specificity->c ? 1 : -1;
  74. }
  75. return 0;
  76. }
  77. }