XPathExpr.php 2.3 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\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. public function addCondition(string $condition): self
  40. {
  41. $this->condition = $this->condition ? sprintf('(%s) and (%s)', $this->condition, $condition) : $condition;
  42. return $this;
  43. }
  44. public function getCondition(): string
  45. {
  46. return $this->condition;
  47. }
  48. public function addNameTest(): self
  49. {
  50. if ('*' !== $this->element) {
  51. $this->addCondition('name() = '.Translator::getXpathLiteral($this->element));
  52. $this->element = '*';
  53. }
  54. return $this;
  55. }
  56. public function addStarPrefix(): self
  57. {
  58. $this->path .= '*/';
  59. return $this;
  60. }
  61. /**
  62. * Joins another XPathExpr with a combiner.
  63. *
  64. * @return $this
  65. */
  66. public function join(string $combiner, self $expr): self
  67. {
  68. $path = $this->__toString().$combiner;
  69. if ('*/' !== $expr->path) {
  70. $path .= $expr->path;
  71. }
  72. $this->path = $path;
  73. $this->element = $expr->element;
  74. $this->condition = $expr->condition;
  75. return $this;
  76. }
  77. public function __toString(): string
  78. {
  79. $path = $this->path.$this->element;
  80. $condition = null === $this->condition || '' === $this->condition ? '' : '['.$this->condition.']';
  81. return $path.$condition;
  82. }
  83. }