Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Tools to automatically format PHP, JavaScript and CSS files

Original – by Freek Van der Herten – 2 minute read

When working on a project with other people, it's important to pick a coding standard. A coding standard like PSR-2 in the PHP world specifies rules on where certain characters, like braces of an if statement, or comma's should be put. Agreeing on a coding standard makes the code more readable for all developers that need to touch the project.

It's easy to make mistakes against those formatting rules and bit cumbersome to fix all small formatting errors. Luckily there are many tools available that can automatically format this code. In this blog post, I'll show you how to automatically format PHP, JavaScript and CSS files in a Laravel project. Not using Laravel? No problem! Most of this can be applied to any PHP project.

Automatically format PHP files

There are excellent paid services to enforce a coding standard, such as StyleCI, but you can also do this in your own project. An excellent tool for this is PHP-CS-Fixer. Let's take a look at how to use it.

You can install the tool globally, but I recommend to install it into your project, so anybody working on the project can make use of it too.

You can install PHP-CS-Fixer with:

composer require --dev friendsofphp/php-cs-fixer

Next, you can configure it by creating a .php_cs config file in the root of your project. Here's the configuration that I use for my Laravel projects.

<?php

$finder = Symfony\Component\Finder\Finder::create()
    ->notPath('vendor')
    ->notPath('bootstrap')
    ->notPath('storage')
    ->in(__DIR__)
    ->name('*.php')
    ->notName('*.blade.php');

return PhpCsFixer\Config::create()
    ->setRules([
        '@PSR2' => true,
        'array_syntax' => ['syntax' => 'short'],
        'ordered_imports' => ['sortAlgorithm' => 'alpha'],
        'no_unused_imports' => true,
    ])
    ->setFinder($finder);

In the first statement of this configuration, we're using Finder object to select some files. We're going to exclude the vendor because otherwise composer would complain about changes in those files when we upgrade dependencies. In a Laravel app, the bootstrap directory contains some autogenerated caches. We aren't going to modify those. The storage directory will remain untouched as well. In every other directory, we are going to select files ending on .php (except .blade.php files which are view templates).

The second statement contains what we are going to do with the selected files. Our base will be the aforementioned PSR-2 code standard. We're also going to add some extra rules:

  • any usage of array() will be converted to []
  • all the imports will be sorted alphabetically
  • all unused imports will be removed.

PHP-CS-Fixer comes with a bunch of additional rules. Head over to the usage section of the package on GitHub to see all available rules.

When PHP-CS-Fixer runs it will create a temporary .php_cs.cache file. You should add an entry to ignore this file in your .gitignore.

You could run PHP-CS-Fixer like this:

vendor/bin/php-cs-fixer fix

I never run php-cs-fixer with the command above, but using a composer script called. format. Of course, you can name it whatever you want. Using a Composer script has the added benefit that, if you should every change to another tool to auto-format your code, you can change the composer script and still run the same command embedded in your muscle memory.

Add this to your composer.json file:

"scripts": {
    "format": [
        "vendor/bin/php-cs-fixer fix"
    ],
}

You can now run the fixer with:

composer format

And now all your project files are formatted according to PSR-2 and the additional rules you specified.

Automatically format JavaScript, Vue and CSS files

Let's also set up a tool for auto-formatting JavaScript files. An excellent choice for this is Prettier. You can install with yarn by running

yarn add prettier --dev --exact

Users of NPM can run this:

npm install --save-dev --save-exact prettier

Prettier can be configured by adding a .prettierrc file in the root of your directory. The docs contain a list of all available options. Here is the configuration that I use for most projects.

{
    "printWidth": 100,
    "singleQuote": true,
    "tabWidth": 4,
    "trailingComma": "es5"
}

In a typical project minified versions of your assets will be stored somewhere in your public directory. You can let Prettier know it should not scan that directory by adding a .prettierignore file in the root of your project with this content:

public/
vendor/

In a Laravel project, all CSS and JavaScript is typically stored in the resources/ directory. To auto format those files you can run this command.

prettier --write 'resources/**/*.{css,js,vue}'

You probably don't want to type that command every time you need to auto format your files. Let's make running Prettier a tad easier by adding a script in the package.json file.

"scripts": {
   "format": "prettier --write 'resources/**/*.{css,js,vue}' 'nova-components/**/*.{css,js,vue}'",
},

With this in place you can run Prettier with:

yarn format

or with:

npm run format

In closing

PHP-CS-Fixer and Prettier can automatically format your code. If you want to see an example of a Laravel project where both of these tools are being used, head over to the murze.be repo on GitHub that contains the code that runs this very blog.

Recently Prettier gained the ability to format PHP code. I haven't tried it personally, but Chris likes it, it must be good!

Happy formatting!

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "Tools to automatically format PHP, JavaScript and CSS files"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.