3
\$\begingroup\$

I have such part of function:

$token = $this->getToken($user);

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

I have many scenarios:

  1. param type which save in session;
  2. instagram profile exist;
  3. 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?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I am not sure I understand what is supposed to happen in

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

if by any chance $instagramProfile->profile->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->findInstagramProfile($user);

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

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

    $token = $user->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.

\$\endgroup\$
1
  • \$\begingroup\$ shouldn't user in user = $instagramProfile->profile->user; if (!user) be $user \$\endgroup\$ Commented Apr 19, 2018 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.