TokensAnalyzerTest.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136
  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\TestCase;
  14. use PhpCsFixer\Tokenizer\Tokens;
  15. use PhpCsFixer\Tokenizer\TokensAnalyzer;
  16. /**
  17. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  18. * @author Max Voloshin <voloshin.dp@gmail.com>
  19. * @author Gregor Harlan <gharlan@web.de>
  20. *
  21. * @internal
  22. *
  23. * @covers \PhpCsFixer\Tokenizer\TokensAnalyzer
  24. */
  25. final class TokensAnalyzerTest extends TestCase
  26. {
  27. /**
  28. * @param array<int, array{classIndex: int, type: string}> $expectedElements
  29. *
  30. * @dataProvider provideGetClassyElementsCases
  31. */
  32. public function testGetClassyElements(array $expectedElements, string $source): void
  33. {
  34. $tokens = Tokens::fromCode($source);
  35. array_walk(
  36. $expectedElements,
  37. static function (array &$element, int $index) use ($tokens): void {
  38. $element['token'] = $tokens[$index];
  39. ksort($element);
  40. }
  41. );
  42. $tokensAnalyzer = new TokensAnalyzer($tokens);
  43. self::assertSame(
  44. $expectedElements,
  45. $tokensAnalyzer->getClassyElements()
  46. );
  47. }
  48. public static function provideGetClassyElementsCases(): iterable
  49. {
  50. yield 'trait import' => [
  51. [
  52. 10 => [
  53. 'classIndex' => 4,
  54. 'type' => 'trait_import',
  55. ],
  56. 19 => [
  57. 'classIndex' => 4,
  58. 'type' => 'trait_import',
  59. ],
  60. 24 => [
  61. 'classIndex' => 4,
  62. 'type' => 'const',
  63. ],
  64. 35 => [
  65. 'classIndex' => 4,
  66. 'type' => 'method',
  67. ],
  68. 55 => [
  69. 'classIndex' => 49,
  70. 'type' => 'trait_import',
  71. ],
  72. 64 => [
  73. 'classIndex' => 49,
  74. 'type' => 'method',
  75. ],
  76. ],
  77. '<?php
  78. /** */
  79. class Foo
  80. {
  81. use A\B;
  82. //
  83. use Foo;
  84. const A = 1;
  85. public function foo()
  86. {
  87. $a = new class()
  88. {
  89. use Z; // nested trait import
  90. public function bar()
  91. {
  92. echo 123;
  93. }
  94. };
  95. $a->bar();
  96. }
  97. }',
  98. ];
  99. yield [
  100. [
  101. 9 => [
  102. 'classIndex' => 1,
  103. 'type' => 'property',
  104. ],
  105. 14 => [
  106. 'classIndex' => 1,
  107. 'type' => 'property',
  108. ],
  109. 19 => [
  110. 'classIndex' => 1,
  111. 'type' => 'property',
  112. ],
  113. 28 => [
  114. 'classIndex' => 1,
  115. 'type' => 'property',
  116. ],
  117. 42 => [
  118. 'classIndex' => 1,
  119. 'type' => 'const',
  120. ],
  121. 53 => [
  122. 'classIndex' => 1,
  123. 'type' => 'method',
  124. ],
  125. 83 => [
  126. 'classIndex' => 1,
  127. 'type' => 'method',
  128. ],
  129. 140 => [
  130. 'classIndex' => 1,
  131. 'type' => 'method',
  132. ],
  133. 164 => [
  134. 'classIndex' => 158,
  135. 'type' => 'const',
  136. ],
  137. 173 => [
  138. 'classIndex' => 158,
  139. 'type' => 'trait_import',
  140. ],
  141. ],
  142. <<<'PHP'
  143. <?php
  144. class Foo
  145. {
  146. public $prop0;
  147. protected $prop1;
  148. private $prop2 = 1;
  149. var $prop3 = array(1,2,3);
  150. const CONSTANT = 'constant value';
  151. public function bar4()
  152. {
  153. $a = 5;
  154. return " ({$a})";
  155. }
  156. public function bar5($data)
  157. {
  158. $message = $data;
  159. $example = function ($arg) use ($message) {
  160. echo $arg . ' ' . $message;
  161. };
  162. $example('hello');
  163. }function A(){}
  164. }
  165. function test(){}
  166. class Foo2
  167. {
  168. const CONSTANT = 'constant value';
  169. use Foo\Bar; // expected in the return value
  170. }
  171. PHP,
  172. ];
  173. }
  174. public function testGetClassyElementsWithNullableProperties(): void
  175. {
  176. $source = <<<'PHP'
  177. <?php
  178. class Foo
  179. {
  180. public int $prop0;
  181. protected ?array $prop1;
  182. private string $prop2 = 1;
  183. var ? Foo\Bar $prop3 = array(1,2,3);
  184. }
  185. PHP;
  186. $tokens = Tokens::fromCode($source);
  187. $tokensAnalyzer = new TokensAnalyzer($tokens);
  188. $elements = $tokensAnalyzer->getClassyElements();
  189. self::assertSame(
  190. [
  191. 11 => [
  192. 'classIndex' => 1,
  193. 'token' => $tokens[11],
  194. 'type' => 'property',
  195. ],
  196. 19 => [
  197. 'classIndex' => 1,
  198. 'token' => $tokens[19],
  199. 'type' => 'property',
  200. ],
  201. 26 => [
  202. 'classIndex' => 1,
  203. 'token' => $tokens[26],
  204. 'type' => 'property',
  205. ],
  206. 41 => [
  207. 'classIndex' => 1,
  208. 'token' => $tokens[41],
  209. 'type' => 'property',
  210. ],
  211. ],
  212. $elements
  213. );
  214. }
  215. public function testGetClassyElementsWithAnonymousClass(): void
  216. {
  217. $source = <<<'PHP'
  218. <?php
  219. class A {
  220. public $A;
  221. private function B()
  222. {
  223. return new class(){
  224. protected $level1;
  225. private function XYZ() {
  226. return new class(){private $level2 = 1;};
  227. }
  228. };
  229. }
  230. private function C() {
  231. }
  232. }
  233. function B() {} // do not count this
  234. PHP;
  235. $tokens = Tokens::fromCode($source);
  236. $tokensAnalyzer = new TokensAnalyzer($tokens);
  237. $elements = $tokensAnalyzer->getClassyElements();
  238. self::assertSame(
  239. [
  240. 9 => [
  241. 'classIndex' => 1,
  242. 'token' => $tokens[9],
  243. 'type' => 'property', // $A
  244. ],
  245. 14 => [
  246. 'classIndex' => 1,
  247. 'token' => $tokens[14],
  248. 'type' => 'method', // B
  249. ],
  250. 33 => [
  251. 'classIndex' => 26,
  252. 'token' => $tokens[33],
  253. 'type' => 'property', // $level1
  254. ],
  255. 38 => [
  256. 'classIndex' => 26,
  257. 'token' => $tokens[38],
  258. 'type' => 'method', // XYZ
  259. ],
  260. 56 => [
  261. 'classIndex' => 50,
  262. 'token' => $tokens[56],
  263. 'type' => 'property', // $level2
  264. ],
  265. 74 => [
  266. 'classIndex' => 1,
  267. 'token' => $tokens[74],
  268. 'type' => 'method', // C
  269. ],
  270. ],
  271. $elements
  272. );
  273. }
  274. public function testGetClassyElementsWithMultipleAnonymousClass(): void
  275. {
  276. $source = <<<'PHP'
  277. <?php class A0
  278. {
  279. public function AA0()
  280. {
  281. return new class
  282. {
  283. public function BB0()
  284. {
  285. }
  286. };
  287. }
  288. public function otherFunction0()
  289. {
  290. }
  291. }
  292. class A1
  293. {
  294. public function AA1()
  295. {
  296. return new class
  297. {
  298. public function BB1()
  299. {
  300. return new class
  301. {
  302. public function CC1()
  303. {
  304. return new class
  305. {
  306. public function DD1()
  307. {
  308. return new class{};
  309. }
  310. public function DD2()
  311. {
  312. return new class{};
  313. }
  314. };
  315. }
  316. };
  317. }
  318. public function BB2()
  319. {
  320. return new class
  321. {
  322. public function CC2()
  323. {
  324. return new class
  325. {
  326. public function DD2()
  327. {
  328. return new class{};
  329. }
  330. };
  331. }
  332. };
  333. }
  334. };
  335. }
  336. public function otherFunction1()
  337. {
  338. }
  339. }
  340. PHP;
  341. $tokens = Tokens::fromCode($source);
  342. $tokensAnalyzer = new TokensAnalyzer($tokens);
  343. $elements = $tokensAnalyzer->getClassyElements();
  344. self::assertSame(
  345. [
  346. 9 => [
  347. 'classIndex' => 1,
  348. 'token' => $tokens[9],
  349. 'type' => 'method',
  350. ],
  351. 27 => [
  352. 'classIndex' => 21,
  353. 'token' => $tokens[27],
  354. 'type' => 'method',
  355. ],
  356. 44 => [
  357. 'classIndex' => 1,
  358. 'token' => $tokens[44],
  359. 'type' => 'method',
  360. ],
  361. 64 => [
  362. 'classIndex' => 56,
  363. 'token' => $tokens[64],
  364. 'type' => 'method',
  365. ],
  366. 82 => [
  367. 'classIndex' => 76,
  368. 'token' => $tokens[82],
  369. 'type' => 'method',
  370. ],
  371. 100 => [
  372. 'classIndex' => 94,
  373. 'token' => $tokens[100],
  374. 'type' => 'method',
  375. ],
  376. 118 => [
  377. 'classIndex' => 112,
  378. 'token' => $tokens[118],
  379. 'type' => 'method',
  380. ],
  381. 139 => [
  382. 'classIndex' => 112,
  383. 'token' => $tokens[139],
  384. 'type' => 'method',
  385. ],
  386. 170 => [
  387. 'classIndex' => 76,
  388. 'token' => $tokens[170],
  389. 'type' => 'method',
  390. ],
  391. 188 => [
  392. 'classIndex' => 182,
  393. 'token' => $tokens[188],
  394. 'type' => 'method',
  395. ],
  396. 206 => [
  397. 'classIndex' => 200,
  398. 'token' => $tokens[206],
  399. 'type' => 'method',
  400. ],
  401. 242 => [
  402. 'classIndex' => 56,
  403. 'token' => $tokens[242],
  404. 'type' => 'method',
  405. ],
  406. ],
  407. $elements
  408. );
  409. }
  410. public function testGetClassyElements74(): void
  411. {
  412. $source = <<<'PHP'
  413. <?php
  414. class Foo
  415. {
  416. public int $bar = 3;
  417. protected ?string $baz;
  418. private ?string $bazNull = null;
  419. public static iterable $staticProp;
  420. public float $x, $y;
  421. var bool $flag1;
  422. var ?bool $flag2;
  423. }
  424. PHP;
  425. $tokens = Tokens::fromCode($source);
  426. $tokensAnalyzer = new TokensAnalyzer($tokens);
  427. $elements = $tokensAnalyzer->getClassyElements();
  428. $expected = [];
  429. foreach ([11, 23, 31, 44, 51, 54, 61, 69] as $index) {
  430. $expected[$index] = [
  431. 'classIndex' => 1,
  432. 'token' => $tokens[$index],
  433. 'type' => 'property',
  434. ];
  435. }
  436. self::assertSame($expected, $elements);
  437. }
  438. /**
  439. * @param array<int, array{classIndex: int, type: string}> $expected
  440. *
  441. * @dataProvider provideGetClassyElements81Cases
  442. *
  443. * @requires PHP 8.1
  444. */
  445. public function testGetClassyElements81(array $expected, string $source): void
  446. {
  447. $tokens = Tokens::fromCode($source);
  448. $tokensAnalyzer = new TokensAnalyzer($tokens);
  449. $elements = $tokensAnalyzer->getClassyElements();
  450. array_walk(
  451. $expected,
  452. static function (array &$element, int $index) use ($tokens): void {
  453. $element['token'] = $tokens[$index];
  454. ksort($element);
  455. }
  456. );
  457. self::assertSame($expected, $elements);
  458. }
  459. public static function provideGetClassyElements81Cases(): iterable
  460. {
  461. yield [
  462. [
  463. 11 => [
  464. 'classIndex' => 1,
  465. 'type' => 'property', // $prop1
  466. ],
  467. 20 => [
  468. 'classIndex' => 1,
  469. 'type' => 'property', // $prop2
  470. ],
  471. 29 => [
  472. 'classIndex' => 1,
  473. 'type' => 'property', // $prop13
  474. ],
  475. ],
  476. '<?php
  477. class Foo
  478. {
  479. readonly string $prop1;
  480. readonly public string $prop2;
  481. public readonly string $prop3;
  482. }
  483. ',
  484. ];
  485. yield 'final const' => [
  486. [
  487. 11 => [
  488. 'classIndex' => 1,
  489. 'type' => 'const', // A
  490. ],
  491. 24 => [
  492. 'classIndex' => 1,
  493. 'type' => 'const', // B
  494. ],
  495. ],
  496. '<?php
  497. class Foo
  498. {
  499. final public const A = "1";
  500. public final const B = "2";
  501. }
  502. ',
  503. ];
  504. yield 'enum final const' => [
  505. [
  506. 11 => [
  507. 'classIndex' => 1,
  508. 'type' => 'const', // A
  509. ],
  510. 24 => [
  511. 'classIndex' => 1,
  512. 'type' => 'const', // B
  513. ],
  514. ],
  515. '<?php
  516. enum Foo
  517. {
  518. final public const A = "1";
  519. public final const B = "2";
  520. }
  521. ',
  522. ];
  523. yield 'enum case' => [
  524. [
  525. 12 => [
  526. 'classIndex' => 1,
  527. 'type' => 'const', // Spades
  528. ],
  529. 21 => [
  530. 'classIndex' => 1,
  531. 'type' => 'case', // Hearts
  532. ],
  533. 32 => [
  534. 'classIndex' => 1,
  535. 'type' => 'method', // function tests
  536. ],
  537. 81 => [
  538. 'classIndex' => 75,
  539. 'type' => 'method', // function bar123
  540. ],
  541. 135 => [
  542. 'classIndex' => 127,
  543. 'type' => 'method', // function bar7
  544. ],
  545. ],
  546. '<?php
  547. enum Foo: string
  548. {
  549. private const Spades = 123;
  550. case Hearts = "H";
  551. private function test($foo) {
  552. switch ($foo) {
  553. case 1:
  554. // case 2
  555. case 3:
  556. echo 123;
  557. break;
  558. }
  559. return new class {
  560. public function bar123($foo) {
  561. switch ($foo) {
  562. case 1:
  563. // case 2
  564. case 3:
  565. echo 123;
  566. };
  567. }
  568. };
  569. }
  570. }
  571. class Bar {
  572. public function bar7($foo) {
  573. switch ($foo) {
  574. case 1:
  575. // case 2
  576. case 3:
  577. echo 123;
  578. };
  579. }
  580. }
  581. ',
  582. ];
  583. yield 'enum' => [
  584. [
  585. 10 => [
  586. 'classIndex' => 1,
  587. 'type' => 'case',
  588. ],
  589. 19 => [
  590. 'classIndex' => 1,
  591. 'type' => 'case',
  592. ],
  593. 28 => [
  594. 'classIndex' => 1,
  595. 'type' => 'method',
  596. ],
  597. ],
  598. '<?php
  599. enum Foo: string
  600. {
  601. case Bar = "bar";
  602. case Baz = "baz";
  603. function qux() {
  604. switch (true) {
  605. case "x": break;
  606. }
  607. }
  608. }
  609. ',
  610. ];
  611. }
  612. /**
  613. * @param array<int, array{classIndex: int, type: string}> $expected
  614. *
  615. * @dataProvider provideGetClassyElements82Cases
  616. *
  617. * @requires PHP 8.2
  618. */
  619. public function testGetClassyElements82(array $expected, string $source): void
  620. {
  621. $tokens = Tokens::fromCode($source);
  622. $tokensAnalyzer = new TokensAnalyzer($tokens);
  623. $elements = $tokensAnalyzer->getClassyElements();
  624. array_walk(
  625. $expected,
  626. static function (array &$element, int $index) use ($tokens): void {
  627. $element['token'] = $tokens[$index];
  628. ksort($element);
  629. },
  630. );
  631. self::assertSame($expected, $elements);
  632. }
  633. public static function provideGetClassyElements82Cases(): iterable
  634. {
  635. yield 'constant in trait' => [
  636. [
  637. 7 => [
  638. 'classIndex' => 1,
  639. 'type' => 'const',
  640. ],
  641. 18 => [
  642. 'classIndex' => 1,
  643. 'type' => 'const',
  644. ],
  645. ],
  646. <<<'PHP'
  647. <?php
  648. trait Foo
  649. {
  650. const BAR = 0;
  651. final const BAZ = 1;
  652. }
  653. PHP,
  654. ];
  655. }
  656. /**
  657. * @param array<int, bool> $expected
  658. *
  659. * @dataProvider provideIsAnonymousClassCases
  660. */
  661. public function testIsAnonymousClass(array $expected, string $source): void
  662. {
  663. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  664. foreach ($expected as $index => $expectedValue) {
  665. self::assertSame($expectedValue, $tokensAnalyzer->isAnonymousClass($index));
  666. }
  667. }
  668. /**
  669. * @return iterable<array{array<int, bool>, string}>
  670. */
  671. public static function provideIsAnonymousClassCases(): iterable
  672. {
  673. yield [
  674. [1 => false],
  675. '<?php class foo {}',
  676. ];
  677. yield [
  678. [7 => true],
  679. '<?php $foo = new class() {};',
  680. ];
  681. yield [
  682. [7 => true],
  683. '<?php $foo = new class() extends Foo implements Bar, Baz {};',
  684. ];
  685. yield [
  686. [1 => false, 19 => true],
  687. '<?php class Foo { function bar() { return new class() {}; } }',
  688. ];
  689. yield [
  690. [7 => true, 11 => true],
  691. '<?php $a = new class(new class($d->a) implements B{}) extends C{};',
  692. ];
  693. yield [
  694. [1 => false],
  695. '<?php interface foo {}',
  696. ];
  697. }
  698. /**
  699. * @param array<int, bool> $expected
  700. *
  701. * @dataProvider provideIsAnonymousClass80Cases
  702. *
  703. * @requires PHP 8.0
  704. */
  705. public function testIsAnonymousClass80(array $expected, string $source): void
  706. {
  707. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  708. foreach ($expected as $index => $expectedValue) {
  709. self::assertSame($expectedValue, $tokensAnalyzer->isAnonymousClass($index));
  710. }
  711. }
  712. /**
  713. * @return iterable<array{array<int, bool>, string}>
  714. */
  715. public static function provideIsAnonymousClass80Cases(): iterable
  716. {
  717. yield [
  718. [11 => true],
  719. '<?php $object = new #[ExampleAttribute] class(){};',
  720. ];
  721. yield [
  722. [27 => true],
  723. '<?php $object = new #[A] #[B] #[C]#[D]/* */ /** */#[E]class(){};',
  724. ];
  725. }
  726. /**
  727. * @param array<int, bool> $expected
  728. *
  729. * @dataProvider provideIsAnonymousClass81Cases
  730. *
  731. * @requires PHP 8.1
  732. */
  733. public function testIsAnonymousClass81(array $expected, string $source): void
  734. {
  735. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  736. foreach ($expected as $index => $expectedValue) {
  737. self::assertSame($expectedValue, $tokensAnalyzer->isAnonymousClass($index));
  738. }
  739. }
  740. /**
  741. * @return iterable<array{array<int, bool>, string}>
  742. */
  743. public static function provideIsAnonymousClass81Cases(): iterable
  744. {
  745. yield [
  746. [1 => false],
  747. '<?php enum foo {}',
  748. ];
  749. }
  750. /**
  751. * @param array<int, bool> $expected
  752. *
  753. * @dataProvider provideIsAnonymousClass83Cases
  754. *
  755. * @requires PHP 8.3
  756. */
  757. public function testIsAnonymousClass83(array $expected, string $source): void
  758. {
  759. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  760. foreach ($expected as $index => $expectedValue) {
  761. self::assertSame($expectedValue, $tokensAnalyzer->isAnonymousClass($index));
  762. }
  763. }
  764. /**
  765. * @return iterable<array{array<int, bool>, string}>
  766. */
  767. public static function provideIsAnonymousClass83Cases(): iterable
  768. {
  769. yield 'simple readonly anonymous class' => [
  770. [9 => true],
  771. '<?php $instance = new readonly class {};',
  772. ];
  773. yield 'readonly anonymous class with attribute' => [
  774. [13 => true],
  775. '<?php $instance = new #[Foo] readonly class {};',
  776. ];
  777. yield 'readonly anonymous class with multiple attributes' => [
  778. [17 => true],
  779. '<?php $instance = new #[Foo] #[BAR] readonly class {};',
  780. ];
  781. }
  782. /**
  783. * @param array<int, bool> $expected
  784. *
  785. * @dataProvider provideIsLambdaCases
  786. */
  787. public function testIsLambda(array $expected, string $source): void
  788. {
  789. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  790. foreach ($expected as $index => $isLambda) {
  791. self::assertSame($isLambda, $tokensAnalyzer->isLambda($index));
  792. }
  793. }
  794. public static function provideIsLambdaCases(): iterable
  795. {
  796. yield [
  797. [1 => false],
  798. '<?php function foo () {};',
  799. ];
  800. yield [
  801. [1 => false],
  802. '<?php function /** foo */ foo () {};',
  803. ];
  804. yield [
  805. [5 => true],
  806. '<?php $foo = function () {};',
  807. ];
  808. yield [
  809. [5 => true],
  810. '<?php $foo = function /** foo */ () {};',
  811. ];
  812. yield [
  813. [7 => true],
  814. '<?php
  815. preg_replace_callback(
  816. "/(^|[a-z])/",
  817. function (array $matches) {
  818. return "a";
  819. },
  820. $string
  821. );',
  822. ];
  823. yield [
  824. [5 => true],
  825. '<?php $foo = function &() {};',
  826. ];
  827. yield [
  828. [6 => true],
  829. '<?php
  830. $a = function (): array {
  831. return [];
  832. };',
  833. ];
  834. yield [
  835. [2 => false],
  836. '<?php
  837. function foo (): array {
  838. return [];
  839. };',
  840. ];
  841. yield [
  842. [6 => true],
  843. '<?php
  844. $a = function (): void {
  845. return [];
  846. };',
  847. ];
  848. yield [
  849. [2 => false],
  850. '<?php
  851. function foo (): void {
  852. return [];
  853. };',
  854. ];
  855. yield [
  856. [6 => true],
  857. '<?php
  858. $a = function (): ?int {
  859. return [];
  860. };',
  861. ];
  862. yield [
  863. [6 => true],
  864. '<?php
  865. $a = function (): int {
  866. return [];
  867. };',
  868. ];
  869. yield [
  870. [2 => false],
  871. '<?php
  872. function foo (): ?int {
  873. return [];
  874. };',
  875. ];
  876. }
  877. /**
  878. * @param array<int, bool> $expected
  879. *
  880. * @dataProvider provideIsLambda74Cases
  881. */
  882. public function testIsLambda74(array $expected, string $source): void
  883. {
  884. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  885. foreach ($expected as $index => $expectedValue) {
  886. self::assertSame($expectedValue, $tokensAnalyzer->isLambda($index));
  887. }
  888. }
  889. public static function provideIsLambda74Cases(): iterable
  890. {
  891. yield [
  892. [5 => true],
  893. '<?php $fn = fn() => [];',
  894. ];
  895. yield [
  896. [5 => true],
  897. '<?php $fn = fn () => [];',
  898. ];
  899. }
  900. /**
  901. * @param array<int, bool> $expected
  902. *
  903. * @dataProvider provideIsLambda80Cases
  904. *
  905. * @requires PHP 8.0
  906. */
  907. public function testIsLambda80(array $expected, string $source): void
  908. {
  909. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  910. foreach ($expected as $index => $expectedValue) {
  911. self::assertSame($expectedValue, $tokensAnalyzer->isLambda($index));
  912. }
  913. }
  914. public static function provideIsLambda80Cases(): iterable
  915. {
  916. yield [
  917. [6 => true],
  918. '<?php
  919. $a = function (): ?static {
  920. return [];
  921. };',
  922. ];
  923. yield [
  924. [6 => true],
  925. '<?php
  926. $a = function (): static {
  927. return [];
  928. };',
  929. ];
  930. yield [
  931. [14 => true],
  932. '<?php
  933. $c = 4; //
  934. $a = function(
  935. $a,
  936. $b,
  937. ) use (
  938. $c,
  939. ) {
  940. echo $a + $b + $c;
  941. };
  942. $a(1,2);',
  943. ];
  944. }
  945. public function testIsLambdaInvalid(): void
  946. {
  947. $this->expectException(\LogicException::class);
  948. $this->expectExceptionMessage('No T_FUNCTION or T_FN at given index 0, got "T_OPEN_TAG".');
  949. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode('<?php '));
  950. $tokensAnalyzer->isLambda(0);
  951. }
  952. /**
  953. * @param array<int, bool> $expected
  954. *
  955. * @dataProvider provideIsConstantInvocationCases
  956. */
  957. public function testIsConstantInvocation(array $expected, string $source): void
  958. {
  959. $this->doIsConstantInvocationTest($expected, $source);
  960. }
  961. public static function provideIsConstantInvocationCases(): iterable
  962. {
  963. yield [
  964. [3 => true],
  965. '<?php echo FOO;',
  966. ];
  967. yield [
  968. [4 => true],
  969. '<?php echo \FOO;',
  970. ];
  971. yield [
  972. [3 => false, 5 => false, 7 => true],
  973. '<?php echo Foo\Bar\BAR;',
  974. ];
  975. yield [
  976. [3 => true, 7 => true, 11 => true],
  977. '<?php echo FOO ? BAR : BAZ;',
  978. ];
  979. yield 'Bitwise & and bitwise |' => [
  980. [3 => true, 7 => true, 11 => true],
  981. '<?php echo FOO & BAR | BAZ;',
  982. ];
  983. yield 'Bitwise &' => [
  984. [3 => true],
  985. '<?php echo FOO & $bar;',
  986. ];
  987. yield [
  988. [5 => true],
  989. '<?php echo $foo[BAR];',
  990. ];
  991. yield [
  992. [3 => true, 5 => true],
  993. '<?php echo FOO[BAR];',
  994. ];
  995. yield [
  996. [1 => false, 3 => true, 6 => false, 8 => true],
  997. '<?php func(FOO, Bar\BAZ);',
  998. ];
  999. yield [
  1000. [4 => true, 8 => true],
  1001. '<?php if (FOO && BAR) {}',
  1002. ];
  1003. yield [
  1004. [3 => true, 7 => false, 9 => false, 11 => true],
  1005. '<?php return FOO * X\Y\BAR;',
  1006. ];
  1007. yield [
  1008. [3 => false, 11 => true, 16 => true, 20 => true],
  1009. '<?php function x() { yield FOO; yield FOO => BAR; }',
  1010. ];
  1011. yield [
  1012. [11 => true],
  1013. '<?php switch ($a) { case FOO: break; }',
  1014. ];
  1015. yield [
  1016. [3 => false],
  1017. '<?php namespace FOO;',
  1018. ];
  1019. yield [
  1020. [3 => false],
  1021. '<?php use FOO;',
  1022. ];
  1023. yield [
  1024. [5 => false, 7 => false, 9 => false],
  1025. '<?php use function FOO\BAR\BAZ;',
  1026. ];
  1027. yield [
  1028. [3 => false, 8 => false],
  1029. '<?php namespace X; const FOO = 1;',
  1030. ];
  1031. yield [
  1032. [3 => false],
  1033. '<?php class FOO {}',
  1034. ];
  1035. yield [
  1036. [3 => false],
  1037. '<?php interface FOO {}',
  1038. ];
  1039. yield [
  1040. [3 => false],
  1041. '<?php trait FOO {}',
  1042. ];
  1043. yield [
  1044. [3 => false, 7 => false],
  1045. '<?php class x extends FOO {}',
  1046. ];
  1047. yield [
  1048. [3 => false, 7 => false],
  1049. '<?php class x implements FOO {}',
  1050. ];
  1051. yield [
  1052. [3 => false, 7 => false, 10 => false, 13 => false],
  1053. '<?php class x implements FOO, BAR, BAZ {}',
  1054. ];
  1055. yield [
  1056. [3 => false, 9 => false],
  1057. '<?php class x { const FOO = 1; }',
  1058. ];
  1059. yield [
  1060. [3 => false, 9 => false],
  1061. '<?php class x { use FOO; }',
  1062. ];
  1063. yield [
  1064. [3 => false, 9 => false, 12 => false, 16 => false, 18 => false, 22 => false],
  1065. '<?php class x { use FOO, BAR { FOO::BAZ insteadof BAR; } }',
  1066. ];
  1067. yield [
  1068. [3 => false, 6 => false, 11 => false, 17 => false],
  1069. '<?php function x (FOO $foo, BAR &$bar, BAZ ...$baz) {}',
  1070. ];
  1071. yield [
  1072. [1 => false],
  1073. '<?php FOO();',
  1074. ];
  1075. yield [
  1076. [1 => false, 3 => false],
  1077. '<?php FOO::x();',
  1078. ];
  1079. yield [
  1080. [1 => false, 3 => false],
  1081. '<?php x::FOO();',
  1082. ];
  1083. yield [
  1084. [5 => false],
  1085. '<?php $foo instanceof FOO;',
  1086. ];
  1087. yield [
  1088. [9 => false],
  1089. '<?php try {} catch (FOO $e) {}',
  1090. ];
  1091. yield [
  1092. [4 => false],
  1093. '<?php "$foo[BAR]";',
  1094. ];
  1095. yield [
  1096. [5 => true],
  1097. '<?php "{$foo[BAR]}";',
  1098. ];
  1099. yield [
  1100. [1 => false, 6 => false],
  1101. '<?php FOO: goto FOO;',
  1102. ];
  1103. yield [
  1104. [1 => false, 3 => true, 7 => true],
  1105. '<?php foo(E_USER_DEPRECATED | E_DEPRECATED);',
  1106. ];
  1107. yield [
  1108. [3 => false, 7 => false, 10 => false, 13 => false],
  1109. '<?php interface Foo extends Bar, Baz, Qux {}',
  1110. ];
  1111. yield [
  1112. [3 => false, 5 => false, 8 => false, 10 => false, 13 => false, 15 => false],
  1113. '<?php use Foo\Bar, Foo\Baz, Foo\Qux;',
  1114. ];
  1115. yield [
  1116. [3 => false, 8 => false],
  1117. '<?php function x(): FOO {}',
  1118. ];
  1119. yield [
  1120. [3 => false, 5 => false, 8 => false, 11 => false, 15 => false, 18 => false],
  1121. '<?php use X\Y\{FOO, BAR as BAR2, BAZ};',
  1122. ];
  1123. yield [
  1124. [6 => false, 16 => false, 21 => false],
  1125. '<?php
  1126. abstract class Baz
  1127. {
  1128. abstract public function test(): Foo;
  1129. }
  1130. ',
  1131. ];
  1132. yield [
  1133. [3 => false, 6 => false],
  1134. '<?php function x(?FOO $foo) {}',
  1135. ];
  1136. yield [
  1137. [3 => false, 9 => false],
  1138. '<?php function x(): ?FOO {}',
  1139. ];
  1140. yield [
  1141. [9 => false, 11 => false, 13 => false],
  1142. '<?php try {} catch (FOO|BAR|BAZ $e) {}',
  1143. ];
  1144. yield [
  1145. [3 => false, 11 => false, 16 => false],
  1146. '<?php interface Foo { public function bar(): Baz; }',
  1147. ];
  1148. yield [
  1149. [3 => false, 11 => false, 17 => false],
  1150. '<?php interface Foo { public function bar(): \Baz; }',
  1151. ];
  1152. yield [
  1153. [3 => false, 11 => false, 17 => false],
  1154. '<?php interface Foo { public function bar(): ?Baz; }',
  1155. ];
  1156. yield [
  1157. [3 => false, 11 => false, 18 => false],
  1158. '<?php interface Foo { public function bar(): ?\Baz; }',
  1159. ];
  1160. }
  1161. /**
  1162. * @param array<int, bool> $expected
  1163. *
  1164. * @dataProvider provideIsConstantInvocationPhp80Cases
  1165. *
  1166. * @requires PHP 8.0
  1167. */
  1168. public function testIsConstantInvocationPhp80(array $expected, string $source): void
  1169. {
  1170. $this->doIsConstantInvocationTest($expected, $source);
  1171. }
  1172. public static function provideIsConstantInvocationPhp80Cases(): iterable
  1173. {
  1174. yield 'abstract method return alternation' => [
  1175. [6 => false, 16 => false, 21 => false, 23 => false],
  1176. '<?php
  1177. abstract class Baz
  1178. {
  1179. abstract public function test(): Foo|Bar;
  1180. }
  1181. ',
  1182. ];
  1183. yield 'function return alternation' => [
  1184. [3 => false, 8 => false, 10 => false],
  1185. '<?php function test(): Foo|Bar {}',
  1186. ];
  1187. yield 'nullsafe operator' => [
  1188. [3 => false, 5 => false],
  1189. '<?php $a?->b?->c;',
  1190. ];
  1191. yield 'non-capturing catch' => [
  1192. [9 => false],
  1193. '<?php try {} catch (Exception) {}',
  1194. ];
  1195. yield 'non-capturing catch 2' => [
  1196. [10 => false],
  1197. '<?php try {} catch (\Exception) {}',
  1198. ];
  1199. yield 'non-capturing multiple catch' => [
  1200. [9 => false, 13 => false],
  1201. '<?php try {} catch (Foo | Bar) {}',
  1202. ];
  1203. yield 'attribute 1' => [
  1204. [2 => false, 5 => false, 10 => false],
  1205. '<?php #[Foo, Bar] function foo() {}',
  1206. ];
  1207. yield 'attribute 2' => [
  1208. [2 => false, 7 => false, 14 => false],
  1209. '<?php #[Foo(), Bar()] function foo() {}',
  1210. ];
  1211. yield [
  1212. [2 => false, 9 => false],
  1213. '<?php #[Foo()] function foo() {}',
  1214. ];
  1215. yield [
  1216. [3 => false, 10 => false],
  1217. '<?php #[\Foo()] function foo() {}',
  1218. ];
  1219. yield [
  1220. [2 => false, 4 => false, 11 => false],
  1221. '<?php #[A\Foo()] function foo() {}',
  1222. ];
  1223. yield [
  1224. [3 => false, 5 => false, 12 => false],
  1225. '<?php #[\A\Foo()] function foo() {}',
  1226. ];
  1227. yield 'multiple type catch with variable' => [
  1228. [5 => false, 15 => false, 18 => false],
  1229. '<?php try { foo(); } catch(\InvalidArgumentException|\LogicException $e) {}',
  1230. ];
  1231. yield 'multiple type catch without variable 1' => [
  1232. [5 => false, 15 => false, 18 => false],
  1233. '<?php try { foo(); } catch(\InvalidArgumentException|\LogicException) {}',
  1234. ];
  1235. yield 'multiple type catch without variable 2' => [
  1236. [5 => false, 15 => false, 17 => false, 19 => false, 21 => false, 24 => false, 27 => false],
  1237. '<?php try { foo(); } catch(\D|Z|A\B|\InvalidArgumentException|\LogicException) {}',
  1238. ];
  1239. yield 'multiple type catch without variable 3' => [
  1240. [5 => false, 14 => false, 16 => false, 19 => false, 22 => false],
  1241. '<?php try { foo(); } catch(A\B|\InvalidArgumentException|\LogicException) {}',
  1242. ];
  1243. yield 'attribute before' => [
  1244. [4 => false, 6 => false, 8 => false, 13 => false, 17 => false, 23 => false, 25 => false],
  1245. '<?php
  1246. use Psr\Log\LoggerInterface;
  1247. function f( #[Target(\'xxx\')] LoggerInterface|null $logger) {}
  1248. ',
  1249. ];
  1250. }
  1251. /**
  1252. * @param array<int, bool> $expected
  1253. *
  1254. * @dataProvider provideIsConstantInvocationPhp81Cases
  1255. *
  1256. * @requires PHP 8.1
  1257. */
  1258. public function testIsConstantInvocationPhp81(array $expected, string $source): void
  1259. {
  1260. $this->doIsConstantInvocationTest($expected, $source);
  1261. }
  1262. public static function provideIsConstantInvocationPhp81Cases(): iterable
  1263. {
  1264. yield [
  1265. [5 => false, 15 => false],
  1266. '<?php
  1267. abstract class Baz
  1268. {
  1269. final public const Y = "i";
  1270. }
  1271. ',
  1272. ];
  1273. yield [
  1274. [4 => false, 12 => false, 23 => false],
  1275. '<?php
  1276. class Test {
  1277. public function __construct(
  1278. public $prop = new Foo,
  1279. ) {}
  1280. }
  1281. ',
  1282. ];
  1283. yield 'intersection' => [
  1284. [3 => false, 9 => false, 11 => false],
  1285. '<?php function foo(): \Foo&Bar {}',
  1286. ];
  1287. yield 'abstract method return intersection' => [
  1288. [6 => false, 16 => false, 21 => false, 23 => false, 25 => false, 27 => false, 29 => false],
  1289. '<?php
  1290. abstract class Baz
  1291. {
  1292. abstract public function foo(): Foo&Bar1&Bar2&Bar3&Bar4;
  1293. }
  1294. ',
  1295. ];
  1296. }
  1297. /**
  1298. * @param array<int, bool> $expected
  1299. *
  1300. * @dataProvider provideIsConstantInvocationPhp82Cases
  1301. *
  1302. * @requires PHP 8.2
  1303. */
  1304. public function testIsConstantInvocationPhp82(array $expected, string $source): void
  1305. {
  1306. $this->doIsConstantInvocationTest($expected, $source);
  1307. }
  1308. /**
  1309. * @return iterable<array{array<int, bool>, string}>
  1310. */
  1311. public static function provideIsConstantInvocationPhp82Cases(): iterable
  1312. {
  1313. yield [
  1314. [3 => false, 11 => false, 13 => false, 17 => false, 20 => false, 23 => false, 25 => false, 28 => false, 31 => false, 33 => false, 35 => false, 39 => false, 42 => false, 44 => false],
  1315. '<?php class Foo { public (\A&B)|(C&\D)|E\F|\G|(A&H\I)|(A&\J\K) $var; }',
  1316. ];
  1317. yield [
  1318. [3 => false, 8 => false, 10 => false, 14 => false, 17 => false, 20 => false, 22 => false, 25 => false, 28 => false, 30 => false, 32 => false, 36 => false, 39 => false, 41 => false],
  1319. '<?php function foo ((\A&B)|(C&\D)|E\F|\G|(A&H\I)|(A&\J\K) $var) {}',
  1320. ];
  1321. }
  1322. /**
  1323. * @param array<int, bool> $expected
  1324. *
  1325. * @dataProvider provideIsConstantInvocationPhp83Cases
  1326. *
  1327. * @requires PHP 8.3
  1328. */
  1329. public function testIsConstantInvocationPhp83(array $expected, string $source): void
  1330. {
  1331. $this->doIsConstantInvocationTest($expected, $source);
  1332. }
  1333. /**
  1334. * @return iterable<array{array<int, bool>, string}>
  1335. */
  1336. public static function provideIsConstantInvocationPhp83Cases(): iterable
  1337. {
  1338. yield [
  1339. [3 => false, 11 => false, 13 => false, 17 => true],
  1340. '<?php class Foo { public const A FOO = BAR; }',
  1341. ];
  1342. yield [
  1343. [3 => false, 11 => false, 13 => false, 15 => false, 19 => true],
  1344. '<?php class Foo { public const A|B FOO = BAR; }',
  1345. ];
  1346. yield [
  1347. [3 => false, 11 => false, 13 => false, 15 => false, 19 => true],
  1348. '<?php class Foo { public const A&B FOO = BAR; }',
  1349. ];
  1350. yield [
  1351. [3 => false, 12 => false, 14 => false, 17 => false, 19 => false, 23 => true],
  1352. '<?php class Foo { public const (A&B)|C FOO = BAR; }',
  1353. ];
  1354. yield [
  1355. [3 => false, 12 => false, 14 => false, 18 => false, 20 => false, 23 => false, 27 => true],
  1356. '<?php class Foo { public const (A&B)|(C&D) FOO = BAR; }',
  1357. ];
  1358. yield [
  1359. [3 => false, 12 => false, 15 => false, 17 => false, 21 => false, 23 => false, 25 => false, 28 => false, 32 => true],
  1360. '<?php class Foo { public const (A&\B\C)|(D\E&F) FOO = BAR; }',
  1361. ];
  1362. }
  1363. public function testIsConstantInvocationInvalid(): void
  1364. {
  1365. $this->expectException(\LogicException::class);
  1366. $this->expectExceptionMessage('No T_STRING at given index 0, got "T_OPEN_TAG".');
  1367. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode('<?php '));
  1368. $tokensAnalyzer->isConstantInvocation(0);
  1369. }
  1370. /**
  1371. * @requires PHP 8.0
  1372. */
  1373. public function testIsConstantInvocationForNullSafeObjectOperator(): void
  1374. {
  1375. $tokens = Tokens::fromCode('<?php $a?->b?->c;');
  1376. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1377. foreach ($tokens as $index => $token) {
  1378. if (!$token->isGivenKind(T_STRING)) {
  1379. continue;
  1380. }
  1381. self::assertFalse($tokensAnalyzer->isConstantInvocation($index));
  1382. }
  1383. }
  1384. /**
  1385. * @param array<int, bool> $expected
  1386. *
  1387. * @dataProvider provideIsUnarySuccessorOperatorCases
  1388. */
  1389. public function testIsUnarySuccessorOperator(array $expected, string $source): void
  1390. {
  1391. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1392. foreach ($expected as $index => $isUnary) {
  1393. self::assertSame($isUnary, $tokensAnalyzer->isUnarySuccessorOperator($index));
  1394. if ($isUnary) {
  1395. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1396. self::assertFalse($tokensAnalyzer->isBinaryOperator($index));
  1397. }
  1398. }
  1399. }
  1400. public static function provideIsUnarySuccessorOperatorCases(): iterable
  1401. {
  1402. yield [
  1403. [2 => true],
  1404. '<?php $a++;',
  1405. ];
  1406. yield [
  1407. [2 => true],
  1408. '<?php $a--;',
  1409. ];
  1410. yield [
  1411. [3 => true],
  1412. '<?php $a ++;',
  1413. ];
  1414. yield [
  1415. [2 => true, 4 => false],
  1416. '<?php $a++ + 1;',
  1417. ];
  1418. yield [
  1419. [5 => true],
  1420. '<?php ${"a"}++;',
  1421. ];
  1422. yield [
  1423. [4 => true],
  1424. '<?php $foo->bar++;',
  1425. ];
  1426. yield [
  1427. [6 => true],
  1428. '<?php $foo->{"bar"}++;',
  1429. ];
  1430. yield 'array access' => [
  1431. [5 => true],
  1432. '<?php $a["foo"]++;',
  1433. ];
  1434. yield 'array curly access' => [
  1435. [5 => true],
  1436. '<?php $a{"foo"}++;',
  1437. ];
  1438. }
  1439. /**
  1440. * @param list<int> $expected
  1441. *
  1442. * @dataProvider provideIsUnaryPredecessorOperatorCases
  1443. */
  1444. public function testIsUnaryPredecessorOperator(array $expected, string $source): void
  1445. {
  1446. $tokens = Tokens::fromCode($source);
  1447. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1448. foreach ($tokens as $index => $token) {
  1449. $expect = \in_array($index, $expected, true);
  1450. self::assertSame(
  1451. $expect,
  1452. $tokensAnalyzer->isUnaryPredecessorOperator($index),
  1453. sprintf('Expected %sunary predecessor operator, got @ %d "%s".', $expect ? '' : 'no ', $index, var_export($token, true))
  1454. );
  1455. if ($expect) {
  1456. self::assertFalse(
  1457. $tokensAnalyzer->isUnarySuccessorOperator($index),
  1458. sprintf('Expected no unary successor operator, got @ %d "%s".', $index, var_export($token, true))
  1459. );
  1460. self::assertFalse(
  1461. $tokensAnalyzer->isBinaryOperator($index),
  1462. sprintf('Expected no binary operator, got @ %d "%s".', $index, var_export($token, true))
  1463. );
  1464. }
  1465. }
  1466. }
  1467. public static function provideIsUnaryPredecessorOperatorCases(): iterable
  1468. {
  1469. yield [
  1470. [1],
  1471. '<?php ++$a;',
  1472. ];
  1473. yield [
  1474. [1],
  1475. '<?php --$a;',
  1476. ];
  1477. yield [
  1478. [1],
  1479. '<?php -- $a;',
  1480. ];
  1481. yield [
  1482. [5],
  1483. '<?php $a + ++$b;',
  1484. ];
  1485. yield [
  1486. [1, 2],
  1487. '<?php !!$a;',
  1488. ];
  1489. yield [
  1490. [5],
  1491. '<?php $a = &$b;',
  1492. ];
  1493. yield [
  1494. [3],
  1495. '<?php function &foo() {}',
  1496. ];
  1497. yield [
  1498. [1],
  1499. '<?php @foo();',
  1500. ];
  1501. yield [
  1502. [3, 8],
  1503. '<?php foo(+ $a, -$b);',
  1504. ];
  1505. yield [
  1506. [5, 11, 17],
  1507. '<?php function foo(&$a, array &$b, Bar &$c) {}',
  1508. ];
  1509. yield [
  1510. [8],
  1511. '<?php function foo($a, ...$b) {}',
  1512. ];
  1513. yield [
  1514. [5, 6],
  1515. '<?php function foo(&...$b) {}',
  1516. ];
  1517. yield [
  1518. [7],
  1519. '<?php function foo(array ...$b) {}',
  1520. ];
  1521. yield [
  1522. [7],
  1523. '<?php $foo = function(...$a) {};',
  1524. ];
  1525. yield [
  1526. [10],
  1527. '<?php $foo = function($a, ...$b) {};',
  1528. ];
  1529. yield [
  1530. [9],
  1531. '<?php $foo = function(int &$x) {};',
  1532. ];
  1533. yield [
  1534. [9],
  1535. '<?php $foo = fn(int &$x) => null;',
  1536. ];
  1537. yield [
  1538. [],
  1539. '<?php fn() => A_CONSTANT & $object->property;',
  1540. ];
  1541. }
  1542. /**
  1543. * @param list<int> $expected
  1544. *
  1545. * @dataProvider provideIsBinaryOperatorCases
  1546. */
  1547. public function testIsBinaryOperator(array $expected, string $source): void
  1548. {
  1549. $tokens = Tokens::fromCode($source);
  1550. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1551. foreach ($tokens as $index => $token) {
  1552. $expect = \in_array($index, $expected, true);
  1553. self::assertSame(
  1554. $expect,
  1555. $tokensAnalyzer->isBinaryOperator($index),
  1556. sprintf('Expected %sbinary operator, got @ %d "%s".', $expect ? '' : 'no ', $index, var_export($token, true))
  1557. );
  1558. if ($expect) {
  1559. self::assertFalse(
  1560. $tokensAnalyzer->isUnarySuccessorOperator($index),
  1561. sprintf('Expected no unary successor operator, got @ %d "%s".', $index, var_export($token, true))
  1562. );
  1563. self::assertFalse(
  1564. $tokensAnalyzer->isUnaryPredecessorOperator($index),
  1565. sprintf('Expected no unary predecessor operator, got @ %d "%s".', $index, var_export($token, true))
  1566. );
  1567. }
  1568. }
  1569. }
  1570. public static function provideIsBinaryOperatorCases(): iterable
  1571. {
  1572. yield [
  1573. [8],
  1574. '<?php echo $a[1] + 1;',
  1575. ];
  1576. yield [
  1577. [8],
  1578. '<?php echo $a{1} + 1;',
  1579. ];
  1580. yield [
  1581. [3],
  1582. '<?php $a .= $b; ?>',
  1583. ];
  1584. yield [
  1585. [3],
  1586. '<?php $a . \'a\' ?>',
  1587. ];
  1588. yield [
  1589. [3],
  1590. '<?php $a &+ $b;',
  1591. ];
  1592. yield [
  1593. [3],
  1594. '<?php $a && $b;',
  1595. ];
  1596. yield [
  1597. [3],
  1598. '<?php $a & $b;',
  1599. ];
  1600. yield [
  1601. [4],
  1602. '<?php [] + [];',
  1603. ];
  1604. yield [
  1605. [3],
  1606. '<?php $a + $b;',
  1607. ];
  1608. yield [
  1609. [3],
  1610. '<?php 1 + $b;',
  1611. ];
  1612. yield [
  1613. [3],
  1614. '<?php 0.2 + $b;',
  1615. ];
  1616. yield [
  1617. [6],
  1618. '<?php $a[1] + $b;',
  1619. ];
  1620. yield [
  1621. [3],
  1622. '<?php FOO + $b;',
  1623. ];
  1624. yield [
  1625. [5],
  1626. '<?php foo() + $b;',
  1627. ];
  1628. yield [
  1629. [6],
  1630. '<?php ${"foo"} + $b;',
  1631. ];
  1632. yield [
  1633. [2],
  1634. '<?php $a+$b;',
  1635. ];
  1636. yield [
  1637. [5],
  1638. '<?php $a /* foo */ + /* bar */ $b;',
  1639. ];
  1640. yield [
  1641. [3],
  1642. '<?php $a =
  1643. $b;',
  1644. ];
  1645. yield [
  1646. [3],
  1647. '<?php $a
  1648. = $b;',
  1649. ];
  1650. yield [
  1651. [3, 9],
  1652. '<?php $a = array("b" => "c", );',
  1653. ];
  1654. yield [
  1655. [3],
  1656. '<?php $a * -$b;',
  1657. ];
  1658. yield [
  1659. [3, 8],
  1660. '<?php $a = -2 / +5;',
  1661. ];
  1662. yield [
  1663. [3, 5 => false],
  1664. '<?php $a = &$b;',
  1665. ];
  1666. yield [
  1667. [4],
  1668. '<?php $a++ + $b;',
  1669. ];
  1670. yield [
  1671. [3, 7],
  1672. '<?php $a = FOO & $bar;',
  1673. ];
  1674. yield [
  1675. [3],
  1676. '<?php __LINE__ - 1;',
  1677. ];
  1678. yield [
  1679. [5],
  1680. '<?php `echo 1` + 1;',
  1681. ];
  1682. yield [
  1683. [3],
  1684. '<?php $a ** $b;',
  1685. ];
  1686. yield [
  1687. [3],
  1688. '<?php $a **= $b;',
  1689. ];
  1690. yield [
  1691. [3],
  1692. '<?php $a = "{$value}-{$theSwitch}";',
  1693. ];
  1694. yield [
  1695. [],
  1696. '<?=$path?>-<?=$id?>',
  1697. ];
  1698. $operators = [
  1699. '+', '-', '*', '/', '%', '<', '>', '|', '^', '&=', '&&', '||', '.=', '/=', '==', '>=', '===', '!=',
  1700. '<>', '!==', '<=', 'and', 'or', 'xor', '-=', '%=', '*=', '|=', '+=', '<<', '<<=', '>>', '>>=', '^',
  1701. ];
  1702. foreach ($operators as $operator) {
  1703. yield [
  1704. [3],
  1705. '<?php $a '.$operator.' $b;',
  1706. ];
  1707. }
  1708. yield [
  1709. [3],
  1710. '<?php $a <=> $b;',
  1711. ];
  1712. yield [
  1713. [3],
  1714. '<?php $a ?? $b;',
  1715. ];
  1716. yield [
  1717. [],
  1718. '<?php try {} catch (A | B $e) {}',
  1719. ];
  1720. yield [
  1721. [3],
  1722. '<?php $a ??= $b;',
  1723. ];
  1724. yield [
  1725. [5, 11],
  1726. '<?php fn() => $object->property & A_CONSTANT;',
  1727. ];
  1728. }
  1729. /**
  1730. * @dataProvider provideIsArrayCases
  1731. */
  1732. public function testIsArray(string $source, int $tokenIndex, bool $isMultiLineArray = false): void
  1733. {
  1734. $tokens = Tokens::fromCode($source);
  1735. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1736. self::assertTrue($tokensAnalyzer->isArray($tokenIndex), 'Expected to be an array.');
  1737. self::assertSame($isMultiLineArray, $tokensAnalyzer->isArrayMultiLine($tokenIndex), sprintf('Expected %sto be a multiline array', $isMultiLineArray ? '' : 'not '));
  1738. }
  1739. public static function provideIsArrayCases(): iterable
  1740. {
  1741. yield [
  1742. '<?php
  1743. array("a" => 1);
  1744. ',
  1745. 2,
  1746. ];
  1747. yield [
  1748. '<?php
  1749. ["a" => 2];
  1750. ',
  1751. 2, false,
  1752. ];
  1753. yield [
  1754. '<?php
  1755. array(
  1756. "a" => 3
  1757. );
  1758. ',
  1759. 2, true,
  1760. ];
  1761. yield [
  1762. '<?php
  1763. [
  1764. "a" => 4
  1765. ];
  1766. ',
  1767. 2, true,
  1768. ];
  1769. yield [
  1770. '<?php
  1771. array(
  1772. "a" => array(5, 6, 7),
  1773. 8 => new \Exception(\'Hello\')
  1774. );
  1775. ',
  1776. 2, true,
  1777. ];
  1778. yield [
  1779. // mix short array syntax
  1780. '<?php
  1781. array(
  1782. "a" => [9, 10, 11],
  1783. 12 => new \Exception(\'Hello\')
  1784. );
  1785. ',
  1786. 2, true,
  1787. ];
  1788. // Windows/Max EOL testing
  1789. yield [
  1790. "<?php\r\narray('a' => 13);\r\n",
  1791. 1,
  1792. ];
  1793. yield [
  1794. "<?php\r\n array(\r\n 'a' => 14,\r\n 'b' => 15\r\n );\r\n",
  1795. 2, true,
  1796. ];
  1797. }
  1798. /**
  1799. * @param list<int> $tokenIndexes
  1800. *
  1801. * @dataProvider provideIsArray71Cases
  1802. */
  1803. public function testIsArray71(string $source, array $tokenIndexes): void
  1804. {
  1805. $tokens = Tokens::fromCode($source);
  1806. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1807. foreach ($tokens as $index => $token) {
  1808. $expect = \in_array($index, $tokenIndexes, true);
  1809. self::assertSame(
  1810. $expect,
  1811. $tokensAnalyzer->isArray($index),
  1812. sprintf('Expected %sarray, got @ %d "%s".', $expect ? '' : 'no ', $index, var_export($token, true))
  1813. );
  1814. }
  1815. }
  1816. public static function provideIsArray71Cases(): iterable
  1817. {
  1818. yield [
  1819. '<?php
  1820. [$a] = $z;
  1821. ["a" => $a, "b" => $b] = $array;
  1822. $c = [$d, $e] = $array[$a];
  1823. [[$a, $b], [$c, $d]] = $d;
  1824. $array = []; $d = array();
  1825. ',
  1826. [76, 84],
  1827. ];
  1828. }
  1829. /**
  1830. * @param array<int, bool> $expected
  1831. *
  1832. * @dataProvider provideIsBinaryOperator80Cases
  1833. *
  1834. * @requires PHP 8.0
  1835. */
  1836. public function testIsBinaryOperator80(array $expected, string $source): void
  1837. {
  1838. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1839. foreach ($expected as $index => $isBinary) {
  1840. self::assertSame($isBinary, $tokensAnalyzer->isBinaryOperator($index));
  1841. if ($isBinary) {
  1842. self::assertFalse($tokensAnalyzer->isUnarySuccessorOperator($index));
  1843. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1844. }
  1845. }
  1846. }
  1847. public static function provideIsBinaryOperator80Cases(): iterable
  1848. {
  1849. yield [
  1850. [6 => false],
  1851. '<?php function foo(array|string $x) {}',
  1852. ];
  1853. yield [
  1854. [6 => false],
  1855. '<?php function foo(string|array $x) {}',
  1856. ];
  1857. yield [
  1858. [6 => false],
  1859. '<?php function foo(int|callable $x) {}',
  1860. ];
  1861. yield [
  1862. [6 => false],
  1863. '<?php function foo(callable|int $x) {}',
  1864. ];
  1865. yield [
  1866. [6 => false],
  1867. '<?php function foo(bool|int &$x) {}',
  1868. ];
  1869. }
  1870. /**
  1871. * @param array<int, bool> $expected
  1872. *
  1873. * @dataProvider provideIsBinaryOperator81Cases
  1874. *
  1875. * @requires PHP 8.1
  1876. */
  1877. public function testIsBinaryOperator81(array $expected, string $source): void
  1878. {
  1879. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1880. foreach ($expected as $index => $isBinary) {
  1881. self::assertSame($isBinary, $tokensAnalyzer->isBinaryOperator($index));
  1882. if ($isBinary) {
  1883. self::assertFalse($tokensAnalyzer->isUnarySuccessorOperator($index));
  1884. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1885. }
  1886. }
  1887. }
  1888. public static function provideIsBinaryOperator81Cases(): iterable
  1889. {
  1890. yield 'type intersection' => [
  1891. [6 => false],
  1892. '<?php function foo(array&string $x) {}',
  1893. ];
  1894. }
  1895. /**
  1896. * @param array<int, bool> $expected
  1897. *
  1898. * @dataProvider provideIsBinaryOperator82Cases
  1899. *
  1900. * @requires PHP 8.2
  1901. */
  1902. public function testIsBinaryOperator82(array $expected, string $source): void
  1903. {
  1904. $tokens = Tokens::fromCode($source);
  1905. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1906. foreach ($tokens as $index => $token) {
  1907. $isBinary = isset($expected[$index]);
  1908. self::assertSame($isBinary, $tokensAnalyzer->isBinaryOperator($index));
  1909. if ($isBinary) {
  1910. self::assertFalse($tokensAnalyzer->isUnarySuccessorOperator($index));
  1911. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1912. }
  1913. }
  1914. }
  1915. public static function provideIsBinaryOperator82Cases(): iterable
  1916. {
  1917. yield [
  1918. [],
  1919. '<?php class Dnf { public static I|(P&S11) $f2;}',
  1920. ];
  1921. yield [
  1922. [],
  1923. '<?php function Foo((A&B)|I $x): (X&Z)|(p\f\G&Y\Z)|z { return foo();}',
  1924. ];
  1925. $particularEndOfFile = 'A|(B&C); }';
  1926. yield sprintf('block "%s" at the end of file that is a type', $particularEndOfFile) => [
  1927. [],
  1928. '<?php abstract class A { abstract function foo(): '.$particularEndOfFile,
  1929. ];
  1930. yield sprintf('block "%s" at the end of file that is not a type', $particularEndOfFile) => [
  1931. [12 => true, 15 => true],
  1932. '<?php function foo() { return '.$particularEndOfFile,
  1933. ];
  1934. }
  1935. /**
  1936. * @dataProvider provideArrayExceptionsCases
  1937. */
  1938. public function testIsNotArray(string $source, int $tokenIndex): void
  1939. {
  1940. $tokens = Tokens::fromCode($source);
  1941. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1942. self::assertFalse($tokensAnalyzer->isArray($tokenIndex));
  1943. }
  1944. /**
  1945. * @dataProvider provideArrayExceptionsCases
  1946. */
  1947. public function testIsMultiLineArrayException(string $source, int $tokenIndex): void
  1948. {
  1949. $this->expectException(\InvalidArgumentException::class);
  1950. $tokens = Tokens::fromCode($source);
  1951. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1952. $tokensAnalyzer->isArrayMultiLine($tokenIndex);
  1953. }
  1954. public static function provideArrayExceptionsCases(): iterable
  1955. {
  1956. yield ['<?php $a;', 1];
  1957. yield ["<?php\n \$a = (0+1); // [0,1]", 4];
  1958. yield ['<?php $text = "foo $bbb[0] bar";', 8];
  1959. yield ['<?php $text = "foo ${aaa[123]} bar";', 9];
  1960. }
  1961. public function testIsBlockMultilineException(): void
  1962. {
  1963. $this->expectException(\LogicException::class);
  1964. $tokens = Tokens::fromCode('<?php foo(1, 2, 3);');
  1965. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1966. $tokensAnalyzer->isBlockMultiline($tokens, 1);
  1967. }
  1968. /**
  1969. * @dataProvider provideIsBlockMultilineCases
  1970. */
  1971. public function testIsBlockMultiline(bool $isBlockMultiline, string $source, int $tokenIndex): void
  1972. {
  1973. $tokens = Tokens::fromCode($source);
  1974. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1975. self::assertSame($isBlockMultiline, $tokensAnalyzer->isBlockMultiline($tokens, $tokenIndex));
  1976. }
  1977. public static function provideIsBlockMultilineCases(): iterable
  1978. {
  1979. yield [
  1980. false,
  1981. '<?php foo(1, 2, 3);',
  1982. 2,
  1983. ];
  1984. yield [
  1985. true,
  1986. '<?php foo(1,
  1987. 2,
  1988. 3
  1989. );',
  1990. 2,
  1991. ];
  1992. yield [
  1993. false,
  1994. '<?php foo(1, "Multi
  1995. string", 2, 3);',
  1996. 2,
  1997. ];
  1998. yield [
  1999. false,
  2000. '<?php foo(1, havingNestedBlockThatIsMultilineDoesNotMakeTheMainBlockMultiline(
  2001. "a",
  2002. "b"
  2003. ), 2, 3);',
  2004. 2,
  2005. ];
  2006. }
  2007. /**
  2008. * @param array{visibility: ?int, static: bool, abstract: bool, final: bool} $expected
  2009. *
  2010. * @dataProvider provideGetFunctionPropertiesCases
  2011. */
  2012. public function testGetFunctionProperties(string $source, int $index, array $expected): void
  2013. {
  2014. $tokens = Tokens::fromCode($source);
  2015. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2016. $attributes = $tokensAnalyzer->getMethodAttributes($index);
  2017. self::assertSame($expected, $attributes);
  2018. }
  2019. public static function provideGetFunctionPropertiesCases(): iterable
  2020. {
  2021. $defaultAttributes = [
  2022. 'visibility' => null,
  2023. 'static' => false,
  2024. 'abstract' => false,
  2025. 'final' => false,
  2026. ];
  2027. $template = '
  2028. <?php
  2029. class TestClass {
  2030. %s function a() {
  2031. //
  2032. }
  2033. }
  2034. ';
  2035. $cases = [];
  2036. $attributes = $defaultAttributes;
  2037. $attributes['visibility'] = T_PRIVATE;
  2038. $cases[] = [sprintf($template, 'private'), 10, $attributes];
  2039. $attributes = $defaultAttributes;
  2040. $attributes['visibility'] = T_PUBLIC;
  2041. $cases[] = [sprintf($template, 'public'), 10, $attributes];
  2042. $attributes = $defaultAttributes;
  2043. $attributes['visibility'] = T_PROTECTED;
  2044. $cases[] = [sprintf($template, 'protected'), 10, $attributes];
  2045. $attributes = $defaultAttributes;
  2046. $attributes['visibility'] = null;
  2047. $attributes['static'] = true;
  2048. $cases[] = [sprintf($template, 'static'), 10, $attributes];
  2049. $attributes = $defaultAttributes;
  2050. $attributes['visibility'] = T_PUBLIC;
  2051. $attributes['static'] = true;
  2052. $attributes['final'] = true;
  2053. $cases[] = [sprintf($template, 'final public static'), 14, $attributes];
  2054. $attributes = $defaultAttributes;
  2055. $attributes['visibility'] = null;
  2056. $attributes['abstract'] = true;
  2057. $cases[] = [sprintf($template, 'abstract'), 10, $attributes];
  2058. $attributes = $defaultAttributes;
  2059. $attributes['visibility'] = T_PUBLIC;
  2060. $attributes['abstract'] = true;
  2061. $cases[] = [sprintf($template, 'abstract public'), 12, $attributes];
  2062. $attributes = $defaultAttributes;
  2063. $cases[] = [sprintf($template, ''), 8, $attributes];
  2064. return $cases;
  2065. }
  2066. public function testIsWhilePartOfDoWhile(): void
  2067. {
  2068. $source =
  2069. <<<'SRC'
  2070. <?php
  2071. // `not do`
  2072. while(false) {
  2073. }
  2074. while (false);
  2075. while (false)?>
  2076. <?php
  2077. if(false){
  2078. }while(false);
  2079. if(false){
  2080. }while(false)?><?php
  2081. while(false){}while(false){}
  2082. while ($i <= 10):
  2083. echo $i;
  2084. $i++;
  2085. endwhile;
  2086. ?>
  2087. <?php while(false): ?>
  2088. <?php endwhile ?>
  2089. <?php
  2090. // `do`
  2091. do{
  2092. } while(false);
  2093. do{
  2094. } while(false)?>
  2095. <?php
  2096. if (false){}do{}while(false);
  2097. // `not do`, `do`
  2098. if(false){}while(false){}do{}while(false);
  2099. SRC;
  2100. $expected = [
  2101. 3 => false,
  2102. 12 => false,
  2103. 19 => false,
  2104. 34 => false,
  2105. 47 => false,
  2106. 53 => false,
  2107. 59 => false,
  2108. 66 => false,
  2109. 91 => false,
  2110. 112 => true,
  2111. 123 => true,
  2112. 139 => true,
  2113. 153 => false,
  2114. 162 => true,
  2115. ];
  2116. $tokens = Tokens::fromCode($source);
  2117. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2118. foreach ($tokens as $index => $token) {
  2119. if (!$token->isGivenKind(T_WHILE)) {
  2120. continue;
  2121. }
  2122. self::assertSame(
  2123. $expected[$index],
  2124. $tokensAnalyzer->isWhilePartOfDoWhile($index),
  2125. sprintf('Expected token at index "%d" to be detected as %sa "do-while"-loop.', $index, true === $expected[$index] ? '' : 'not ')
  2126. );
  2127. }
  2128. }
  2129. /**
  2130. * @dataProvider provideIsEnumCaseCases
  2131. *
  2132. * @param array<int, bool> $expected
  2133. *
  2134. * @requires PHP 8.1
  2135. */
  2136. public function testIsEnumCase(string $source, array $expected): void
  2137. {
  2138. $tokens = Tokens::fromCode($source);
  2139. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2140. foreach ($tokens as $index => $token) {
  2141. if (!$token->isGivenKind(T_CASE)) {
  2142. try {
  2143. $tokensAnalyzer->isEnumCase($index);
  2144. self::fail('TokensAnalyzer::isEnumCase() did not throw LogicException.');
  2145. } catch (\Throwable $e) {
  2146. self::assertInstanceOf(\LogicException::class, $e);
  2147. self::assertMatchesRegularExpression('/^No T_CASE given at index \d+, got \S+ instead\.$/', $e->getMessage());
  2148. }
  2149. continue;
  2150. }
  2151. self::assertSame($expected[$index], $tokensAnalyzer->isEnumCase($index));
  2152. }
  2153. }
  2154. public static function provideIsEnumCaseCases(): iterable
  2155. {
  2156. yield 'switch only' => [
  2157. '<?php
  2158. function bar(string $a): string
  2159. {
  2160. switch ($a) {
  2161. case \'one\':
  2162. return $a;
  2163. case \'two\':
  2164. default:
  2165. return strtoupper($a);
  2166. }
  2167. }
  2168. ',
  2169. [
  2170. 23 => false,
  2171. 33 => false,
  2172. ],
  2173. ];
  2174. yield 'pure enum' => [
  2175. '<?php
  2176. enum Foo
  2177. {
  2178. case One;
  2179. case Two;
  2180. }
  2181. ',
  2182. [
  2183. 7 => true,
  2184. 12 => true,
  2185. ],
  2186. ];
  2187. yield 'pure enum with switch' => [
  2188. '<?php
  2189. enum Foo
  2190. {
  2191. case One;
  2192. case Two;
  2193. public static function getLowerName(self $instance): string
  2194. {
  2195. switch ($instance->name) {
  2196. case \'One\':
  2197. case \'Two\':
  2198. return strtolower($instance->name);
  2199. }
  2200. }
  2201. }
  2202. ',
  2203. [
  2204. 7 => true,
  2205. 12 => true,
  2206. 45 => false,
  2207. 50 => false,
  2208. ],
  2209. ];
  2210. yield 'backed enum' => [
  2211. '<?php
  2212. enum Suit: string
  2213. {
  2214. case Hearts = \'hearts\';
  2215. case Spades = \'spades\';
  2216. case Clubs = \'clubs\';
  2217. case Diamonds = \'diamonds\';
  2218. }
  2219. ',
  2220. [
  2221. 10 => true,
  2222. 19 => true,
  2223. 28 => true,
  2224. 37 => true,
  2225. ],
  2226. ];
  2227. yield 'backed enum with switch' => [
  2228. '<?php
  2229. enum Suit: string
  2230. {
  2231. case Hearts = \'hearts\';
  2232. case Spades = \'spades\';
  2233. case Clubs = \'clubs\';
  2234. case Diamonds = \'diamonds\';
  2235. public static function getUppercasedValue(self $instance): string
  2236. {
  2237. switch ($instance->value) {
  2238. case \'hearts\':
  2239. case \'spades\':
  2240. return strtoupper($instance->value);
  2241. default:
  2242. return $instance->value;
  2243. }
  2244. }
  2245. }
  2246. ',
  2247. [
  2248. 10 => true,
  2249. 19 => true,
  2250. 28 => true,
  2251. 37 => true,
  2252. 74 => false,
  2253. 79 => false,
  2254. ],
  2255. ];
  2256. }
  2257. /**
  2258. * @param array<int, list<int>>|list<int> $expected
  2259. *
  2260. * @dataProvider provideGetImportUseIndexesCases
  2261. */
  2262. public function testGetImportUseIndexes(array $expected, string $input, bool $perNamespace = false): void
  2263. {
  2264. $tokens = Tokens::fromCode($input);
  2265. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2266. self::assertSame($expected, $tokensAnalyzer->getImportUseIndexes($perNamespace));
  2267. }
  2268. public static function provideGetImportUseIndexesCases(): iterable
  2269. {
  2270. yield [
  2271. [1, 8],
  2272. '<?php use E\F?><?php use A\B;',
  2273. ];
  2274. yield [
  2275. [[1], [14], [29]],
  2276. '<?php
  2277. use T\A;
  2278. namespace A { use D\C; }
  2279. namespace b { use D\C; }
  2280. ',
  2281. true,
  2282. ];
  2283. yield [
  2284. [[1, 8]],
  2285. '<?php use D\B; use A\C?>',
  2286. true,
  2287. ];
  2288. yield [
  2289. [1, 8],
  2290. '<?php use D\B; use A\C?>',
  2291. ];
  2292. yield [
  2293. [7, 22],
  2294. '<?php
  2295. namespace A { use D\C; }
  2296. namespace b { use D\C; }
  2297. ',
  2298. ];
  2299. yield [
  2300. [3, 10, 34, 45, 54, 59, 77, 95],
  2301. <<<'EOF'
  2302. use Zoo\Bar;
  2303. use Foo\Bar;
  2304. use Foo\Zar\Baz;
  2305. <?php
  2306. use Foo\Bar;
  2307. use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar as FooBaz;
  2308. use Foo\Bir as FBB;
  2309. use Foo\Zar\Baz;
  2310. use SomeClass;
  2311. use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
  2312. use Zoo\Bar;
  2313. $a = new someclass();
  2314. use Zoo\Tar;
  2315. class AnnotatedClass
  2316. {
  2317. }
  2318. EOF,
  2319. ];
  2320. yield [
  2321. [1, 22, 41],
  2322. '<?php
  2323. use some\a\{ClassA, ClassB, ClassC as C};
  2324. use function some\a\{fn_a, fn_b, fn_c};
  2325. use const some\a\{ConstA, ConstB, ConstC};
  2326. ',
  2327. ];
  2328. yield [
  2329. [[1, 22, 41]],
  2330. '<?php
  2331. use some\a\{ClassA, ClassB, ClassC as C};
  2332. use function some\a\{fn_a, fn_b, fn_c};
  2333. use const some\a\{ConstA, ConstB, ConstC};
  2334. ',
  2335. true,
  2336. ];
  2337. yield [
  2338. [1, 23, 43],
  2339. '<?php
  2340. use some\a\{ClassA, ClassB, ClassC as C,};
  2341. use function some\a\{fn_a, fn_b, fn_c,};
  2342. use const some\a\{ConstA, ConstB, ConstC,};
  2343. ',
  2344. ];
  2345. yield [
  2346. [[1, 23, 43]],
  2347. '<?php
  2348. use some\a\{ClassA, ClassB, ClassC as C,};
  2349. use function some\a\{fn_a, fn_b, fn_c,};
  2350. use const some\a\{ConstA, ConstB, ConstC,};
  2351. ',
  2352. true,
  2353. ];
  2354. }
  2355. public function testGetClassyElementsWithMultipleNestedAnonymousClass(): void
  2356. {
  2357. $source = '<?php
  2358. class MyTestWithAnonymousClass extends TestCase
  2359. {
  2360. public function setUp()
  2361. {
  2362. $provider = new class(function () {}) {};
  2363. }
  2364. public function testSomethingWithMoney(
  2365. Money $amount
  2366. ) {
  2367. $a = new class(function () {
  2368. new class(function () {
  2369. new class(function () {})
  2370. {
  2371. const A=1;
  2372. };
  2373. })
  2374. {
  2375. const B=1;
  2376. public function foo() {
  2377. $c = new class() {const AA=3;};
  2378. $d = new class {const AB=3;};
  2379. }
  2380. };
  2381. })
  2382. {
  2383. const C=1;
  2384. };
  2385. }
  2386. }';
  2387. $tokens = Tokens::fromCode($source);
  2388. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2389. $elements = $tokensAnalyzer->getClassyElements();
  2390. self::assertSame([
  2391. 13 => [
  2392. 'classIndex' => 1,
  2393. 'token' => $tokens[13],
  2394. 'type' => 'method', // setUp
  2395. ],
  2396. 46 => [
  2397. 'classIndex' => 1,
  2398. 'token' => $tokens[46],
  2399. 'type' => 'method', // testSomethingWithMoney
  2400. ],
  2401. 100 => [
  2402. 'classIndex' => 87,
  2403. 'token' => $tokens[100], // const A
  2404. 'type' => 'const',
  2405. ],
  2406. 115 => [
  2407. 'classIndex' => 65,
  2408. 'token' => $tokens[115], // const B
  2409. 'type' => 'const',
  2410. ],
  2411. 124 => [
  2412. 'classIndex' => 65, // $a
  2413. 'token' => $tokens[124],
  2414. 'type' => 'method', // foo
  2415. ],
  2416. 143 => [
  2417. 'classIndex' => 138,
  2418. 'token' => $tokens[143], // const AA
  2419. 'type' => 'const',
  2420. ],
  2421. 161 => [
  2422. 'classIndex' => 158,
  2423. 'token' => $tokens[161], // const AB
  2424. 'type' => 'const',
  2425. ],
  2426. ], $elements);
  2427. }
  2428. /**
  2429. * @dataProvider provideIsSuperGlobalCases
  2430. */
  2431. public function testIsSuperGlobal(bool $expected, string $source, int $index): void
  2432. {
  2433. $tokens = Tokens::fromCode($source);
  2434. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2435. self::assertSame($expected, $tokensAnalyzer->isSuperGlobal($index));
  2436. }
  2437. public static function provideIsSuperGlobalCases(): iterable
  2438. {
  2439. $superNames = [
  2440. '$_COOKIE',
  2441. '$_ENV',
  2442. '$_FILES',
  2443. '$_GET',
  2444. '$_POST',
  2445. '$_REQUEST',
  2446. '$_SERVER',
  2447. '$_SESSION',
  2448. '$GLOBALS',
  2449. ];
  2450. $cases = [];
  2451. foreach ($superNames as $superName) {
  2452. $cases[] = [
  2453. true,
  2454. sprintf('<?php echo %s[0];', $superName),
  2455. 3,
  2456. ];
  2457. }
  2458. $notGlobalCodeCases = [
  2459. '<?php echo 1; $a = static function($b) use ($a) { $a->$b(); }; // $_SERVER',
  2460. '<?php class Foo{}?> <?php $_A = 1; /* $_SESSION */',
  2461. ];
  2462. foreach ($notGlobalCodeCases as $notGlobalCodeCase) {
  2463. $tokensCount = \count(Tokens::fromCode($notGlobalCodeCase));
  2464. for ($i = 0; $i < $tokensCount; ++$i) {
  2465. $cases[] = [
  2466. false,
  2467. $notGlobalCodeCase,
  2468. $i,
  2469. ];
  2470. }
  2471. }
  2472. return $cases;
  2473. }
  2474. /**
  2475. * @dataProvider provideGetClassyModifiersCases
  2476. *
  2477. * @param array<string, null|int> $expectedModifiers
  2478. */
  2479. public function testGetClassyModifiers(array $expectedModifiers, int $index, string $source): void
  2480. {
  2481. $tokens = Tokens::fromCode($source);
  2482. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2483. self::assertSame($expectedModifiers, $tokensAnalyzer->getClassyModifiers($index));
  2484. }
  2485. public static function provideGetClassyModifiersCases(): iterable
  2486. {
  2487. yield 'final' => [
  2488. ['final' => 1, 'abstract' => null, 'readonly' => null],
  2489. 3,
  2490. '<?php final class Foo {}',
  2491. ];
  2492. yield 'abstract' => [
  2493. ['final' => null, 'abstract' => 3, 'readonly' => null],
  2494. 5,
  2495. '<?php /* comment */ abstract class Foo {}',
  2496. ];
  2497. }
  2498. /**
  2499. * @requires PHP 8.2
  2500. *
  2501. * @dataProvider provideGetClassyModifiersOnPhp82Cases
  2502. *
  2503. * @param array<string, null|int> $expectedModifiers
  2504. */
  2505. public function testGetClassyModifiersOnPhp82(array $expectedModifiers, int $index, string $source): void
  2506. {
  2507. $tokens = Tokens::fromCode($source);
  2508. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2509. self::assertSame($expectedModifiers, $tokensAnalyzer->getClassyModifiers($index));
  2510. }
  2511. public static function provideGetClassyModifiersOnPhp82Cases(): iterable
  2512. {
  2513. yield 'readonly' => [
  2514. ['final' => null, 'abstract' => null, 'readonly' => 1],
  2515. 3,
  2516. '<?php readonly class Foo {}',
  2517. ];
  2518. yield 'readonly final' => [
  2519. ['final' => 3, 'abstract' => null, 'readonly' => 1],
  2520. 5,
  2521. '<?php readonly final class Foo {}',
  2522. ];
  2523. yield 'readonly final reversed' => [
  2524. ['final' => 1, 'abstract' => null, 'readonly' => 3],
  2525. 5,
  2526. '<?php final readonly class Foo {}',
  2527. ];
  2528. yield 'readonly final reversed + comment' => [
  2529. ['final' => 1, 'abstract' => null, 'readonly' => 5],
  2530. 7,
  2531. '<?php final /* comment */ readonly class Foo {}',
  2532. ];
  2533. yield 'readonly abstract' => [
  2534. ['final' => null, 'abstract' => 3, 'readonly' => 1],
  2535. 5,
  2536. '<?php readonly abstract class Foo {}',
  2537. ];
  2538. yield 'readonly abstract reversed' => [
  2539. ['final' => null, 'abstract' => 1, 'readonly' => 3],
  2540. 5,
  2541. '<?php abstract readonly class Foo {}',
  2542. ];
  2543. yield 'readonly abstract reversed + comment' => [
  2544. ['final' => null, 'abstract' => 1, 'readonly' => 5],
  2545. 7,
  2546. '<?php abstract /* comment */ readonly class Foo {}',
  2547. ];
  2548. }
  2549. public function testGetClassyModifiersForNonClassyThrowsAnException(): void
  2550. {
  2551. $tokens = Tokens::fromCode('<?php echo 1;');
  2552. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2553. $this->expectException(\InvalidArgumentException::class);
  2554. $tokensAnalyzer->getClassyModifiers(1);
  2555. }
  2556. /**
  2557. * @dataProvider provideGetLastTokenIndexOfArrowFunctionCases
  2558. *
  2559. * @param array<int, int> $expectations
  2560. */
  2561. public function testGetLastTokenIndexOfArrowFunction(array $expectations, string $source): void
  2562. {
  2563. $tokens = Tokens::fromCode($source);
  2564. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2565. $indices = [];
  2566. foreach ($expectations as $index => $expectedEndIndex) {
  2567. $indices[$index] = $tokensAnalyzer->getLastTokenIndexOfArrowFunction($index);
  2568. }
  2569. self::assertSame($expectations, $indices);
  2570. }
  2571. public static function provideGetLastTokenIndexOfArrowFunctionCases(): iterable
  2572. {
  2573. yield 'simple cases' => [
  2574. [
  2575. 2 => 11,
  2576. 16 => 25,
  2577. 28 => 39,
  2578. 46 => 61,
  2579. ],
  2580. '<?php
  2581. fn(array $x) => $x;
  2582. static fn(): int => $x;
  2583. fn($x = 42) => $x;
  2584. $eq = fn ($x, $y) => $x == $y;
  2585. ',
  2586. ];
  2587. yield 'references, splat and arrow cases' => [
  2588. [
  2589. 2 => 10,
  2590. 13 => 21,
  2591. 24 => 35,
  2592. 42 => 51,
  2593. 65 => 77,
  2594. ],
  2595. '<?php
  2596. fn(&$x) => $x;
  2597. fn&($x) => $x;
  2598. fn($x, ...$rest) => $rest;
  2599. $fn = fn(&$x) => $x++;
  2600. $y = &$fn($x);
  2601. fn($x, &...$rest) => 1;
  2602. ',
  2603. ];
  2604. yield 'different endings' => [
  2605. [
  2606. 9 => 21,
  2607. 31 => 43,
  2608. ],
  2609. '<?php
  2610. $results = array_map(
  2611. fn ($item) => $item * 2,
  2612. $list
  2613. );
  2614. return fn ($y) => $x * $y ?>
  2615. ',
  2616. ];
  2617. yield 'nested arrow function' => [
  2618. [
  2619. 1 => 26,
  2620. 14 => 25,
  2621. ],
  2622. '<?php fn(array $x, $z) => (fn(int $z):bool => $z);',
  2623. ];
  2624. yield 'arrow function as argument' => [
  2625. [
  2626. 5 => 14,
  2627. ],
  2628. '<?php return foo(fn(array $x) => $x);',
  2629. ];
  2630. yield 'arrow function as collection item' => [
  2631. [
  2632. 9 => 18,
  2633. 26 => 35,
  2634. 46 => 55,
  2635. 62 => 69,
  2636. ],
  2637. '<?php return [
  2638. [1, fn(array $x) => $x1, 1],
  2639. [fn(array $x) => $x2, 1],
  2640. [1, fn(array $x) => $x3],
  2641. ([(fn($x4) => $x5)]),
  2642. ];',
  2643. ];
  2644. yield 'nested inside anonymous class' => [
  2645. [
  2646. 1 => 46,
  2647. 33 => 41,
  2648. ],
  2649. '<?php fn($x) => $a = new class($x) { public function foo() { return fn(&$x) => $x; } };',
  2650. ];
  2651. yield 'array destructuring' => [
  2652. [
  2653. 4 => 13,
  2654. ],
  2655. '<?php return [fn(array $x) => $x1] = $x;',
  2656. ];
  2657. yield 'array_map() callback with different token blocks' => [
  2658. [
  2659. 9 => 28,
  2660. ],
  2661. '<?php
  2662. $a = array_map(
  2663. fn (array $item) => $item[\'callback\']($item[\'value\']),
  2664. [/* items */]
  2665. );
  2666. ',
  2667. ];
  2668. yield 'arrow function returning array' => [
  2669. [
  2670. 5 => 21,
  2671. ],
  2672. '<?php $z = fn ($a) => [0, 1, $a];',
  2673. ];
  2674. }
  2675. public function testCannotGetLastTokenIndexOfArrowFunctionForNonFnToken(): void
  2676. {
  2677. $tokens = Tokens::fromCode('<?php echo 1;');
  2678. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2679. $this->expectException(\InvalidArgumentException::class);
  2680. $tokensAnalyzer->getLastTokenIndexOfArrowFunction(1);
  2681. }
  2682. /**
  2683. * @param array<int, bool> $expected
  2684. */
  2685. private function doIsConstantInvocationTest(array $expected, string $source): void
  2686. {
  2687. $tokens = Tokens::fromCode($source);
  2688. self::assertCount(
  2689. $tokens->countTokenKind(T_STRING),
  2690. $expected,
  2691. 'All T_STRING tokens must be tested'
  2692. );
  2693. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2694. foreach ($expected as $index => $expectedValue) {
  2695. self::assertSame(
  2696. $expectedValue,
  2697. $tokensAnalyzer->isConstantInvocation($index),
  2698. sprintf('Token at index '.$index.' should match the expected value (%s).', $expectedValue ? 'true' : 'false')
  2699. );
  2700. }
  2701. }
  2702. }