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