| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Infrastructure\Container; |
| 4 |
|
| 5 |
use RuntimeException; |
| 6 |
|
| 7 |
defined('ABSPATH') || exit; |
| 8 |
|
| 9 |
class Container implements ContainerInterface |
| 10 |
{ |
| 11 |
/** @var array<string, array{factory: callable, shared: bool}> */ |
| 12 |
private array $bindings = []; |
| 13 |
|
| 14 |
/** @var array<string, mixed> */ |
| 15 |
private array $instances = []; |
| 16 |
|
| 17 |
/** @var array<string, string> */ |
| 18 |
private array $aliases = []; |
| 19 |
|
| 20 |
public function bind(string $id, callable $factory): void |
| 21 |
{ |
| 22 |
$this->bindings[$id] = [ |
| 23 |
'factory' => $factory, |
| 24 |
'shared' => false, |
| 25 |
]; |
| 26 |
} |
| 27 |
|
| 28 |
public function singleton(string $id, callable $factory): void |
| 29 |
{ |
| 30 |
$this->bindings[$id] = [ |
| 31 |
'factory' => $factory, |
| 32 |
'shared' => true, |
| 33 |
]; |
| 34 |
} |
| 35 |
|
| 36 |
public function alias(string $alias, string $id): void |
| 37 |
{ |
| 38 |
$this->aliases[$alias] = $id; |
| 39 |
} |
| 40 |
|
| 41 |
public function has(string $id): bool |
| 42 |
{ |
| 43 |
$resolvedId = $this->resolveAlias($id); |
| 44 |
|
| 45 |
return isset($this->instances[$resolvedId]) |
| 46 |
|| isset($this->bindings[$resolvedId]) |
| 47 |
|| class_exists($resolvedId); |
| 48 |
} |
| 49 |
|
| 50 |
public function get(string $id) |
| 51 |
{ |
| 52 |
$resolvedId = $this->resolveAlias($id); |
| 53 |
|
| 54 |
if (array_key_exists($resolvedId, $this->instances)) { |
| 55 |
return $this->instances[$resolvedId]; |
| 56 |
} |
| 57 |
|
| 58 |
if (isset($this->bindings[$resolvedId])) { |
| 59 |
$entry = $this->bindings[$resolvedId]; |
| 60 |
$instance = $entry['factory']($this); |
| 61 |
|
| 62 |
if ($entry['shared']) { |
| 63 |
$this->instances[$resolvedId] = $instance; |
| 64 |
} |
| 65 |
|
| 66 |
return $instance; |
| 67 |
} |
| 68 |
|
| 69 |
if (class_exists($resolvedId)) { |
| 70 |
$instance = new $resolvedId(); |
| 71 |
return $instance; |
| 72 |
} |
| 73 |
|
| 74 |
throw new RuntimeException(esc_html(sprintf('Service "%s" is not bound in container.', $id))); |
| 75 |
} |
| 76 |
|
| 77 |
public function provider(ServiceProviderInterface $provider): void |
| 78 |
{ |
| 79 |
$provider->register($this); |
| 80 |
} |
| 81 |
|
| 82 |
private function resolveAlias(string $id): string |
| 83 |
{ |
| 84 |
return $this->aliases[$id] ?? $id; |
| 85 |
} |
| 86 |
} |
| 87 |
|