cookbook_fixers.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. ==============================================
  2. Cookbook - Making a new Fixer for PHP CS Fixer
  3. ==============================================
  4. You want to make a new fixer to PHP CS Fixer and do not know how to
  5. start. Follow this document and you will be able to do it.
  6. Background
  7. ----------
  8. In order to be able to create a new fixer, you need some background.
  9. PHP CS Fixer is a transcompiler which takes valid PHP code and pretty
  10. print valid PHP code. It does all transformations in multiple passes,
  11. a.k.a., multi-pass compiler.
  12. Therefore, a new fixer is meant to be ideally idempotent_, or at least atomic
  13. in its actions. More on this later.
  14. All contributions go through a code review process. Do not feel
  15. discouraged - it is meant only to give more people more chance to
  16. contribute, and to detect bugs (`Linus's Law`_).
  17. If possible, try to get acquainted with the public interface for the
  18. `Tokens class`_ and `Token class`_ classes.
  19. Assumptions
  20. -----------
  21. * You are familiar with Test Driven Development.
  22. * Forked PHP-CS-Fixer/PHP-CS-Fixer into your own GitHub Account.
  23. * Cloned your forked repository locally.
  24. * Installed the dependencies of PHP CS Fixer using Composer_.
  25. * You have read `CONTRIBUTING.md`_.
  26. Step by step
  27. ------------
  28. For this step-by-step, we are going to create a simple fixer that
  29. removes all comments from the code that are preceded by `;` (semicolon).
  30. We are calling it ``remove_comments`` (code name), or,
  31. ``RemoveCommentsFixer`` (class name).
  32. Step 1 - Creating files
  33. _______________________
  34. Create a new file in ``src/Fixer/Comment/RemoveCommentsFixer.php``.
  35. Put this content inside:
  36. .. code-block:: php
  37. <?php
  38. /*
  39. * This file is part of PHP CS Fixer.
  40. *
  41. * (c) Fabien Potencier <fabien@symfony.com>
  42. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  43. *
  44. * This source file is subject to the MIT license that is bundled
  45. * with this source code in the file LICENSE.
  46. */
  47. namespace PhpCsFixer\Fixer\Comment;
  48. use PhpCsFixer\AbstractFixer;
  49. use PhpCsFixer\Tokenizer\Tokens;
  50. /**
  51. * @author Your name <your@email.com>
  52. */
  53. final class RemoveCommentsFixer extends AbstractFixer
  54. {
  55. public function getDefinition(): FixerDefinition
  56. {
  57. // Return a definition of the fixer, it will be used in the documentation.
  58. }
  59. public function isCandidate(Tokens $tokens): bool
  60. {
  61. // Check whether the collection is a candidate for fixing.
  62. // Has to be ultra cheap to execute.
  63. }
  64. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  65. {
  66. // Add the fixing logic of the fixer here.
  67. }
  68. }
  69. Note how the class and file name match. Also keep in mind that all
  70. fixers must implement ``Fixer\FixerInterface``. In this case, the fixer is
  71. inheriting from ``AbstractFixer``, which fulfills the interface with some
  72. default behavior.
  73. Now let us create the test file at
  74. ``tests/Fixer/Comment/RemoveCommentsFixerTest.php``. Put this content inside:
  75. .. code-block:: php
  76. <?php
  77. /*
  78. * This file is part of PHP CS Fixer.
  79. *
  80. * (c) Fabien Potencier <fabien@symfony.com>
  81. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  82. *
  83. * This source file is subject to the MIT license that is bundled
  84. * with this source code in the file LICENSE.
  85. */
  86. namespace PhpCsFixer\Tests\Fixer\Comment;
  87. use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
  88. /**
  89. * @author Your name <your@email.com>
  90. *
  91. * @internal
  92. *
  93. * @covers \PhpCsFixer\Fixer\Comment\RemoveCommentsFixer
  94. */
  95. final class RemoveCommentsFixerTest extends AbstractFixerTestCase
  96. {
  97. /**
  98. * @dataProvider provideFixCases
  99. */
  100. public function testFix(string $expected, ?string $input = null): void
  101. {
  102. $this->doTest($expected, $input);
  103. }
  104. public static function provideFixCases()
  105. {
  106. return [];
  107. }
  108. }
  109. Step 2 - Using tests to define fixers behavior
  110. ______________________________________________
  111. Now that the files are created, you can start writing tests to define the
  112. behavior of the fixer. You have to do it in two ways: first, ensuring
  113. the fixer changes what it should be changing; second, ensuring that
  114. fixer does not change what is not supposed to change. Thus:
  115. Keeping things as they are:
  116. .. code-block:: php
  117. // tests/Fixer/Comment/RemoveCommentsFixerTest.php
  118. // ...
  119. public static function provideFixCases()
  120. {
  121. return [
  122. ['<?php echo "This should not be changed";'], // Each sub-array is a test
  123. ];
  124. }
  125. // ...
  126. Ensuring things change:
  127. .. code-block:: php
  128. // tests/Fixer/Comment/RemoveCommentsFixerTest.php
  129. // ...
  130. public static function provideFixCases()
  131. {
  132. return [
  133. [
  134. '<?php echo "This should be changed"; ', // This is expected output
  135. '<?php echo "This should be changed"; /* Comment */', // This is input
  136. ],
  137. ];
  138. }
  139. // ...
  140. Note that expected outputs are **always** tested alone to ensure your fixer will not change it.
  141. We want to have a failing test to start with, so the test file now looks
  142. like:
  143. .. code-block:: php
  144. <?php
  145. // tests/Fixer/Comment/RemoveCommentsFixerTest.php
  146. /*
  147. * This file is part of PHP CS Fixer.
  148. *
  149. * (c) Fabien Potencier <fabien@symfony.com>
  150. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  151. *
  152. * This source file is subject to the MIT license that is bundled
  153. * with this source code in the file LICENSE.
  154. */
  155. namespace PhpCsFixer\Tests\Fixer\Comment;
  156. use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
  157. /**
  158. * @author Your name <your@email.com>
  159. *
  160. * @internal
  161. */
  162. final class RemoveCommentsFixerTest extends AbstractFixerTestCase
  163. {
  164. /**
  165. * @dataProvider provideFixCases
  166. */
  167. public function testFix(string $expected, ?string $input = null): void
  168. {
  169. $this->doTest($expected, $input);
  170. }
  171. public static function provideFixCases()
  172. {
  173. return [
  174. [
  175. '<?php echo "This should be changed"; ', // This is expected output
  176. '<?php echo "This should be changed"; /* Comment */', // This is input
  177. ],
  178. ];
  179. }
  180. }
  181. Step 3 - Implement your solution
  182. ________________________________
  183. You have defined the behavior of your fixer in tests. Now it is time to
  184. implement it.
  185. First, we need to create one method to describe what this fixer does:
  186. .. code-block:: php
  187. // src/Fixer/Comment/RemoveCommentsFixer.php
  188. final class RemoveCommentsFixer extends AbstractFixer
  189. {
  190. public function getDefinition(): FixerDefinition
  191. {
  192. return new FixerDefinition(
  193. 'Removes all comments of the code that are preceded by `;` (semicolon).', // Trailing dot is important. We thrive to use English grammar properly.
  194. [
  195. new CodeSample(
  196. "<?php echo 123; /* Comment */\n"
  197. ),
  198. ]
  199. );
  200. }
  201. }
  202. Next, we need to update the documentation.
  203. Fortunately, PHP CS Fixer can help you here.
  204. Execute the following command in your command shell:
  205. .. code-block:: console
  206. php dev-tools/doc.php
  207. Next, we must filter what type of tokens we want to fix. Here, we are interested in code that contains ``T_COMMENT`` tokens:
  208. .. code-block:: php
  209. // src/Fixer/Comment/RemoveCommentsFixer.php
  210. final class RemoveCommentsFixer extends AbstractFixer
  211. {
  212. // ...
  213. public function isCandidate(Tokens $tokens): bool
  214. {
  215. return $tokens->isTokenKindFound(T_COMMENT);
  216. }
  217. }
  218. For now, let us just make a fixer that applies no modification:
  219. .. code-block:: php
  220. // src/Fixer/Comment/RemoveCommentsFixer.php
  221. final class RemoveCommentsFixer extends AbstractFixer
  222. {
  223. // ...
  224. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  225. {
  226. // no action
  227. }
  228. }
  229. Run ``phpunit tests/Fixer/Comment/RemoveCommentsFixerTest.php``.
  230. You are going to see that the tests fail.
  231. Break
  232. _____
  233. Now we have pretty much a cradle to work with. A file with a failing
  234. test, and the fixer, that for now does not do anything.
  235. How do fixers work? In the PHP CS Fixer, they work by iterating through
  236. pieces of codes (each being a Token), and inspecting what exists before
  237. and after that bit and making a decision, usually:
  238. * Adding code.
  239. * Modifying code.
  240. * Deleting code.
  241. * Ignoring code.
  242. In our case, we want to find all comments, and foreach (pun intended)
  243. one of them check if they are preceded by a semicolon symbol.
  244. Now you need to do some reading, because all these symbols obey a list
  245. defined by the PHP compiler. It is the `List of Parser Tokens`_.
  246. Internally, PHP CS Fixer transforms some of PHP native tokens into custom
  247. tokens through the use of Transformers_, they aim to help you reason about the
  248. changes you may want to do in the fixers.
  249. So we can get to move forward, humor me in believing that comments have
  250. one symbol name: ``T_COMMENT``.
  251. Step 3 - Implement your solution - continuation.
  252. ________________________________________________
  253. We do not want all symbols to be analysed. Only ``T_COMMENT``. So let us
  254. iterate the token(s) we are interested in.
  255. .. code-block:: php
  256. // src/Fixer/Comment/RemoveCommentsFixer.php
  257. final class RemoveCommentsFixer extends AbstractFixer
  258. {
  259. // ...
  260. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  261. {
  262. foreach ($tokens as $index => $token) {
  263. if (!$token->isGivenKind(T_COMMENT)) {
  264. continue;
  265. }
  266. // need to figure out what to do here!
  267. }
  268. }
  269. }
  270. OK, now for each ``T_COMMENT``, all we need to do is check if the previous
  271. token is a semicolon.
  272. .. code-block:: php
  273. // src/Fixer/Comment/RemoveCommentsFixer.php
  274. final class RemoveCommentsFixer extends AbstractFixer
  275. {
  276. // ...
  277. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  278. {
  279. foreach ($tokens as $index => $token) {
  280. if (!$token->isGivenKind(T_COMMENT)) {
  281. continue;
  282. }
  283. $prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
  284. $prevToken = $tokens[$prevTokenIndex];
  285. if ($prevToken->equals(';')) {
  286. $tokens->clearAt($index);
  287. }
  288. }
  289. }
  290. }
  291. So the fixer in the end looks like this:
  292. .. code-block:: php
  293. <?php
  294. /*
  295. * This file is part of PHP CS Fixer.
  296. *
  297. * (c) Fabien Potencier <fabien@symfony.com>
  298. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  299. *
  300. * This source file is subject to the MIT license that is bundled
  301. * with this source code in the file LICENSE.
  302. */
  303. namespace PhpCsFixer\Fixer\Comment;
  304. use PhpCsFixer\AbstractFixer;
  305. use PhpCsFixer\Tokenizer\Tokens;
  306. /**
  307. * @author Your name <your@email.com>
  308. */
  309. final class RemoveCommentsFixer extends AbstractFixer
  310. {
  311. public function getDefinition(): FixerDefinition
  312. {
  313. return new FixerDefinition(
  314. 'Removes all comments of the code that are preceded by `;` (semicolon).', // Trailing dot is important. We thrive to use English grammar properly.
  315. [
  316. new CodeSample(
  317. "<?php echo 123; /* Comment */\n"
  318. ),
  319. ]
  320. );
  321. }
  322. public function isCandidate(Tokens $tokens): bool
  323. {
  324. return $tokens->isTokenKindFound(T_COMMENT);
  325. }
  326. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  327. {
  328. foreach ($tokens as $index => $token) {
  329. if (!$token->isGivenKind(T_COMMENT)) {
  330. continue;
  331. }
  332. $prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
  333. $prevToken = $tokens[$prevTokenIndex];
  334. if ($prevToken->equals(';')) {
  335. $tokens->clearAt($index);
  336. }
  337. }
  338. }
  339. }
  340. Step 4 - Format, Commit, PR.
  341. ____________________________
  342. Note that so far, we have not coded adhering to PSR-1/2. This is done on
  343. purpose. For every commit you make, you must use PHP CS Fixer to fix
  344. itself. Thus, on the command line call:
  345. .. code-block:: console
  346. php php-cs-fixer fix
  347. This will fix all the coding style mistakes.
  348. After the final CS fix, you are ready to commit. Do it.
  349. Now, go to GitHub and open a Pull Request.
  350. Step 5 - Peer review: it is all about code and community building.
  351. __________________________________________________________________
  352. Congratulations, you have made your first fixer. Be proud. Your work
  353. will be reviewed carefully by PHP CS Fixer community.
  354. The review usually flows like this:
  355. 1. People will check your code for common mistakes and logical
  356. caveats. Usually, the person building a fixer is blind about some
  357. behavior mistakes of fixers. Expect to write few more tests to cater for
  358. the reviews.
  359. 2. People will discuss the relevance of your fixer. If it is
  360. something that goes along with Symfony style standards, or PSR-1/PSR-2
  361. standards, they will ask you to add it to existing ruleset.
  362. 3. People will also discuss whether your fixer is idempotent or not.
  363. If they understand that your fixer must always run before or after a
  364. certain fixer, they will ask you to override a method named
  365. ``getPriority()``. Do not be afraid of asking the reviewer for help on how
  366. to do it.
  367. 4. People may ask you to rebase your code to unify commits or to get
  368. rid of merge commits.
  369. 5. Go to 1 until no actions are needed anymore.
  370. Your fixer will be incorporated in the next release.
  371. Congratulations! You have done it.
  372. Q&A
  373. ---
  374. Why is not my PR merged yet?
  375. PHP CS Fixer is used by many people, that expect it to be stable. So
  376. sometimes, few PR are delayed a bit so to avoid cluttering at @dev
  377. channel on composer.
  378. Other possibility is that reviewers are giving time to other members of
  379. PHP CS Fixer community to partake on the review debates of your fixer.
  380. In any case, we care a lot about what you do and we want to see it being
  381. part of the application as soon as possible.
  382. Why am I asked to use ``getPrevMeaningfulToken()`` instead of ``getPrevNonWhitespace()``?
  383. The main difference is that ``getPrevNonWhitespace()`` ignores only
  384. whitespaces (``T_WHITESPACE``), while ``getPrevMeaningfulToken()`` ignores
  385. whitespaces and comments. And usually that is what you want. For
  386. example:
  387. .. code-block:: php
  388. $a->/*comment*/func();
  389. If you are inspecting ``func()``, and you want to check whether this is
  390. part of an object, if you use ``getPrevNonWhitespace()`` you are going to
  391. get ``/*comment*/``, which might belie your test. On the other hand, if
  392. you use ``getPrevMeaningfulToken()``, no matter if you have got a comment
  393. or a whitespace, the returned token will always be ``->``.
  394. .. _Composer: https://getcomposer.org
  395. .. _CONTRIBUTING.md: ../CONTRIBUTING.md
  396. .. _idempotent: https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning
  397. .. _Linus's Law: https://en.wikipedia.org/wiki/Linus%27s_Law
  398. .. _List of Parser Tokens: https://php.net/manual/en/tokens.php
  399. .. _Token class: ../src/Tokenizer/Token.php
  400. .. _Tokens class: ../src/Tokenizer/Tokens.php
  401. .. _Transformers: ../src/Tokenizer/Transformer