-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinimalContainer.php
More file actions
77 lines (61 loc) · 1.74 KB
/
MinimalContainer.php
File metadata and controls
77 lines (61 loc) · 1.74 KB
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 Chubbyphp\Container;
use Chubbyphp\Container\Exceptions\ContainerException;
use Chubbyphp\Container\Exceptions\NotFoundException;
final class MinimalContainer implements ContainerInterface
{
/**
* @var array<string, callable>
*/
private array $factories = [];
/**
* @var array<string, mixed>
*/
private array $services = [];
/**
* @param array<string, callable> $factories
*/
public function __construct(array $factories = [])
{
$this->factories($factories);
}
/**
* @param array<string, callable> $factories
*/
public function factories(array $factories): ContainerInterface
{
foreach ($factories as $id => $factory) {
$this->factory($id, $factory);
}
return $this;
}
public function factory(string $id, callable $factory): ContainerInterface
{
if (isset($this->factories[$id])) {
$factory = new Factory($this->factories[$id], $factory);
}
unset($this->services[$id]);
$this->factories[$id] = $factory;
return $this;
}
public function get(string $id): mixed
{
return $this->services[$id] ?? $this->services[$id] = $this->createFromFactory($id);
}
public function has(string $id): bool
{
return isset($this->factories[$id]);
}
private function createFromFactory(string $id): mixed
{
if (!isset($this->factories[$id])) {
throw NotFoundException::create($id);
}
try {
return ($this->factories[$id])($this);
} catch (\Throwable $throwable) {
throw ContainerException::create($id, $throwable);
}
}
}