-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceLocator.php
More file actions
82 lines (70 loc) · 1.78 KB
/
ServiceLocator.php
File metadata and controls
82 lines (70 loc) · 1.78 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
78
79
80
81
82
<?php
namespace FDevs\Container;
use FDevs\Container\Exception\ServiceCircularReferenceException;
use FDevs\Container\Exception\ServiceNotFoundException;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
class ServiceLocator implements ContainerInterface
{
/**
* @var array|callable[]
*/
private $factories;
/**
* @var array|string[]
*/
private $loading = [];
/**
* @param callable[] $factories
*/
public function __construct(array $factories = [])
{
$this->factories = $factories;
}
/**
* {@inheritdoc}
*/
public function has($id)
{
return isset($this->factories[$id]);
}
/**
* {@inheritdoc}
*/
public function get($id)
{
if (!$this->has($id)) {
throw $this->createNotFoundException($id);
}
if (isset($this->loading[$id])) {
$ids = array_values($this->loading);
$ids = array_slice($this->loading, array_search($id, $ids));
$ids[] = $id;
throw new ServiceCircularReferenceException($id, $ids);
}
$this->loading[$id] = $id;
try {
return $this->factories[$id]();
} finally {
unset($this->loading[$id]);
}
}
/**
* @param string $id
*
* @return mixed|null
*/
public function __invoke($id)
{
return isset($this->factories[$id]) ? $this->get($id) : null;
}
/**
* @param string $id
*
* @return NotFoundExceptionInterface
*/
protected function createNotFoundException(string $id): NotFoundExceptionInterface
{
return new ServiceNotFoundException($id, end($this->loading) ?: null, array_keys($this->factories));
}
}