forked from laminas/laminas-di
/
AutowireFactory.php
77 lines (67 loc) · 2.21 KB
/
AutowireFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
declare(strict_types=1);
namespace Laminas\Di\Container;
use Laminas\Di\Exception;
use Laminas\Di\InjectorInterface;
use Psr\Container\ContainerInterface;
/**
* Create instances with autowiring
*/
class AutowireFactory
{
/**
* Retrieves the injector from a container
*
* @param ContainerInterface $container The container context for this factory
* @throws Exception\RuntimeException When no dependency injector is available.
*/
private function getInjector(ContainerInterface $container): InjectorInterface
{
$injector = $container->get(InjectorInterface::class);
if (! $injector instanceof InjectorInterface) {
throw new Exception\RuntimeException(
'Could not get a dependency injector form the container implementation'
);
}
return $injector;
}
/**
* Check creatability of the requested name
*
* @param string $requestedName
* @return bool
*/
public function canCreate(ContainerInterface $container, $requestedName)
{
if (! $container->has(InjectorInterface::class)) {
return false;
}
/** @psalm-suppress RedundantCastGivenDocblockType Avoid behavior BC break */
return $this->getInjector($container)->canCreate((string) $requestedName);
}
/**
* Create an instance
*
* @template T of object
* @param string|class-string<T> $requestedName
* @param array<mixed>|null $options
* @return T
*/
public function create(ContainerInterface $container, string $requestedName, ?array $options = null)
{
return $this->getInjector($container)->create($requestedName, $options ?: []);
}
/**
* Make invokable and implement the laminas-service factory pattern
*
* @template T of object
* @param string|class-string<T> $requestedName
* @param array<mixed>|null $options
* @return T
*/
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
{
/** @psalm-suppress RedundantCastGivenDocblockType Avoid behavior BC break */
return $this->create($container, (string) $requestedName, $options);
}
}