RangeAnalyzerTest.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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\Tokenizer\Analyzer;
  13. use PhpCsFixer\Tests\TestCase;
  14. use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer;
  15. use PhpCsFixer\Tokenizer\Tokens;
  16. /**
  17. * @internal
  18. *
  19. * @covers \PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer
  20. */
  21. final class RangeAnalyzerTest extends TestCase
  22. {
  23. /**
  24. * @param array{start: int, end: int} $range1
  25. * @param array{start: int, end: int} $range2
  26. *
  27. * @dataProvider provideRangeEqualsRangeCases
  28. */
  29. public function testRangeEqualsRange(bool $expected, string $code, array $range1, array $range2): void
  30. {
  31. $tokens = Tokens::fromCode($code);
  32. self::assertSame($expected, RangeAnalyzer::rangeEqualsRange($tokens, $range1, $range2));
  33. }
  34. public static function provideRangeEqualsRangeCases(): iterable
  35. {
  36. $ranges = [
  37. [['start' => 2, 'end' => 6], ['start' => 10, 'end' => 14]],
  38. [['start' => 10, 'end' => 14], ['start' => 20, 'end' => 24]],
  39. [['start' => 1, 'end' => 6], ['start' => 20, 'end' => 25]],
  40. ];
  41. foreach ($ranges as $i => [$range1, $range2]) {
  42. yield 'extra "()" and space #'.$i => [
  43. true,
  44. '<?php
  45. $a = 1;
  46. ($a = 1);
  47. (($a = 1 ));
  48. ',
  49. $range1,
  50. $range2,
  51. ];
  52. }
  53. yield [
  54. false,
  55. '<?php echo 1;',
  56. ['start' => 0, 'end' => 1],
  57. ['start' => 1, 'end' => 2],
  58. ];
  59. yield 'comment + space' => [
  60. true,
  61. '<?php
  62. foo(1);
  63. /* */ foo/* */(1) /* */ ;
  64. ',
  65. ['start' => 1, 'end' => 5],
  66. ['start' => 9, 'end' => 17],
  67. ];
  68. }
  69. /**
  70. * @requires PHP <8.0
  71. */
  72. public function testFixPrePHP80(): void
  73. {
  74. $code = '<?php
  75. $a = [1,2,3];
  76. echo $a[1];
  77. echo $a{1};
  78. ';
  79. $tokens = Tokens::fromCode($code);
  80. $ranges = [
  81. [
  82. ['start' => 15, 'end' => 21],
  83. ['start' => 23, 'end' => 29],
  84. ],
  85. [
  86. ['start' => 17, 'end' => 20],
  87. ['start' => 24, 'end' => 28],
  88. ],
  89. ];
  90. foreach ($ranges as [$range1, $range2]) {
  91. self::assertTrue(RangeAnalyzer::rangeEqualsRange($tokens, $range1, $range2));
  92. }
  93. }
  94. }