1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace N1215\Jugoya\Resolver; |
4
|
|
|
|
5
|
|
|
use Interop\Http\ServerMiddleware\DelegateInterface; |
6
|
|
|
use N1215\Jugoya\Wrapper\CallableDelegate; |
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Psr\Container\NotFoundExceptionInterface; |
9
|
|
|
use Psr\Container\ContainerExceptionInterface; |
10
|
|
|
|
11
|
|
View Code Duplication |
class DelegateResolver implements DelegateResolverInterface |
|
|
|
|
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var ContainerInterface |
16
|
|
|
*/ |
17
|
|
|
protected $container; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param ContainerInterface $container |
21
|
|
|
*/ |
22
|
11 |
|
public function __construct(ContainerInterface $container) |
23
|
|
|
{ |
24
|
11 |
|
$this->container = $container; |
25
|
11 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param string|callable|DelegateInterface $ref |
29
|
|
|
* @return DelegateInterface |
30
|
|
|
* @throws UnresolvedException |
31
|
|
|
*/ |
32
|
10 |
|
public function resolve($ref) |
33
|
|
|
{ |
34
|
10 |
|
if ($ref instanceof DelegateInterface) { |
35
|
2 |
|
return $ref; |
36
|
|
|
} |
37
|
|
|
|
38
|
8 |
|
if (is_callable($ref)) { |
39
|
2 |
|
return new CallableDelegate($ref); |
40
|
|
|
} |
41
|
|
|
|
42
|
6 |
|
if (!is_string($ref)) { |
43
|
1 |
|
throw new \InvalidArgumentException("Argument 1 \$ref must be one of an instance of DelegateInterface, a callable or string."); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
try { |
47
|
5 |
|
$entry = $this->container->get($ref); |
48
|
5 |
|
} catch (NotFoundExceptionInterface $e) { |
49
|
1 |
|
throw new UnresolvedException('Could not found an entry from the container.', 0, $e); |
50
|
1 |
|
} catch (ContainerExceptionInterface $e) { |
51
|
1 |
|
throw new UnresolvedException('Something wrong with the container.', 0, $e); |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
if (!$entry instanceof DelegateInterface) { |
55
|
1 |
|
$type = is_object($entry) ? get_class($entry) : gettype($entry); |
56
|
1 |
|
throw new UnresolvedException("Expected container returns an instance of DelegateInterface, {$type} given."); |
57
|
|
|
} |
58
|
|
|
|
59
|
2 |
|
return $entry; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.