|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spiral\Core\Config; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
|
8
|
|
|
|
|
9
|
|
|
class Proxy extends Binding |
|
10
|
|
|
{ |
|
11
|
|
|
private readonly bool $hasFactory; |
|
12
|
|
|
/** |
|
13
|
|
|
* @template T |
|
14
|
|
|
* @param class-string<T> $interface |
|
|
|
|
|
|
15
|
|
|
* @param null|\Closure(ContainerInterface, \Stringable|string|null): T $fallbackFactory Factory that will be used |
|
16
|
|
|
* to create an instance if the value is resolved from a proxy. |
|
17
|
|
|
*/ |
|
18
|
402 |
|
public function __construct( |
|
19
|
|
|
protected readonly string $interface, |
|
20
|
|
|
public readonly bool $singleton = false, |
|
21
|
|
|
public readonly ?\Closure $fallbackFactory = null, |
|
22
|
|
|
) { |
|
23
|
402 |
|
\interface_exists($interface) or throw new \InvalidArgumentException( |
|
24
|
402 |
|
"Interface `{$interface}` does not exist.", |
|
25
|
402 |
|
); |
|
26
|
401 |
|
$this->singleton and $this->fallbackFactory !== null and throw new \InvalidArgumentException( |
|
27
|
401 |
|
'Singleton proxies must not have a fallback factory.', |
|
28
|
401 |
|
); |
|
29
|
401 |
|
$this->hasFactory = $fallbackFactory !== null && (new \ReflectionFunction($fallbackFactory)) |
|
|
|
|
|
|
30
|
401 |
|
->getReturnType()->__toString() !== 'never'; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @return class-string |
|
|
|
|
|
|
35
|
|
|
* @deprecated Use {@see getReturnClass()} instead. |
|
36
|
|
|
*/ |
|
37
|
|
|
public function getInterface(): string |
|
38
|
|
|
{ |
|
39
|
|
|
return $this->interface; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @return class-string |
|
|
|
|
|
|
44
|
|
|
* @internal |
|
45
|
|
|
*/ |
|
46
|
397 |
|
public function getReturnClass(): string |
|
47
|
|
|
{ |
|
48
|
397 |
|
return $this->interface; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @return bool Returns {@see true} if the factory is presented, and it doesn't have the {@see never} type. |
|
53
|
|
|
*/ |
|
54
|
4 |
|
public function hasFactory(): bool |
|
55
|
|
|
{ |
|
56
|
4 |
|
return $this->hasFactory; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
1 |
|
public function __toString(): string |
|
60
|
|
|
{ |
|
61
|
1 |
|
return \sprintf('Proxy to `%s`', $this->interface); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|