XPathExpr.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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\XPath;
  11. /**
  12. * XPath expression translator interface.
  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. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  18. *
  19. * @internal
  20. */
  21. class XPathExpr
  22. {
  23. public function __construct(
  24. private string $path = '',
  25. private string $element = '*',
  26. private string $condition = '',
  27. bool $starPrefix = false,
  28. ) {
  29. if ($starPrefix) {
  30. $this->addStarPrefix();
  31. }
  32. }
  33. public function getElement(): string
  34. {
  35. return $this->element;
  36. }
  37. /**
  38. * @return $this
  39. */
  40. public function addCondition(string $condition, string $operator = 'and'): static
  41. {
  42. $this->condition = $this->condition ? \sprintf('(%s) %s (%s)', $this->condition, $operator, $condition) : $condition;
  43. return $this;
  44. }
  45. public function getCondition(): string
  46. {
  47. return $this->condition;
  48. }
  49. /**
  50. * @return $this
  51. */
  52. public function addNameTest(): static
  53. {
  54. if ('*' !== $this->element) {
  55. $this->addCondition('name() = '.Translator::getXpathLiteral($this->element));
  56. $this->element = '*';
  57. }
  58. return $this;
  59. }
  60. /**
  61. * @return $this
  62. */
  63. public function addStarPrefix(): static
  64. {
  65. $this->path .= '*/';
  66. return $this;
  67. }
  68. /**
  69. * Joins another XPathExpr with a combiner.
  70. *
  71. * @return $this
  72. */
  73. public function join(string $combiner, self $expr): static
  74. {
  75. $path = $this->__toString().$combiner;
  76. if ('*/' !== $expr->path) {
  77. $path .= $expr->path;
  78. }
  79. $this->path = $path;
  80. $this->element = $expr->element;
  81. $this->condition = $expr->condition;
  82. return $this;
  83. }
  84. public function __toString(): string
  85. {
  86. $path = $this->path.$this->element;
  87. $condition = '' === $this->condition ? '' : '['.$this->condition.']';
  88. return $path.$condition;
  89. }
  90. }