1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\Foundry; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* @author Kevin Bond <[email protected]> |
7
|
|
|
* |
8
|
|
|
* @method static Proxy get(string $name) |
9
|
|
|
*/ |
10
|
|
|
abstract class Story |
11
|
|
|
{ |
12
|
|
|
/** @var array<string, mixed> */ |
13
|
10 |
|
private $state = []; |
14
|
|
|
|
15
|
10 |
|
final public function __call(string $method, array $arguments) |
16
|
|
|
{ |
17
|
|
|
if ('get' !== $method) { |
18
|
24 |
|
return $this->getState($method); |
19
|
|
|
} |
20
|
24 |
|
|
21
|
|
|
trigger_deprecation('zenstruck/foundry', '1.17', 'Calling instance method "%1$s::get()" is deprecated and will be removed in 2.0, use the static "%1$s::get()" method instead.', static::class); |
22
|
|
|
|
23
|
|
|
return $this->getState($arguments[0]); |
24
|
|
|
} |
25
|
|
|
|
26
|
405 |
|
public static function __callStatic(string $method, array $arguments) |
27
|
|
|
{ |
28
|
405 |
|
if ('get' !== $method) { |
29
|
|
|
return static::load()->getState($method); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
return static::load()->getState($arguments[0]); |
33
|
|
|
} |
34
|
398 |
|
|
35
|
|
|
/** |
36
|
|
|
* @return static |
37
|
398 |
|
*/ |
38
|
10 |
|
final public static function load(): self |
39
|
|
|
{ |
40
|
|
|
return Factory::configuration()->stories()->load(static::class); |
41
|
|
|
} |
42
|
398 |
|
|
43
|
10 |
|
/** |
44
|
|
|
* @return static |
45
|
|
|
*/ |
46
|
|
|
final public function add(string $name, $state): self |
47
|
398 |
|
{ |
48
|
10 |
|
if (\is_object($state)) { |
49
|
|
|
// ensure factories are persisted |
50
|
|
|
if ($state instanceof Factory) { |
51
|
398 |
|
$state = $state->create(); |
52
|
|
|
} |
53
|
398 |
|
|
54
|
|
|
// ensure objects are proxied |
55
|
|
|
if (!$state instanceof Proxy) { |
56
|
44 |
|
$state = new Proxy($state); |
57
|
|
|
} |
58
|
44 |
|
|
59
|
10 |
|
// ensure proxies are persisted |
60
|
|
|
if (!$state->isPersisted()) { |
61
|
|
|
$state->save(); |
62
|
34 |
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$this->state[$name] = $state; |
66
|
|
|
|
67
|
|
|
return $this; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
abstract public function build(): void; |
71
|
|
|
|
72
|
|
|
private function getState(string $name): Proxy |
73
|
|
|
{ |
74
|
|
|
if (!\array_key_exists($name, $this->state)) { |
75
|
|
|
throw new \InvalidArgumentException(\sprintf('"%s" was not registered. Did you forget to call "%s::add()"?', $name, static::class)); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $this->state[$name]; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|