Reader.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. /**
  24. * @var string
  25. */
  26. private $source;
  27. /**
  28. * @var int
  29. */
  30. private $length;
  31. /**
  32. * @var int
  33. */
  34. private $position = 0;
  35. /**
  36. * @param string $source
  37. */
  38. public function __construct($source)
  39. {
  40. $this->source = $source;
  41. $this->length = strlen($source);
  42. }
  43. /**
  44. * @return bool
  45. */
  46. public function isEOF()
  47. {
  48. return $this->position >= $this->length;
  49. }
  50. /**
  51. * @return int
  52. */
  53. public function getPosition()
  54. {
  55. return $this->position;
  56. }
  57. /**
  58. * @return int
  59. */
  60. public function getRemainingLength()
  61. {
  62. return $this->length - $this->position;
  63. }
  64. /**
  65. * @param int $length
  66. * @param int $offset
  67. *
  68. * @return string
  69. */
  70. public function getSubstring($length, $offset = 0)
  71. {
  72. return substr($this->source, $this->position + $offset, $length);
  73. }
  74. /**
  75. * @param string $string
  76. *
  77. * @return int
  78. */
  79. public function getOffset($string)
  80. {
  81. $position = strpos($this->source, $string, $this->position);
  82. return false === $position ? false : $position - $this->position;
  83. }
  84. /**
  85. * @param string $pattern
  86. *
  87. * @return array|false
  88. */
  89. public function findPattern($pattern)
  90. {
  91. $source = substr($this->source, $this->position);
  92. if (preg_match($pattern, $source, $matches)) {
  93. return $matches;
  94. }
  95. return false;
  96. }
  97. /**
  98. * @param int $length
  99. */
  100. public function moveForward($length)
  101. {
  102. $this->position += $length;
  103. }
  104. public function moveToEnd()
  105. {
  106. $this->position = $this->length;
  107. }
  108. }