-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFixtureLoaderTrait.php
79 lines (65 loc) · 1.97 KB
/
FixtureLoaderTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace Golossus\TestFixtureLoading;
/**
* Trait FixtureLoaderTrait.
*/
trait FixtureLoaderTrait
{
/**
* Builds the data fixture and injects any possible dependency it may have. This is done commonly by
* a service container instance.
*/
abstract protected function buildFixture(string $namespace): Fixture;
/**
* Loads a bunch of data fixtures from a given array of namespaces.
*
* @param string[] $fixtures
*
* @throws CycleDependencyException
*/
protected function loadFixtures(array $fixtures): FixtureRepository
{
$fixtureRepository = new FixtureRepository();
$resolvedFixtures = array();
$pending = array();
foreach ($fixtures as $fixtureClass) {
$this->resolveFixture($fixtureClass, $resolvedFixtures, $pending);
}
foreach ($resolvedFixtures as $fixture) {
$fixture->load($fixtureRepository);
}
return $fixtureRepository;
}
/**
* Resolved data fixtures taking into account their dependencies.
*
* @return void
*
* @throws CycleDependencyException
*/
final private function resolveFixture(
string $fixtureClass,
array &$loaded,
array &$pending
) {
if (isset($loaded[$fixtureClass])) {
return;
}
$fixture = $this->buildFixture($fixtureClass);
$dependencies = $fixture->depends();
if (empty($dependencies)) {
$loaded[$fixtureClass] = $fixture;
return;
}
$pending[$fixtureClass] = true;
foreach ($dependencies as $dependency) {
if (isset($pending[$dependency])) {
throw CycleDependencyException::create($dependency, $fixtureClass);
}
$this->resolveFixture($dependency, $loaded, $pending);
}
$loaded[$fixtureClass] = $fixture;
unset($pending[$fixtureClass]);
}
}