Specificity.php 1.7 KB

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