TokensTest.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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. /**
  1233. * @dataProvider provideInsertSlicesAtMultiplePlacesCases
  1234. *
  1235. * @param array<int, Token> $slices
  1236. */
  1237. public function testInsertSlicesAtMultiplePlaces(string $expected, array $slices): void
  1238. {
  1239. $input = <<<'EOF'
  1240. <?php
  1241. $after = get_class($after);
  1242. $before = get_class($before);
  1243. EOF;
  1244. $tokens = Tokens::fromCode($input);
  1245. $tokens->insertSlices([
  1246. 16 => $slices,
  1247. 6 => $slices,
  1248. ]);
  1249. static::assertSame($expected, $tokens->generateCode());
  1250. }
  1251. public function provideInsertSlicesAtMultiplePlacesCases(): \Generator
  1252. {
  1253. yield 'one slice count' => [
  1254. <<<'EOF'
  1255. <?php
  1256. $after = get_class($after);
  1257. $before = get_class($before);
  1258. EOF
  1259. ,
  1260. [new Token([T_WHITESPACE, ' '])],
  1261. ];
  1262. yield 'two slice count' => [
  1263. <<<'EOF'
  1264. <?php
  1265. $after = (string) get_class($after);
  1266. $before = (string) get_class($before);
  1267. EOF
  1268. ,
  1269. [new Token([T_STRING_CAST, '(string)']), new Token([T_WHITESPACE, ' '])],
  1270. ];
  1271. yield 'three slice count' => [
  1272. <<<'EOF'
  1273. <?php
  1274. $after = !(bool) get_class($after);
  1275. $before = !(bool) get_class($before);
  1276. EOF
  1277. ,
  1278. [new Token('!'), new Token([T_BOOL_CAST, '(bool)']), new Token([T_WHITESPACE, ' '])],
  1279. ];
  1280. }
  1281. public function testInsertSlicesChangesState(): void
  1282. {
  1283. $tokens = Tokens::fromCode('<?php echo 1234567890;');
  1284. static::assertFalse($tokens->isChanged());
  1285. static::assertFalse($tokens->isTokenKindFound(T_COMMENT));
  1286. static::assertSame(5, $tokens->getSize());
  1287. $tokens->insertSlices([1 => new Token([T_COMMENT, '/* comment */'])]);
  1288. static::assertTrue($tokens->isChanged());
  1289. static::assertTrue($tokens->isTokenKindFound(T_COMMENT));
  1290. static::assertSame(6, $tokens->getSize());
  1291. }
  1292. /**
  1293. * @dataProvider provideInsertSlicesCases
  1294. */
  1295. public function testInsertSlices(Tokens $expected, Tokens $tokens, array $slices): void
  1296. {
  1297. $tokens->insertSlices($slices);
  1298. static::assertTokens($expected, $tokens);
  1299. }
  1300. public function provideInsertSlicesCases(): iterable
  1301. {
  1302. // basic insert of single token at 3 different locations including appending as new token
  1303. $template = "<?php\n%s\n/* single token test header */%s\necho 1;\n%s";
  1304. $commentContent = '/* test */';
  1305. $commentToken = new Token([T_COMMENT, $commentContent]);
  1306. $from = Tokens::fromCode(sprintf($template, '', '', ''));
  1307. yield 'single insert @ 1' => [
  1308. Tokens::fromCode(sprintf($template, $commentContent, '', '')),
  1309. clone $from,
  1310. [1 => $commentToken],
  1311. ];
  1312. yield 'single insert @ 3' => [
  1313. Tokens::fromCode(sprintf($template, '', $commentContent, '')),
  1314. clone $from,
  1315. [3 => Tokens::fromArray([$commentToken])],
  1316. ];
  1317. yield 'single insert @ 9' => [
  1318. Tokens::fromCode(sprintf($template, '', '', $commentContent)),
  1319. clone $from,
  1320. [9 => [$commentToken]],
  1321. ];
  1322. // basic tests for single token, array of that token and tokens object with that token
  1323. $openTagToken = new Token([T_OPEN_TAG, "<?php\n"]);
  1324. $expected = Tokens::fromArray([$openTagToken]);
  1325. $slices = [
  1326. [0 => $openTagToken],
  1327. [0 => [clone $openTagToken]],
  1328. [0 => clone Tokens::fromArray([$openTagToken])],
  1329. ];
  1330. foreach ($slices as $i => $slice) {
  1331. yield 'insert open tag @ 0 into empty collection '.$i => [$expected, new Tokens(), $slice];
  1332. }
  1333. // test insert lists of tokens, index out of order
  1334. $setOne = [
  1335. new Token([T_ECHO, 'echo']),
  1336. new Token([T_WHITESPACE, ' ']),
  1337. new Token([T_CONSTANT_ENCAPSED_STRING, '"new"']),
  1338. new Token(';'),
  1339. ];
  1340. $setTwo = [
  1341. new Token([T_WHITESPACE, ' ']),
  1342. new Token([T_COMMENT, '/* new comment */']),
  1343. ];
  1344. $setThree = Tokens::fromArray([
  1345. new Token([T_VARIABLE, '$new']),
  1346. new Token([T_WHITESPACE, ' ']),
  1347. new Token('='),
  1348. new Token([T_WHITESPACE, ' ']),
  1349. new Token([T_LNUMBER, '8899']),
  1350. new Token(';'),
  1351. new Token([T_WHITESPACE, "\n"]),
  1352. ]);
  1353. $template = "<?php\n%s\n/* header */%s\necho 789;\n%s";
  1354. $expected = Tokens::fromCode(
  1355. sprintf(
  1356. $template,
  1357. 'echo "new";',
  1358. ' /* new comment */',
  1359. "\$new = 8899;\n"
  1360. )
  1361. );
  1362. $from = Tokens::fromCode(sprintf($template, '', '', ''));
  1363. yield 'insert 3 token collections' => [$expected, $from, [9 => $setThree, 1 => $setOne, 3 => $setTwo]];
  1364. $sets = [];
  1365. for ($j = 0; $j < 4; ++$j) {
  1366. $set = ['tokens' => [], 'content' => ''];
  1367. for ($i = 0; $i < 10; ++$i) {
  1368. $content = sprintf('/* new %d|%s */', $j, $i);
  1369. $set['tokens'][] = new Token([T_COMMENT, $content]);
  1370. $set['content'] .= $content;
  1371. }
  1372. $sets[$j] = $set;
  1373. }
  1374. yield 'overlapping inserts of bunch of comments ' => [
  1375. Tokens::fromCode(sprintf("<?php\n%s/* line 1 */\n%s/* line 2 */\n%s/* line 3 */%s", $sets[0]['content'], $sets[1]['content'], $sets[2]['content'], $sets[3]['content'])),
  1376. Tokens::fromCode("<?php\n/* line 1 */\n/* line 2 */\n/* line 3 */"),
  1377. [1 => $sets[0]['tokens'], 3 => $sets[1]['tokens'], 5 => $sets[2]['tokens'], 6 => $sets[3]['tokens']],
  1378. ];
  1379. }
  1380. private static function assertFindBlockEnd(int $expectedIndex, string $source, int $type, int $searchIndex): void
  1381. {
  1382. Tokens::clearCache();
  1383. $tokens = Tokens::fromCode($source);
  1384. static::assertSame($expectedIndex, $tokens->findBlockEnd($type, $searchIndex));
  1385. static::assertSame($searchIndex, $tokens->findBlockStart($type, $expectedIndex));
  1386. $detectedType = Tokens::detectBlockType($tokens[$searchIndex]);
  1387. static::assertIsArray($detectedType);
  1388. static::assertArrayHasKey('type', $detectedType);
  1389. static::assertArrayHasKey('isStart', $detectedType);
  1390. static::assertSame($type, $detectedType['type']);
  1391. static::assertTrue($detectedType['isStart']);
  1392. $detectedType = Tokens::detectBlockType($tokens[$expectedIndex]);
  1393. static::assertIsArray($detectedType);
  1394. static::assertArrayHasKey('type', $detectedType);
  1395. static::assertArrayHasKey('isStart', $detectedType);
  1396. static::assertSame($type, $detectedType['type']);
  1397. static::assertFalse($detectedType['isStart']);
  1398. }
  1399. /**
  1400. * @param null|Token[] $expected
  1401. * @param null|Token[] $input
  1402. */
  1403. private static function assertEqualsTokensArray(array $expected = null, array $input = null): void
  1404. {
  1405. if (null === $expected) {
  1406. static::assertNull($input);
  1407. return;
  1408. }
  1409. if (null === $input) {
  1410. static::fail('While "input" is <null>, "expected" is not.');
  1411. }
  1412. static::assertSame(array_keys($expected), array_keys($input), 'Both arrays need to have same keys.');
  1413. foreach ($expected as $index => $expectedToken) {
  1414. static::assertTrue(
  1415. $expectedToken->equals($input[$index]),
  1416. sprintf('The token at index %d should be %s, got %s', $index, $expectedToken->toJson(), $input[$index]->toJson())
  1417. );
  1418. }
  1419. }
  1420. /**
  1421. * @param int[] $indexes
  1422. * @param Token[] $expected
  1423. */
  1424. private function doTestClearTokens(string $source, array $indexes, array $expected): void
  1425. {
  1426. Tokens::clearCache();
  1427. $tokens = Tokens::fromCode($source);
  1428. foreach ($indexes as $index) {
  1429. $tokens->clearTokenAndMergeSurroundingWhitespace($index);
  1430. }
  1431. static::assertSame(\count($expected), $tokens->count());
  1432. foreach ($expected as $index => $expectedToken) {
  1433. $token = $tokens[$index];
  1434. $expectedPrototype = $expectedToken->getPrototype();
  1435. if (\is_array($expectedPrototype)) {
  1436. unset($expectedPrototype[2]); // don't compare token lines as our token mutations don't deal with line numbers
  1437. }
  1438. static::assertTrue($token->equals($expectedPrototype), sprintf('The token at index %d should be %s, got %s', $index, json_encode($expectedPrototype), $token->toJson()));
  1439. }
  1440. }
  1441. }