Passed
Pull Request — master (#1)
by Kevin
12:50
created

StoryManager   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 61
rs 10
ccs 26
cts 26
cp 1
wmc 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getOrCreateStory() 0 10 3
A reset() 0 3 1
A setGlobalState() 0 4 1
A globalReset() 0 3 1
A load() 0 14 3
A __construct() 0 3 1
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 $globalInstances = [];
14
15
    /** @var array<string, Story> */
16
    private static $instances = [];
17
18
    /** @var Story[] */
19
    private $stories;
20
21
    /**
22
     * @param Story[] $stories
23
     */
24 278
    public function __construct(iterable $stories)
25
    {
26 278
        $this->stories = $stories;
0 ignored issues
show
Documentation Bug introduced by
It seems like $stories of type iterable is incompatible with the declared type Zenstruck\Foundry\Story[] of property $stories.

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..

Loading history...
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