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

Completed
Pull Request — master (#69)
by Jérémiah
05:24
created

ErrorHandler::setUserWarningClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
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;
15
use GraphQL\Executor\ExecutionResult;
16
use Psr\Log\LoggerInterface;
17
use Psr\Log\NullLogger;
18
use Psr\Log\LogLevel;
19
20
class ErrorHandler
21
{
22
    const DEFAULT_ERROR_MESSAGE = 'Internal server Error';
23
    const DEFAULT_USER_WARNING_CLASS = 'Overblog\\GraphQLBundle\\Error\\UserWarning';
24
    const DEFAULT_USER_ERROR_CLASS = 'Overblog\\GraphQLBundle\\Error\\UserError';
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 13
    public function __construct($internalErrorMessage = null, LoggerInterface $logger = null, array $exceptionMap = [])
42
    {
43 13
        $this->logger = (null === $logger) ? new NullLogger() : $logger;
44 13
        if (empty($internalErrorMessage)) {
45 12
            $internalErrorMessage = self::DEFAULT_ERROR_MESSAGE;
46 12
        }
47 13
        $this->internalErrorMessage = $internalErrorMessage;
48 13
        $this->exceptionMap = $exceptionMap;
49 13
    }
50
51 8
    public function setUserWarningClass($userWarningClass)
52
    {
53 8
        $this->userWarningClass = $userWarningClass;
54
55 8
        return $this;
56
    }
57
58 8
    public function setUserErrorClass($userErrorClass)
59
    {
60 8
        $this->userErrorClass = $userErrorClass;
61
62 8
        return $this;
63 1
    }
64
65
    /**
66
     * @param Error[] $errors
67
     * @param bool    $throwRawException
68
     *
69
     * @return array
70
     *
71
     * @throws \Exception
72
     */
73 47
    protected function treatExceptions(array $errors, $throwRawException)
74
    {
75
        $treatedExceptions = [
76 47
            'errors' => [],
77
            'extensions' => [
78 47
                'warnings' => [],
79 47
            ],
80 47
        ];
81
82
        /** @var Error $error */
83 47
        foreach ($errors as $error) {
84 12
            $rawException = $this->convertException($error->getPrevious());
85
86
            // Parse error or user error
87 12
            if (null === $rawException) {
88 4
                $treatedExceptions['errors'][] = $error;
89 4
                continue;
90
            }
91
92
            // user error
93 9
            if ($rawException instanceof $this->userErrorClass) {
94 4
                $treatedExceptions['errors'][] = $error;
95 4
                if ($rawException->getPrevious()) {
96 1
                    $this->logException($rawException->getPrevious());
97 1
                }
98 4
                continue;
99
            }
100
101
            // user warning
102 6
            if ($rawException instanceof $this->userWarningClass) {
103 5
                $treatedExceptions['extensions']['warnings'][] = $error;
104 5
                if ($rawException->getPrevious()) {
105 1
                    $this->logException($rawException->getPrevious(), LogLevel::WARNING);
106 1
                }
107 5
                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'][] = Error::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 Error(
127 1
                $this->internalErrorMessage,
128 1
                $error->nodes,
129 1
                $rawException,
130 1
                $error->getSource(),
131 1
                $error->getPositions()
132 1
            );
133 46
        }
134
135 46
        return $treatedExceptions;
136
    }
137
138 3
    public function logException(\Exception $exception, $errorLevel = LogLevel::ERROR)
139
    {
140 3
        $message = sprintf(
141 3
            '%s: %s[%d] (caught exception) at %s line %s.',
142 3
            get_class($exception),
143 3
            $exception->getMessage(),
144 3
            $exception->getCode(),
145 3
            $exception->getFile(),
146 3
            $exception->getLine()
147 3
        );
148
149 3
        $this->logger->$errorLevel($message, ['exception' => $exception]);
150 3
    }
151
152 47
    public function handleErrors(ExecutionResult $executionResult, $throwRawException = false)
153
    {
154 47
        $exceptions = $this->treatExceptions($executionResult->errors, $throwRawException);
155 46
        $executionResult->errors = $exceptions['errors'];
156 46
        if (!empty($exceptions['extensions']['warnings'])) {
157 5
            $executionResult->extensions['warnings'] = array_map(['GraphQL\Error', 'formatError'], $exceptions['extensions']['warnings']);
158 5
        }
159 46
    }
160
161
    /**
162
     * Tries to convert a raw exception into a user warning or error
163
     * that is displayed to the user.
164
     *
165
     * @param \Exception $rawException
166
     *
167
     * @return \Exception
168
     */
169 12
    protected function convertException(\Exception $rawException = null)
170
    {
171 12
        if (null === $rawException) {
172 4
            return;
173
        }
174
175 9
        if (!empty($this->exceptionMap[get_class($rawException)])) {
176 2
            $errorClass = $this->exceptionMap[get_class($rawException)];
177
178 2
            return new $errorClass($rawException->getMessage(), $rawException->getCode(), $rawException);
179
        }
180
181 7
        return $rawException;
182
    }
183
}
184