我有这样一部分的职能:
$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;
}
};
}我有很多种情景:
type;在世界上-非常简单,但在代码中,它是不可理解的。
我如何优化这部分代码?
也许能创造出更抽象的功能?
发布于 2018-04-19 07:35:36
我不知道该怎么做
if ('main' !== session('type') && is_null($token)) {
$instagramProfile = $this->findInstagramProfile($user);
$token = $instagramProfile->profile->user->api_token ?? null;
}如果$instagramProfile->profile->user碰巧是null的话。否则,重构是非常简单的。只需一个接一个地将常见的操作从if/else中删除:
$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;注意到这只是一次机械重写。
PS:我认为create_instagram_profile可以通过null参数安全地调用;无论如何,您都在这样做。
https://codereview.stackexchange.com/questions/192435
复制相似问题