CombinationExtension.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\Extension;
  11. use Symfony\Component\CssSelector\XPath\XPathExpr;
  12. /**
  13. * XPath expression translator combination extension.
  14. *
  15. * This component is a port of the Python cssselect library,
  16. * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
  17. *
  18. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  19. *
  20. * @internal
  21. */
  22. class CombinationExtension extends AbstractExtension
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function getCombinationTranslators(): array
  28. {
  29. return [
  30. ' ' => [$this, 'translateDescendant'],
  31. '>' => [$this, 'translateChild'],
  32. '+' => [$this, 'translateDirectAdjacent'],
  33. '~' => [$this, 'translateIndirectAdjacent'],
  34. ];
  35. }
  36. /**
  37. * @return XPathExpr
  38. */
  39. public function translateDescendant(XPathExpr $xpath, XPathExpr $combinedXpath): XPathExpr
  40. {
  41. return $xpath->join('/descendant-or-self::*/', $combinedXpath);
  42. }
  43. /**
  44. * @return XPathExpr
  45. */
  46. public function translateChild(XPathExpr $xpath, XPathExpr $combinedXpath)
  47. {
  48. return $xpath->join('/', $combinedXpath);
  49. }
  50. /**
  51. * @return XPathExpr
  52. */
  53. public function translateDirectAdjacent(XPathExpr $xpath, XPathExpr $combinedXpath)
  54. {
  55. return $xpath
  56. ->join('/following-sibling::', $combinedXpath)
  57. ->addNameTest()
  58. ->addCondition('position() = 1');
  59. }
  60. /**
  61. * @return XPathExpr
  62. */
  63. public function translateIndirectAdjacent(XPathExpr $xpath, XPathExpr $combinedXpath)
  64. {
  65. return $xpath->join('/following-sibling::', $combinedXpath);
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function getName()
  71. {
  72. return 'combination';
  73. }
  74. }