cookbook_fixers.rst 15 KB

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