ResolverHost::resolve()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 2
crap 3
1
<?php
2
3
namespace mindplay\unravel;
4
5
use ReflectionParameter;
6
7
/**
8
 * This class implements a "middleware stack" for Resolvers.
9
 *
10
 * It also implements the Resolver interface itself, allowing for modular composition of Resolvers.
11
 */
12
class ResolverHost implements Resolver
13
{
14
    /**
15
     * @var Resolver[]
16
     */
17
    protected $resolvers;
18
19
    /**
20
     * @param Resolver[] $resolvers
21
     */
22 1
    public function __construct($resolvers)
23
    {
24 1
        $this->resolvers = $resolvers;
25 1
    }
26
27
    /**
28
     * Resolve a given Parameter by passing it through the resolver stack.
29
     *
30
     * @param ReflectionParameter $param
31
     * @param callable|null       $next resolver delegate (used internally when composing hosts)
32
     *
33
     * @return mixed
34
     *
35
     * @throws UnresolvedException if the given Parameter could not be resolved
36
     */
37 1
    public function resolve(ReflectionParameter $param, $next = null)
38
    {
39 1
        $result = call_user_func($this->delegate(0), $param);
40
41 1
        if ($result instanceof Unresolved) {
42 1
            if ($next) {
43 1
                return $next($param);
44
            }
45
46 1
            throw new UnresolvedException($param);
47
        }
48
49 1
        return $result;
50
    }
51
52
    /**
53
     * @param int $index
54
     *
55
     * @return callable function (ReflectionParameter $param): mixed
56
     */
57 1
    protected function delegate($index)
58
    {
59 1
        if (isset($this->resolvers[$index])) {
60
            return function (ReflectionParameter $param) use ($index) {
61 1
                return $this->resolvers[$index]->resolve($param, $this->delegate($index + 1));
62 1
            };
63
        }
64
65 1
        return function () {
66 1
            return new Unresolved();
67 1
        };
68
    }
69
}
70