AttributeEmulator.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Lexer\TokenEmulator;
  3. use PhpParser\PhpVersion;
  4. use PhpParser\Token;
  5. final class AttributeEmulator extends TokenEmulator {
  6. public function getPhpVersion(): PhpVersion {
  7. return PhpVersion::fromComponents(8, 0);
  8. }
  9. public function isEmulationNeeded(string $code): bool {
  10. return strpos($code, '#[') !== false;
  11. }
  12. public function emulate(string $code, array $tokens): array {
  13. // We need to manually iterate and manage a count because we'll change
  14. // the tokens array on the way.
  15. for ($i = 0, $c = count($tokens); $i < $c; ++$i) {
  16. $token = $tokens[$i];
  17. if ($token->text === '#' && isset($tokens[$i + 1]) && $tokens[$i + 1]->text === '[') {
  18. array_splice($tokens, $i, 2, [
  19. new Token(\T_ATTRIBUTE, '#[', $token->line, $token->pos),
  20. ]);
  21. $c--;
  22. continue;
  23. }
  24. }
  25. return $tokens;
  26. }
  27. public function reverseEmulate(string $code, array $tokens): array {
  28. // TODO
  29. return $tokens;
  30. }
  31. public function preprocessCode(string $code, array &$patches): string {
  32. $pos = 0;
  33. while (false !== $pos = strpos($code, '#[', $pos)) {
  34. // Replace #[ with %[
  35. $code[$pos] = '%';
  36. $patches[] = [$pos, 'replace', '#'];
  37. $pos += 2;
  38. }
  39. return $code;
  40. }
  41. }