Skip to content

Instantly share code, notes, and snippets.

@jackmakiyama
Last active June 15, 2021 21:27
Show Gist options
  • Save jackmakiyama/ee3927b153ff173c71569e79ff0713d1 to your computer and use it in GitHub Desktop.
Save jackmakiyama/ee3927b153ff173c71569e79ff0713d1 to your computer and use it in GitHub Desktop.

Refatorando Condicionais: função switch.

Nesse caso do uso indevido da função switch, pode ser refatorada sem mesmo usar condicionais.

Em meio aos códigos legados de um projeto que trabalho encontrei esse fragmento de código:

<?php

function status($statusId)
{
    switch ($statusId) {
        case "1":$statusName = "Aprovado";
            break;
        case "2":$statusName = "Aguardando Pagto";
            break;
        case "3":$statusName = "Em Analise";
            break;
        case "4":$statusName = "Rejeitado";
            break;
        case "5":$statusName = "Devolvido";
            break;
        case "6":$statusName = "Cancelado";
            break;
        case "3":$statusName = "Bloqueado";
            break;
    }
    return $statusName;
}

O switch pode ser substituído tranquilamente por um simples array. :)

<?php

function status($statusId)
{
    $statusName = [
        1 => "Aprovado",
        2 => "Aguardando Pagto",
        3 => "Em Analise",
        4 => "Rejeitado",
        5 => "Devolvido",
        6 => "Cancelado",
        3 => "Bloqueado",
    ];

    return $statusName[$statusId];
}

Além de diminuir a quantia de código fica de fácil leitura.

@jackmakiyama
Copy link
Author

jackmakiyama commented Jun 15, 2021

Um exemplo para o mesmo resultado, muda um pouco a abordagem para usar enums do PHP 8.1.

<?php

declare(strict_types=1);

enum Status: int
{
    case STATUS_APPROVAL = 1;
    case STATUS_WAITING_PAYMENT = 2;
    case STATUS_ANALISYS = 3;
    case STATUS_REJECTED = 4;
    case STATUS_RETURNED = 5;
    case STATUS_CANCELED = 6;
    case STATUS_BLOCKED = 7;

    public function label(): string
    {
        return match($this) 
        {
            self::STATUS_APPROVAL => 'Aprovado',
            self::STATUS_WAITING_PAYMENT => 'Aguardando Pagto',
            self::STATUS_ANALISYS => 'Em Analise',
            self::STATUS_REJECTED => 'Rejeitado',
            self::STATUS_RETURNED => 'Devolvido',
            self::STATUS_CANCELED => 'Cancelado',
            self::STATUS_BLOCKED => 'Bloqueado'
        };
    }
}
$status = Status::STATUS_RETURNED;
echo $status->label() . ' - ' . $status->value . PHP_EOL; // Devolvido - 5

$status = Status::tryFrom(3);
echo $status->label() . ' - ' . $status->value . PHP_EOL; // Em Analise - 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment