rivassh / laravel-microscope

Fearless refactoring, it does a lot of smart checks to find certain errors.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Do you dare to move a class?

Find Bugs Before They Bite

Give your eyes a rest, we will detect and fix them for you.

widgetize_header

Built with ❀️ for lazy laravel developers ;)

Required Laravel Version Required PHP Version Latest Version on Packagist Quality Score Total Downloads Today Downloads

Key things to know:

  • It is created to be smarter than phpstorm and other IDEs in finding errors.
  • It is created to understand laravel run-time and magic.
  • It does not show you stupid false errors, all the errors are really errors.
  • Even If you have written a lot of tests for your app, you may still need this.
  • It can refactor your code, by applying early returns automatically.
  • It is written from scratch to yield the maximum performance possible.

🎞️ Video tutorial here

⭐ Your Stars Make Us Do More

If you found this package useful, and you want to encourage the maintainer to work on it, just press the star button to declare your willingness.

Stargazers

⬇️ Installation

You can install the package via composer:

composer require imanghafoori/laravel-microscope --dev

You may also publish config file:

php artisan vendor:publish

πŸ’Ž Usage

You can run:

πŸ”Ή php artisan check:events

πŸ”Ή php artisan check:gates

πŸ”Ή php artisan check:views

πŸ”Ή php artisan check:routes

πŸ”Ή php artisan check:psr4 {-s|--nofix}

πŸ”Ή php artisan check:imports {-s|--nofix}

πŸ”Ή php artisan check:stringy_classes

πŸ”Ή php artisan check:dd

πŸ”Ή php artisan check:early_returns

πŸ”Ή php artisan check:compact

πŸ”Ή php artisan check:blade_queries

πŸ”Ή php artisan check:action_comments

πŸ”Ή php artisan check:bad_practices

πŸ”Ή php artisan check:extract_blades

πŸ”Ή php artisan pp:route

πŸ”Ή php artisan check:generate

πŸ”Ή php artisan check:endif

πŸ”Ή php artisan check:all

Also You will have access to some global helper functions:

  • microscope_dd_listeners($event);

In case you wonder what are the listeners and where are they?! You can use this (0_o) microscope_dd_listeners(MyEvent::class); This call, also can be in boot or register as well. And it works like a normal dd(...); meaning that it will halt.

πŸ“– What the Commands do?

Lets start with:

php artisan check:early_returns

This will scan all your Psr-4 loaded classes and flattens your functions and loops by applying the early return rule. For example:

<?php

foreach ($products as $product) {
    if ($someCond) {
        // A lot of code 1
        // A lot of code 1
        // A lot of code 1
        // A lot of code 1
        // A lot of code 1
        if ($someOtherCond) {
            // A lot more code 2
            // A lot more code 2
            // A lot more code 2
            // A lot more code 2 
            // A lot more code 2
            //
        } // <--- closes second if
    } // <--- closes first if
}

Will be discovered and converted into:

<?php

foreach ($products as $product) {
    if (! $someCond) {
        continue;
    }
    
    // A lot of code 1
    // A lot of code 1
    // A lot of code 1
    // A lot of code 1
    // A lot of code 1

    if (! $someOtherCond) {
        continue;
    }
 
    // A lot more code 2
    // A lot more code 2
    // A lot more code 2
    // A lot more code 2 
    // A lot more code 2
}

The same thing will apply for functions and methods, but with return

<?php

if ($cond1) {
    if ($cond2) {
        ....       
    }
}

// merge into:

if ($cond1 && $cond2) { 
    ...  
}
  • It also supports the ruby-like if():/endif; syntax;
<?php

if ($var1 > 1):
    if ($var2 > 2):
        echo 'Hey Man';
    endif;
endif;

// or if you avoid putting curly braces...
if ($var1 > 1)
    if ($var2 > 2)
        echo 'Hey Man';

Although this type of refactoring is totally safe and is guaranteed to do the same thing as before, but be careful to commit everything before trying this feature, in case of a weird bug or something.


php artisan check:psr4
  • It checks for all the psr4 autoloads defined in the composer.json file and goes through all the classes to have the right namespace, according to PSR-4 standard.
  • It automatically corrects namespaces (according to PSR-4 rules)
  • It also checks for references to the old namespace with the system and replaces them with the new one.

php artisan check:generate

You make an empty file, we fill it, based on naming conventions.

If you create an empty .php file which ends with ServiceProvider.php after running this command: 1 - It will be filled with a boilerplate and correct Psr-4 namespace. 2 - It will be appended to the providers array in the config/app.php


php artisan check:imports
  • It checks all the imports (use statements) to be valid and reports invalid ones.
  • It auto-corrects some of the references, it no ambiguity is around the class name.
  • It can understand the laravel aliased classes so use Request; would be valid.

php artisan check:bad_practices
  • It detects bad practices like env() calls outside of the config files.

php artisan check:routes
  • It checks that your routes refer to valid controller classes and methods.
  • It checks all the controller methods to have valid type-hints.
  • It scans for route(), redirect()->route(), \Redirect::route() to refer to valid routes.
  • It will report the public methods of controllers, which have no routes pointing to them. In other words dead controllers are detected.

php artisan check:compact
  • In php 7.3 if you "compact" a non-existent variable you will get an error, so this command checks the entire project for wrong compact() calls and reports to you, which parameters should be removed.

php artisan check:blade_queries
  • Blade files should not contain DB queries. we should move them back into controllers and pass variables. This command searches all the blade files for Eloquent models and DB query builder and shows them if any.

php artisan check:extract_blades
  • If you want to extract a blade partial out and make it included like: @include('myPartials.someFile')

you can use {!! extractBlade('myPartials.someFile') !!} in your blade files to indicate start/end line and the path/name of the partial you intend to be made.

 <html>
      
      {!! extractBlade('myPartials.head') !!}
          <head>...</head>
      {!! extractBlade() !!}

      
      {!! extractBlade('myPartials.body') !!}
          <body>...</body>
      {!! extractBlade() !!}
      
 </html>

After you execute php artisan check:extract_blades it will become:

<html>
    @include('myPartials.head')
    @include('myPartials.body')
</html>

Also, it will create:

  • resources/views/myPartials/head.blade.php
  • resources/views/myPartials/body.blade.php

and put the corresponding content in them.

  • It is also compatible with namespaced views in modular laravel applications. So this syntax will work: 'MyMod::myPartials.body'

php artisan check:action_comments
  • This adds annotations in the controller actions so that you know which route is pointing to the current controller action.

php artisan pp:route
  • First you have to put this in your route file: microscope_pretty_print_route('my.route.name');
  • You can also pass the Controller@method syntax to the function.
  • You can call it multiple times in order to pretty-print multiple routes.

php artisan check:views
  • It scans your code and find the view() and View::make() and reports if they refer to the wrong files.
  • It scans your blade files for @include() and @extends() and reports if they refer to the wrong files.

Also, it can detect unused variables which are passed into your view from the controller like this: view('hello', [...]); For that you must open up the page in the browser and then visit the log file to see a message like this:

local.INFO: Laravel Microscope: The view file: welcome.index-1 at App\Http\Controllers\HomeController@index has some unused variables passed to it:   
local.INFO: array ('$var1' , '$var2');

Remember some variables are passed into your view from a view composer and not the controller. Those variables are also taken into consideration when detecting unused variables.


php artisan check:events

For example consider:

Event::listen(MyEvent::class, '\App\Listeners\MyListener@myMethod');

1 - It checks the \App\Listeners\MyListener classpath to be valid.

2 - It checks the myMethod to exist on the MyListener class

3 - It checks the myMethod to have the right type-hint (if any) in its signature, for example:

public function myMethod(OtherEvent $e) // <---- notice type-hint here
{
    //
}

This is a valid but wrong type-hint, and will be reported to you. Very cool, isn't it ??!

  • Note that it does not matter how you are setting your event listener,

1- in the EventServiceProvider,

2- By Event::listen facade,

3- By Subscriber class... or any other way. The error would be found. :)


php artisan check:gates

It checks the validity of all the gates you have defined, making sure that they refer to a valid class and method.

It also checks for the policy definitions to be valid.

Gate::policy(User::class, 'UserPolicy@someMethod');
Gate::define('someAbility', 'UserGate@someMethod');

1 - It checks the User classpath to be valid.

2 - It checks the UserPolicy classpath to be valid.

3 - It checks the someMethod to exist.


and more features will be added soon. ;)

Credits

License

The MIT License (MIT). Please see License File for more information.


πŸ™‹ Contributing

If you find an issue or have a better way to do something, feel free to open an issue, or a pull request. If you use laravel-microscope in your open source project, create a pull request to provide its URL as a sample application in the README.md file.

❗ Security

If you discover any security-related issues, please email imanghafoori1@gmail.com instead of using the issue tracker.

More from the author:

Laravel HeyMan

πŸ’Ž It allows us to write expressive code to authorize, validate and authenticate.


Laravel Terminator

πŸ’Ž A minimal yet powerful package to give you the opportunity to refactor your controllers.


Laravel AnyPass

πŸ’Ž It allows you to login with any password in the local environment only.


Eloquent Relativity

πŸ’Ž It allows you to decouple your eloquent models to reach a modular structure


Todo:

  • Detect Bad code
  • Facadize static method calls
  • Detect return keyword in eloquent relations
  • Detect wrong action() calls
  • Enhance blocky code detection
  • Detect return abort();
  • Detect un-registered service providers
  • Detect unused middlewares
A man will never fail unless he stops trying.

Albert einstein

About

Fearless refactoring, it does a lot of smart checks to find certain errors.

License:MIT License


Languages

Language:PHP 99.9%Language:Batchfile 0.1%