michaelnguyen547's avatar

code review with if, switch, foreach

I have this code, it works but it is messy. Any advices to improve it?

foreach ($request->platform as $platform) {
    switch ($platform) {
        case \App\Enums\Platform::SMS:

            // customized drivers
            if ($request->recipients) {
                $recipients = \App\Provider::find(explode(',', $request->recipients));
                foreach ($recipients as $recipient) {
                    ProcessSMS::dispatch($recipient, $message);
                }
            } else {
                foreach ($request->driverStatus as $driverStatus) {
                    \App\Provider::where('type', $driverStatus)->chunk(100, function ($recipients) use ($message) {
                        foreach ($recipients as $recipient) {
                            ProcessSMS::dispatch($recipient, $message);
                        }
                    });
                }
            }

            break;

        case \App\Enums\Platform::PUSH:

            if ($request->recipients) {
                $recipients = \App\Provider::find(explode(',', $request->recipients));
                foreach ($recipients as $recipient) {
                    ProcessPushNotification::dispatch($recipient, $message);
                }
            } else {
                foreach ($request->driverStatus as $driverStatus) {
                    \App\Provider::where('type', $driverStatus)->chunk(100, function ($recipients) use ($message) {
                        foreach ($recipients as $recipient) {
                            ProcessPushNotification::dispatch($recipient, $message);
                        }
                    });
                }
            }
            break;
    }
}
0 likes
2 replies
Drfraker's avatar

Start by creating a new class for each thing you are doing in the switch statement and each if statement. You will begin to see patterns in your code that you will be able to further abstract as you go down that path. Show your code as you go if you have more questions.

wing5wong's avatar

Design an interface, then create classes for each branch. Then you can do,e.g.

foreach($request->platform as $platform){ (new $platform)->handle(); }

Please or to participate in this conversation.