Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Passed
Pull Request — master (#137)
by Jérémiah
08:18
created

ErrorHandler::treatExceptions()   C

Complexity

Conditions 10
Paths 10

Size

Total Lines 65
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 38
CRAP Score 10.0125

Importance

Changes 0
Metric Value
dl 0
loc 65
ccs 38
cts 40
cp 0.95
rs 6.2553
c 0
b 0
f 0
cc 10
eloc 36
nc 10
nop 2
crap 10.0125

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the OverblogGraphQLBundle package.
5
 *
6
 * (c) Overblog <http://github.com/overblog/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Overblog\GraphQLBundle\Error;
13
14
use GraphQL\Error\Error as GraphQLError;
15
use GraphQL\Executor\ExecutionResult;
16
use Psr\Log\LoggerInterface;
17
use Psr\Log\LogLevel;
18
use Psr\Log\NullLogger;
19
20
class ErrorHandler
21
{
22
    const DEFAULT_ERROR_MESSAGE = 'Internal server Error';
23
    const DEFAULT_USER_WARNING_CLASS = UserWarning::class;
24
    const DEFAULT_USER_ERROR_CLASS = UserError::class;
25
26
    /** @var LoggerInterface */
27
    private $logger;
28
29
    /** @var string */
30
    private $internalErrorMessage;
31
32
    /** @var array */
33
    private $exceptionMap;
34
35
    /** @var string */
36
    private $userWarningClass = self::DEFAULT_USER_WARNING_CLASS;
37
38
    /** @var string */
39
    private $userErrorClass = self::DEFAULT_USER_ERROR_CLASS;
40
41 5
    public function __construct($internalErrorMessage = null, LoggerInterface $logger = null, array $exceptionMap = [])
42
    {
43 5
        $this->logger = (null === $logger) ? new NullLogger() : $logger;
44 5
        if (empty($internalErrorMessage)) {
45 5
            $internalErrorMessage = self::DEFAULT_ERROR_MESSAGE;
46 5
        }
47 5
        $this->internalErrorMessage = $internalErrorMessage;
48 5
        $this->exceptionMap = $exceptionMap;
49 5
    }
50
51
    public function setUserWarningClass($userWarningClass)
52
    {
53
        $this->userWarningClass = $userWarningClass;
54
55
        return $this;
56
    }
57
58
    public function setUserErrorClass($userErrorClass)
59
    {
60
        $this->userErrorClass = $userErrorClass;
61
62
        return $this;
63
    }
64
65
    /**
66
     * @param GraphQLError[] $errors
67
     * @param bool           $throwRawException
68
     *
69
     * @return array
70
     *
71
     * @throws \Exception
72
     */
73 5
    protected function treatExceptions(array $errors, $throwRawException)
74
    {
75
        $treatedExceptions = [
76 5
            'errors' => [],
77
            'extensions' => [
78 5
                'warnings' => [],
79 5
            ],
80 5
        ];
81
82
        /** @var GraphQLError $error */
83 5
        foreach ($errors as $error) {
84 5
            $rawException = $this->convertException($error->getPrevious());
85
86
            // Parse error or user error
87 5
            if (null === $rawException) {
88 2
                $treatedExceptions['errors'][] = $error;
89 2
                continue;
90
            }
91
92
            // user error
93 4
            if ($rawException instanceof $this->userErrorClass) {
94 2
                $treatedExceptions['errors'][] = $error;
95 2
                if ($rawException->getPrevious()) {
96
                    $this->logException($rawException->getPrevious());
97
                }
98 2
                continue;
99
            }
100
101
            // user warning
102 3
            if ($rawException instanceof $this->userWarningClass) {
103 2
                $treatedExceptions['extensions']['warnings'][] = $error;
104 2
                if ($rawException->getPrevious()) {
105 1
                    $this->logException($rawException->getPrevious(), LogLevel::WARNING);
106 1
                }
107 2
                continue;
108
            }
109
110
            // multiple errors
111 2
            if ($rawException instanceof UserErrors) {
112 1
                $rawExceptions = $rawException;
113 1
                foreach ($rawExceptions->getErrors() as $rawException) {
114 1
                    $treatedExceptions['errors'][] = GraphQLError::createLocatedError($rawException, $error->nodes);
115 1
                }
116 1
                continue;
117
            }
118
119
            // if is a try catch exception wrapped in Error
120 2
            if ($throwRawException) {
121 1
                throw $rawException;
122
            }
123
124 1
            $this->logException($rawException, LogLevel::CRITICAL);
125
126 1
            $treatedExceptions['errors'][] = new GraphQLError(
127 1
                $this->internalErrorMessage,
128 1
                $error->nodes,
129 1
                $error->getSource(),
130 1
                $error->getPositions(),
131 1
                $error->path,
132
                $rawException
133 1
            );
134 4
        }
135
136 4
        return $treatedExceptions;
137
    }
138
139
    /**
140
     * @param \Exception|\Error $exception
141
     * @param string            $errorLevel
142
     */
143 2
    public function logException($exception, $errorLevel = LogLevel::ERROR)
144
    {
145 2
        $message = sprintf(
146 2
            '%s: %s[%d] (caught exception) at %s line %s.',
147 2
            get_class($exception),
148 2
            $exception->getMessage(),
149 2
            $exception->getCode(),
150 2
            $exception->getFile(),
151 2
            $exception->getLine()
152 2
        );
153
154 2
        $this->logger->$errorLevel($message, ['exception' => $exception]);
155 2
    }
156
157 5
    public function handleErrors(ExecutionResult $executionResult, $throwRawException = false)
158
    {
159 5
        $exceptions = $this->treatExceptions($executionResult->errors, $throwRawException);
160 4
        $executionResult->errors = $exceptions['errors'];
161 4
        if (!empty($exceptions['extensions']['warnings'])) {
162 2
            $executionResult->extensions['warnings'] = array_map([GraphQLError::class, 'formatError'], $exceptions['extensions']['warnings']);
163 2
        }
164 4
    }
165
166
    /**
167
     * Tries to convert a raw exception into a user warning or error
168
     * that is displayed to the user.
169
     *
170
     * @param \Exception|\Error $rawException
171
     *
172
     * @return \Exception|\Error
173
     */
174 5
    protected function convertException($rawException = null)
175
    {
176 5
        if (null === $rawException) {
177 2
            return;
178
        }
179
180 4
        $rawExceptionClass = get_class($rawException);
181 4
        if (isset($this->exceptionMap[$rawExceptionClass])) {
182 1
            $errorClass = $this->exceptionMap[$rawExceptionClass];
183
184 1
            return new $errorClass($rawException->getMessage(), $rawException->getCode(), $rawException);
185
        }
186
187 3
        return $rawException;
188
    }
189
}
190