Passed
Push — master ( 02609a...02cd0c )
by Kevin
04:31
created

Story   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 11
eloc 19
c 4
b 0
f 2
dl 0
loc 66
ccs 19
cts 19
cp 1
rs 10

6 Methods

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