Improve your Laravel Coding Standards Using GrumPHP

No matter whether you are an experienced developer or a fresher, you should improve your coding standards to become a better developer. Either 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 missed sometimes things which we should not. To prevent such issues, we should automate our workflow. Doing so, our automated system will take care of the task we have assigned to it and 99.99% of the time it never fails.

GrumPHP is a library which keep an eye on your each git commit. If your code not following given standards then the library does not allow you to commit code. You should fix your code first and then only you are able to commit to Git.

Sounds good? Let’s see it in action.

Getting Started

As we are talking about Laravel coding standards, you should have a Laravel project setup. If you don’t have it then install it by the command:

composer create-project --prefer-dist laravel/laravel laravel-dev

Here ‘laravel-dev’ is the name of your 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. This is where it works. When we install GrumPHP it creates a hook inside .git folder and then keep watch on every commit.

Now, add and commit your current files to the git using the commands below one by one.

git add -A
git commit -m 'initial commit'

Improve Laravel Coding Standard Using GrumPHP

Once we have git setup in our Laravel project we are good to go for installing GrumPHP library. To install it, run the command below:

composer require --dev phpro/grumphp

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

Watch out! GrumPHP is sniffing your commits!

It means the package is installed successfully. Next, open the grumphp.yml file and add the below code in it.

parameters:
    git_dir: .
    bin_dir: vendor/bin
    tasks: { 
        phpcs: {
            standard: PSR2
        }
     }

In the above code the important part is the line standard: PSR2. Here, we are telling to GrumPHP that check PSR2 coding conventions against the files which are going to commit. We used PSR2 here because Laravel follows the PSR2 coding standards. After this, GrumPHP would perform their task and inform us about the error in a console if found.

If you have not installed coding standard library then run the command below to install it:

composer require "squizlabs/php_codesniffer=*"

This library has PSR2 coding standards included in its core. So, GrumPHP will check your Laravel code against the PSR2 and suggest you changes if you are not following PSR2 standards.

Let’s say we have ImageController.php file in our project and have 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]);
    }
}

Next, try to commit the code above and you should see output something like below:

Commit Error

It gives the coding error in details along with line number and description. You may also notice the line:

PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY

How to use PHPCBF Command

By running a PHPCBF command we can fix some errors automatically. Head over to ‘vendor/bin’ directory from the terminal and run the below command to fix the errors using PHPCBF.

PHPCBF --standard=PSR2 PATH_TO_YOUR_CONTROLLER

Replace placeholder with the actual values. Probably if you are running this command in Git bash you will get the error of ‘bash: phpcbf: command not found’. In that case, run this command in the Windows command prompt. In our case, we see the following output on the terminal.

PHPCBF

Keep a note of not all errors are resolved by PHPCBH. Sometimes you need to resolve error manually as well. Now when you try to commit the code you should get the success message and code also get committed.

Success

Final Thoughts

In this tutorial, we have discussed improving Laravel coding standards using GrumPHP. But it’s not limited to Laravel only. You can also use this library in your other CMS, Frameworks. We are using GrumPHP library for our Laravel, WordPress and core PHP projects. It really helps us to maintain our coding style consistently.

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 *