cookbook_fixers.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. <?php
  118. // tests/Fixer/Comment/RemoveCommentsFixerTest.php
  119. // ...
  120. public static function provideFixCases()
  121. {
  122. return [
  123. ['<?php echo "This should not be changed";'], // Each sub-array is a test
  124. ];
  125. }
  126. // ...
  127. Ensuring things change:
  128. .. code-block:: php
  129. <?php
  130. // tests/Fixer/Comment/RemoveCommentsFixerTest.php
  131. // ...
  132. public static function provideFixCases()
  133. {
  134. return [
  135. [
  136. '<?php echo "This should be changed"; ', // This is expected output
  137. '<?php echo "This should be changed"; /* Comment */', // This is input
  138. ],
  139. ];
  140. }
  141. // ...
  142. Note that expected outputs are **always** tested alone to ensure your fixer will not change it.
  143. We want to have a failing test to start with, so the test file now looks
  144. like:
  145. .. code-block:: php
  146. <?php
  147. // tests/Fixer/Comment/RemoveCommentsFixerTest.php
  148. /*
  149. * This file is part of PHP CS Fixer.
  150. *
  151. * (c) Fabien Potencier <fabien@symfony.com>
  152. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  153. *
  154. * This source file is subject to the MIT license that is bundled
  155. * with this source code in the file LICENSE.
  156. */
  157. namespace PhpCsFixer\Tests\Fixer\Comment;
  158. use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
  159. /**
  160. * @author Your name <your@email.com>
  161. *
  162. * @internal
  163. */
  164. final class RemoveCommentsFixerTest extends AbstractFixerTestCase
  165. {
  166. /**
  167. * @dataProvider provideFixCases
  168. */
  169. public function testFix(string $expected, ?string $input = null): void
  170. {
  171. $this->doTest($expected, $input);
  172. }
  173. public static function provideFixCases()
  174. {
  175. return [
  176. [
  177. '<?php echo "This should be changed"; ', // This is expected output
  178. '<?php echo "This should be changed"; /* Comment */', // This is input
  179. ],
  180. ];
  181. }
  182. }
  183. Step 3 - Implement your solution
  184. ________________________________
  185. You have defined the behavior of your fixer in tests. Now it is time to
  186. implement it.
  187. First, we need to create one method to describe what this fixer does:
  188. .. code-block:: php
  189. <?php
  190. // src/Fixer/Comment/RemoveCommentsFixer.php
  191. final class RemoveCommentsFixer extends AbstractFixer
  192. {
  193. public function getDefinition(): FixerDefinition
  194. {
  195. return new FixerDefinition(
  196. 'Removes all comments of the code that are preceded by `;` (semicolon).', // Trailing dot is important. We thrive to use English grammar properly.
  197. [
  198. new CodeSample(
  199. "<?php echo 123; /* Comment */\n"
  200. ),
  201. ]
  202. );
  203. }
  204. }
  205. Next, we need to update the documentation.
  206. Fortunately, PHP CS Fixer can help you here.
  207. Execute the following command in your command shell:
  208. .. code-block:: console
  209. php dev-tools/doc.php
  210. Next, we must filter what type of tokens we want to fix. Here, we are interested in code that contains ``T_COMMENT`` tokens:
  211. .. code-block:: php
  212. <?php
  213. // src/Fixer/Comment/RemoveCommentsFixer.php
  214. final class RemoveCommentsFixer extends AbstractFixer
  215. {
  216. // ...
  217. public function isCandidate(Tokens $tokens): bool
  218. {
  219. return $tokens->isTokenKindFound(T_COMMENT);
  220. }
  221. }
  222. For now, let us just make a fixer that applies no modification:
  223. .. code-block:: php
  224. <?php
  225. // src/Fixer/Comment/RemoveCommentsFixer.php
  226. final class RemoveCommentsFixer extends AbstractFixer
  227. {
  228. // ...
  229. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  230. {
  231. // no action
  232. }
  233. }
  234. Run ``phpunit tests/Fixer/Comment/RemoveCommentsFixerTest.php``.
  235. You are going to see that the tests fail.
  236. Break
  237. _____
  238. Now we have pretty much a cradle to work with. A file with a failing
  239. test, and the fixer, that for now does not do anything.
  240. How do fixers work? In the PHP CS Fixer, they work by iterating through
  241. pieces of codes (each being a Token), and inspecting what exists before
  242. and after that bit and making a decision, usually:
  243. * Adding code.
  244. * Modifying code.
  245. * Deleting code.
  246. * Ignoring code.
  247. In our case, we want to find all comments, and foreach (pun intended)
  248. one of them check if they are preceded by a semicolon symbol.
  249. Now you need to do some reading, because all these symbols obey a list
  250. defined by the PHP compiler. It is the `List of Parser Tokens`_.
  251. Internally, PHP CS Fixer transforms some of PHP native tokens into custom
  252. tokens through the use of Transformers_, they aim to help you reason about the
  253. changes you may want to do in the fixers.
  254. So we can get to move forward, humor me in believing that comments have
  255. one symbol name: ``T_COMMENT``.
  256. Step 3 - Implement your solution - continuation.
  257. ________________________________________________
  258. We do not want all symbols to be analysed. Only ``T_COMMENT``. So let us
  259. iterate the token(s) we are interested in.
  260. .. code-block:: php
  261. <?php
  262. // src/Fixer/Comment/RemoveCommentsFixer.php
  263. final class RemoveCommentsFixer extends AbstractFixer
  264. {
  265. // ...
  266. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  267. {
  268. foreach ($tokens as $index => $token) {
  269. if (!$token->isGivenKind(T_COMMENT)) {
  270. continue;
  271. }
  272. // need to figure out what to do here!
  273. }
  274. }
  275. }
  276. OK, now for each ``T_COMMENT``, all we need to do is check if the previous
  277. token is a semicolon.
  278. .. code-block:: php
  279. <?php
  280. // src/Fixer/Comment/RemoveCommentsFixer.php
  281. final class RemoveCommentsFixer extends AbstractFixer
  282. {
  283. // ...
  284. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  285. {
  286. foreach ($tokens as $index => $token) {
  287. if (!$token->isGivenKind(T_COMMENT)) {
  288. continue;
  289. }
  290. $prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
  291. $prevToken = $tokens[$prevTokenIndex];
  292. if ($prevToken->equals(';')) {
  293. $tokens->clearAt($index);
  294. }
  295. }
  296. }
  297. }
  298. So the fixer in the end looks like this:
  299. .. code-block:: php
  300. <?php
  301. /*
  302. * This file is part of PHP CS Fixer.
  303. *
  304. * (c) Fabien Potencier <fabien@symfony.com>
  305. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  306. *
  307. * This source file is subject to the MIT license that is bundled
  308. * with this source code in the file LICENSE.
  309. */
  310. namespace PhpCsFixer\Fixer\Comment;
  311. use PhpCsFixer\AbstractFixer;
  312. use PhpCsFixer\Tokenizer\Tokens;
  313. /**
  314. * @author Your name <your@email.com>
  315. */
  316. final class RemoveCommentsFixer extends AbstractFixer
  317. {
  318. public function getDefinition(): FixerDefinition
  319. {
  320. return new FixerDefinition(
  321. 'Removes all comments of the code that are preceded by `;` (semicolon).', // Trailing dot is important. We thrive to use English grammar properly.
  322. [
  323. new CodeSample(
  324. "<?php echo 123; /* Comment */\n"
  325. ),
  326. ]
  327. );
  328. }
  329. public function isCandidate(Tokens $tokens): bool
  330. {
  331. return $tokens->isTokenKindFound(T_COMMENT);
  332. }
  333. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  334. {
  335. foreach ($tokens as $index => $token) {
  336. if (!$token->isGivenKind(T_COMMENT)) {
  337. continue;
  338. }
  339. $prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
  340. $prevToken = $tokens[$prevTokenIndex];
  341. if ($prevToken->equals(';')) {
  342. $tokens->clearAt($index);
  343. }
  344. }
  345. }
  346. }
  347. Step 4 - Format, Commit, PR.
  348. ____________________________
  349. Note that so far, we have not coded adhering to PSR-1/2. This is done on
  350. purpose. For every commit you make, you must use PHP CS Fixer to fix
  351. itself. Thus, on the command line call:
  352. .. code-block:: console
  353. php php-cs-fixer fix
  354. This will fix all the coding style mistakes.
  355. After the final CS fix, you are ready to commit. Do it.
  356. Now, go to GitHub and open a Pull Request.
  357. Step 5 - Peer review: it is all about code and community building.
  358. __________________________________________________________________
  359. Congratulations, you have made your first fixer. Be proud. Your work
  360. will be reviewed carefully by PHP CS Fixer community.
  361. The review usually flows like this:
  362. 1. People will check your code for common mistakes and logical
  363. caveats. Usually, the person building a fixer is blind about some
  364. behavior mistakes of fixers. Expect to write few more tests to cater for
  365. the reviews.
  366. 2. People will discuss the relevance of your fixer. If it is
  367. something that goes along with Symfony style standards, or PSR-1/PSR-2
  368. standards, they will ask you to add it to existing ruleset.
  369. 3. People will also discuss whether your fixer is idempotent or not.
  370. If they understand that your fixer must always run before or after a
  371. certain fixer, they will ask you to override a method named
  372. ``getPriority()``. Do not be afraid of asking the reviewer for help on how
  373. to do it.
  374. 4. People may ask you to rebase your code to unify commits or to get
  375. rid of merge commits.
  376. 5. Go to 1 until no actions are needed anymore.
  377. Your fixer will be incorporated in the next release.
  378. Congratulations! You have done it.
  379. Q&A
  380. ---
  381. Why is not my PR merged yet?
  382. PHP CS Fixer is used by many people, that expect it to be stable. So
  383. sometimes, few PR are delayed a bit so to avoid cluttering at @dev
  384. channel on composer.
  385. Other possibility is that reviewers are giving time to other members of
  386. PHP CS Fixer community to partake on the review debates of your fixer.
  387. In any case, we care a lot about what you do and we want to see it being
  388. part of the application as soon as possible.
  389. Why am I asked to use ``getPrevMeaningfulToken()`` instead of ``getPrevNonWhitespace()``?
  390. The main difference is that ``getPrevNonWhitespace()`` ignores only
  391. whitespaces (``T_WHITESPACE``), while ``getPrevMeaningfulToken()`` ignores
  392. whitespaces and comments. And usually that is what you want. For
  393. example:
  394. .. code-block:: php
  395. $a->/*comment*/func();
  396. If you are inspecting ``func()``, and you want to check whether this is
  397. part of an object, if you use ``getPrevNonWhitespace()`` you are going to
  398. get ``/*comment*/``, which might belie your test. On the other hand, if
  399. you use ``getPrevMeaningfulToken()``, no matter if you have got a comment
  400. or a whitespace, the returned token will always be ``->``.
  401. .. _Composer: https://getcomposer.org
  402. .. _CONTRIBUTING.md: ./../CONTRIBUTING.md
  403. .. _idempotent: https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning
  404. .. _Linus's Law: https://en.wikipedia.org/wiki/Linus%27s_Law
  405. .. _List of Parser Tokens: https://php.net/manual/en/tokens.php
  406. .. _Token class: ./../src/Tokenizer/Token.php
  407. .. _Tokens class: ./../src/Tokenizer/Tokens.php
  408. .. _Transformers: ./../src/Tokenizer/Transformer