Help refactoring PHP function

I have the following PHP function from an ExpressionEngine plugin and having a little difficulty figuring out how to refactor this to be more efficient, and shorter.

    public function checkuser() {
        $first_name = $this->EE->input->post("FirstName");
        $last_name  = $this->EE->input->post("LastName");
        $DOB        = $this->EE->input->post("DOB");
        $email      = $this->EE->input->post("Email");
        $this->return_data['error'] = '';
        
        $senddata = array("SearchBy"       =>  "FIND",
                          "UserID"         =>  null,
                          "Username"       =>  null,
                          "Sha1Password"   =>  null,
                          "FirstName"      =>  $first_name,
                          "LastName"       =>  $last_name,
                          "DOB"            =>  $DOB,
                          "Address"        =>  null,
                          "Zip"            =>  null,
                          "Phone"          =>  null,
                          "Email"          =>  $email 
        );

        $url = $this->scic_db_url.'SC2/FindUser';
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_USERAGENT, 'HAC');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($senddata));
        $re = curl_exec($ch);
        $curl_err = curl_error($ch);
        curl_close($ch);
        $part = json_decode($re, true);

        if($curl_err) return $curl_err;
        if(!array_key_exists("Exception", $part)) {
            // User exists. check email for the $part to see if it matches one passed?
            if($part["Primary_Email_Address"] !== $email) {
                $this->return_data['error'] = "* Your account information is in our database, however, it contains a different email address.";
            } else {
                $this->return_data['error'] = "* An Account with this email has already been created";
            }
        } elseif(strpos($part["Message"],"No records found") > -1) {
            // Person with that information doesn't exist but let's check for the email addy once again, for safeties sake
            $senddata = array("SearchBy"       =>  "EMAIL",
                              "UserID"         =>  null,
                              "Username"       =>  null,
                              "Sha1Password"   =>  null,
                              "FirstName"      =>  null,
                              "LastName"       =>  null,
                              "DOB"            =>  null,
                              "Address"        =>  null,
                              "Zip"            =>  null,
                              "Phone"          =>  null,
                              "Email"          =>  $email // ONLY REQUIRED parameter for EMAIL searches
            );

            $url = $this->scic_db_url.'SC2/FindUser';
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
            curl_setopt($ch, CURLOPT_USERAGENT, 'HAC');
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($senddata));
            $re = curl_exec($ch);
            $curl_err = curl_error($ch);
            curl_close($ch);
            $part = json_decode($re, true);
            if($part["Primary_Email_Address"] === $email) {
                $this->return_data['error'] = "* An Account with this email has already been created";
            }
        } else {
            $this->return_data['success'] = true;
        }
        return json_encode($this->return_data);
    }

Open in new window


I'd preferably like to have a function that I could pass the method, "FIND" or "EMAIL" and the arguments and have it return either the error message or success.
LVL 27
Eddie ShipmanAll-around developerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
Read comments in the code:
//factor out all the curl stuff onto its own function.  Just pass the urls and parms
    public function checkuser() {
        $this->return_data['error'] = '';
        
		//supply only the non-null values.  fetchInfo() will provide the 
		//remaining fields with null values
        $senddata = array("SearchBy"       =>  "FIND",
                          "FirstName"      =>  $this->EE->input->post("FirstName"),
                          "LastName"       =>  $this->EE->input->post("LastName"),
                          "DOB"            =>  $this->EE->input->post("DOB"),
                          "Email"          =>  $this->EE->input->post("Email")
        );
		
		
		$result = fetchInfo($this->scic_db_url.'SC2/FindUser', $senddata);
		
		if( false!==$result->error)
		{
			return $result->error;
		}
		
		$part = json_decode($result->content, true);
		
        if(!array_key_exists("Exception", $part)) {
            // User exists. check email for the $part to see if it matches one passed?
            if($part["Primary_Email_Address"] !== $email) {
                $this->return_data['error'] = "* Your account information is in our database, however, it contains a different email address.";
            } else {
                $this->return_data['error'] = "* An Account with this email has already been created";
            }
        } elseif(strpos($part["Message"],"No records found") > -1) {
            // Person with that information doesn't exist but let's check for the email addy once again, for safeties sake
			// pass only the info that is not null
            $senddata = array("SearchBy"       =>  "EMAIL",
                              "Email"          =>  $email
            );
		
			$result = doPost($this->scic_db_url.'SC2/FindUser', $senddata);
			
    		if( false!==$result->error)
    		{
    			return $result->error;
    		}

            $part = json_decode($result->content, true);
			
            if($part["Primary_Email_Address"] === $email) {
                $this->return_data['error'] = "* An Account with this email has already been created";
            }
			
        } else {
            $this->return_data['success'] = true;
        }
        return json_encode($this->return_data);
    }


	private function fetchInfo($url,$params){
			//all the params have a null value.  Whichever of these you passed
			//to the function at the time of the call will take precedence
			//over the null value
            $defaults = array("SearchBy"       =>  null,
                              "UserID"         =>  null,
                              "Username"       =>  null,
                              "Sha1Password"   =>  null,
                              "FirstName"      =>  null,
                              "LastName"       =>  null,
                              "DOB"            =>  null,
                              "Address"        =>  null,
                              "Zip"            =>  null,
                              "Phone"          =>  null,
                              "Email"          =>  null
            );
			
			$result=new stdClass;
			$result->content='';
			$result->error=false;

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
            curl_setopt($ch, CURLOPT_USERAGENT, 'HAC');
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array_merge($defaults, $params)) );
            $result->content = curl_exec($ch);
            $result->error = curl_error($ch);
            curl_close($ch);
	return $result;
	}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.