Completed
Push — master ( 24c89a...7da8a2 )
by n
02:26
created

ResolverAbstract::resolveWithType()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 16
cts 16
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 17
nc 7
nop 3
crap 7
1
<?php
2
3
namespace N1215\Jugoya\Resolver;
4
5
use Psr\Container\ContainerInterface;
6
use Psr\Container\NotFoundExceptionInterface;
7
use Psr\Container\ContainerExceptionInterface;
8
9
class ResolverAbstract
10
{
11
12
    /**
13
     * @var ContainerInterface
14
     */
15
    protected $container;
16
17
    /**
18
     * @param ContainerInterface $container
19
     */
20 18
    public function __construct(ContainerInterface $container)
21
    {
22 18
        $this->container = $container;
23 18
    }
24
25
    /**
26
     * @param string|callable|mixed $ref
27
     * @param string $returnType
28
     * @param string $callableWrapperClass
29
     * @return mixed
30
     * @throws UnresolvedException
31
     */
32 17
    protected function resolveWithType($ref, $returnType, $callableWrapperClass)
33
    {
34 17
        if ($ref instanceof $returnType) {
35 5
            return $ref;
36
        }
37
38 15
        if (is_callable($ref)) {
39 5
            return new $callableWrapperClass($ref);
40
        }
41
42 13
        if (!is_string($ref)) {
43 2
            throw new \InvalidArgumentException("Argument 1 \$ref must be one of an instance of {$returnType}, a callable or string.");
44
        }
45
46
        try {
47 11
            $entry = $this->container->get($ref);
48 11
        } catch (NotFoundExceptionInterface $e) {
49 2
            throw new UnresolvedException('Could not found an entry from the container.', 0, $e);
50 2
        } catch (ContainerExceptionInterface $e) {
51 2
            throw new UnresolvedException('Something wrong with the container.', 0, $e);
52
        }
53
54 7
        if (! $entry instanceof $returnType) {
55 2
            $type = gettype($entry);
56 2
            throw new UnresolvedException("Expected container returns an instance of {$returnType}, {$type} given.");
57
        }
58
59 5
        return $entry;
60
    }
61
}