No Description

XPathExpr.php 2.4KB

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