TokensWithObservedTransformers.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. /**
  20. * @var null|string
  21. */
  22. public $currentTransformer;
  23. /**
  24. * @var array<string, list<int|string>>
  25. */
  26. public $observedModificationsPerTransformer = [];
  27. public function offsetSet($index, $newval): void
  28. {
  29. if (null !== $this->currentTransformer) {
  30. $this->observedModificationsPerTransformer[$this->currentTransformer][] = $this->extractTokenKind($newval);
  31. }
  32. parent::offsetSet($index, $newval);
  33. }
  34. /**
  35. * @internal
  36. */
  37. protected function applyTransformers(): void
  38. {
  39. $this->observedModificationsPerTransformer = [];
  40. $transformers = Transformers::createSingleton();
  41. foreach (AccessibleObject::create($transformers)->items as $transformer) {
  42. $this->currentTransformer = $transformer->getName();
  43. $this->observedModificationsPerTransformer[$this->currentTransformer] = [];
  44. foreach ($this as $index => $token) {
  45. $transformer->process($this, $token, $index);
  46. }
  47. }
  48. $this->currentTransformer = null;
  49. }
  50. /**
  51. * @param array{int}|string|Token $token token prototype
  52. *
  53. * @return int|string
  54. */
  55. private function extractTokenKind($token)
  56. {
  57. return $token instanceof Token
  58. ? ($token->isArray() ? $token->getId() : $token->getContent())
  59. : (\is_array($token) ? $token[0] : $token);
  60. }
  61. }