TokensAnalyzerTest.php 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060
  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. public function testIsConstantInvocationInvalid(): void
  1298. {
  1299. $this->expectException(\LogicException::class);
  1300. $this->expectExceptionMessage('No T_STRING at given index 0, got "T_OPEN_TAG".');
  1301. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode('<?php '));
  1302. $tokensAnalyzer->isConstantInvocation(0);
  1303. }
  1304. /**
  1305. * @requires PHP 8.0
  1306. */
  1307. public function testIsConstantInvocationForNullSafeObjectOperator(): void
  1308. {
  1309. $tokens = Tokens::fromCode('<?php $a?->b?->c;');
  1310. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1311. foreach ($tokens as $index => $token) {
  1312. if (!$token->isGivenKind(T_STRING)) {
  1313. continue;
  1314. }
  1315. self::assertFalse($tokensAnalyzer->isConstantInvocation($index));
  1316. }
  1317. }
  1318. /**
  1319. * @param array<int, bool> $expected
  1320. *
  1321. * @dataProvider provideIsUnarySuccessorOperatorCases
  1322. */
  1323. public function testIsUnarySuccessorOperator(array $expected, string $source): void
  1324. {
  1325. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1326. foreach ($expected as $index => $isUnary) {
  1327. self::assertSame($isUnary, $tokensAnalyzer->isUnarySuccessorOperator($index));
  1328. if ($isUnary) {
  1329. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1330. self::assertFalse($tokensAnalyzer->isBinaryOperator($index));
  1331. }
  1332. }
  1333. }
  1334. public static function provideIsUnarySuccessorOperatorCases(): iterable
  1335. {
  1336. yield [
  1337. [2 => true],
  1338. '<?php $a++;',
  1339. ];
  1340. yield [
  1341. [2 => true],
  1342. '<?php $a--;',
  1343. ];
  1344. yield [
  1345. [3 => true],
  1346. '<?php $a ++;',
  1347. ];
  1348. yield [
  1349. [2 => true, 4 => false],
  1350. '<?php $a++ + 1;',
  1351. ];
  1352. yield [
  1353. [5 => true],
  1354. '<?php ${"a"}++;',
  1355. ];
  1356. yield [
  1357. [4 => true],
  1358. '<?php $foo->bar++;',
  1359. ];
  1360. yield [
  1361. [6 => true],
  1362. '<?php $foo->{"bar"}++;',
  1363. ];
  1364. yield 'array access' => [
  1365. [5 => true],
  1366. '<?php $a["foo"]++;',
  1367. ];
  1368. yield 'array curly access' => [
  1369. [5 => true],
  1370. '<?php $a{"foo"}++;',
  1371. ];
  1372. }
  1373. /**
  1374. * @param list<int> $expected
  1375. *
  1376. * @dataProvider provideIsUnaryPredecessorOperatorCases
  1377. */
  1378. public function testIsUnaryPredecessorOperator(array $expected, string $source): void
  1379. {
  1380. $tokens = Tokens::fromCode($source);
  1381. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1382. foreach ($tokens as $index => $token) {
  1383. $expect = \in_array($index, $expected, true);
  1384. self::assertSame(
  1385. $expect,
  1386. $tokensAnalyzer->isUnaryPredecessorOperator($index),
  1387. sprintf('Expected %sunary predecessor operator, got @ %d "%s".', $expect ? '' : 'no ', $index, var_export($token, true))
  1388. );
  1389. if ($expect) {
  1390. self::assertFalse(
  1391. $tokensAnalyzer->isUnarySuccessorOperator($index),
  1392. sprintf('Expected no unary successor operator, got @ %d "%s".', $index, var_export($token, true))
  1393. );
  1394. self::assertFalse(
  1395. $tokensAnalyzer->isBinaryOperator($index),
  1396. sprintf('Expected no binary operator, got @ %d "%s".', $index, var_export($token, true))
  1397. );
  1398. }
  1399. }
  1400. }
  1401. public static function provideIsUnaryPredecessorOperatorCases(): iterable
  1402. {
  1403. yield [
  1404. [1],
  1405. '<?php ++$a;',
  1406. ];
  1407. yield [
  1408. [1],
  1409. '<?php --$a;',
  1410. ];
  1411. yield [
  1412. [1],
  1413. '<?php -- $a;',
  1414. ];
  1415. yield [
  1416. [5],
  1417. '<?php $a + ++$b;',
  1418. ];
  1419. yield [
  1420. [1, 2],
  1421. '<?php !!$a;',
  1422. ];
  1423. yield [
  1424. [5],
  1425. '<?php $a = &$b;',
  1426. ];
  1427. yield [
  1428. [3],
  1429. '<?php function &foo() {}',
  1430. ];
  1431. yield [
  1432. [1],
  1433. '<?php @foo();',
  1434. ];
  1435. yield [
  1436. [3, 8],
  1437. '<?php foo(+ $a, -$b);',
  1438. ];
  1439. yield [
  1440. [5, 11, 17],
  1441. '<?php function foo(&$a, array &$b, Bar &$c) {}',
  1442. ];
  1443. yield [
  1444. [8],
  1445. '<?php function foo($a, ...$b) {}',
  1446. ];
  1447. yield [
  1448. [5, 6],
  1449. '<?php function foo(&...$b) {}',
  1450. ];
  1451. yield [
  1452. [7],
  1453. '<?php function foo(array ...$b) {}',
  1454. ];
  1455. yield [
  1456. [7],
  1457. '<?php $foo = function(...$a) {};',
  1458. ];
  1459. yield [
  1460. [10],
  1461. '<?php $foo = function($a, ...$b) {};',
  1462. ];
  1463. yield [
  1464. [9],
  1465. '<?php $foo = function(int &$x) {};',
  1466. ];
  1467. yield [
  1468. [9],
  1469. '<?php $foo = fn(int &$x) => null;',
  1470. ];
  1471. yield [
  1472. [],
  1473. '<?php fn() => A_CONSTANT & $object->property;',
  1474. ];
  1475. }
  1476. /**
  1477. * @param list<int> $expected
  1478. *
  1479. * @dataProvider provideIsBinaryOperatorCases
  1480. */
  1481. public function testIsBinaryOperator(array $expected, string $source): void
  1482. {
  1483. $tokens = Tokens::fromCode($source);
  1484. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1485. foreach ($tokens as $index => $token) {
  1486. $expect = \in_array($index, $expected, true);
  1487. self::assertSame(
  1488. $expect,
  1489. $tokensAnalyzer->isBinaryOperator($index),
  1490. sprintf('Expected %sbinary operator, got @ %d "%s".', $expect ? '' : 'no ', $index, var_export($token, true))
  1491. );
  1492. if ($expect) {
  1493. self::assertFalse(
  1494. $tokensAnalyzer->isUnarySuccessorOperator($index),
  1495. sprintf('Expected no unary successor operator, got @ %d "%s".', $index, var_export($token, true))
  1496. );
  1497. self::assertFalse(
  1498. $tokensAnalyzer->isUnaryPredecessorOperator($index),
  1499. sprintf('Expected no unary predecessor operator, got @ %d "%s".', $index, var_export($token, true))
  1500. );
  1501. }
  1502. }
  1503. }
  1504. public static function provideIsBinaryOperatorCases(): iterable
  1505. {
  1506. yield [
  1507. [8],
  1508. '<?php echo $a[1] + 1;',
  1509. ];
  1510. yield [
  1511. [8],
  1512. '<?php echo $a{1} + 1;',
  1513. ];
  1514. yield [
  1515. [3],
  1516. '<?php $a .= $b; ?>',
  1517. ];
  1518. yield [
  1519. [3],
  1520. '<?php $a . \'a\' ?>',
  1521. ];
  1522. yield [
  1523. [3],
  1524. '<?php $a &+ $b;',
  1525. ];
  1526. yield [
  1527. [3],
  1528. '<?php $a && $b;',
  1529. ];
  1530. yield [
  1531. [3],
  1532. '<?php $a & $b;',
  1533. ];
  1534. yield [
  1535. [4],
  1536. '<?php [] + [];',
  1537. ];
  1538. yield [
  1539. [3],
  1540. '<?php $a + $b;',
  1541. ];
  1542. yield [
  1543. [3],
  1544. '<?php 1 + $b;',
  1545. ];
  1546. yield [
  1547. [3],
  1548. '<?php 0.2 + $b;',
  1549. ];
  1550. yield [
  1551. [6],
  1552. '<?php $a[1] + $b;',
  1553. ];
  1554. yield [
  1555. [3],
  1556. '<?php FOO + $b;',
  1557. ];
  1558. yield [
  1559. [5],
  1560. '<?php foo() + $b;',
  1561. ];
  1562. yield [
  1563. [6],
  1564. '<?php ${"foo"} + $b;',
  1565. ];
  1566. yield [
  1567. [2],
  1568. '<?php $a+$b;',
  1569. ];
  1570. yield [
  1571. [5],
  1572. '<?php $a /* foo */ + /* bar */ $b;',
  1573. ];
  1574. yield [
  1575. [3],
  1576. '<?php $a =
  1577. $b;',
  1578. ];
  1579. yield [
  1580. [3],
  1581. '<?php $a
  1582. = $b;',
  1583. ];
  1584. yield [
  1585. [3, 9],
  1586. '<?php $a = array("b" => "c", );',
  1587. ];
  1588. yield [
  1589. [3],
  1590. '<?php $a * -$b;',
  1591. ];
  1592. yield [
  1593. [3, 8],
  1594. '<?php $a = -2 / +5;',
  1595. ];
  1596. yield [
  1597. [3, 5 => false],
  1598. '<?php $a = &$b;',
  1599. ];
  1600. yield [
  1601. [4],
  1602. '<?php $a++ + $b;',
  1603. ];
  1604. yield [
  1605. [3, 7],
  1606. '<?php $a = FOO & $bar;',
  1607. ];
  1608. yield [
  1609. [3],
  1610. '<?php __LINE__ - 1;',
  1611. ];
  1612. yield [
  1613. [5],
  1614. '<?php `echo 1` + 1;',
  1615. ];
  1616. yield [
  1617. [3],
  1618. '<?php $a ** $b;',
  1619. ];
  1620. yield [
  1621. [3],
  1622. '<?php $a **= $b;',
  1623. ];
  1624. yield [
  1625. [3],
  1626. '<?php $a = "{$value}-{$theSwitch}";',
  1627. ];
  1628. yield [
  1629. [],
  1630. '<?=$path?>-<?=$id?>',
  1631. ];
  1632. $operators = [
  1633. '+', '-', '*', '/', '%', '<', '>', '|', '^', '&=', '&&', '||', '.=', '/=', '==', '>=', '===', '!=',
  1634. '<>', '!==', '<=', 'and', 'or', 'xor', '-=', '%=', '*=', '|=', '+=', '<<', '<<=', '>>', '>>=', '^',
  1635. ];
  1636. foreach ($operators as $operator) {
  1637. yield [
  1638. [3],
  1639. '<?php $a '.$operator.' $b;',
  1640. ];
  1641. }
  1642. yield [
  1643. [3],
  1644. '<?php $a <=> $b;',
  1645. ];
  1646. yield [
  1647. [3],
  1648. '<?php $a ?? $b;',
  1649. ];
  1650. yield [
  1651. [],
  1652. '<?php try {} catch (A | B $e) {}',
  1653. ];
  1654. yield [
  1655. [3],
  1656. '<?php $a ??= $b;',
  1657. ];
  1658. yield [
  1659. [5, 11],
  1660. '<?php fn() => $object->property & A_CONSTANT;',
  1661. ];
  1662. }
  1663. /**
  1664. * @dataProvider provideIsArrayCases
  1665. */
  1666. public function testIsArray(string $source, int $tokenIndex, bool $isMultiLineArray = false): void
  1667. {
  1668. $tokens = Tokens::fromCode($source);
  1669. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1670. self::assertTrue($tokensAnalyzer->isArray($tokenIndex), 'Expected to be an array.');
  1671. self::assertSame($isMultiLineArray, $tokensAnalyzer->isArrayMultiLine($tokenIndex), sprintf('Expected %sto be a multiline array', $isMultiLineArray ? '' : 'not '));
  1672. }
  1673. public static function provideIsArrayCases(): iterable
  1674. {
  1675. yield [
  1676. '<?php
  1677. array("a" => 1);
  1678. ',
  1679. 2,
  1680. ];
  1681. yield [
  1682. '<?php
  1683. ["a" => 2];
  1684. ',
  1685. 2, false,
  1686. ];
  1687. yield [
  1688. '<?php
  1689. array(
  1690. "a" => 3
  1691. );
  1692. ',
  1693. 2, true,
  1694. ];
  1695. yield [
  1696. '<?php
  1697. [
  1698. "a" => 4
  1699. ];
  1700. ',
  1701. 2, true,
  1702. ];
  1703. yield [
  1704. '<?php
  1705. array(
  1706. "a" => array(5, 6, 7),
  1707. 8 => new \Exception(\'Hello\')
  1708. );
  1709. ',
  1710. 2, true,
  1711. ];
  1712. yield [
  1713. // mix short array syntax
  1714. '<?php
  1715. array(
  1716. "a" => [9, 10, 11],
  1717. 12 => new \Exception(\'Hello\')
  1718. );
  1719. ',
  1720. 2, true,
  1721. ];
  1722. // Windows/Max EOL testing
  1723. yield [
  1724. "<?php\r\narray('a' => 13);\r\n",
  1725. 1,
  1726. ];
  1727. yield [
  1728. "<?php\r\n array(\r\n 'a' => 14,\r\n 'b' => 15\r\n );\r\n",
  1729. 2, true,
  1730. ];
  1731. }
  1732. /**
  1733. * @param list<int> $tokenIndexes
  1734. *
  1735. * @dataProvider provideIsArray71Cases
  1736. */
  1737. public function testIsArray71(string $source, array $tokenIndexes): void
  1738. {
  1739. $tokens = Tokens::fromCode($source);
  1740. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1741. foreach ($tokens as $index => $token) {
  1742. $expect = \in_array($index, $tokenIndexes, true);
  1743. self::assertSame(
  1744. $expect,
  1745. $tokensAnalyzer->isArray($index),
  1746. sprintf('Expected %sarray, got @ %d "%s".', $expect ? '' : 'no ', $index, var_export($token, true))
  1747. );
  1748. }
  1749. }
  1750. public static function provideIsArray71Cases(): iterable
  1751. {
  1752. yield [
  1753. '<?php
  1754. [$a] = $z;
  1755. ["a" => $a, "b" => $b] = $array;
  1756. $c = [$d, $e] = $array[$a];
  1757. [[$a, $b], [$c, $d]] = $d;
  1758. $array = []; $d = array();
  1759. ',
  1760. [76, 84],
  1761. ];
  1762. }
  1763. /**
  1764. * @param array<int, bool> $expected
  1765. *
  1766. * @dataProvider provideIsBinaryOperator80Cases
  1767. *
  1768. * @requires PHP 8.0
  1769. */
  1770. public function testIsBinaryOperator80(array $expected, string $source): void
  1771. {
  1772. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1773. foreach ($expected as $index => $isBinary) {
  1774. self::assertSame($isBinary, $tokensAnalyzer->isBinaryOperator($index));
  1775. if ($isBinary) {
  1776. self::assertFalse($tokensAnalyzer->isUnarySuccessorOperator($index));
  1777. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1778. }
  1779. }
  1780. }
  1781. public static function provideIsBinaryOperator80Cases(): iterable
  1782. {
  1783. yield [
  1784. [6 => false],
  1785. '<?php function foo(array|string $x) {}',
  1786. ];
  1787. yield [
  1788. [6 => false],
  1789. '<?php function foo(string|array $x) {}',
  1790. ];
  1791. yield [
  1792. [6 => false],
  1793. '<?php function foo(int|callable $x) {}',
  1794. ];
  1795. yield [
  1796. [6 => false],
  1797. '<?php function foo(callable|int $x) {}',
  1798. ];
  1799. yield [
  1800. [6 => false],
  1801. '<?php function foo(bool|int &$x) {}',
  1802. ];
  1803. }
  1804. /**
  1805. * @param array<int, bool> $expected
  1806. *
  1807. * @dataProvider provideIsBinaryOperator81Cases
  1808. *
  1809. * @requires PHP 8.1
  1810. */
  1811. public function testIsBinaryOperator81(array $expected, string $source): void
  1812. {
  1813. $tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
  1814. foreach ($expected as $index => $isBinary) {
  1815. self::assertSame($isBinary, $tokensAnalyzer->isBinaryOperator($index));
  1816. if ($isBinary) {
  1817. self::assertFalse($tokensAnalyzer->isUnarySuccessorOperator($index));
  1818. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1819. }
  1820. }
  1821. }
  1822. public static function provideIsBinaryOperator81Cases(): iterable
  1823. {
  1824. yield 'type intersection' => [
  1825. [6 => false],
  1826. '<?php function foo(array&string $x) {}',
  1827. ];
  1828. }
  1829. /**
  1830. * @param array<int, bool> $expected
  1831. *
  1832. * @dataProvider provideIsBinaryOperator82Cases
  1833. *
  1834. * @requires PHP 8.2
  1835. */
  1836. public function testIsBinaryOperator82(array $expected, string $source): void
  1837. {
  1838. $tokens = Tokens::fromCode($source);
  1839. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1840. foreach ($tokens as $index => $token) {
  1841. $isBinary = isset($expected[$index]);
  1842. self::assertSame($isBinary, $tokensAnalyzer->isBinaryOperator($index));
  1843. if ($isBinary) {
  1844. self::assertFalse($tokensAnalyzer->isUnarySuccessorOperator($index));
  1845. self::assertFalse($tokensAnalyzer->isUnaryPredecessorOperator($index));
  1846. }
  1847. }
  1848. }
  1849. public static function provideIsBinaryOperator82Cases(): iterable
  1850. {
  1851. yield [
  1852. [],
  1853. '<?php class Dnf { public static I|(P&S11) $f2;}',
  1854. ];
  1855. yield [
  1856. [],
  1857. '<?php function Foo((A&B)|I $x): (X&Z)|(p\f\G&Y\Z)|z { return foo();}',
  1858. ];
  1859. $particularEndOfFile = 'A|(B&C); }';
  1860. yield sprintf('block "%s" at the end of file that is a type', $particularEndOfFile) => [
  1861. [],
  1862. '<?php abstract class A { abstract function foo(): '.$particularEndOfFile,
  1863. ];
  1864. yield sprintf('block "%s" at the end of file that is not a type', $particularEndOfFile) => [
  1865. [12 => true, 15 => true],
  1866. '<?php function foo() { return '.$particularEndOfFile,
  1867. ];
  1868. }
  1869. /**
  1870. * @dataProvider provideArrayExceptionsCases
  1871. */
  1872. public function testIsNotArray(string $source, int $tokenIndex): void
  1873. {
  1874. $tokens = Tokens::fromCode($source);
  1875. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1876. self::assertFalse($tokensAnalyzer->isArray($tokenIndex));
  1877. }
  1878. /**
  1879. * @dataProvider provideArrayExceptionsCases
  1880. */
  1881. public function testIsMultiLineArrayException(string $source, int $tokenIndex): void
  1882. {
  1883. $this->expectException(\InvalidArgumentException::class);
  1884. $tokens = Tokens::fromCode($source);
  1885. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1886. $tokensAnalyzer->isArrayMultiLine($tokenIndex);
  1887. }
  1888. public static function provideArrayExceptionsCases(): iterable
  1889. {
  1890. yield ['<?php $a;', 1];
  1891. yield ["<?php\n \$a = (0+1); // [0,1]", 4];
  1892. yield ['<?php $text = "foo $bbb[0] bar";', 8];
  1893. yield ['<?php $text = "foo ${aaa[123]} bar";', 9];
  1894. }
  1895. public function testIsBlockMultilineException(): void
  1896. {
  1897. $this->expectException(\LogicException::class);
  1898. $tokens = Tokens::fromCode('<?php foo(1, 2, 3);');
  1899. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1900. $tokensAnalyzer->isBlockMultiline($tokens, 1);
  1901. }
  1902. /**
  1903. * @dataProvider provideIsBlockMultilineCases
  1904. */
  1905. public function testIsBlockMultiline(bool $isBlockMultiline, string $source, int $tokenIndex): void
  1906. {
  1907. $tokens = Tokens::fromCode($source);
  1908. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1909. self::assertSame($isBlockMultiline, $tokensAnalyzer->isBlockMultiline($tokens, $tokenIndex));
  1910. }
  1911. public static function provideIsBlockMultilineCases(): iterable
  1912. {
  1913. yield [
  1914. false,
  1915. '<?php foo(1, 2, 3);',
  1916. 2,
  1917. ];
  1918. yield [
  1919. true,
  1920. '<?php foo(1,
  1921. 2,
  1922. 3
  1923. );',
  1924. 2,
  1925. ];
  1926. yield [
  1927. false,
  1928. '<?php foo(1, "Multi
  1929. string", 2, 3);',
  1930. 2,
  1931. ];
  1932. yield [
  1933. false,
  1934. '<?php foo(1, havingNestedBlockThatIsMultilineDoesNotMakeTheMainBlockMultiline(
  1935. "a",
  1936. "b"
  1937. ), 2, 3);',
  1938. 2,
  1939. ];
  1940. }
  1941. /**
  1942. * @param array{visibility: ?int, static: bool, abstract: bool, final: bool} $expected
  1943. *
  1944. * @dataProvider provideGetFunctionPropertiesCases
  1945. */
  1946. public function testGetFunctionProperties(string $source, int $index, array $expected): void
  1947. {
  1948. $tokens = Tokens::fromCode($source);
  1949. $tokensAnalyzer = new TokensAnalyzer($tokens);
  1950. $attributes = $tokensAnalyzer->getMethodAttributes($index);
  1951. self::assertSame($expected, $attributes);
  1952. }
  1953. public static function provideGetFunctionPropertiesCases(): iterable
  1954. {
  1955. $defaultAttributes = [
  1956. 'visibility' => null,
  1957. 'static' => false,
  1958. 'abstract' => false,
  1959. 'final' => false,
  1960. ];
  1961. $template = '
  1962. <?php
  1963. class TestClass {
  1964. %s function a() {
  1965. //
  1966. }
  1967. }
  1968. ';
  1969. $cases = [];
  1970. $attributes = $defaultAttributes;
  1971. $attributes['visibility'] = T_PRIVATE;
  1972. $cases[] = [sprintf($template, 'private'), 10, $attributes];
  1973. $attributes = $defaultAttributes;
  1974. $attributes['visibility'] = T_PUBLIC;
  1975. $cases[] = [sprintf($template, 'public'), 10, $attributes];
  1976. $attributes = $defaultAttributes;
  1977. $attributes['visibility'] = T_PROTECTED;
  1978. $cases[] = [sprintf($template, 'protected'), 10, $attributes];
  1979. $attributes = $defaultAttributes;
  1980. $attributes['visibility'] = null;
  1981. $attributes['static'] = true;
  1982. $cases[] = [sprintf($template, 'static'), 10, $attributes];
  1983. $attributes = $defaultAttributes;
  1984. $attributes['visibility'] = T_PUBLIC;
  1985. $attributes['static'] = true;
  1986. $attributes['final'] = true;
  1987. $cases[] = [sprintf($template, 'final public static'), 14, $attributes];
  1988. $attributes = $defaultAttributes;
  1989. $attributes['visibility'] = null;
  1990. $attributes['abstract'] = true;
  1991. $cases[] = [sprintf($template, 'abstract'), 10, $attributes];
  1992. $attributes = $defaultAttributes;
  1993. $attributes['visibility'] = T_PUBLIC;
  1994. $attributes['abstract'] = true;
  1995. $cases[] = [sprintf($template, 'abstract public'), 12, $attributes];
  1996. $attributes = $defaultAttributes;
  1997. $cases[] = [sprintf($template, ''), 8, $attributes];
  1998. return $cases;
  1999. }
  2000. public function testIsWhilePartOfDoWhile(): void
  2001. {
  2002. $source =
  2003. <<<'SRC'
  2004. <?php
  2005. // `not do`
  2006. while(false) {
  2007. }
  2008. while (false);
  2009. while (false)?>
  2010. <?php
  2011. if(false){
  2012. }while(false);
  2013. if(false){
  2014. }while(false)?><?php
  2015. while(false){}while(false){}
  2016. while ($i <= 10):
  2017. echo $i;
  2018. $i++;
  2019. endwhile;
  2020. ?>
  2021. <?php while(false): ?>
  2022. <?php endwhile ?>
  2023. <?php
  2024. // `do`
  2025. do{
  2026. } while(false);
  2027. do{
  2028. } while(false)?>
  2029. <?php
  2030. if (false){}do{}while(false);
  2031. // `not do`, `do`
  2032. if(false){}while(false){}do{}while(false);
  2033. SRC;
  2034. $expected = [
  2035. 3 => false,
  2036. 12 => false,
  2037. 19 => false,
  2038. 34 => false,
  2039. 47 => false,
  2040. 53 => false,
  2041. 59 => false,
  2042. 66 => false,
  2043. 91 => false,
  2044. 112 => true,
  2045. 123 => true,
  2046. 139 => true,
  2047. 153 => false,
  2048. 162 => true,
  2049. ];
  2050. $tokens = Tokens::fromCode($source);
  2051. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2052. foreach ($tokens as $index => $token) {
  2053. if (!$token->isGivenKind(T_WHILE)) {
  2054. continue;
  2055. }
  2056. self::assertSame(
  2057. $expected[$index],
  2058. $tokensAnalyzer->isWhilePartOfDoWhile($index),
  2059. sprintf('Expected token at index "%d" to be detected as %sa "do-while"-loop.', $index, true === $expected[$index] ? '' : 'not ')
  2060. );
  2061. }
  2062. }
  2063. /**
  2064. * @dataProvider provideIsEnumCaseCases
  2065. *
  2066. * @param array<int, bool> $expected
  2067. *
  2068. * @requires PHP 8.1
  2069. */
  2070. public function testIsEnumCase(string $source, array $expected): void
  2071. {
  2072. $tokens = Tokens::fromCode($source);
  2073. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2074. foreach ($tokens as $index => $token) {
  2075. if (!$token->isGivenKind(T_CASE)) {
  2076. try {
  2077. $tokensAnalyzer->isEnumCase($index);
  2078. self::fail('TokensAnalyzer::isEnumCase() did not throw LogicException.');
  2079. } catch (\Throwable $e) {
  2080. self::assertInstanceOf(\LogicException::class, $e);
  2081. self::assertMatchesRegularExpression('/^No T_CASE given at index \d+, got \S+ instead\.$/', $e->getMessage());
  2082. }
  2083. continue;
  2084. }
  2085. self::assertSame($expected[$index], $tokensAnalyzer->isEnumCase($index));
  2086. }
  2087. }
  2088. public static function provideIsEnumCaseCases(): iterable
  2089. {
  2090. yield 'switch only' => [
  2091. '<?php
  2092. function bar(string $a): string
  2093. {
  2094. switch ($a) {
  2095. case \'one\':
  2096. return $a;
  2097. case \'two\':
  2098. default:
  2099. return strtoupper($a);
  2100. }
  2101. }
  2102. ',
  2103. [
  2104. 23 => false,
  2105. 33 => false,
  2106. ],
  2107. ];
  2108. yield 'pure enum' => [
  2109. '<?php
  2110. enum Foo
  2111. {
  2112. case One;
  2113. case Two;
  2114. }
  2115. ',
  2116. [
  2117. 7 => true,
  2118. 12 => true,
  2119. ],
  2120. ];
  2121. yield 'pure enum with switch' => [
  2122. '<?php
  2123. enum Foo
  2124. {
  2125. case One;
  2126. case Two;
  2127. public static function getLowerName(self $instance): string
  2128. {
  2129. switch ($instance->name) {
  2130. case \'One\':
  2131. case \'Two\':
  2132. return strtolower($instance->name);
  2133. }
  2134. }
  2135. }
  2136. ',
  2137. [
  2138. 7 => true,
  2139. 12 => true,
  2140. 45 => false,
  2141. 50 => false,
  2142. ],
  2143. ];
  2144. yield 'backed enum' => [
  2145. '<?php
  2146. enum Suit: string
  2147. {
  2148. case Hearts = \'hearts\';
  2149. case Spades = \'spades\';
  2150. case Clubs = \'clubs\';
  2151. case Diamonds = \'diamonds\';
  2152. }
  2153. ',
  2154. [
  2155. 10 => true,
  2156. 19 => true,
  2157. 28 => true,
  2158. 37 => true,
  2159. ],
  2160. ];
  2161. yield 'backed enum with switch' => [
  2162. '<?php
  2163. enum Suit: string
  2164. {
  2165. case Hearts = \'hearts\';
  2166. case Spades = \'spades\';
  2167. case Clubs = \'clubs\';
  2168. case Diamonds = \'diamonds\';
  2169. public static function getUppercasedValue(self $instance): string
  2170. {
  2171. switch ($instance->value) {
  2172. case \'hearts\':
  2173. case \'spades\':
  2174. return strtoupper($instance->value);
  2175. default:
  2176. return $instance->value;
  2177. }
  2178. }
  2179. }
  2180. ',
  2181. [
  2182. 10 => true,
  2183. 19 => true,
  2184. 28 => true,
  2185. 37 => true,
  2186. 74 => false,
  2187. 79 => false,
  2188. ],
  2189. ];
  2190. }
  2191. /**
  2192. * @param array<int, list<int>>|list<int> $expected
  2193. *
  2194. * @dataProvider provideGetImportUseIndexesCases
  2195. */
  2196. public function testGetImportUseIndexes(array $expected, string $input, bool $perNamespace = false): void
  2197. {
  2198. $tokens = Tokens::fromCode($input);
  2199. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2200. self::assertSame($expected, $tokensAnalyzer->getImportUseIndexes($perNamespace));
  2201. }
  2202. public static function provideGetImportUseIndexesCases(): iterable
  2203. {
  2204. yield [
  2205. [1, 8],
  2206. '<?php use E\F?><?php use A\B;',
  2207. ];
  2208. yield [
  2209. [[1], [14], [29]],
  2210. '<?php
  2211. use T\A;
  2212. namespace A { use D\C; }
  2213. namespace b { use D\C; }
  2214. ',
  2215. true,
  2216. ];
  2217. yield [
  2218. [[1, 8]],
  2219. '<?php use D\B; use A\C?>',
  2220. true,
  2221. ];
  2222. yield [
  2223. [1, 8],
  2224. '<?php use D\B; use A\C?>',
  2225. ];
  2226. yield [
  2227. [7, 22],
  2228. '<?php
  2229. namespace A { use D\C; }
  2230. namespace b { use D\C; }
  2231. ',
  2232. ];
  2233. yield [
  2234. [3, 10, 34, 45, 54, 59, 77, 95],
  2235. <<<'EOF'
  2236. use Zoo\Bar;
  2237. use Foo\Bar;
  2238. use Foo\Zar\Baz;
  2239. <?php
  2240. use Foo\Bar;
  2241. use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar as FooBaz;
  2242. use Foo\Bir as FBB;
  2243. use Foo\Zar\Baz;
  2244. use SomeClass;
  2245. use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
  2246. use Zoo\Bar;
  2247. $a = new someclass();
  2248. use Zoo\Tar;
  2249. class AnnotatedClass
  2250. {
  2251. }
  2252. EOF,
  2253. ];
  2254. yield [
  2255. [1, 22, 41],
  2256. '<?php
  2257. use some\a\{ClassA, ClassB, ClassC as C};
  2258. use function some\a\{fn_a, fn_b, fn_c};
  2259. use const some\a\{ConstA, ConstB, ConstC};
  2260. ',
  2261. ];
  2262. yield [
  2263. [[1, 22, 41]],
  2264. '<?php
  2265. use some\a\{ClassA, ClassB, ClassC as C};
  2266. use function some\a\{fn_a, fn_b, fn_c};
  2267. use const some\a\{ConstA, ConstB, ConstC};
  2268. ',
  2269. true,
  2270. ];
  2271. yield [
  2272. [1, 23, 43],
  2273. '<?php
  2274. use some\a\{ClassA, ClassB, ClassC as C,};
  2275. use function some\a\{fn_a, fn_b, fn_c,};
  2276. use const some\a\{ConstA, ConstB, ConstC,};
  2277. ',
  2278. ];
  2279. yield [
  2280. [[1, 23, 43]],
  2281. '<?php
  2282. use some\a\{ClassA, ClassB, ClassC as C,};
  2283. use function some\a\{fn_a, fn_b, fn_c,};
  2284. use const some\a\{ConstA, ConstB, ConstC,};
  2285. ',
  2286. true,
  2287. ];
  2288. }
  2289. public function testGetClassyElementsWithMultipleNestedAnonymousClass(): void
  2290. {
  2291. $source = '<?php
  2292. class MyTestWithAnonymousClass extends TestCase
  2293. {
  2294. public function setUp()
  2295. {
  2296. $provider = new class(function () {}) {};
  2297. }
  2298. public function testSomethingWithMoney(
  2299. Money $amount
  2300. ) {
  2301. $a = new class(function () {
  2302. new class(function () {
  2303. new class(function () {})
  2304. {
  2305. const A=1;
  2306. };
  2307. })
  2308. {
  2309. const B=1;
  2310. public function foo() {
  2311. $c = new class() {const AA=3;};
  2312. $d = new class {const AB=3;};
  2313. }
  2314. };
  2315. })
  2316. {
  2317. const C=1;
  2318. };
  2319. }
  2320. }';
  2321. $tokens = Tokens::fromCode($source);
  2322. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2323. $elements = $tokensAnalyzer->getClassyElements();
  2324. self::assertSame([
  2325. 13 => [
  2326. 'classIndex' => 1,
  2327. 'token' => $tokens[13],
  2328. 'type' => 'method', // setUp
  2329. ],
  2330. 46 => [
  2331. 'classIndex' => 1,
  2332. 'token' => $tokens[46],
  2333. 'type' => 'method', // testSomethingWithMoney
  2334. ],
  2335. 100 => [
  2336. 'classIndex' => 87,
  2337. 'token' => $tokens[100], // const A
  2338. 'type' => 'const',
  2339. ],
  2340. 115 => [
  2341. 'classIndex' => 65,
  2342. 'token' => $tokens[115], // const B
  2343. 'type' => 'const',
  2344. ],
  2345. 124 => [
  2346. 'classIndex' => 65, // $a
  2347. 'token' => $tokens[124],
  2348. 'type' => 'method', // foo
  2349. ],
  2350. 143 => [
  2351. 'classIndex' => 138,
  2352. 'token' => $tokens[143], // const AA
  2353. 'type' => 'const',
  2354. ],
  2355. 161 => [
  2356. 'classIndex' => 158,
  2357. 'token' => $tokens[161], // const AB
  2358. 'type' => 'const',
  2359. ],
  2360. ], $elements);
  2361. }
  2362. /**
  2363. * @dataProvider provideIsSuperGlobalCases
  2364. */
  2365. public function testIsSuperGlobal(bool $expected, string $source, int $index): void
  2366. {
  2367. $tokens = Tokens::fromCode($source);
  2368. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2369. self::assertSame($expected, $tokensAnalyzer->isSuperGlobal($index));
  2370. }
  2371. public static function provideIsSuperGlobalCases(): iterable
  2372. {
  2373. $superNames = [
  2374. '$_COOKIE',
  2375. '$_ENV',
  2376. '$_FILES',
  2377. '$_GET',
  2378. '$_POST',
  2379. '$_REQUEST',
  2380. '$_SERVER',
  2381. '$_SESSION',
  2382. '$GLOBALS',
  2383. ];
  2384. $cases = [];
  2385. foreach ($superNames as $superName) {
  2386. $cases[] = [
  2387. true,
  2388. sprintf('<?php echo %s[0];', $superName),
  2389. 3,
  2390. ];
  2391. }
  2392. $notGlobalCodeCases = [
  2393. '<?php echo 1; $a = static function($b) use ($a) { $a->$b(); }; // $_SERVER',
  2394. '<?php class Foo{}?> <?php $_A = 1; /* $_SESSION */',
  2395. ];
  2396. foreach ($notGlobalCodeCases as $notGlobalCodeCase) {
  2397. $tokensCount = \count(Tokens::fromCode($notGlobalCodeCase));
  2398. for ($i = 0; $i < $tokensCount; ++$i) {
  2399. $cases[] = [
  2400. false,
  2401. $notGlobalCodeCase,
  2402. $i,
  2403. ];
  2404. }
  2405. }
  2406. return $cases;
  2407. }
  2408. /**
  2409. * @dataProvider provideGetClassyModifiersCases
  2410. *
  2411. * @param array<string, null|int> $expectedModifiers
  2412. */
  2413. public function testGetClassyModifiers(array $expectedModifiers, int $index, string $source): void
  2414. {
  2415. $tokens = Tokens::fromCode($source);
  2416. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2417. self::assertSame($expectedModifiers, $tokensAnalyzer->getClassyModifiers($index));
  2418. }
  2419. public static function provideGetClassyModifiersCases(): iterable
  2420. {
  2421. yield 'final' => [
  2422. ['final' => 1, 'abstract' => null, 'readonly' => null],
  2423. 3,
  2424. '<?php final class Foo {}',
  2425. ];
  2426. yield 'abstract' => [
  2427. ['final' => null, 'abstract' => 3, 'readonly' => null],
  2428. 5,
  2429. '<?php /* comment */ abstract class Foo {}',
  2430. ];
  2431. }
  2432. /**
  2433. * @requires PHP 8.2
  2434. *
  2435. * @dataProvider provideGetClassyModifiersOnPhp82Cases
  2436. *
  2437. * @param array<string, null|int> $expectedModifiers
  2438. */
  2439. public function testGetClassyModifiersOnPhp82(array $expectedModifiers, int $index, string $source): void
  2440. {
  2441. $tokens = Tokens::fromCode($source);
  2442. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2443. self::assertSame($expectedModifiers, $tokensAnalyzer->getClassyModifiers($index));
  2444. }
  2445. public static function provideGetClassyModifiersOnPhp82Cases(): iterable
  2446. {
  2447. yield 'readonly' => [
  2448. ['final' => null, 'abstract' => null, 'readonly' => 1],
  2449. 3,
  2450. '<?php readonly class Foo {}',
  2451. ];
  2452. yield 'readonly final' => [
  2453. ['final' => 3, 'abstract' => null, 'readonly' => 1],
  2454. 5,
  2455. '<?php readonly final class Foo {}',
  2456. ];
  2457. yield 'readonly final reversed' => [
  2458. ['final' => 1, 'abstract' => null, 'readonly' => 3],
  2459. 5,
  2460. '<?php final readonly class Foo {}',
  2461. ];
  2462. yield 'readonly final reversed + comment' => [
  2463. ['final' => 1, 'abstract' => null, 'readonly' => 5],
  2464. 7,
  2465. '<?php final /* comment */ readonly class Foo {}',
  2466. ];
  2467. yield 'readonly abstract' => [
  2468. ['final' => null, 'abstract' => 3, 'readonly' => 1],
  2469. 5,
  2470. '<?php readonly abstract class Foo {}',
  2471. ];
  2472. yield 'readonly abstract reversed' => [
  2473. ['final' => null, 'abstract' => 1, 'readonly' => 3],
  2474. 5,
  2475. '<?php abstract readonly class Foo {}',
  2476. ];
  2477. yield 'readonly abstract reversed + comment' => [
  2478. ['final' => null, 'abstract' => 1, 'readonly' => 5],
  2479. 7,
  2480. '<?php abstract /* comment */ readonly class Foo {}',
  2481. ];
  2482. }
  2483. public function testGetClassyModifiersForNonClassyThrowsAnException(): void
  2484. {
  2485. $tokens = Tokens::fromCode('<?php echo 1;');
  2486. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2487. $this->expectException(\InvalidArgumentException::class);
  2488. $tokensAnalyzer->getClassyModifiers(1);
  2489. }
  2490. /**
  2491. * @dataProvider provideGetLastTokenIndexOfArrowFunctionCases
  2492. *
  2493. * @param array<int, int> $expectations
  2494. */
  2495. public function testGetLastTokenIndexOfArrowFunction(array $expectations, string $source): void
  2496. {
  2497. $tokens = Tokens::fromCode($source);
  2498. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2499. $indices = [];
  2500. foreach ($expectations as $index => $expectedEndIndex) {
  2501. $indices[$index] = $tokensAnalyzer->getLastTokenIndexOfArrowFunction($index);
  2502. }
  2503. self::assertSame($expectations, $indices);
  2504. }
  2505. public static function provideGetLastTokenIndexOfArrowFunctionCases(): iterable
  2506. {
  2507. yield 'simple cases' => [
  2508. [
  2509. 2 => 11,
  2510. 16 => 25,
  2511. 28 => 39,
  2512. 46 => 61,
  2513. ],
  2514. '<?php
  2515. fn(array $x) => $x;
  2516. static fn(): int => $x;
  2517. fn($x = 42) => $x;
  2518. $eq = fn ($x, $y) => $x == $y;
  2519. ',
  2520. ];
  2521. yield 'references, splat and arrow cases' => [
  2522. [
  2523. 2 => 10,
  2524. 13 => 21,
  2525. 24 => 35,
  2526. 42 => 51,
  2527. 65 => 77,
  2528. ],
  2529. '<?php
  2530. fn(&$x) => $x;
  2531. fn&($x) => $x;
  2532. fn($x, ...$rest) => $rest;
  2533. $fn = fn(&$x) => $x++;
  2534. $y = &$fn($x);
  2535. fn($x, &...$rest) => 1;
  2536. ',
  2537. ];
  2538. yield 'different endings' => [
  2539. [
  2540. 9 => 21,
  2541. 31 => 43,
  2542. ],
  2543. '<?php
  2544. $results = array_map(
  2545. fn ($item) => $item * 2,
  2546. $list
  2547. );
  2548. return fn ($y) => $x * $y ?>
  2549. ',
  2550. ];
  2551. yield 'nested arrow function' => [
  2552. [
  2553. 1 => 26,
  2554. 14 => 25,
  2555. ],
  2556. '<?php fn(array $x, $z) => (fn(int $z):bool => $z);',
  2557. ];
  2558. yield 'arrow function as argument' => [
  2559. [
  2560. 5 => 14,
  2561. ],
  2562. '<?php return foo(fn(array $x) => $x);',
  2563. ];
  2564. yield 'arrow function as collection item' => [
  2565. [
  2566. 9 => 18,
  2567. 26 => 35,
  2568. 46 => 55,
  2569. 62 => 69,
  2570. ],
  2571. '<?php return [
  2572. [1, fn(array $x) => $x1, 1],
  2573. [fn(array $x) => $x2, 1],
  2574. [1, fn(array $x) => $x3],
  2575. ([(fn($x4) => $x5)]),
  2576. ];',
  2577. ];
  2578. yield 'nested inside anonymous class' => [
  2579. [
  2580. 1 => 46,
  2581. 33 => 41,
  2582. ],
  2583. '<?php fn($x) => $a = new class($x) { public function foo() { return fn(&$x) => $x; } };',
  2584. ];
  2585. yield 'array destructuring' => [
  2586. [
  2587. 4 => 13,
  2588. ],
  2589. '<?php return [fn(array $x) => $x1] = $x;',
  2590. ];
  2591. yield 'array_map() callback with different token blocks' => [
  2592. [
  2593. 9 => 28,
  2594. ],
  2595. '<?php
  2596. $a = array_map(
  2597. fn (array $item) => $item[\'callback\']($item[\'value\']),
  2598. [/* items */]
  2599. );
  2600. ',
  2601. ];
  2602. yield 'arrow function returning array' => [
  2603. [
  2604. 5 => 21,
  2605. ],
  2606. '<?php $z = fn ($a) => [0, 1, $a];',
  2607. ];
  2608. }
  2609. public function testCannotGetLastTokenIndexOfArrowFunctionForNonFnToken(): void
  2610. {
  2611. $tokens = Tokens::fromCode('<?php echo 1;');
  2612. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2613. $this->expectException(\InvalidArgumentException::class);
  2614. $tokensAnalyzer->getLastTokenIndexOfArrowFunction(1);
  2615. }
  2616. /**
  2617. * @param array<int, bool> $expected
  2618. */
  2619. private function doIsConstantInvocationTest(array $expected, string $source): void
  2620. {
  2621. $tokens = Tokens::fromCode($source);
  2622. self::assertCount(
  2623. $tokens->countTokenKind(T_STRING),
  2624. $expected,
  2625. 'All T_STRING tokens must be tested'
  2626. );
  2627. $tokensAnalyzer = new TokensAnalyzer($tokens);
  2628. foreach ($expected as $index => $expectedValue) {
  2629. self::assertSame(
  2630. $expectedValue,
  2631. $tokensAnalyzer->isConstantInvocation($index),
  2632. sprintf('Token at index '.$index.' should match the expected value (%s).', $expectedValue ? 'true' : 'false')
  2633. );
  2634. }
  2635. }
  2636. }