|
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
|
|
|
|