1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Knp\FriendlyContexts\Alice; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\DependencyInjection\ContainerInterface; |
6
|
|
|
|
7
|
|
|
class ProviderResolver |
8
|
|
|
{ |
9
|
|
|
private $container; |
10
|
|
|
private $providers; |
11
|
|
|
|
12
|
|
|
public function __construct(ContainerInterface $container, array $providers) |
13
|
|
|
{ |
14
|
|
|
$this->container = $container; |
15
|
|
|
$this->providers = $providers; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function all() |
19
|
|
|
{ |
20
|
|
|
$services = []; |
21
|
|
|
|
22
|
|
|
foreach ($this->providers as $provider) { |
23
|
|
|
if (null !== $service = $this->getFromClass($provider)) { |
24
|
|
|
$services[] = $service; |
25
|
|
|
continue; |
26
|
|
|
} |
27
|
|
|
if (null !== $service = $this->getFromContainer($provider)) { |
28
|
|
|
$services[] = $service; |
29
|
|
|
continue; |
30
|
|
|
} |
31
|
|
|
if (null !== $service = $this->getFromKernel($provider)) { |
32
|
|
|
$services[] = $service; |
33
|
|
|
continue; |
34
|
|
|
} |
35
|
|
|
throw new \Exception(sprintf('Cannot find any class or service called "%s"', $provider)); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return $services; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function getFromClass($name) |
42
|
|
|
{ |
43
|
|
|
if (class_exists($name)) { |
44
|
|
|
|
45
|
|
|
return new $name; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function getFromContainer($name) |
50
|
|
|
{ |
51
|
|
|
if (0 !== strpos($name, '@')) { |
52
|
|
|
|
53
|
|
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$service = substr($name, 1); |
57
|
|
|
|
58
|
|
|
if (false === $this->container->has($service)) { |
59
|
|
|
|
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $this->container->get($service); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private function getFromKernel($name) |
|
|
|
|
67
|
|
|
{ |
68
|
|
|
if (0 !== strpos($name, '@')) { |
69
|
|
|
|
70
|
|
|
return; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$service = substr($name, 1); |
74
|
|
|
|
75
|
|
|
if (false === $this->container->has('friendly.symfony.kernel')) { |
76
|
|
|
|
77
|
|
|
return; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
$kernel = $this->container->get('friendly.symfony.kernel'); |
81
|
|
|
$kernel->boot(); |
82
|
|
|
|
83
|
|
|
if (false === $kernel->getContainer()->has($service)) { |
84
|
|
|
|
85
|
|
|
return; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
return $kernel->getContainer()->get($service); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.