1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\Foundry; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* @internal |
7
|
|
|
* |
8
|
|
|
* @author Kevin Bond <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
final class StoryManager |
11
|
|
|
{ |
12
|
|
|
/** @var array<string, Story> */ |
13
|
|
|
private static array $globalInstances = []; |
14
|
|
|
|
15
|
|
|
/** @var array<string, Story> */ |
16
|
|
|
private static array $instances = []; |
17
|
|
|
|
18
|
|
|
/** @var Story[] */ |
19
|
|
|
private iterable $stories; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Story[] $stories |
23
|
|
|
*/ |
24
|
278 |
|
public function __construct(iterable $stories) |
25
|
|
|
{ |
26
|
278 |
|
$this->stories = $stories; |
|
|
|
|
27
|
278 |
|
} |
28
|
|
|
|
29
|
162 |
|
public function load(string $class): Story |
30
|
|
|
{ |
31
|
162 |
|
if (\array_key_exists($class, self::$globalInstances)) { |
32
|
4 |
|
return self::$globalInstances[$class]; |
33
|
|
|
} |
34
|
|
|
|
35
|
162 |
|
if (\array_key_exists($class, self::$instances)) { |
36
|
4 |
|
return self::$instances[$class]; |
37
|
|
|
} |
38
|
|
|
|
39
|
162 |
|
$story = $this->getOrCreateStory($class); |
40
|
162 |
|
$story->build(); |
41
|
|
|
|
42
|
162 |
|
return self::$instances[$class] = $story; |
43
|
|
|
} |
44
|
|
|
|
45
|
162 |
|
public static function setGlobalState(): void |
46
|
|
|
{ |
47
|
162 |
|
self::$globalInstances = self::$instances; |
48
|
162 |
|
self::$instances = []; |
49
|
162 |
|
} |
50
|
|
|
|
51
|
162 |
|
public static function reset(): void |
52
|
|
|
{ |
53
|
162 |
|
self::$instances = []; |
54
|
162 |
|
} |
55
|
|
|
|
56
|
162 |
|
public static function globalReset(): void |
57
|
|
|
{ |
58
|
162 |
|
self::$globalInstances = self::$instances = []; |
59
|
162 |
|
} |
60
|
|
|
|
61
|
162 |
|
private function getOrCreateStory(string $class): Story |
62
|
|
|
{ |
63
|
162 |
|
foreach ($this->stories as $story) { |
64
|
82 |
|
if ($class === \get_class($story)) { |
65
|
2 |
|
return $story; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
// todo better error if story has constructor argument(s) but not registered as a service |
70
|
162 |
|
return new $class(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..