PHP Code Style
Tags: php, codestyle, csfixer
Published: 2021-12-01 12:57:45

Few ways you can simplify, how you should standardise your PHP code style, by following [PSR-12](https://www.php-fig.org/psr/psr-12/).

For start, you need to use PHP CS Fixer to automate fixing the code style. Do [install](https://github.com/FriendsOfPHP/PHP-CS-Fixer) 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:

```bash
#!/usr/bin/env bash

CSFIX="php-cs-fixer"

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

$CSFIX fix

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

echo $MESSAGE
```

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

```
. ./csfix
```

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:

```json
{
    "scripts": {
        "csfix": [
            "PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix",
            "git add . && git commit -m '🎨 Apply PHP CS Fixer'"
        ]
    }
}
```

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:

```bash
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(-)
```

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](https://github.com/OskarStark/php-cs-fixer-ga) example, how it can be done or you can refer to the  following snippet:

```yaml
name: Check & fix styling

on: [push]

jobs:
  php-cs-fixer:
    runs-on: ubuntu-latest

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

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

      - name: Commit changes
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: Fix styling
```

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

<hr>

Photo by <a href="https://unsplash.com/@eugen1980?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Eugen Str</a> on <a href="https://unsplash.com/s/photos/fix?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>