TokenCollection.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php declare(strict_types = 1);
  2. namespace TheSeer\Tokenizer;
  3. class TokenCollection implements \ArrayAccess, \Iterator, \Countable {
  4. /** @var Token[] */
  5. private $tokens = [];
  6. /** @var int */
  7. private $pos;
  8. public function addToken(Token $token): void {
  9. $this->tokens[] = $token;
  10. }
  11. public function current(): Token {
  12. return \current($this->tokens);
  13. }
  14. public function key(): int {
  15. return \key($this->tokens);
  16. }
  17. public function next(): void {
  18. \next($this->tokens);
  19. $this->pos++;
  20. }
  21. public function valid(): bool {
  22. return $this->count() > $this->pos;
  23. }
  24. public function rewind(): void {
  25. \reset($this->tokens);
  26. $this->pos = 0;
  27. }
  28. public function count(): int {
  29. return \count($this->tokens);
  30. }
  31. public function offsetExists($offset): bool {
  32. return isset($this->tokens[$offset]);
  33. }
  34. /**
  35. * @throws TokenCollectionException
  36. */
  37. public function offsetGet($offset): Token {
  38. if (!$this->offsetExists($offset)) {
  39. throw new TokenCollectionException(
  40. \sprintf('No Token at offest %s', $offset)
  41. );
  42. }
  43. return $this->tokens[$offset];
  44. }
  45. /**
  46. * @param Token $value
  47. *
  48. * @throws TokenCollectionException
  49. */
  50. public function offsetSet($offset, $value): void {
  51. if (!\is_int($offset)) {
  52. $type = \gettype($offset);
  53. throw new TokenCollectionException(
  54. \sprintf(
  55. 'Offset must be of type integer, %s given',
  56. $type === 'object' ? \get_class($value) : $type
  57. )
  58. );
  59. }
  60. if (!$value instanceof Token) {
  61. $type = \gettype($value);
  62. throw new TokenCollectionException(
  63. \sprintf(
  64. 'Value must be of type %s, %s given',
  65. Token::class,
  66. $type === 'object' ? \get_class($value) : $type
  67. )
  68. );
  69. }
  70. $this->tokens[$offset] = $value;
  71. }
  72. public function offsetUnset($offset): void {
  73. unset($this->tokens[$offset]);
  74. }
  75. }