-
Notifications
You must be signed in to change notification settings - Fork 0
/
InjectionChain.php
82 lines (70 loc) · 2.12 KB
/
InjectionChain.php
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
/**
* Qubus\Injector
*
* @link https://github.com/QubusPHP/injector
* @copyright 2020 Joshua Parker <[email protected]>
* @copyright 2013-2014 Daniel Lowrey, Levi Morrison, Dan Ackroyd
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\Injector;
use RuntimeException;
use function array_flip;
use function array_pop;
use function count;
use function is_numeric;
class InjectionChain
{
/**
* Store the chain of instantiations.
*
* @var array $chain
*/
private array $chain;
/**
* Instantiate an InjectionChain object.
*
* @param array $inProgressMakes Optional. Array of instantiations.
*/
public function __construct(array $inProgressMakes = [])
{
// Swap class names and indexes around.
$this->chain = array_flip($inProgressMakes);
// Remove the Qubus\Injector\InjectionChain class.
array_pop($this->chain);
}
/**
* Get the chain of instantiations.
*
* @return array Array of instantiations.
*/
public function getChain(): array
{
return $this->chain;
}
/**
* Get the instantiation at a specific index.
*
* The first (root) instantiation is 0, with each subsequent level adding 1
* more to the index.
*
* Provide a negative index to step back from the end of the chain.
* Example: `getByIndex( -2 )` will return the second-to-last element.
*
* @param int $index Element index to retrieve. Negative value to fetch from the end of the chain.
* @return string|false Class name of the element at the specified index. False if index not found.
* @throws RuntimeException If the index is not a numeric value.
*/
public function getByIndex(int $index): false|string
{
if (! is_numeric($index)) {
throw new RuntimeException('Index needs to be a numeric value.');
}
$index = (int) $index;
if ($index < 0) {
$index += count($this->chain);
}
return $this->chain[$index] ?? false;
}
}