ResolverTrait::assertInstanceOf()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 3
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
rs 9.8666
c 0
b 0
f 0
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 14
    protected function resolveByContainer($ref, ContainerInterface $container, $expectedClass)
20
    {
21
        try {
22 14
            $entry = $container->get($ref);
23 4
        } catch (NotFoundExceptionInterface $e) {
24 2
            throw new UnresolvedException(
25 2
                "Could not found an entry identified by '{$ref}' from the container.",
26 2
                ErrorCode::NOT_FOUND,
27 2
                $e
28
            );
29 2
        } catch (ContainerExceptionInterface $e) {
30 2
            throw new UnresolvedException(
31 2
                "Something went wrong with the container when trying to get an entry identified by '{$ref}'.",
32 2
                ErrorCode::CONTAINER_ERROR,
33 2
                $e
34
            );
35
        }
36
37 10
        $this->assertInstanceOf($expectedClass, $entry, $ref);
38
39 8
        return $entry;
40
    }
41
42
    /**
43
     * @param string $expectedClass
44
     * @param mixed $entry
45
     * @param string $ref
46
     * @return void
47
     * @throws UnresolvedException
48
     */
49 10
    private function assertInstanceOf($expectedClass, $entry, $ref)
50
    {
51 10
        if ($entry instanceof $expectedClass) {
52 8
            return;
53
        }
54
55 2
        $type = is_object($entry) ? get_class($entry) : gettype($entry);
56 2
        throw new UnresolvedException(
57 2
            "Expected container returns an instance of {$expectedClass}, {$type} given. id='{$ref}'.",
58 2
            ErrorCode::TYPE_ERROR
59
        );
60
    }
61
}
62