Skip to content
Advertisement

Please Suggest ways to simplify this function

Please suggest how to reduce the number of returns in this function. Sonar-lint suggests to limit the number of returns to 3. https://rules.sonarsource.com/php/RSPEC-1142

  public function index(Request $request)
    {
        $req_body = (json_decode($request->getContent(), true));

        switch ($req_body['action']) {
            case "init":
                return $this->init($req_body['data']);
                break;
            case "login":
                return $this->login($req_body['data']);
                break;
            case "requestOtp":
                return $this->requestOtp($req_body['data']);
                break;
            case "addDetails":
                return $this->addDetails($req_body['data']);
                break;
            case "logout":
                return $this->logout($req_body['data']);
                break;
            case "home":
                return $this->home($req_body['data']);
                break;
            case "getDepartments":
                return $this->getDepartments($req_body['data']);
                break;
            case "getDoctors":
                return $this->getDoctors($req_body['data']);
                break;


            default:
                return response()->json([
                    'error' => true,
                    'message' => 'Invalid action',
                    'data' => (object)null,
                ]);
        }
    }

Advertisement

Answer

Something like:

public function index(Request $request)
{
    $req_body = (json_decode($request->getContent(), true));

    // Collect all available methods here:
    $methods = ['init', 'login', 'requestOtp'];  // etc

    // if method name is in the collection - call this method
    if (in_array($req_body['action'], $methods)) {
        return $this->{$req_body['action']}($req_body['data']);
    }

    return response()->json([
        'error' => true,
         'message' => 'Invalid action',
         'data' => (object)null,
    ]);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement