Refactoring to match In this refactoring we change a switch statement to a match statement https://www.php.net/manual/en/control-structures.match.php
requires: php 8.0.0

The match expression branches evaluation based on an identity check of a value. Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==). Match expressions are available as of PHP 8.0.0.

Original code



        $status = (int)$args['status'];

        switch (
$status) {
            case 
1:
                
$notifier $this->sendPendingNotification();
                break;
            case 
2:
                
$notifier $this->sendAcceptedNotification();
                break;
            case 
3:
                
$notifier $this->sendRejectedNotification();
                break;
            case 
4:
                
$notifier $this->sendBlockedNotification();
            default:
                
$notifier $this->sendDefaultNotification();
                break;
        }

        

Refactored code



        $status = (int)$args['status'];

        
$notifier = match ($status) {
            
self::PENDING => $this->sendPendingNotification(),
            
self::ACCEPTED => $this->sendAcceptedNotification(),
            
self::REJECTED => $this->sendRejectedNotification(),
            
self::BLOCKED => $this->sendBlockedNotification(),
            default => 
$this->sendDefaultNotification()
        };

        

Here is the output of the code

This is the output of original

Invoked method sendAcceptedNotification

This is the output of refactor

Invoked method sendAcceptedNotification

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github