TokensTest.php 52 KB

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