PHPCS is the shortened name for PHP_CodeSniffer, which is a package to help monitor and keep code written to a coding standard. It comes with many coding standards built in with customization to change bits as needed. To quote themselves:
PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.
We could very well run this tool occassionally on our codebase by hand… But equally we can automate it instead.
If you use Github, you may be familar with their in-build CI tool, called Actions. This CI tool is available on free accounts and enables you to run scripts and checks when something happens, like when a pull-request is opened. We’re going to use Actions to run our
phpcs command in this way - which will check the code in our pull request and report back warnings or errors as github comments on that pull request.
We’ve made an example PR with some failures to see what it will look like:
To get this on a project of yours, you will need to add a workflow file to your project, like shown below.
name: PHPCS check on: pull_request jobs: phpcs: name: PHPCS runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: PHPCS check uses: chekalsky/phpcs-action@v1
We are using a pre-made action by chekalsky to do most of the work under the hood. Based on the yml field “on”, we’ve told it to run on all new pull requests.
Another step, is to configure PHPCS to run how we would like. In the example below, we’re saying run on all files (which is what the full stop is for) and we’re also changing the line length rule.
<?xml version="1.0"?> <ruleset name="PHP_CodeSniffer"> <description>PHPCS configuration file.</description> <file>.</file> <!-- Our base rule: set to PSR12--> <rule ref="PSR12"/> <rule ref="Generic.Files.LineLength"> <properties> <property name="lineLimit" value="120"/> <property name="absoluteLineLimit" value="0"/> </properties> </rule> </ruleset>
With these two parts in place, if you push new code into the pull request, or create a new pull request already with these files then it should run. If it finds anything, it will look like the screenshot below:
You may also get an email like this:
That’s all there is to it. Let us know if this was useful in comments below.