Learn To Code With Style: Use Linters!

Are you tired of always writing the same comments on others pull requests? Are you tired of always reading the same comments on your pull requests? Stop wasting time, here’s the solution.

Step One: Install linters on your project

For your php files

Inspired by this CodeSniffer and PhpStorm Code Inspection article, we can install phpcs with a specific coding standard directly on your project.

Install CodeSniffer

composer require --dev squizlabs/php_codesniffer

Install a coding standard

When I start working on a Symfony2 project, it was with the djoos/Symfony2-coding-standard repository.

composer require --dev escapestudios/symfony2-coding-standard

Now i made my own my fork with more rules, try it!

composer require --dev vincentlanglet/symfony3-custom-coding-standard

Use it

Let’s try with this file

// yourfile.php

<?php

class Entity {
    function getVariable() {
        return $this->variable;
    }

    function setVariable($newValue) {
        $this->variable = $newValue;
    }

    private $variable;
}

The following command

vendor/bin/phpcs --standard=../../../../vincentlanglet/symfony3-custom-coding-standard/Symfony3Custom yourfile.php

will return error messages
Phpcs

that you can easily correct

<?php

namespace AppBundle\Entity;

/**
 * Class Entity
 *
 * @package AppBundle\Entity
 */
class Entity
{
    /**
     * @var string
     */
    private $variable;

    /**
     * @return string
     */
    public function getVariable()
    {
        return $this->variable;
    }

    /**
     * @param string $newValue
     */
    public function setVariable($newValue)
    {
        $this->variable = $newValue;
    }
}

NB: If you are tired to write --standard=../../../../vincentlanglet/symfony3-custom-coding-standard/Symfony3Custom,
or if you need to configure phpcs to use it with PhpStorm, try

vendor/bin/phpcs --config-set default_standard ../../../../vincentlanglet/symfony3-custom-coding-standard/Symfony3Custom

You can find others options here.

For your javascript files

Let’s do the same with eslint.

Install eslint

npm install eslint --save-dev

Generate a configuration file

To start the configuration of eslint, use

./node_modules/.bin/eslint --init

After answering a few questions, it will generate a .eslintrc file configured like this

{
  "extends": "eslint:recommended",
  "rules": {
    "semi": ["error", "always"],
    "quotes": ["error", "double"]
  }
}
  • extends apply all the rules of eslint:recommended to your project. I recommend the airbnb config.
  • semi and quotes are extra rules. The first value is the error value of the rule.

Use it

Let’s try with this file

// yourfile.js

var object={
  'key': 3,
     "otherKey" :2
};

console.log(object)

The following command

./node_modules/.bin/eslint yourfile.js

will return error messages
Eslint

that you can easily correct

const object = {
  key: 3,
  otherKey: 2,
}

console.log(object)

Even for your css files

In the same way, you can lint your css files thanks to stylelint.

Install stylelint

npm install stylelint --save-dev

Write your configuration file

I recommend the stylelint-config-standard.

npm install stylelint-config-standard --save-dev

Now you have to create your .stylelintrc file, it works like your .eslintrc file:

{
  "extends": "stylelint-config-standard",
  "rules": {
    "string-quotes": "single"
  }
}

Use it

Let’s try with this file

/* yourfile.css */

.header {

}

body {
text-color: red;
margin-top: 10px;
margin-bottom: 10px;
margin: 0;
}

The following command

./node_modules/.bin/stylelint yourfile.css

will return error messages
Stylelint

that you can easily correct

body {
  color: red;
  margin: 10px 0;
}

Step Two: Use linters automatically before each commit

Use pre-commit hooks

Pre-commit hooks were already introduced in this article, but personally I prefer using a npm package.

Install pre-commit

npm install pre-commit --save-dev

Configure pre-commit

You just need to specify scripts you want to launch before committing in your package.json.
You could even launch tests before commits if you wanted.

{
  "name": "Something",
  "version": "0.0.0",
  "description": "Something else",
  "main": "index.js",
  "scripts": {
    "lint:php": "vendor/bin/phpcs --standard=../../../../escapestudios/symfony2-coding-standard/Symfony2 *.php",
    "lint:js": "eslint *.js",
    "lint:css": "stylelint *.css"
  },
  "pre-commit": [
    "lint:php",
    "lint:js",
    "lint:css"
  ]
}

Use it

Just commit!

But don’t worry, you can still force a commit by telling git to skip the pre-commit hooks by simply committing using --no-verify.

Check only modified files to be more user-friendly

Running a lint process on a whole project is slow and linting results can be irrelevant. Ultimately you only want to lint files that will be committed. Lint-staged will be used to run linter on staged files, filtered by a specified glob pattern.

Install lint-staged

npm install lint-staged --save-dev

Configure lint-staged

Launch lint-staged with pre-commit and precise which linter you want to use for specific files pattern in your package.json.

{
  "name": "Something",
  "version": "0.0.0",
  "description": "Something else",
  "main": "index.js",
  "scripts": {
    "lint-staged": "lint-staged"
  },
  "lint-staged": {
    "*.php": "vendor/bin/phpcs --standard=../../../../escapestudios/symfony2-coding-standard/Symfony2",
    "*.js": "eslint",
    "*.css": "stylelint"
  },
  "pre-commit": [
    "lint-staged"
  ]
}

Use it

Wait


You liked this article? You'd probably be a good match for our ever-growing tech team at Theodo.

Join Us

  • Airbnb Javascript Style Guide and its eslint configuration is indeed really nice and should sort most issues related to styling!
    A good rule of thumb once you have it (and maybe a formatting tool like Prettier for JS) is to then never losing time asking for changes related to code style: just make sure the linter is passing :)
    And if something looks wrong to you, you can always make a change in the configuration to enforce its use in the whole codebase.

  • Vincent Langlet

    Indeed, since the coding style is very subjective, the configuration is there to define standards and no longer waste time in debate. It should therefore be amended only to add a missing rule which is the subject of debate in the team.

  • tipy

    Great thanks ! I was looking for some linter tips for javascript and you got it covered. For PHP code, I use Grumphp to run phpcs and other stuffs (phpmd, phpdcd, …) and ensure code quality with a pre-commit hook. You should give it a try

  • Thanks for sharing tips, this my favorite field in PHP programming :)

    You mentioned Symfony sniffs. Do you know about https://github.com/FriendsOfPHP/PHP-CS-Fixer?

    If so, I wonder, why do you prefer that to PHP-CS-Fixer Symfony level?

  • Also, you might like this tool: https://www.tomasvotruba.cz/blog/2017/05/03/combine-power-of-php-code-sniffer-and-php-cs-fixer-in-3-lines/

    It combined PHP_CodeSniffer and PHP-CS-Fixer in most simple way.

  • Vincent Langlet

    Hi !
    I discovered Php-cs-fixer, when I wrote my article so I never used it. With Phpcs, you have Phpcbf to fix sniffs so I was wondering what Php-cs-fixer could have more.

  • Vincent Langlet

    Thanks ! I will.
    Does grumphp offer something more than Phpcs for linting?

  • To bad, it will save you so much work.

    The best is to combined them, because each has around 150-200 checkers, that do work for you. And even if part of them cover the same thing, combined 300 checkers in total is way more than 200 and will provide much better code control without no additional work.

    There is even more. PHP-CS-Fixer is evolving much faster, having new fixers every week. E.g. a month old 2.2 release added very nice Doctrine annotations fixers (and much more).

    I see many people writing sniff feature and test to it, that’s been in fixer for years, no added value here. I think you have much better think you’d like to invest that into.

    It makes no sense to drop the other and use only one for 100%.

    I wrote a post about that: https://www.tomasvotruba.cz/blog/2017/05/03/combine-power-of-php-code-sniffer-and-php-cs-fixer-in-3-lines/

  • Vincent Langlet

    Thanks. I will look at it for sure.

  • Hii nice to see your post here. i had some information about DevOps in my site.

    http://www.kellytechno.com/Online/Course/Devops-Training

  • ohhanibaek

    The blog quite often and I truly appreciate your information.I feel Today i am learn some good information about the linters concepts where it is placed and why it used.Thanks for posting.
    Python Training Institutes In Hyderabad

  • Linter is a base linter provider for the hackable Atom Editor. Additionally, you need to install a specific linter for your language. You will find a full list on atomlinter.github.io.

    It provides a top-level API to its consumer so that they can visualize errors and other types of messages with ease.

  • Thanks for sharing the details! thanks for sharing information,nice article.
    i would like to more information from your side!
    please added more then tips!Am working in
    mainframe training institute in Hyderabad

  • sadha onnisa

    Thanks to making this .i had some updates about online training courses in my site..click here and get valuable information. https://techenoid.com/

  • sadha onnisa

    hiiii

  • sadha onnisa
  • ganesh reddy

    well! Thanks for providing a good stuff related to DevOps Explination is good, nice Article
    anyone want to learn advance devops tools or devops online training
    DevOps Online Training

  • sadha onnisa

    Thanks for sharing this ! it really great helpfull for me. We offer Robotic process automation training in techenoid platform with real time industry consultants to provide quality training for all professionals and students. We are motivated to give you the high-quality online training at an affordable price is our core value. visit https://techenoid.com/rpa-training