Completed
Push — master ( 84dd72...3d3d30 )
by n
02:27
created

ResolverTrait::assertInstanceOf()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 2
crap 3
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
trait ResolverTrait
10
{
11
12
    /**
13
     * @param string $ref
14
     * @param ContainerInterface $container
15
     * @param string $expectedClass
16
     * @return mixed
17
     * @throws UnresolvedException
18
     */
19 11
    protected function resolveByContainer($ref, ContainerInterface $container, $expectedClass)
20
    {
21
        try {
22 11
            $entry = $container->get($ref);
23 11
        } catch (NotFoundExceptionInterface $e) {
24 2
            throw new UnresolvedException('Could not found an entry from the container.', 0, $e);
25 2
        } catch (ContainerExceptionInterface $e) {
26 2
            throw new UnresolvedException('Something wrong with the container.', 0, $e);
27
        }
28
29 7
        $this->assertInstanceOf($expectedClass, $entry);
30
31 5
        return $entry;
32
    }
33
34
    /**
35
     * @param string $expectedClass
36
     * @param mixed $entry
37
     * @return void
38
     * @throws UnresolvedException
39
     */
40 7
    private function assertInstanceOf($expectedClass, $entry)
41
    {
42 7
        if ($entry instanceof $expectedClass) {
43 5
            return;
44
        }
45 2
        $type = is_object($entry) ? get_class($entry) : gettype($entry);
46 2
        throw new UnresolvedException("Expected container returns an instance of {$expectedClass}, {$type} given.");
47
    }
48
}
49