TokensTest.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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;
  13. use PhpCsFixer\Tests\Test\Assert\AssertTokensTrait;
  14. use PhpCsFixer\Tests\TestCase;
  15. use PhpCsFixer\Tokenizer\Token;
  16. use PhpCsFixer\Tokenizer\Tokens;
  17. /**
  18. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  19. *
  20. * @internal
  21. *
  22. * @covers \PhpCsFixer\Tokenizer\Tokens
  23. */
  24. final class TokensTest extends TestCase
  25. {
  26. use AssertTokensTrait;
  27. public function testReadFromCacheAfterClearing(): void
  28. {
  29. $code = '<?php echo 1;';
  30. $tokens = Tokens::fromCode($code);
  31. $countBefore = $tokens->count();
  32. for ($i = 0; $i < $countBefore; ++$i) {
  33. $tokens->clearAt($i);
  34. }
  35. $tokens = Tokens::fromCode($code);
  36. static::assertSame($countBefore, $tokens->count());
  37. }
  38. /**
  39. * @param Token[] $sequence
  40. * @param null|array|bool $caseSensitive
  41. *
  42. * @dataProvider provideFindSequenceCases
  43. */
  44. public function testFindSequence(
  45. string $source,
  46. ?array $expected,
  47. array $sequence,
  48. int $start = 0,
  49. int $end = null,
  50. $caseSensitive = true
  51. ): void {
  52. $tokens = Tokens::fromCode($source);
  53. static::assertEqualsTokensArray(
  54. $expected,
  55. $tokens->findSequence(
  56. $sequence,
  57. $start,
  58. $end,
  59. $caseSensitive
  60. )
  61. );
  62. }
  63. public function provideFindSequenceCases(): array
  64. {
  65. return [
  66. [
  67. '<?php $x = 1;',
  68. null,
  69. [
  70. new Token(';'),
  71. ],
  72. 7,
  73. ],
  74. [
  75. '<?php $x = 2;',
  76. null,
  77. [
  78. [T_OPEN_TAG],
  79. [T_VARIABLE, '$y'],
  80. ],
  81. ],
  82. [
  83. '<?php $x = 3;',
  84. [
  85. 0 => new Token([T_OPEN_TAG, '<?php ']),
  86. 1 => new Token([T_VARIABLE, '$x']),
  87. ],
  88. [
  89. [T_OPEN_TAG],
  90. [T_VARIABLE, '$x'],
  91. ],
  92. ],
  93. [
  94. '<?php $x = 4;',
  95. [
  96. 3 => new Token('='),
  97. 5 => new Token([T_LNUMBER, '4']),
  98. 6 => new Token(';'),
  99. ],
  100. [
  101. '=',
  102. [T_LNUMBER, '4'],
  103. ';',
  104. ],
  105. ],
  106. [
  107. '<?php $x = 5;',
  108. [
  109. 0 => new Token([T_OPEN_TAG, '<?php ']),
  110. 1 => new Token([T_VARIABLE, '$x']),
  111. ],
  112. [
  113. [T_OPEN_TAG],
  114. [T_VARIABLE, '$x'],
  115. ],
  116. 0,
  117. ],
  118. [
  119. '<?php $x = 6;',
  120. null,
  121. [
  122. [T_OPEN_TAG],
  123. [T_VARIABLE, '$x'],
  124. ],
  125. 1,
  126. ],
  127. [
  128. '<?php $x = 7;',
  129. [
  130. 3 => new Token('='),
  131. 5 => new Token([T_LNUMBER, '7']),
  132. 6 => new Token(';'),
  133. ],
  134. [
  135. '=',
  136. [T_LNUMBER, '7'],
  137. ';',
  138. ],
  139. 3,
  140. 6,
  141. ],
  142. [
  143. '<?php $x = 8;',
  144. null,
  145. [
  146. '=',
  147. [T_LNUMBER, '8'],
  148. ';',
  149. ],
  150. 4,
  151. 6,
  152. ],
  153. [
  154. '<?php $x = 9;',
  155. null,
  156. [
  157. '=',
  158. [T_LNUMBER, '9'],
  159. ';',
  160. ],
  161. 3,
  162. 5,
  163. ],
  164. [
  165. '<?php $x = 10;',
  166. [
  167. 0 => new Token([T_OPEN_TAG, '<?php ']),
  168. 1 => new Token([T_VARIABLE, '$x']),
  169. ],
  170. [
  171. [T_OPEN_TAG],
  172. [T_VARIABLE, '$x'],
  173. ],
  174. 0,
  175. 1,
  176. true,
  177. ],
  178. [
  179. '<?php $x = 11;',
  180. null,
  181. [
  182. [T_OPEN_TAG],
  183. [T_VARIABLE, '$X'],
  184. ],
  185. 0,
  186. 1,
  187. true,
  188. ],
  189. [
  190. '<?php $x = 12;',
  191. null,
  192. [
  193. [T_OPEN_TAG],
  194. [T_VARIABLE, '$X'],
  195. ],
  196. 0,
  197. 1,
  198. [1 => true],
  199. ],
  200. [
  201. '<?php $x = 13;',
  202. [
  203. 0 => new Token([T_OPEN_TAG, '<?php ']),
  204. 1 => new Token([T_VARIABLE, '$x']),
  205. ],
  206. [
  207. [T_OPEN_TAG],
  208. [T_VARIABLE, '$X'],
  209. ],
  210. 0,
  211. 1,
  212. false,
  213. ],
  214. [
  215. '<?php $x = 14;',
  216. [
  217. 0 => new Token([T_OPEN_TAG, '<?php ']),
  218. 1 => new Token([T_VARIABLE, '$x']),
  219. ],
  220. [
  221. [T_OPEN_TAG],
  222. [T_VARIABLE, '$X'],
  223. ],
  224. 0,
  225. 1,
  226. [1 => false],
  227. ],
  228. [
  229. '<?php $x = 15;',
  230. [
  231. 0 => new Token([T_OPEN_TAG, '<?php ']),
  232. 1 => new Token([T_VARIABLE, '$x']),
  233. ],
  234. [
  235. [T_OPEN_TAG],
  236. [T_VARIABLE, '$X'],
  237. ],
  238. 0,
  239. 1,
  240. [1 => false],
  241. ],
  242. [
  243. '<?php $x = 16;',
  244. null,
  245. [
  246. [T_OPEN_TAG],
  247. [T_VARIABLE, '$X'],
  248. ],
  249. 0,
  250. 1,
  251. [2 => false],
  252. ],
  253. [
  254. '<?php $x = 17;',
  255. null,
  256. [
  257. [T_VARIABLE, '$X'],
  258. '=',
  259. ],
  260. 0,
  261. 10,
  262. ],
  263. ];
  264. }
  265. /**
  266. * @dataProvider provideFindSequenceExceptionCases
  267. */
  268. public function testFindSequenceException(string $message, array $sequence): void
  269. {
  270. $this->expectException(\InvalidArgumentException::class);
  271. $this->expectExceptionMessage($message);
  272. $tokens = Tokens::fromCode('<?php $x = 1;');
  273. $tokens->findSequence($sequence);
  274. }
  275. public function provideFindSequenceExceptionCases(): array
  276. {
  277. $emptyToken = new Token('');
  278. return [
  279. ['Invalid sequence.', []],
  280. [
  281. 'Non-meaningful token at position: "0".',
  282. [[T_WHITESPACE, ' ']],
  283. ],
  284. [
  285. 'Non-meaningful token at position: "1".',
  286. ['{', [T_COMMENT, '// Foo'], '}'],
  287. ],
  288. [
  289. 'Non-meaningful (empty) token at position: "2".',
  290. ['{', '!', $emptyToken, '}'],
  291. ],
  292. ];
  293. }
  294. public function testClearRange(): void
  295. {
  296. $source = <<<'PHP'
  297. <?php
  298. class FooBar
  299. {
  300. public function foo()
  301. {
  302. return 'bar';
  303. }
  304. public function bar()
  305. {
  306. return 'foo';
  307. }
  308. }
  309. PHP;
  310. $tokens = Tokens::fromCode($source);
  311. [$fooIndex, $barIndex] = array_keys($tokens->findGivenKind(T_PUBLIC));
  312. $tokens->clearRange($fooIndex, $barIndex - 1);
  313. $newPublicIndexes = array_keys($tokens->findGivenKind(T_PUBLIC));
  314. static::assertSame($barIndex, reset($newPublicIndexes));
  315. for ($i = $fooIndex; $i < $barIndex; ++$i) {
  316. static::assertTrue($tokens[$i]->isWhitespace());
  317. }
  318. }
  319. /**
  320. * @dataProvider provideMonolithicPhpDetectionCases
  321. */
  322. public function testMonolithicPhpDetection(string $source, bool $isMonolithic): void
  323. {
  324. $tokens = Tokens::fromCode($source);
  325. static::assertSame($isMonolithic, $tokens->isMonolithicPhp());
  326. }
  327. public function provideMonolithicPhpDetectionCases(): array
  328. {
  329. return [
  330. ["<?php\n", true],
  331. ["<?php\n?>", true],
  332. ['', false],
  333. [' ', false],
  334. ["#!/usr/bin/env php\n<?php\n", false],
  335. [" <?php\n", false],
  336. ["<?php\n?> ", false],
  337. ["<?php\n?><?php\n", false],
  338. ];
  339. }
  340. /**
  341. * @dataProvider provideShortOpenTagMonolithicPhpDetectionCases
  342. */
  343. public function testShortOpenTagMonolithicPhpDetection(string $source, bool $monolithic): void
  344. {
  345. if (!ini_get('short_open_tag')) {
  346. $monolithic = false;
  347. }
  348. $tokens = Tokens::fromCode($source);
  349. static::assertSame($monolithic, $tokens->isMonolithicPhp());
  350. }
  351. public function provideShortOpenTagMonolithicPhpDetectionCases(): array
  352. {
  353. return [
  354. ["<?\n", true],
  355. ["<?\n?>", true],
  356. [" <?\n", false],
  357. ["<?\n?> ", false],
  358. ["<?\n?><?\n", false],
  359. ["<?\n?><?php\n", false],
  360. ["<?\n?><?=' ';\n", false],
  361. ["<?php\n?><?\n", false],
  362. ["<?=' '\n?><?\n", false],
  363. ];
  364. }
  365. /**
  366. * @dataProvider provideShortOpenTagEchoMonolithicPhpDetectionCases
  367. */
  368. public function testShortOpenTagEchoMonolithicPhpDetection(string $source, bool $monolithic): void
  369. {
  370. $tokens = Tokens::fromCode($source);
  371. static::assertSame($monolithic, $tokens->isMonolithicPhp());
  372. }
  373. public function provideShortOpenTagEchoMonolithicPhpDetectionCases(): array
  374. {
  375. return [
  376. ["<?=' ';\n", true],
  377. ["<?=' '?>", true],
  378. [" <?=' ';\n", false],
  379. ["<?=' '?> ", false],
  380. ["<?php\n?><?=' ';\n", false],
  381. ["<?=' '\n?><?php\n", false],
  382. ["<?=' '\n?><?=' ';\n", false],
  383. ];
  384. }
  385. public function testTokenKindsFound(): void
  386. {
  387. $code = <<<'EOF'
  388. <?php
  389. class Foo
  390. {
  391. public $foo;
  392. }
  393. if (!function_exists('bar')) {
  394. function bar()
  395. {
  396. return 'bar';
  397. }
  398. }
  399. EOF;
  400. $tokens = Tokens::fromCode($code);
  401. static::assertTrue($tokens->isTokenKindFound(T_CLASS));
  402. static::assertTrue($tokens->isTokenKindFound(T_RETURN));
  403. static::assertFalse($tokens->isTokenKindFound(T_INTERFACE));
  404. static::assertFalse($tokens->isTokenKindFound(T_ARRAY));
  405. static::assertTrue($tokens->isAllTokenKindsFound([T_CLASS, T_RETURN]));
  406. static::assertFalse($tokens->isAllTokenKindsFound([T_CLASS, T_INTERFACE]));
  407. static::assertTrue($tokens->isAnyTokenKindsFound([T_CLASS, T_RETURN]));
  408. static::assertTrue($tokens->isAnyTokenKindsFound([T_CLASS, T_INTERFACE]));
  409. static::assertFalse($tokens->isAnyTokenKindsFound([T_INTERFACE, T_ARRAY]));
  410. }
  411. public function testFindGivenKind(): void
  412. {
  413. $source = <<<'PHP'
  414. <?php
  415. class FooBar
  416. {
  417. public function foo()
  418. {
  419. return 'bar';
  420. }
  421. public function bar()
  422. {
  423. return 'foo';
  424. }
  425. }
  426. PHP;
  427. $tokens = Tokens::fromCode($source);
  428. /** @var Token[] $found */
  429. $found = $tokens->findGivenKind(T_CLASS);
  430. static::assertCount(1, $found);
  431. static::assertArrayHasKey(1, $found);
  432. static::assertSame(T_CLASS, $found[1]->getId());
  433. $found = $tokens->findGivenKind([T_CLASS, T_FUNCTION]);
  434. static::assertCount(2, $found);
  435. static::assertArrayHasKey(T_CLASS, $found);
  436. static::assertIsArray($found[T_CLASS]);
  437. static::assertCount(1, $found[T_CLASS]);
  438. static::assertArrayHasKey(1, $found[T_CLASS]);
  439. static::assertSame(T_CLASS, $found[T_CLASS][1]->getId());
  440. static::assertArrayHasKey(T_FUNCTION, $found);
  441. static::assertIsArray($found[T_FUNCTION]);
  442. static::assertCount(2, $found[T_FUNCTION]);
  443. static::assertArrayHasKey(9, $found[T_FUNCTION]);
  444. static::assertSame(T_FUNCTION, $found[T_FUNCTION][9]->getId());
  445. static::assertArrayHasKey(26, $found[T_FUNCTION]);
  446. static::assertSame(T_FUNCTION, $found[T_FUNCTION][26]->getId());
  447. // test offset and limits of the search
  448. $found = $tokens->findGivenKind([T_CLASS, T_FUNCTION], 10);
  449. static::assertCount(0, $found[T_CLASS]);
  450. static::assertCount(1, $found[T_FUNCTION]);
  451. static::assertArrayHasKey(26, $found[T_FUNCTION]);
  452. $found = $tokens->findGivenKind([T_CLASS, T_FUNCTION], 2, 10);
  453. static::assertCount(0, $found[T_CLASS]);
  454. static::assertCount(1, $found[T_FUNCTION]);
  455. static::assertArrayHasKey(9, $found[T_FUNCTION]);
  456. }
  457. /**
  458. * @param Token[] $expected tokens
  459. * @param int[] $indexes to clear
  460. *
  461. * @dataProvider provideGetClearTokenAndMergeSurroundingWhitespaceCases
  462. */
  463. public function testClearTokenAndMergeSurroundingWhitespace(string $source, array $indexes, array $expected): void
  464. {
  465. $this->doTestClearTokens($source, $indexes, $expected);
  466. if (\count($indexes) > 1) {
  467. $this->doTestClearTokens($source, array_reverse($indexes), $expected);
  468. }
  469. }
  470. public function provideGetClearTokenAndMergeSurroundingWhitespaceCases(): array
  471. {
  472. $clearToken = new Token('');
  473. return [
  474. [
  475. '<?php if($a){}else{}',
  476. [7, 8, 9],
  477. [
  478. new Token([T_OPEN_TAG, '<?php ']),
  479. new Token([T_IF, 'if']),
  480. new Token('('),
  481. new Token([T_VARIABLE, '$a']),
  482. new Token(')'),
  483. new Token('{'),
  484. new Token('}'),
  485. $clearToken,
  486. $clearToken,
  487. $clearToken,
  488. ],
  489. ],
  490. [
  491. '<?php $a;/**/;',
  492. [2],
  493. [
  494. // <?php $a /**/;
  495. new Token([T_OPEN_TAG, '<?php ']),
  496. new Token([T_VARIABLE, '$a']),
  497. $clearToken,
  498. new Token([T_COMMENT, '/**/']),
  499. new Token(';'),
  500. ],
  501. ],
  502. [
  503. '<?php ; ; ;',
  504. [3],
  505. [
  506. // <?php ; ;
  507. new Token([T_OPEN_TAG, '<?php ']),
  508. new Token(';'),
  509. new Token([T_WHITESPACE, ' ']),
  510. $clearToken,
  511. $clearToken,
  512. new Token(';'),
  513. ],
  514. ],
  515. [
  516. '<?php ; ; ;',
  517. [1, 5],
  518. [
  519. // <?php ;
  520. new Token([T_OPEN_TAG, '<?php ']),
  521. new Token([T_WHITESPACE, ' ']),
  522. $clearToken,
  523. new Token(';'),
  524. new Token([T_WHITESPACE, ' ']),
  525. $clearToken,
  526. ],
  527. ],
  528. [
  529. '<?php ; ; ;',
  530. [1, 3],
  531. [
  532. // <?php ;
  533. new Token([T_OPEN_TAG, '<?php ']),
  534. new Token([T_WHITESPACE, ' ']),
  535. $clearToken,
  536. $clearToken,
  537. $clearToken,
  538. new Token(';'),
  539. ],
  540. ],
  541. [
  542. '<?php ; ; ;',
  543. [1],
  544. [
  545. // <?php ; ;
  546. new Token([T_OPEN_TAG, '<?php ']),
  547. new Token([T_WHITESPACE, ' ']),
  548. $clearToken,
  549. new Token(';'),
  550. new Token([T_WHITESPACE, ' ']),
  551. new Token(';'),
  552. ],
  553. ],
  554. ];
  555. }
  556. /**
  557. * @param ?int $expectedIndex
  558. *
  559. * @dataProvider provideTokenOfKindSiblingCases
  560. */
  561. public function testTokenOfKindSibling(
  562. ?int $expectedIndex,
  563. int $direction,
  564. int $index,
  565. array $findTokens,
  566. bool $caseSensitive = true
  567. ): void {
  568. $source =
  569. '<?php
  570. $a = function ($b) {
  571. return $b;
  572. };
  573. echo $a(1);
  574. // test
  575. return 123;';
  576. Tokens::clearCache();
  577. $tokens = Tokens::fromCode($source);
  578. if (1 === $direction) {
  579. static::assertSame($expectedIndex, $tokens->getNextTokenOfKind($index, $findTokens, $caseSensitive));
  580. } else {
  581. static::assertSame($expectedIndex, $tokens->getPrevTokenOfKind($index, $findTokens, $caseSensitive));
  582. }
  583. static::assertSame($expectedIndex, $tokens->getTokenOfKindSibling($index, $direction, $findTokens, $caseSensitive));
  584. }
  585. public function provideTokenOfKindSiblingCases(): array
  586. {
  587. return [
  588. // find next cases
  589. [
  590. 35, 1, 34, [';'],
  591. ],
  592. [
  593. 14, 1, 0, [[T_RETURN]],
  594. ],
  595. [
  596. 32, 1, 14, [[T_RETURN]],
  597. ],
  598. [
  599. 6, 1, 0, [[T_RETURN], [T_FUNCTION]],
  600. ],
  601. // find previous cases
  602. [
  603. 14, -1, 32, [[T_RETURN], [T_FUNCTION]],
  604. ],
  605. [
  606. 6, -1, 7, [[T_FUNCTION]],
  607. ],
  608. [
  609. null, -1, 6, [[T_FUNCTION]],
  610. ],
  611. ];
  612. }
  613. /**
  614. * @dataProvider provideFindBlockEndCases
  615. */
  616. public function testFindBlockEnd(int $expectedIndex, string $source, int $type, int $searchIndex): void
  617. {
  618. static::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
  619. }
  620. public function provideFindBlockEndCases(): array
  621. {
  622. return [
  623. [4, '<?php ${$bar};', Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, 2],
  624. [4, '<?php test(1);', Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2],
  625. [4, '<?php $a{1};', Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, 2],
  626. [4, '<?php $a[1];', Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, 2],
  627. [6, '<?php [1, "foo"];', Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, 1],
  628. [5, '<?php $foo->{$bar};', Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, 3],
  629. [4, '<?php list($a) = $b;', Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2],
  630. [6, '<?php if($a){}?>', Tokens::BLOCK_TYPE_CURLY_BRACE, 5],
  631. [11, '<?php $foo = (new Foo());', Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, 5],
  632. [10, '<?php $object->{"set_{$name}"}(42);', Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, 3],
  633. [19, '<?php $foo = (new class () implements Foo {});', Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, 5],
  634. [10, '<?php use a\{ClassA, ClassB};', Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, 5],
  635. [3, '<?php [$a] = $array;', Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, 1],
  636. ];
  637. }
  638. /**
  639. * @requires PHP 8.0
  640. * @dataProvider provideFindBlockEnd80Cases
  641. */
  642. public function testFindBlockEnd80(int $expectedIndex, string $source, int $type, int $searchIndex): void
  643. {
  644. static::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
  645. }
  646. public function provideFindBlockEnd80Cases(): array
  647. {
  648. return [
  649. [
  650. 9,
  651. '<?php class Foo {
  652. #[Required]
  653. public $bar;
  654. }',
  655. Tokens::BLOCK_TYPE_ATTRIBUTE,
  656. 7,
  657. ],
  658. ];
  659. }
  660. public function testFindBlockEndInvalidType(): void
  661. {
  662. $this->expectException(\InvalidArgumentException::class);
  663. $this->expectExceptionMessageMatches('/^Invalid param type: "-1"\.$/');
  664. Tokens::clearCache();
  665. $tokens = Tokens::fromCode('<?php ');
  666. $tokens->findBlockEnd(-1, 0);
  667. }
  668. public function testFindBlockEndInvalidStart(): void
  669. {
  670. $this->expectException(\InvalidArgumentException::class);
  671. $this->expectExceptionMessageMatches('/^Invalid param \$startIndex - not a proper block "start"\.$/');
  672. Tokens::clearCache();
  673. $tokens = Tokens::fromCode('<?php ');
  674. $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, 0);
  675. }
  676. public function testFindBlockEndCalledMultipleTimes(): void
  677. {
  678. Tokens::clearCache();
  679. $tokens = Tokens::fromCode('<?php foo(1, 2);');
  680. static::assertSame(7, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2));
  681. $this->expectException(\InvalidArgumentException::class);
  682. $this->expectExceptionMessageMatches('/^Invalid param \$startIndex - not a proper block "start"\.$/');
  683. $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 7);
  684. }
  685. public function testFindBlockStartEdgeCalledMultipleTimes(): void
  686. {
  687. Tokens::clearCache();
  688. $tokens = Tokens::fromCode('<?php foo(1, 2);');
  689. static::assertSame(2, $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 7));
  690. $this->expectException(\InvalidArgumentException::class);
  691. $this->expectExceptionMessageMatches('/^Invalid param \$startIndex - not a proper block "end"\.$/');
  692. $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2);
  693. }
  694. public function testEmptyTokens(): void
  695. {
  696. $code = '';
  697. $tokens = Tokens::fromCode($code);
  698. static::assertCount(0, $tokens);
  699. static::assertFalse($tokens->isTokenKindFound(T_OPEN_TAG));
  700. }
  701. public function testEmptyTokensMultiple(): void
  702. {
  703. $code = '';
  704. $tokens = Tokens::fromCode($code);
  705. static::assertFalse($tokens->isChanged());
  706. $tokens->insertAt(0, new Token([T_WHITESPACE, ' ']));
  707. static::assertCount(1, $tokens);
  708. static::assertFalse($tokens->isTokenKindFound(T_OPEN_TAG));
  709. static::assertTrue($tokens->isChanged());
  710. $tokens2 = Tokens::fromCode($code);
  711. static::assertCount(0, $tokens2);
  712. static::assertFalse($tokens->isTokenKindFound(T_OPEN_TAG));
  713. }
  714. public function testFromArray(): void
  715. {
  716. $code = '<?php echo 1;';
  717. $tokens1 = Tokens::fromCode($code);
  718. $tokens2 = Tokens::fromArray($tokens1->toArray());
  719. static::assertTrue($tokens1->isTokenKindFound(T_OPEN_TAG));
  720. static::assertTrue($tokens2->isTokenKindFound(T_OPEN_TAG));
  721. static::assertSame($tokens1->getCodeHash(), $tokens2->getCodeHash());
  722. }
  723. public function testFromArrayEmpty(): void
  724. {
  725. $tokens = Tokens::fromArray([]);
  726. static::assertFalse($tokens->isTokenKindFound(T_OPEN_TAG));
  727. }
  728. /**
  729. * @dataProvider provideIsEmptyCases
  730. */
  731. public function testIsEmpty(Token $token, bool $isEmpty): void
  732. {
  733. $tokens = Tokens::fromArray([$token]);
  734. Tokens::clearCache();
  735. static::assertSame($isEmpty, $tokens->isEmptyAt(0), $token->toJson());
  736. }
  737. public function provideIsEmptyCases(): array
  738. {
  739. return [
  740. [new Token(''), true],
  741. [new Token('('), false],
  742. [new Token([T_WHITESPACE, ' ']), false],
  743. ];
  744. }
  745. public function testClone(): void
  746. {
  747. $code = '<?php echo 1;';
  748. $tokens = Tokens::fromCode($code);
  749. $tokensClone = clone $tokens;
  750. static::assertTrue($tokens->isTokenKindFound(T_OPEN_TAG));
  751. static::assertTrue($tokensClone->isTokenKindFound(T_OPEN_TAG));
  752. $count = \count($tokens);
  753. static::assertCount($count, $tokensClone);
  754. for ($i = 0; $i < $count; ++$i) {
  755. static::assertTrue($tokens[$i]->equals($tokensClone[$i]));
  756. static::assertNotSame($tokens[$i], $tokensClone[$i]);
  757. }
  758. }
  759. /**
  760. * @dataProvider provideEnsureWhitespaceAtIndexCases
  761. */
  762. public function testEnsureWhitespaceAtIndex(string $expected, string $input, int $index, int $offset, string $whiteSpace): void
  763. {
  764. $tokens = Tokens::fromCode($input);
  765. $tokens->ensureWhitespaceAtIndex($index, $offset, $whiteSpace);
  766. $tokens->clearEmptyTokens();
  767. static::assertTokens(Tokens::fromCode($expected), $tokens);
  768. }
  769. public function provideEnsureWhitespaceAtIndexCases(): array
  770. {
  771. return [
  772. [
  773. '<?php echo 1;',
  774. '<?php echo 1;',
  775. 1,
  776. 1,
  777. ' ',
  778. ],
  779. [
  780. '<?php echo 7;',
  781. '<?php echo 7;',
  782. 1,
  783. 1,
  784. ' ',
  785. ],
  786. [
  787. '<?php ',
  788. '<?php ',
  789. 1,
  790. 1,
  791. ' ',
  792. ],
  793. [
  794. '<?php $a. $b;',
  795. '<?php $a.$b;',
  796. 2,
  797. 1,
  798. ' ',
  799. ],
  800. [
  801. '<?php $a .$b;',
  802. '<?php $a.$b;',
  803. 2,
  804. 0,
  805. ' ',
  806. ],
  807. [
  808. "<?php\r\n",
  809. '<?php ',
  810. 0,
  811. 1,
  812. "\r\n",
  813. ],
  814. [
  815. '<?php $a.$b;',
  816. '<?php $a.$b;',
  817. 2,
  818. -1,
  819. ' ',
  820. ],
  821. [
  822. "<?php\t ",
  823. "<?php\n",
  824. 0,
  825. 1,
  826. "\t ",
  827. ],
  828. [
  829. '<?php ',
  830. '<?php ',
  831. 0,
  832. 1,
  833. ' ',
  834. ],
  835. [
  836. "<?php\n",
  837. '<?php ',
  838. 0,
  839. 1,
  840. "\n",
  841. ],
  842. [
  843. "<?php\t",
  844. '<?php ',
  845. 0,
  846. 1,
  847. "\t",
  848. ],
  849. [
  850. '<?php
  851. //
  852. echo $a;',
  853. '<?php
  854. //
  855. echo $a;',
  856. 2,
  857. 1,
  858. "\n ",
  859. ],
  860. [
  861. '<?php
  862. echo $a;',
  863. '<?php
  864. echo $a;',
  865. 0,
  866. 1,
  867. "\n ",
  868. ],
  869. [
  870. '<?php
  871. echo $a;',
  872. '<?php echo $a;',
  873. 0,
  874. 1,
  875. "\n",
  876. ],
  877. [
  878. "<?php\techo \$a;",
  879. '<?php echo $a;',
  880. 0,
  881. 1,
  882. "\t",
  883. ],
  884. ];
  885. }
  886. public function testAssertTokensAfterChanging(): void
  887. {
  888. $template =
  889. '<?php class SomeClass {
  890. %s//
  891. public function __construct($name)
  892. {
  893. $this->name = $name;
  894. }
  895. }';
  896. $tokens = Tokens::fromCode(sprintf($template, ''));
  897. $commentIndex = $tokens->getNextTokenOfKind(0, [[T_COMMENT]]);
  898. $tokens->insertAt(
  899. $commentIndex,
  900. [
  901. new Token([T_PRIVATE, 'private']),
  902. new Token([T_WHITESPACE, ' ']),
  903. new Token([T_VARIABLE, '$name']),
  904. new Token(';'),
  905. ]
  906. );
  907. static::assertTrue($tokens->isChanged());
  908. $expected = Tokens::fromCode(sprintf($template, 'private $name;'));
  909. static::assertFalse($expected->isChanged());
  910. static::assertTokens($expected, $tokens);
  911. }
  912. /**
  913. * @dataProvider provideRemoveLeadingWhitespaceCases
  914. */
  915. public function testRemoveLeadingWhitespace(int $index, ?string $whitespaces, string $expected, string $input = null): void
  916. {
  917. Tokens::clearCache();
  918. $tokens = Tokens::fromCode($input ?? $expected);
  919. $tokens->removeLeadingWhitespace($index, $whitespaces);
  920. static::assertSame($expected, $tokens->generateCode());
  921. }
  922. public function provideRemoveLeadingWhitespaceCases(): array
  923. {
  924. return [
  925. [
  926. 7,
  927. null,
  928. "<?php echo 1;//\necho 2;",
  929. ],
  930. [
  931. 7,
  932. null,
  933. "<?php echo 1;//\necho 2;",
  934. "<?php echo 1;//\n echo 2;",
  935. ],
  936. [
  937. 7,
  938. null,
  939. "<?php echo 1;//\r\necho 2;",
  940. "<?php echo 1;//\r\n echo 2;",
  941. ],
  942. [
  943. 7,
  944. " \t",
  945. "<?php echo 1;//\n//",
  946. "<?php echo 1;//\n //",
  947. ],
  948. [
  949. 6,
  950. "\t ",
  951. '<?php echo 1;//',
  952. "<?php echo 1;\t \t \t //",
  953. ],
  954. [
  955. 8,
  956. null,
  957. '<?php $a = 1;//',
  958. '<?php $a = 1; //',
  959. ],
  960. [
  961. 6,
  962. null,
  963. '<?php echo 1;echo 2;',
  964. "<?php echo 1; \n \n \n \necho 2;",
  965. ],
  966. [
  967. 8,
  968. null,
  969. "<?php echo 1; // 1\necho 2;",
  970. "<?php echo 1; // 1\n \n \n \necho 2;",
  971. ],
  972. ];
  973. }
  974. /**
  975. * @dataProvider provideRemoveTrailingWhitespaceCases
  976. */
  977. public function testRemoveTrailingWhitespace(int $index, ?string $whitespaces, string $expected, string $input = null): void
  978. {
  979. Tokens::clearCache();
  980. $tokens = Tokens::fromCode($input ?? $expected);
  981. $tokens->removeTrailingWhitespace($index, $whitespaces);
  982. static::assertSame($expected, $tokens->generateCode());
  983. }
  984. public function provideRemoveTrailingWhitespaceCases(): \Generator
  985. {
  986. $leadingCases = $this->provideRemoveLeadingWhitespaceCases();
  987. foreach ($leadingCases as $leadingCase) {
  988. $leadingCase[0] -= 2;
  989. yield $leadingCase;
  990. }
  991. }
  992. public function testRemovingLeadingWhitespaceWithEmptyTokenInCollection(): void
  993. {
  994. $code = "<?php\n /* I will be removed */MY_INDEX_IS_THREE;foo();";
  995. $tokens = Tokens::fromCode($code);
  996. $tokens->clearAt(2);
  997. $tokens->removeLeadingWhitespace(3);
  998. $tokens->clearEmptyTokens();
  999. static::assertTokens(Tokens::fromCode("<?php\nMY_INDEX_IS_THREE;foo();"), $tokens);
  1000. }
  1001. public function testRemovingTrailingWhitespaceWithEmptyTokenInCollection(): void
  1002. {
  1003. $code = "<?php\nMY_INDEX_IS_ONE/* I will be removed */ ;foo();";
  1004. $tokens = Tokens::fromCode($code);
  1005. $tokens->clearAt(2);
  1006. $tokens->removeTrailingWhitespace(1);
  1007. $tokens->clearEmptyTokens();
  1008. static::assertTokens(Tokens::fromCode("<?php\nMY_INDEX_IS_ONE;foo();"), $tokens);
  1009. }
  1010. /**
  1011. * Action that begins with the word "remove" should not change the size of collection.
  1012. */
  1013. public function testRemovingLeadingWhitespaceWillNotIncreaseTokensCount(): void
  1014. {
  1015. $tokens = Tokens::fromCode('<?php
  1016. // Foo
  1017. $bar;');
  1018. $originalCount = $tokens->count();
  1019. $tokens->removeLeadingWhitespace(4);
  1020. static::assertSame($originalCount, $tokens->count());
  1021. static::assertSame(
  1022. '<?php
  1023. // Foo
  1024. $bar;',
  1025. $tokens->generateCode()
  1026. );
  1027. }
  1028. /**
  1029. * Action that begins with the word "remove" should not change the size of collection.
  1030. */
  1031. public function testRemovingTrailingWhitespaceWillNotIncreaseTokensCount(): void
  1032. {
  1033. $tokens = Tokens::fromCode('<?php
  1034. // Foo
  1035. $bar;');
  1036. $originalCount = $tokens->count();
  1037. $tokens->removeTrailingWhitespace(2);
  1038. static::assertSame($originalCount, $tokens->count());
  1039. static::assertSame(
  1040. '<?php
  1041. // Foo
  1042. $bar;',
  1043. $tokens->generateCode()
  1044. );
  1045. }
  1046. /**
  1047. * @dataProvider provideDetectBlockTypeCases
  1048. */
  1049. public function testDetectBlockType(?array $expected, string $code, int $index): void
  1050. {
  1051. $tokens = Tokens::fromCode($code);
  1052. static::assertSame($expected, Tokens::detectBlockType($tokens[$index]));
  1053. }
  1054. public function provideDetectBlockTypeCases(): \Generator
  1055. {
  1056. yield [
  1057. [
  1058. 'type' => Tokens::BLOCK_TYPE_CURLY_BRACE,
  1059. 'isStart' => true,
  1060. ],
  1061. '<?php { echo 1; }',
  1062. 1,
  1063. ];
  1064. yield [
  1065. null,
  1066. '<?php { echo 1;}',
  1067. 0,
  1068. ];
  1069. }
  1070. public function testOverrideRangeTokens(): void
  1071. {
  1072. $expected = [
  1073. new Token([T_OPEN_TAG, '<?php ']),
  1074. new Token([T_FUNCTION, 'function']),
  1075. new Token([T_WHITESPACE, ' ']),
  1076. new Token([T_STRING, 'foo']),
  1077. new Token('('),
  1078. new Token([T_ARRAY, 'array']),
  1079. new Token([T_WHITESPACE, ' ']),
  1080. new Token([T_VARIABLE, '$bar']),
  1081. new Token(')'),
  1082. new Token('{'),
  1083. new Token('}'),
  1084. ];
  1085. $code = '<?php function foo(array $bar){}';
  1086. $indexStart = 5;
  1087. $indexEnd = 5;
  1088. $items = Tokens::fromArray([new Token([T_ARRAY, 'array'])]);
  1089. $tokens = Tokens::fromCode($code);
  1090. $tokens->overrideRange($indexStart, $indexEnd, $items);
  1091. $tokens->clearEmptyTokens();
  1092. self::assertTokens(Tokens::fromArray($expected), $tokens);
  1093. }
  1094. /**
  1095. * @param int $indexStart start overriding index
  1096. * @param int $indexEnd end overriding index
  1097. * @param array<Token> $items tokens to insert
  1098. *
  1099. * @dataProvider provideOverrideRangeCases
  1100. */
  1101. public function testOverrideRange(array $expected, string $code, int $indexStart, int $indexEnd, array $items): void
  1102. {
  1103. $tokens = Tokens::fromCode($code);
  1104. $tokens->overrideRange($indexStart, $indexEnd, $items);
  1105. $tokens->clearEmptyTokens();
  1106. self::assertTokens(Tokens::fromArray($expected), $tokens);
  1107. }
  1108. public function provideOverrideRangeCases(): \Generator
  1109. {
  1110. // typically done by transformers, here we test the reverse
  1111. yield 'override different tokens but same content' => [
  1112. [
  1113. new Token([T_OPEN_TAG, '<?php ']),
  1114. new Token([T_FUNCTION, 'function']),
  1115. new Token([T_WHITESPACE, ' ']),
  1116. new Token([T_STRING, 'foo']),
  1117. new Token('('),
  1118. new Token([T_ARRAY, 'array']),
  1119. new Token([T_WHITESPACE, ' ']),
  1120. new Token([T_VARIABLE, '$bar']),
  1121. new Token(')'),
  1122. new Token('{'),
  1123. new Token('}'),
  1124. ],
  1125. '<?php function foo(array $bar){}',
  1126. 5,
  1127. 5,
  1128. [new Token([T_ARRAY, 'array'])],
  1129. ];
  1130. yield 'add more item than in range' => [
  1131. [
  1132. new Token([T_OPEN_TAG, "<?php\n"]),
  1133. new Token([T_COMMENT, '// test']),
  1134. new Token([T_WHITESPACE, "\n"]),
  1135. new Token([T_COMMENT, '// test']),
  1136. new Token([T_WHITESPACE, "\n"]),
  1137. new Token([T_COMMENT, '// test']),
  1138. new Token([T_WHITESPACE, "\n"]),
  1139. ],
  1140. "<?php\n#comment",
  1141. 1,
  1142. 1,
  1143. [
  1144. new Token([T_COMMENT, '// test']),
  1145. new Token([T_WHITESPACE, "\n"]),
  1146. new Token([T_COMMENT, '// test']),
  1147. new Token([T_WHITESPACE, "\n"]),
  1148. new Token([T_COMMENT, '// test']),
  1149. new Token([T_WHITESPACE, "\n"]),
  1150. ],
  1151. ];
  1152. yield [
  1153. [
  1154. new Token([T_OPEN_TAG, "<?php\n"]),
  1155. new Token([T_COMMENT, '#comment1']),
  1156. new Token([T_WHITESPACE, "\n"]),
  1157. new Token([T_COMMENT, '// test 1']),
  1158. new Token([T_WHITESPACE, "\n"]),
  1159. new Token([T_COMMENT, '#comment5']),
  1160. new Token([T_WHITESPACE, "\n"]),
  1161. new Token([T_COMMENT, '#comment6']),
  1162. ],
  1163. "<?php\n#comment1\n#comment2\n#comment3\n#comment4\n#comment5\n#comment6",
  1164. 3,
  1165. 7,
  1166. [
  1167. new Token([T_COMMENT, '// test 1']),
  1168. ],
  1169. ];
  1170. yield [
  1171. [
  1172. new Token([T_OPEN_TAG, "<?php\n"]),
  1173. new Token([T_COMMENT, '// test']),
  1174. ],
  1175. "<?php\n#comment1\n#comment2\n#comment3\n#comment4\n#comment5\n#comment6\n#comment7",
  1176. 1,
  1177. 13,
  1178. [
  1179. new Token([T_COMMENT, '// test']),
  1180. ],
  1181. ];
  1182. yield [
  1183. [
  1184. new Token([T_OPEN_TAG, "<?php\n"]),
  1185. new Token([T_COMMENT, '// test']),
  1186. ],
  1187. "<?php\n#comment",
  1188. 1,
  1189. 1,
  1190. [
  1191. new Token([T_COMMENT, '// test']),
  1192. ],
  1193. ];
  1194. }
  1195. public function testInitialChangedState(): void
  1196. {
  1197. $tokens = Tokens::fromCode("<?php\n");
  1198. static::assertFalse($tokens->isChanged());
  1199. $tokens = Tokens::fromArray(
  1200. [
  1201. new Token([T_OPEN_TAG, "<?php\n"]),
  1202. new Token([T_STRING, 'Foo']),
  1203. new Token(';'),
  1204. ]
  1205. );
  1206. static::assertFalse($tokens->isChanged());
  1207. }
  1208. /**
  1209. * @dataProvider provideGetMeaningfulTokenSiblingCases
  1210. */
  1211. public function testGetMeaningfulTokenSibling(?int $expectIndex, int $index, int $direction, string $source): void
  1212. {
  1213. Tokens::clearCache();
  1214. $tokens = Tokens::fromCode($source);
  1215. static::assertSame($expectIndex, $tokens->getMeaningfulTokenSibling($index, $direction));
  1216. }
  1217. public function provideGetMeaningfulTokenSiblingCases(): \Generator
  1218. {
  1219. yield [null, 0, 1, '<?php '];
  1220. yield [null, 1, 1, '<?php /**/ /**/ /**/ /**/#'];
  1221. for ($i = 0; $i < 3; ++$i) {
  1222. yield '>'.$i => [3, $i, 1, '<?php /**/ foo();'];
  1223. }
  1224. yield '>>' => [4, 3, 1, '<?php /**/ foo();'];
  1225. yield '@ end' => [null, 6, 1, '<?php /**/ foo();'];
  1226. yield 'over end' => [null, 888, 1, '<?php /**/ foo();'];
  1227. yield [0, 3, -1, '<?php /**/ foo();'];
  1228. yield [4, 5, -1, '<?php /**/ foo();'];
  1229. yield [5, 6, -1, '<?php /**/ foo();'];
  1230. yield [null, 0, -1, '<?php /**/ foo();'];
  1231. }
  1232. private static function assertFindBlockEnd(int $expectedIndex, string $source, int $type, int $searchIndex): void
  1233. {
  1234. Tokens::clearCache();
  1235. $tokens = Tokens::fromCode($source);
  1236. static::assertSame($expectedIndex, $tokens->findBlockEnd($type, $searchIndex));
  1237. static::assertSame($searchIndex, $tokens->findBlockStart($type, $expectedIndex));
  1238. $detectedType = Tokens::detectBlockType($tokens[$searchIndex]);
  1239. static::assertIsArray($detectedType);
  1240. static::assertArrayHasKey('type', $detectedType);
  1241. static::assertArrayHasKey('isStart', $detectedType);
  1242. static::assertSame($type, $detectedType['type']);
  1243. static::assertTrue($detectedType['isStart']);
  1244. $detectedType = Tokens::detectBlockType($tokens[$expectedIndex]);
  1245. static::assertIsArray($detectedType);
  1246. static::assertArrayHasKey('type', $detectedType);
  1247. static::assertArrayHasKey('isStart', $detectedType);
  1248. static::assertSame($type, $detectedType['type']);
  1249. static::assertFalse($detectedType['isStart']);
  1250. }
  1251. /**
  1252. * @param null|Token[] $expected
  1253. * @param null|Token[] $input
  1254. */
  1255. private static function assertEqualsTokensArray(array $expected = null, array $input = null): void
  1256. {
  1257. if (null === $expected) {
  1258. static::assertNull($input);
  1259. return;
  1260. }
  1261. if (null === $input) {
  1262. static::fail('While "input" is <null>, "expected" is not.');
  1263. }
  1264. static::assertSame(array_keys($expected), array_keys($input), 'Both arrays need to have same keys.');
  1265. foreach ($expected as $index => $expectedToken) {
  1266. static::assertTrue(
  1267. $expectedToken->equals($input[$index]),
  1268. sprintf('The token at index %d should be %s, got %s', $index, $expectedToken->toJson(), $input[$index]->toJson())
  1269. );
  1270. }
  1271. }
  1272. /**
  1273. * @param int[] $indexes
  1274. * @param Token[] $expected
  1275. */
  1276. private function doTestClearTokens(string $source, array $indexes, array $expected): void
  1277. {
  1278. Tokens::clearCache();
  1279. $tokens = Tokens::fromCode($source);
  1280. foreach ($indexes as $index) {
  1281. $tokens->clearTokenAndMergeSurroundingWhitespace($index);
  1282. }
  1283. static::assertSame(\count($expected), $tokens->count());
  1284. foreach ($expected as $index => $expectedToken) {
  1285. $token = $tokens[$index];
  1286. $expectedPrototype = $expectedToken->getPrototype();
  1287. if (\is_array($expectedPrototype)) {
  1288. unset($expectedPrototype[2]); // don't compare token lines as our token mutations don't deal with line numbers
  1289. }
  1290. static::assertTrue($token->equals($expectedPrototype), sprintf('The token at index %d should be %s, got %s', $index, json_encode($expectedPrototype), $token->toJson()));
  1291. }
  1292. }
  1293. }