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

ErrorHandler::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 14
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
     * @inheritdoc
28
     */
29
    public function handle(ExecutionException $exception, ExecutionContext $context): void
30
    {
31
        $next = function () {
32
            // NO-OP
33
        };
34
35
        foreach (\array_reverse($this->middleware) as $mw) {
36
            $next = function (ExecutionException $exception, ExecutionContext $context) use ($mw, $next) {
37
                /** @var ErrorMiddlewareInterface $mw */
38
                return $mw->handle($exception, $context, $next);
39
            };
40
        }
41
42
        $next($exception, $context);
43
    }
44
45
    /**
46
     * @param ErrorMiddlewareInterface $middleware
47
     */
48
    protected function addMiddleware(ErrorMiddlewareInterface $middleware): void
49
    {
50
        $this->middleware[] = $middleware;
51
    }
52
}
53