Automate Your Workflow Using GitHub Action & PHP_CS-Fixer

General 2 mins read

Table of Content

    Introduction

    When we build an application, codebase getting messy with time, and likely we'll forget to refactor or remove unnecessary stuff such as unused namespaces or make proper indentation etc. Today we will learn about a great feature in GitHub Actions which is: php-cs-fixer job action

    GitHub Action, PHP_CS-Fixer Workflow

    Prerequisite

    You need the basics of GitHub & Background of PHP.

    What is GitHub Action

    From the official landing page

    GitHub Actions makes it easy to automate all your software workflows, now with world-class CI/CD. Build, test, and deploy your code right from GitHub. Make code reviews, branch management, and issue triaging work the way you want.

    What is PHP_CS-Fixer

    a php-cs-fixer it's a tool to automatically fix PHP Coding Standards issues built by symfony maintainers to help you follow the coding standard and best practices.

    From the website

    The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team’s) style through configuration.

    It can modernize your code (like converting the pow function to the ** operator on PHP 5.6) and (micro) optimize it.

    If you are already using a linter to identify coding standards problems in your code, you know that fixing them by hand is tedious, especially on large projects. This tool does not only detect them, but also fixes them for you.

    PHP_CS-Fixer in Existing Laravel/PHP Project

    If you want to begin working with php-cs-fixer in you Laravel application, do the following

    Add PHP_CS-Fixer File in Your Base Directory

    Let's create a file called .php_cs.dist.php in the base directory on your project and add the following lines:

    <?php
    
    $finder = Symfony\Component\Finder\Finder::create()
        ->in([
            __DIR__ . '/src',
            __DIR__ . '/tests',
        ])
        ->name('*.php')
        ->notName('*.blade.php')
        ->ignoreDotFiles(true)
        ->ignoreVCS(true);
    
    return (new PhpCsFixer\Config())
        ->setRules([
            '@PSR2' => true,
            'array_syntax' => ['syntax' => 'short'],
            'ordered_imports' => ['sort_algorithm' => 'alpha'],
            'no_unused_imports' => true,
            'not_operator_with_successor_space' => true,
            'trailing_comma_in_multiline' => true,
            'phpdoc_scalar' => true,
            'unary_operator_spaces' => true,
            'binary_operator_spaces' => true,
            'blank_line_before_statement' => [
                'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'],
            ],
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_var_without_name' => true,
            'class_attributes_separation' => [
                'elements' => [
                    'method' => 'one',
                ],
            ],
            'method_argument_space' => [
                'on_multiline' => 'ensure_fully_multiline',
                'keep_multiple_spaces_after_comma' => true,
            ],
            'single_trait_insert_per_statement' => true,
        ])
        ->setFinder($finder);
    

    This file contains a coding standard you php-cs-fixer plugin will use them to fix your project coding standard.

    If you want to know more about these options and extra ones, Take a look here

    Configure GitHub Actions

    In order to add php-cs-fixer to your GitHub action project repository, you need to create in your project codebase two folders

    cd /path/to/your/project
    
    # And Then run this
    mkdir -p .github/workflows
    

    With this command we created 2 folders, one called .github and the second one is workflows to let GitHub know that the files lives in the directory workflows is for GitHub Action

    Create PHP_CS-Fixer Configuration File

    Inside workflows folder, create a YAML file and call it php-cs-fixer.yml and put this inside it

    name: Check & fix styling
    
    on: [push]
    
    jobs:
        php-cs-fixer:
            runs-on: ubuntu-latest
    
            steps:
                - name: Checkout code
                  uses: actions/[email protected]
                  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/[email protected]
                  with:
                      commit_message: Fix styling
    

    In this file, we tell GitHub to run php-cs-fixer inside your codebase and commit the changes into existing project.

    Note:

    If you want to run php-cs-fixer only in specific branch, let's say you want to run this only in the main or master branch and not in dev branch do the following

    Instead of this

    on: [push]
    

    Do This

    on:
      push:
        branches: [ main ]
      pull_request:
        branches: [ main ]
    

    We Tell GitHub Actions to run the php-cs-fixer only when we push changes or accepting a pull_request, otherwise skip this step.

    Conclusion

    Today We Learned about GitHub Actions and PHP-CS-fixer and how to use them in your application to help you automate your workflow and be more productive and focus on your code rather than fixing coding standards such as removing unused namespaces or remove indentation, because it will be a hard work and time-consuming if you have a big project.

    That's it for today and hope you learned something useful, and if you have any question put them in the comment section, and I'll very be happy to answer them.


    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer

    I'm a full stack web developer and telecommunications engineer who love to share knowledge and build stuff online!


    Comments

    Join Our Newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    Our news letter sent once a week, every tuesday.