Reader.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\Parser;
  11. /**
  12. * CSS selector reader.
  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 Reader
  22. {
  23. private int $length;
  24. private int $position = 0;
  25. public function __construct(
  26. private string $source,
  27. ) {
  28. $this->length = \strlen($source);
  29. }
  30. public function isEOF(): bool
  31. {
  32. return $this->position >= $this->length;
  33. }
  34. public function getPosition(): int
  35. {
  36. return $this->position;
  37. }
  38. public function getRemainingLength(): int
  39. {
  40. return $this->length - $this->position;
  41. }
  42. public function getSubstring(int $length, int $offset = 0): string
  43. {
  44. return substr($this->source, $this->position + $offset, $length);
  45. }
  46. public function getOffset(string $string): int|false
  47. {
  48. $position = strpos($this->source, $string, $this->position);
  49. return false === $position ? false : $position - $this->position;
  50. }
  51. public function findPattern(string $pattern): array|false
  52. {
  53. $source = substr($this->source, $this->position);
  54. if (preg_match($pattern, $source, $matches)) {
  55. return $matches;
  56. }
  57. return false;
  58. }
  59. public function moveForward(int $length): void
  60. {
  61. $this->position += $length;
  62. }
  63. public function moveToEnd(): void
  64. {
  65. $this->position = $this->length;
  66. }
  67. }