CssSelectorConverter.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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;
  11. use Symfony\Component\CssSelector\Parser\Shortcut\ClassParser;
  12. use Symfony\Component\CssSelector\Parser\Shortcut\ElementParser;
  13. use Symfony\Component\CssSelector\Parser\Shortcut\EmptyStringParser;
  14. use Symfony\Component\CssSelector\Parser\Shortcut\HashParser;
  15. use Symfony\Component\CssSelector\XPath\Extension\HtmlExtension;
  16. use Symfony\Component\CssSelector\XPath\Translator;
  17. /**
  18. * CssSelectorConverter is the main entry point of the component and can convert CSS
  19. * selectors to XPath expressions.
  20. *
  21. * @author Christophe Coevoet <stof@notk.org>
  22. */
  23. class CssSelectorConverter
  24. {
  25. private $translator;
  26. /**
  27. * @param bool $html Whether HTML support should be enabled. Disable it for XML documents
  28. */
  29. public function __construct(bool $html = true)
  30. {
  31. $this->translator = new Translator();
  32. if ($html) {
  33. $this->translator->registerExtension(new HtmlExtension($this->translator));
  34. }
  35. $this->translator
  36. ->registerParserShortcut(new EmptyStringParser())
  37. ->registerParserShortcut(new ElementParser())
  38. ->registerParserShortcut(new ClassParser())
  39. ->registerParserShortcut(new HashParser())
  40. ;
  41. }
  42. /**
  43. * Translates a CSS expression to its XPath equivalent.
  44. *
  45. * Optionally, a prefix can be added to the resulting XPath
  46. * expression with the $prefix parameter.
  47. *
  48. * @param string $cssExpr The CSS expression
  49. * @param string $prefix An optional prefix for the XPath expression
  50. *
  51. * @return string
  52. */
  53. public function toXPath($cssExpr, $prefix = 'descendant-or-self::')
  54. {
  55. return $this->translator->cssToXPath($cssExpr, $prefix);
  56. }
  57. }