Improve your Laravel Coding Standards Using GrumPHP

You always want to write better code. For this, you should have to improve your coding standards. Whether you are working alone or with a team, it is always a good practice to have the same coding conventions throughout the project. But maintaining the same standards in all places is not easy if we are checking it manually. It may happen you missed the standard even if you decided to follow it. It’s a human error, we sometimes miss things that we should not. To prevent such issues, we can automate the workflow. The automated system will take care of the assigned task and 99.99% of the time it never fails.

By combining tools like Git and GrumPHP package one can create this automated system that assists in improving coding standards.

GrumPHP is a library that keeps an eye on each Git commit. If your code does not follow the given standards, the library will not allow you to commit code. You should fix your code first and then only you are able to commit to Git.

In this article, I show you how to improve your Laravel coding standards with the help of the GrumPHP package.

Getting Started

As we are talking about Laravel coding standards, you should have installed Laravel on your system. If you don’t have one install it using the command:

composer create-project laravel/laravel laravel-dev

Here ‘laravel-dev’ is the name of the project. Open the terminal in your project root directory and initialize the Git.

git init

It is compulsory to have Git in your project in order to take advantage of GrumPHP. When you install GrumPHP it creates a hook inside the .git folder to keep watch on every commit.

Next, add and commit your current files to Git by running the given commands one by one.

git add -A
git commit -m "initial commit"

Improve Laravel Coding Standard Using GrumPHP

Once you have set up Git, you are good to go for installing the GrumPHP library. To install it, run the command below:

composer require --dev phpro/grumphp

During package installation, it may ask if you want to create a grumphp.yml file. Skip this step. We require this grumphp.yml file but we’ll manually create it in the next step.

Once the package is installed you should see the below message in the terminal:

Watch out! GrumPHP is sniffing your commits!

That means the package is installed successfully. Next, create the grumphp.yml file in the root folder of the project and add the below lines to it.

grumphp:
    fixer:
        enabled: true
        fix_by_default: true
    tasks: {
        phpcs: {
            standard: PSR2
        }
     }

A few things need to be noticed in the above code. I have passed the true value for enabled and fix_by_default under the fixer. It tells the GrumPHP to fix the possible coding conventions automatically. The GrumPHP package can resolve some coding errors themselves if we enable the fixer.

I have also set the PSR2 for the standard key. Here, we are telling GrumPHP to apply PSR2 coding standards against the files which are going to commit. Laravel follows the PSR2 coding standards that’s why we used it. After this, GrumPHP would perform their task and inform us about the error in a console.

How GrumPHP Works?

Let’s say I have an ImageController.php file in the project and have the following piece of code in it.

public function store(Request $request)
{
    if($request->hasFile('profile_image')) {
        //get filename with extension
        $filenamewithextension = $request->file('profile_image')->getClientOriginalName();
 
        //get filename without extension
        $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
 
        //get file extension
        $extension = $request->file('profile_image')->getClientOriginalExtension();
 
        //filename to store
        $filenametostore = $filename.'_'.time().'.'.$extension;
 
        //Upload File
        $request->file('profile_image')->storeAs('public/profile_images', $filenametostore);
 
        if(!file_exists(public_path('storage/profile_images/crop'))) {
            mkdir(public_path('storage/profile_images/crop'), 0755);
        }
 
        // crop image
        $img = Image::make(public_path('storage/profile_images/'.$filenametostore));
        $croppath = public_path('storage/profile_images/crop/'.$filenametostore);
 
        $img->crop($request->input('w'), $request->input('h'), $request->input('x1'), $request->input('y1'));
        $img->save($croppath);
 
        // you can save crop image path below in database
        $path = asset('storage/profile_images/crop/'.$filenametostore);
 
        return redirect('image')->with(['success' => "Image cropped successfully.", 'path' => $path]);
    }
}

When I try to commit this code I get the output something like the below screenshot. It shows me coding errors and immediately runs the fixer:

grumphp-error

Keep a note that GrumPHP will not resolve all errors reported. You also need to resolve a few errors manually.

You can even ignore the GrumPHP checks in certain conditions. Let’s say you have more than 140 characters in a single line and you want to keep it. In such cases, pass -n to the end of the commit to surpass the GrumPHP checks.

git commit -m "committing the code" -n

When your code satisfies the PSR2 standard or you skip the checks only for certain exceptions, you should get the success message from GrumPHP, and the code will also get committed.

grumphp-success

Conclusion

In this tutorial, we have discussed improving Laravel coding standards using GrumPHP. But it’s not limited to Laravel only. You can use this library in other CMS, Frameworks. It really helps to maintain the coding standards consistent throughout the project. Read more about the GrumPHP on their documentation.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *