Passed
Pull Request — master (#318)
by Sam
03:54
created

ErrorHandler::addMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Error\Handler;
4
5
use Digia\GraphQL\Execution\ExecutionContext;
6
use Digia\GraphQL\Execution\ExecutionException;
7
8
class ErrorHandler implements ErrorHandlerInterface
9
{
10
    /**
11
     * @var ErrorMiddlewareInterface[]
12
     */
13
    protected $middleware = [];
14
15
    /**
16
     * ErrorHandler constructor.
17
     * @param ErrorMiddlewareInterface[] $middleware
18
     */
19
    public function __construct(array $middleware)
20
    {
21
        foreach ($middleware as $mw) {
22
            $this->addMiddleware($mw);
23
        }
24
    }
25
26
    /**
27
     * @param \Throwable $exception
28
     */
29
    public function handleError(\Throwable $exception)
30
    {
31
        $next = function () {
32
            // NO-OP
33
        };
34
35
        foreach ($this->middleware as $middleware) {
36
            $next = function (\Throwable $exception) use ($middleware, $next) {
37
                return $middleware->handleError($exception, $next);
38
            };
39
        }
40
41
        \call_user_func($next, $exception);
42
    }
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function handleExecutionError(ExecutionException $exception, ExecutionContext $context)
48
    {
49
        $next = function () {
50
            // NO-OP
51
        };
52
53
        foreach ($this->middleware as $middleware) {
54
            $next = function (ExecutionException $exception, ExecutionContext $context) use ($middleware, $next) {
55
                return $middleware->handleExecutionError($exception, $context, $next);
56
            };
57
        }
58
59
        \call_user_func($next, $exception, $context);
60
    }
61
62
    /**
63
     * @param ErrorMiddlewareInterface $middleware
64
     */
65
    protected function addMiddleware(ErrorMiddlewareInterface $middleware)
66
    {
67
        \array_unshift($this->middleware, $middleware);
68
    }
69
}
70