Passed
Pull Request — master (#46)
by Paweł
02:52
created

DefaultController::getName()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 1
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace app\modules\api\v1\controllers;
4
5
use yii\base\Exception;
6
use yii\base\UserException;
7
use yii\web\Controller;
8
use yii\web\HttpException;
9
use yii\web\NotFoundHttpException;
10
use yii\web\Response;
11
12
/**
13
 * Default controller for the `v1` module
14
 */
15
class DefaultController extends Controller
16
{
17
    /**
18
     * Generic error.
19
     *
20
     * @return array
21
     */
22
    public function actionError()
23
    {
24
        $exception = $this->getException();
25
26
        $name = $this->getName($exception);
27
28
        $message = $this->getMessage($exception);
29
30
        return $this->prepareResponse($name, $message, $exception);
31
    }
32
33
    protected function getException()
34
    {
35
        if (($exception = \Yii::$app->getErrorHandler()->exception) === null) {
36
            // action has been invoked not from error handler, but by direct route, so we display '404 Not Found'
37
            $exception = new NotFoundHttpException('Endpoint not found.');
38
        }
39
40
        return $exception;
41
    }
42
43
    protected function getCode(Exception $exception): int
44
    {
45
        if ($exception instanceof HttpException) {
46
            $code = $exception->statusCode;
47
        } else {
48
            $code = $exception->getCode();
49
        }
50
51
        return $code;
52
    }
53
54
    protected function getName(Exception $exception): string
55
    {
56
        if ($exception instanceof Exception) {
0 ignored issues
show
introduced by
$exception is always a sub-type of yii\base\Exception.
Loading history...
57
            $name = $exception->getName();
58
        } else {
59
            $name = 'Error';
60
        }
61
62
        $code = $this->getCode($exception);
63
64
        if ($code) {
65
            $name .= " (#$code)";
66
        }
67
68
        return $name;
69
    }
70
71
    protected function getMessage(Exception $exception): string
72
    {
73
        if ($exception instanceof UserException) {
74
            $message = $exception->getMessage();
75
        } else {
76
            $message = 'An internal server error occurred.';
77
        }
78
79
        return $message;
80
    }
81
82
    protected function prepareResponse($name, $message, $exception): array
83
    {
84
        \Yii::$app->response->format = Response::FORMAT_JSON;
85
86
        return [
87
            'name' => $name,
88
            'message' => $message,
89
            'exception' => $exception,
90
        ];
91
    }
92
}
93