Nette Coding Standard
Coding Standard automatically formats your PHP code according to the Nette coding standard, from indentation and braces to spacing and the ordering of imports.
Under the hood it combines two industry-standard tools, PHP CS Fixer and PHP CodeSniffer, which come preconfigured, so you do not have to set anything up yourself.
Installation
Install the tool globally using Composer:
composer global require nette/coding-standard
and make sure your global vendor binaries directory is in your
$PATH environment variable.
Usage
The tool provides two commands. The check command only reports violations, while fix repairs them
automatically:
ecs check
ecs fix
Without any arguments it scans the src/ and tests/ directories; you can also pass one or more of your
own paths, for example ecs check app bin.
Before you run the fixer for the first time, be sure to back up your files.
PHP Version
The tool supports PHP 8.0 to 8.5 and applies the rules incrementally according to the version. It detects the version
automatically from your project's composer.json, but you can also set it explicitly with the --preset
option:
ecs check --preset php81
Custom Rules
You can tweak the rules for your project. To change the PHP CS Fixer rules, create an ncs.php file in the
project root:
<?php
return [
'strict_comparison' => false,
];
To change the PHP CodeSniffer rules, create an ncs.xml file. It does not need to reference the version preset (it
is combined with it automatically), and you can use $presets/ to pull in any bundled preset:
<?xml version="1.0"?>
<ruleset name="MyProject">
<!-- enable use function/const imports -->
<rule ref="$presets/optimize-fn.xml"/>
<!-- disable a rule -->
<exclude name="SlevomatCodingStandard.TypeHints.ReturnTypeHint"/>
</ruleset>
Both files are discovered automatically and your rules take precedence over the preset. For a one-off override that you do not
want to commit, pass an extra file with --config-file (.php for the fixer, .xml for the
sniffer).
Continuous Integration
In a CI pipeline, install the tool as a project and run it from there:
- run: composer create-project nette/coding-standard temp/coding-standard
- run: php temp/coding-standard/ecs check