Completed
Pull Request — master (#146)
by
unknown
04:36
created

ErrorHandler::handle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Youshido\GraphQL\Execution\ErrorHandler;
4
5
use Youshido\GraphQL\Exception\InvalidErrorHandlerMiddlewareException;
6
use Youshido\GraphQL\Execution\Context\ExecutionContext;
7
8
class ErrorHandler
9
{
10
    /**
11
     * @var callable
12
     */
13
    private $middlewareChain;
14
    /**
15
     * @param ErrorHandlerMiddlewareInterface[] $middleware
16
     */
17 61
    public function __construct(array $middleware)
18
    {
19 61
        $this->middlewareChain = $this->createExecutionChain($middleware);
20 61
    }
21
22 19
    public function handle($error, ExecutionContext $executionContext)
23
    {
24 19
        $middlewareChain = $this->middlewareChain;
25 19
        return $middlewareChain($error, $executionContext);
26
    }
27
28 61
    private function createExecutionChain($middlewareList)
29
    {
30
        $lastCallable = function () {}; // Last callable is a NO-OP
31 61
        while ($middleware = array_pop($middlewareList)) {
32 61
            if (! $middleware instanceof ErrorHandlerMiddlewareInterface) {
33
                throw InvalidErrorHandlerMiddlewareException::forMiddleware($middleware);
34
            }
35 61
            $lastCallable = function ($error, ExecutionContext $executionContext) use ($middleware, $lastCallable) {
36 19
                return $middleware->execute($error, $executionContext, $lastCallable);
37 61
            };
38
        }
39 61
        return $lastCallable;
40
    }
41
}
42