0

I have this big function that is calling a lot of other functions who that make API requests to BlackBoard, my problem is, in this main function, I create my user and sign him to the current course, but actually we faced this situation: that same user is already registered in BlackBoard, so I made an update function, to that specific case. But that main function it's all in a try catch block, so every time that I call the method:

$userSalvo = $bd->createUser($user)

and the user already exist in BlackBoard database, he immediatly stop my function and call the catch block, to obviously get the exception, but I need if that user already exist, he comeback from this request and go to the next method:

$userSalvo = $bd->updateUser($user, $userId);

I already tried to put this in a if statement, but It doesnt work as it should:

                    if($userSalvo = $bd->createUser($user))
                    {
                        dd('create');
                        $user->id = $userSalvo['id'];
                    }else
                    {
                        dd('update');
                        $userSalvo = $bd->updateUser($user, $userId);
                        $user->id = $userSalvo['id'];
                    }

Anyone has some ideia of how can I do this?

This is the API method that I'm calling to update/create:

     public function updateUser($user, $userId)
    {
        $user->dataSourceId = $this->dataSourceId;
        return $this->bd->patch("/users/{$userId}", json_decode(json_encode($user), true));
    }
    
    public function createUser($user)
    {
        $user->dataSourceId = $this->dataSourceId;
        return $this->bd->post("/users", json_decode(json_encode($user), true));
    }
calebe santana
  • 339
  • 2
  • 8

1 Answers1

1

You should then use the try-catch block if you do not want to refactor your code. What's happening by the sounds of it is your if condition dies as 'createUser' is called.

Rather try this to replace your entire if statement.

try{
    $userSalvo = $bd->createUser($user)
}catch(Exception $e){
    $userSalvo = $bd->updateUser($user, $userId);
}

This is assuming that $user and $userId is defined.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Jordan Casey
  • 955
  • 9
  • 16
  • Got it! The problem in this solution is if I put this piece of code in the catch block, I should move all other piece of code that continues signing users with courses and persisting in database..and obviously, It will be a repeated code, because it does the same in both methods. – calebe santana Aug 09 '21 at 12:23
  • Rock on! I would recommend looking over the code and trying to clean it up so it's easier to maintain if this is a project that you will be working with for a while. If this is the accepted answer, please feel free to click the checkbox as this will then be marked as such! Happy coding! – Jordan Casey Aug 09 '21 at 12:28