DEV Community

Cover image for PHP Code Style
Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

PHP Code Style

Few ways you can simplify, how you should standardise your PHP code style, by following PSR-12.

For start, you need to use PHP CS Fixer to automate fixing the code style. Do install it and try it out.

Few options available for you to use - details as following.

Option 1

You can create your own bash script, to simplify your command to fix your code. One of my choice, is using a Bash script:

#!/usr/bin/env bash


if [ ! -f "$CSFIX" ]; then
    if ! type "php-cs-fixer" > /dev/null; then
      echo "☠️ You need PHP CS Fixer to run this command." 

$CSFIX fix

if [[ `git status --porcelain` ]]; then
  git add .
  git commit -m "Apply PHP CS Fixer"
  MESSAGE="🎉 Successfully complied with PSR-2"
  MESSAGE="🎉 You already complied with PSR-2"

Enter fullscreen mode Exit fullscreen mode

Make sure to make above script executable - chmod +x csfix, then you can run on your current project.

. ./csfix
Enter fullscreen mode Exit fullscreen mode

I like this way, cause you can put some fancy words, and messages on each scenario when running the PHP CS Fixer.

Option 2

Your team may use different operating system - MacOS, Windows, Ubuntu - and above option may not very friendly to Windows. You may go with this option - put it on Composer script command.

In the scripts section in your composer.json file, add the following:

    "scripts": {
        "csfix": [
            "PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix",
            "git add . && git commit -m '🎨 Apply PHP CS Fixer'"
Enter fullscreen mode Exit fullscreen mode

Use the PHP_CS_FIXER_IGNORE_ENV=1 if you are running on PHP8.1. At the moment, still unable to run PHP CS Fixer on PHP8.1.

With above setup, you can run:

composer csfix
> PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix
PHP needs to be a minimum version of PHP 7.2.5 and maximum version of PHP 8.0.*.
Current PHP version: 8.1.0.
Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.
Loaded config default from "/Users/nasrulhazim/Projects/2021/demo/.php-cs-fixer.php".
Using cache file ".php-cs-fixer.cache".
   1) database/seeders/Mock/DemoSeeder.php

Fixed all files in 0.021 seconds, 18.000 MB memory used
> git add . && git commit -m '🎨 Apply PHP CS Fixer'
[develop 254c4d7] 🎨 Apply PHP CS Fixer
 1 file changed, 1 insertion(+), 1 deletion(-)
Enter fullscreen mode Exit fullscreen mode

Noticed that I use the git as well - am too lazy to check if there's changes or not, just commit it right away.

So, with this approach, all your team members can have the same command to be use - composer csfix.

Option 3

If you are looking at more, automated process - you can go with StyleCI, or even have your own Github Action / Bitbucket Pipeline to do all the job.

For Github Action, you may refer to this example, how it can be done or you can refer to the following snippet:

name: Check & fix styling

on: [push]

    runs-on: ubuntu-latest

      - name: Checkout code
        uses: actions/checkout@v2
          ref: ${{ github.head_ref }}

      - name: Run PHP CS Fixer
        uses: docker://oskarstark/php-cs-fixer-ga
          args: --config=.php_cs.dist.php --allow-risky=yes

      - name: Commit changes
        uses: stefanzweifel/git-auto-commit-action@v4
          commit_message: Fix styling
Enter fullscreen mode Exit fullscreen mode

Hopes the options given will help you on make your project much cleaner and standard across your team practices.

Photo by Eugen Str on Unsplash

Top comments (1)

nasrulhazim profile image
Nasrul Hazim Bin Mohamad

PHP CS Fixer configuration for Laravel project:


$finder = PhpCsFixer\Finder::create()

$config = new PhpCsFixer\Config();

return $config
        '@Symfony' => true,
        'array_syntax' => ['syntax' => 'short'],
        // 'binary_operator_spaces' => ['align_double_arrow' => false, 'align_equals' => false],
        'increment_style' => ['style' => 'post'],
        'no_empty_comment' => false,
        'no_extra_blank_lines' => false,
        'no_unneeded_control_parentheses' => false,
        'not_operator_with_successor_space' => true,
        // 'imports_order' => ['sort_algorithm' => 'alpha'],
        'phpdoc_align' => ['tags' => ['param']],
        'phpdoc_no_empty_return' => false,
        'phpdoc_order' => true,
        'increment_style' => false,
        'single_trait_insert_per_statement' => false,
        'yoda_style' => false,
Enter fullscreen mode Exit fullscreen mode