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

TestState::bootFromContainer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
c 2
b 0
f 1
nc 2
nop 1
dl 0
loc 9
rs 10
ccs 4
cts 4
cp 1
crap 2
1
<?php
2
3
namespace Zenstruck\Foundry\Test;
4
5
use Faker;
6
use Psr\Container\ContainerInterface;
7
use Zenstruck\Foundry\Configuration;
8
use Zenstruck\Foundry\Factory;
9
use Zenstruck\Foundry\StoryManager;
10
11
/**
12
 * @author Kevin Bond <[email protected]>
13
 */
14
final class TestState
15
{
16
    /** @var callable|null */
17
    private static $instantiator;
18
19
    /** @var Faker\Generator|null */
20
    private static $faker;
21
22
    /** @var bool */
23
    private static $useBundle = true;
24
25
    /** @var callable[] */
26
    private static $globalStates = [];
27
28
    public static function setInstantiator(callable $instantiator): void
29
    {
30
        self::$instantiator = $instantiator;
31
    }
32
33
    public static function setFaker(Faker\Generator $faker): void
34
    {
35
        self::$faker = $faker;
36
    }
37
38
    public static function withoutBundle(): void
39
    {
40
        self::$useBundle = false;
41
    }
42
43
    public static function addGlobalState(callable $callback): void
44
    {
45
        self::$globalStates[] = $callback;
46
    }
47
48 162
    public static function bootFactory(Configuration $configuration): Configuration
49
    {
50 162
        if (self::$instantiator) {
51
            $configuration->setInstantiator(self::$instantiator);
52
        }
53
54 162
        if (self::$faker) {
55
            $configuration->setFaker(self::$faker);
56
        }
57
58 162
        Factory::boot($configuration);
59
60 162
        return $configuration;
61
    }
62
63
    /**
64
     * @internal
65
     */
66 162
    public static function bootFromContainer(ContainerInterface $container): Configuration
67
    {
68 162
        if (self::$useBundle) {
69
            // todo improve/catch service not found exception - foundry-bundle not installed/configured...
70 82
            return self::bootFactory($container->get(Configuration::class));
71
        }
72
73
        // todo improve/catch service not found exception - doctrine-bundle not installed/configured...
74 80
        return self::bootFactory(new Configuration($container->get('doctrine'), new StoryManager([])));
75
    }
76
77
    /**
78
     * @internal
79
     */
80 162
    public static function flushGlobalState(): void
81
    {
82 162
        StoryManager::globalReset();
83
84 162
        foreach (self::$globalStates as $callback) {
85 162
            $callback();
86
        }
87
88 162
        StoryManager::setGlobalState();
89 162
    }
90
}
91