Skip to content

How to lint with phpcs

If your project has a phpcs.xml file in its root directory, then it has been set up to use Code Sniffer (CS). CS is a tool that catches violations of coding conventions in PHP code. For example, places where whitespace has been used inconsistently, or functions have not been named in camelCase. Your code should not produce any CS errors, and GitLab will automatically run it over your merge request for you.

Some IDEs will run CS automatically for you, for example in PHPStorm go to Code -> Inspect code in the menu. You can also reformat your code with Code -> Reformat code or Ctrl + Alt + L**.

To run CS locally in a shell, try:

./vendor/bin/phpcs

If your branch fails the lint, in some cases your code can be fixed automatically. For example, if you get a message like this:

FILE: ...HelperTest.php
-----------------------------------------------------------------------------------------
FOUND 6 ERRORS AFFECTING 6 LINES
-----------------------------------------------------------------------------------------
  8 | ERROR | [ ] Each class must be in a namespace of at least one level (a top-level
    |       |     vendor name)
 10 | ERROR | [ ] Method name "HelperTest::test_timeHasPassed" is not in camel caps
    |       |     format
 23 | ERROR | [ ] Method name "HelperTest::test_userLink" is not in camel caps format
 41 | ERROR | [x] Function closing brace must go on the next line following the body;
    |       |     found 1 blank lines before brace
 46 | ERROR | [x] Inline control structures are not allowed
 54 | ERROR | [x] The closing brace for the class must go on the next line after the
    |       |     body
-----------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 3 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-----------------------------------------------------------------------------------------

then you can act on the advice in the message, and run phpcbf to fix these problems:

$ vendor/bin/phpcbf

PHPCBF RESULT SUMMARY
----------------------------------------------------------------
FILE                                           FIXED  REMAINING
----------------------------------------------------------------
...
.../HelperTest.php                                3      3
----------------------------------------------------------------
A TOTAL OF 1653 ERRORS WERE FIXED IN 54 FILES
----------------------------------------------------------------

Time: 3.37 secs; Memory: 18Mb
$

In this case, the phpcbf tool has fixed 3 errors and left 3 that the developer must fix themselves. In most cases, you can use your IDE to automate many of these problems (try right-clicking on the code and search for refactor in the context menu).