1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Test\Support\Container; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Psr\Container\ContainerInterface; |
9
|
|
|
use Yiisoft\Test\Support\Container\Exception\NotFoundException; |
10
|
|
|
|
11
|
|
|
use function array_key_exists; |
12
|
|
|
|
13
|
|
|
final class SimpleContainer implements ContainerInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @psalm-var Closure(string) |
17
|
|
|
*/ |
18
|
|
|
private Closure $factory; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @psalm-var Closure(string): bool |
22
|
|
|
*/ |
23
|
|
|
private Closure $hasCallback; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param Closure|null $factory Should be closure that works like ContainerInterface::get(string $id): mixed |
27
|
|
|
* @param Closure|null $hasCallback Should be closure that works like ContainerInterface::has(string $id): bool |
28
|
|
|
* |
29
|
|
|
* @psalm-param Closure(string) $factory |
30
|
|
|
* @psalm-param Closure(string):bool $hasCallback |
31
|
|
|
*/ |
32
|
9 |
|
public function __construct( |
33
|
|
|
private array $definitions = [], |
34
|
|
|
?Closure $factory = null, |
35
|
|
|
?Closure $hasCallback = null |
36
|
|
|
) { |
37
|
9 |
|
$this->factory = $factory ?? |
38
|
|
|
/** @return mixed */ |
39
|
9 |
|
static function (string $id) { |
40
|
2 |
|
throw new NotFoundException($id); |
41
|
5 |
|
}; |
42
|
|
|
|
43
|
9 |
|
$this->hasCallback = $hasCallback ?? |
44
|
9 |
|
function (string $id): bool { |
45
|
|
|
try { |
46
|
2 |
|
$this->get($id); |
47
|
1 |
|
return true; |
48
|
1 |
|
} catch (NotFoundException) { |
49
|
1 |
|
return false; |
50
|
|
|
} |
51
|
8 |
|
}; |
52
|
|
|
} |
53
|
|
|
|
54
|
6 |
|
public function get($id) |
55
|
|
|
{ |
56
|
6 |
|
if (!array_key_exists($id, $this->definitions)) { |
57
|
4 |
|
$this->definitions[$id] = ($this->factory)($id); |
58
|
|
|
} |
59
|
4 |
|
return $this->definitions[$id]; |
60
|
|
|
} |
61
|
|
|
|
62
|
5 |
|
public function has($id): bool |
63
|
|
|
{ |
64
|
5 |
|
if (array_key_exists($id, $this->definitions)) { |
65
|
2 |
|
return true; |
66
|
|
|
} |
67
|
3 |
|
return ($this->hasCallback)($id); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|