Yii2 中简单代码的重构(if-else)

refactoring of simple code in Yii2 (if-else)

我正在对 Yii2 框架中的项目进行一些代码重构。

我只是想问一下是否可以写得更好,减少重复(我尽可能地尝试遵循 DRY)。任何关于此类主题的文献推荐都非常欢迎,抱歉英语不好。

$exception = Yii::$app->errorHandler->exception;

    if ($exception !== null) {
        if (isset($exception->statusCode)) {
            if ($exception->statusCode == 500) {
                return $this->render('error-500', ['exception' => $exception]);
            } elseif ($exception->statusCode == 404) {
                return $this->render('error-404', ['exception' => $exception]);
            } else {
                return $this->render('error', ['exception' => $exception]);
            }
        } elseif (isset($exception->code)) {
            if ($exception->code == 500) {
                return $this->render('error-500', ['exception' => $exception]);
            } elseif ($exception->code == 404) {
                return $this->render('error-404', ['exception' => $exception]);
            } else {
                return $this->render('error', ['exception' => $exception]);
            }
        }
    } else {
        $exception = new \yii\web\HttpException(500);
        return $this->render('error-500', ['exception' => $exception]);
    }

喜欢就可以

    $exception = Yii::$app->errorHandler->exception;

    if ($exception !== null) {
        if (isset($exception->statusCode){
            return $this-render('error-' . $exception->statusCode , ['exception' => $exception] );
        } else if (isset($exception->code)) {
            return $this-render('error-' . $exception->code , ['exception' => $exception] )
        } else {
        $exception = new \yii\web\HttpException(500);
        return $this->render('error-500', ['exception' => $exception]);
        }
    }

左右如果喜欢更紧凑

    if ($exception !== null) {
        if (isset($exception->statusCode,  $exception->code){
            return $this-render('error-' . ($exception->statusCode) ? $exception->statusCode : $exception->code , ['exception' => $exception] );
        } else {
        $exception = new \yii\web\HttpException(500);
        return $this->render('error-500', ['exception' => $exception]);
        }
    }

另一种可能的方式

     if ($exception !== null) {

        $exceptionCode = isset($exception->statusCode)?$exception->statusCode:
                ( isset($exception->code)?$exception->code:null );

        if($exceptionCode){
            $viewFile = ($exceptionCode == 500)?'error-500':
                    ( ($exceptionCode == 404)?'error-404':'error');

            return $this->render($viewFile, ['exception' => $exception]);

        } else {
            // you need to something here
        }

    }