dimanche 19 juin 2016

minimise if and ifelse statements

i would like to minimise my if and else what would you guys recommend?

im using laravel 5.1 framework if that helps :)

im trying to let users log in with multiple columns (e.g id,email,phone) if one fails then checks the next columns one or is there better way of doing it?

code:

$email = $request->only('email', 'password');
        $ssn='';$badgenumber='';$ophone='';$fphone='';$pager='';


        if(preg_match("/^[0-9]+$/",$email['email']) == 1 && strlen($email['email']) < 6){
            $ssn = $request->only('ssn', 'password');
            $badgenumber = $request->only('badgenumber', 'password');
        }

        if(preg_match("/^[0-9]+$/",$email['email']) == 1 && strlen($email['email']) > 6){
            $ophone = $request->only('ophone', 'password');
            $fphone = $request->only('fphone', 'password');
            $pager = $request->only('pager', 'password');
        }

        if(filter_var($email['email'],FILTER_VALIDATE_EMAIL) === false)
            $email ='';

        $error = 1;

        try {
            // verify the $email and create a token for the user

            if ($error == 1 && $email) {
                $error = 0;
                if (!$token = JWTAuth::attempt($email)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $ssn) {
                $error = 0;
                if (!$token = JWTAuth::attempt($ssn)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $badgenumber) {
                $error = 0;
                if (!$token = JWTAuth::attempt($badgenumber)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $ophone) {
                $error = 0;
                if (!$token = JWTAuth::attempt($ophone)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $fphone) {
                $error = 0;
                if (!$token = JWTAuth::attempt($fphone)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $pager) {
                $error = 0;
                if (!$token = JWTAuth::attempt($pager)) {
                    $error = 1;
                }
            }

            if($error == 1){
                return response()->json(['error' => 'invalid_credentials'], 401);
            }

        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire