Specificity.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. /**
  29. * @var int
  30. */
  31. private $a;
  32. /**
  33. * @var int
  34. */
  35. private $b;
  36. /**
  37. * @var int
  38. */
  39. private $c;
  40. /**
  41. * @param int $a
  42. * @param int $b
  43. * @param int $c
  44. */
  45. public function __construct($a, $b, $c)
  46. {
  47. $this->a = $a;
  48. $this->b = $b;
  49. $this->c = $c;
  50. }
  51. /**
  52. * @param Specificity $specificity
  53. *
  54. * @return self
  55. */
  56. public function plus(Specificity $specificity)
  57. {
  58. return new self($this->a + $specificity->a, $this->b + $specificity->b, $this->c + $specificity->c);
  59. }
  60. /**
  61. * Returns global specificity value.
  62. *
  63. * @return int
  64. */
  65. public function getValue()
  66. {
  67. return $this->a * self::A_FACTOR + $this->b * self::B_FACTOR + $this->c * self::C_FACTOR;
  68. }
  69. /**
  70. * Returns -1 if the object specificity is lower than the argument,
  71. * 0 if they are equal, and 1 if the argument is lower.
  72. *
  73. * @param Specificity $specificity
  74. *
  75. * @return int
  76. */
  77. public function compareTo(Specificity $specificity)
  78. {
  79. if ($this->a !== $specificity->a) {
  80. return $this->a > $specificity->a ? 1 : -1;
  81. }
  82. if ($this->b !== $specificity->b) {
  83. return $this->b > $specificity->b ? 1 : -1;
  84. }
  85. if ($this->c !== $specificity->c) {
  86. return $this->c > $specificity->c ? 1 : -1;
  87. }
  88. return 0;
  89. }
  90. }