TokensWithObservedTransformers.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Tests\Test;
  13. use PhpCsFixer\AccessibleObject\AccessibleObject;
  14. use PhpCsFixer\Tokenizer\Token;
  15. use PhpCsFixer\Tokenizer\Tokens;
  16. use PhpCsFixer\Tokenizer\Transformers;
  17. class TokensWithObservedTransformers extends Tokens
  18. {
  19. public ?string $currentTransformer = null;
  20. /**
  21. * @var array<string, list<int|string>>
  22. */
  23. public array $observedModificationsPerTransformer = [];
  24. public function offsetSet($index, $newval): void
  25. {
  26. if (null !== $this->currentTransformer) {
  27. $this->observedModificationsPerTransformer[$this->currentTransformer][] = $this->extractTokenKind($newval);
  28. }
  29. parent::offsetSet($index, $newval);
  30. }
  31. /**
  32. * @internal
  33. */
  34. protected function applyTransformers(): void
  35. {
  36. $this->observedModificationsPerTransformer = [];
  37. $transformers = Transformers::createSingleton();
  38. foreach (AccessibleObject::create($transformers)->items as $transformer) {
  39. $this->currentTransformer = $transformer->getName();
  40. $this->observedModificationsPerTransformer[$this->currentTransformer] = [];
  41. foreach ($this as $index => $token) {
  42. $transformer->process($this, $token, $index);
  43. }
  44. }
  45. $this->currentTransformer = null;
  46. }
  47. /**
  48. * @param array{int}|string|Token $token token prototype
  49. *
  50. * @return int|string
  51. */
  52. private function extractTokenKind($token)
  53. {
  54. return $token instanceof Token
  55. ? ($token->isArray() ? $token->getId() : $token->getContent())
  56. : (\is_array($token) ? $token[0] : $token);
  57. }
  58. }