Specificity.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. public function __construct(int $a, int $b, int $c)
  32. {
  33. $this->a = $a;
  34. $this->b = $b;
  35. $this->c = $c;
  36. }
  37. public function plus(self $specificity): self
  38. {
  39. return new self($this->a + $specificity->a, $this->b + $specificity->b, $this->c + $specificity->c);
  40. }
  41. public function getValue(): int
  42. {
  43. return $this->a * self::A_FACTOR + $this->b * self::B_FACTOR + $this->c * self::C_FACTOR;
  44. }
  45. /**
  46. * Returns -1 if the object specificity is lower than the argument,
  47. * 0 if they are equal, and 1 if the argument is lower.
  48. *
  49. * @return int
  50. */
  51. public function compareTo(self $specificity)
  52. {
  53. if ($this->a !== $specificity->a) {
  54. return $this->a > $specificity->a ? 1 : -1;
  55. }
  56. if ($this->b !== $specificity->b) {
  57. return $this->b > $specificity->b ? 1 : -1;
  58. }
  59. if ($this->c !== $specificity->c) {
  60. return $this->c > $specificity->c ? 1 : -1;
  61. }
  62. return 0;
  63. }
  64. }