How optimize set of nested 'if' in one function? I have such part of function:

$token = $this-&gt;getToken($user);

    if ('main' !== session('type') &amp;&amp; is_null($token)) {
        $instagramProfile = $this-&gt;findInstagramProfile($user);
        $token = $instagramProfile-&gt;profile-&gt;user-&gt;api_token ?? null;
    } else {
        if (!$instagramProfile = $this-&gt;findInstagramProfile($user)) {
            $profile = create_instagram_profile($user);
            $user = $this-&gt;createUser($profile);
            $token = $user-&gt;api_token;
        } else {
            if($instagramProfile-&gt;profile-&gt;user) {
                $token = $instagramProfile-&gt;profile-&gt;user-&gt;api_token;
            } else {
                $user = $this-&gt;createUser($instagramProfile-&gt;profile);
                $token = $user-&gt;api_token;
            }
        };
    }


I have many scenarios:


param type which save in session;
instagram profile exist;
user exists.


In worlds - very simple, but in code it stay not understandable.

How I can optimize such part of code? 

Maybe create more abstract function?
I am not sure I understand what is supposed to happen in

    if ('main' !== session('type') &amp;&amp; is_null($token)) {
        $instagramProfile = $this-&gt;findInstagramProfile($user);
        $token = $instagramProfile-&gt;profile-&gt;user-&gt;api_token ?? null;
    }


if by any chance $instagramProfile-&gt;profile-&gt;user happens to be null. Otherwise, refactoring is very straightforward. Just lift the common actions out of the if/else one by one:

    $instagramProfile = this-&gt;findInstagramProfile($user);

    if (!$instagramProfile) {
        $instagramProfile = create_instagram_profile($user);
    }   

    user = $instagramProfile-&gt;profile-&gt;user;
    if (!user) {
        $user = $this-&gt;createUser($instagramProfile-&gt;profile);
    }

    $token = $user-&gt;api_token;


Observe that it is just a mechanical rewrite.

PS: I presume that create_instagram_profile can be safely called with null argument; you are doing it anyway.