-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathZenstruckFoundryBundle.php
365 lines (321 loc) · 15.8 KB
/
ZenstruckFoundryBundle.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <kevinbond@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zenstruck\Foundry;
use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
use Zenstruck\Foundry\Mongo\MongoResetter;
use Zenstruck\Foundry\Object\Instantiator;
use Zenstruck\Foundry\ORM\ResetDatabase\OrmResetter;
use Zenstruck\Foundry\ORM\ResetDatabase\ResetDatabaseMode;
/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class ZenstruckFoundryBundle extends AbstractBundle implements CompilerPassInterface
{
public function boot(): void
{
if ($this->container && !Configuration::isBooted()) {
Configuration::boot($this->container->get('.zenstruck_foundry.configuration')); // @phpstan-ignore argument.type
}
}
public function configure(DefinitionConfigurator $definition): void
{
$definition->rootNode() // @phpstan-ignore method.notFound
->children()
->booleanNode('auto_refresh_proxies')
->info('Whether to auto-refresh proxies by default (https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#auto-refresh)')
->defaultNull()
->setDeprecated('zenstruck/foundry', '2.0', 'Since 2.0 auto_refresh_proxies defaults to true and this configuration has no effect.')
->end()
->arrayNode('faker')
->addDefaultsIfNotSet()
->info('Configure the faker used by your factories.')
->children()
->scalarNode('locale')
->info('The default locale to use for faker.')
->example('fr_FR')
->defaultNull()
->end()
->scalarNode('seed')
->info('Random number generator seed to produce the same fake values every run.')
->example(1234)
->defaultNull()
->end()
->scalarNode('service')
->info('Service id for custom faker instance.')
->example('my_faker')
->defaultNull()
->end()
->end()
->end()
->arrayNode('instantiator')
->addDefaultsIfNotSet()
->info('Configure the default instantiator used by your object factories.')
->children()
->booleanNode('use_constructor')
->info('Use the constructor to instantiate objects.')
->defaultTrue()
->end()
->booleanNode('allow_extra_attributes')
->info('Whether or not to skip attributes that do not correspond to properties.')
->defaultFalse()
->end()
->booleanNode('always_force_properties')
->info('Whether or not to skip setters and force set object properties (public/private/protected) directly.')
->defaultFalse()
->end()
->scalarNode('service')
->info('Service id of your custom instantiator.')
->example('my_instantiator')
->defaultNull()
->end()
->end()
->end()
->arrayNode('global_state')
->info('Stories or invokable services to be loaded before each test.')
->scalarPrototype()->end()
->end()
->arrayNode('orm')
->addDefaultsIfNotSet()
->children()
->booleanNode('auto_persist')
->info('Automatically persist entities when created.')
->defaultTrue()
->end()
->arrayNode('reset')
->addDefaultsIfNotSet()
->children()
->arrayNode('connections')
->info('DBAL connections to reset with ResetDatabase trait')
->defaultValue(['default'])
->scalarPrototype()->end()
->end()
->arrayNode('entity_managers')
->info('Entity Managers to reset with ResetDatabase trait')
->defaultValue(['default'])
->scalarPrototype()->end()
->end()
->enumNode('mode')
->info('Reset mode to use with ResetDatabase trait')
->defaultValue(ResetDatabaseMode::SCHEMA)
->beforeNormalization()
->ifString()
->then(static fn(string $mode): ?ResetDatabaseMode => ResetDatabaseMode::tryFrom($mode))
->end()
->values(ResetDatabaseMode::cases())
->end()
->arrayNode('migrations')
->addDefaultsIfNotSet()
->children()
->arrayNode('configurations')
->info('Migration configurations')
->defaultValue([])
->scalarPrototype()->end()
->validate()
->ifTrue(function(array $configurationFiles): bool {
foreach ($configurationFiles as $configurationFile) {
if (!\is_file($configurationFile)) {
return true;
}
}
return false;
})
->thenInvalid('At least one migrations configuration file does not exist.')
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('mongo')
->addDefaultsIfNotSet()
->children()
->booleanNode('auto_persist')
->info('Automatically persist documents when created.')
->defaultTrue()
->end()
->arrayNode('reset')
->addDefaultsIfNotSet()
->children()
->arrayNode('document_managers')
->info('Document Managers to reset with ResetDatabase trait')
->defaultValue(['default'])
->scalarPrototype()
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('make_factory')
->addDefaultsIfNotSet()
->children()
->scalarNode('default_namespace')
->info('Default namespace where factories will be created by maker.')
->defaultValue('Factory')
->cannotBeEmpty()
->end()
->end()
->end()
->arrayNode('make_story')
->addDefaultsIfNotSet()
->children()
->scalarNode('default_namespace')
->info('Default namespace where stories will be created by maker.')
->defaultValue('Story')
->cannotBeEmpty()
->end()
->end()
->end()
->end()
;
}
public function loadExtension(array $config, ContainerConfigurator $configurator, ContainerBuilder $container): void // @phpstan-ignore missingType.iterableValue
{
$container->registerForAutoconfiguration(Factory::class)
->addTag('foundry.factory')
;
$container->registerForAutoconfiguration(Story::class)
->addTag('foundry.story')
;
$configurator->import('../config/services.php');
$this->configureInstantiator($config['instantiator'], $container);
$this->configureFaker($config['faker'], $container);
$this->configureGlobalState($config['global_state'], $container);
/** @var array<string, string> $bundles */
$bundles = $container->getParameter('kernel.bundles');
if (isset($bundles['MakerBundle'])) {
$configurator->import('../config/makers.php');
$makeFactoryDefinition = $container->getDefinition('.zenstruck_foundry.maker.factory');
$makeFactoryDefinition->setArgument('$defaultNamespace', $config['make_factory']['default_namespace']);
$makeStoryDefinition = $container->getDefinition('.zenstruck_foundry.maker.story');
$makeStoryDefinition->setArgument('$defaultNamespace', $config['make_story']['default_namespace']);
if (!isset($bundles['DoctrineBundle'])) {
$container->removeDefinition('.zenstruck_foundry.maker.factory.orm_default_properties_guesser');
}
if (!isset($bundles['DoctrineMongoDBBundle'])) {
$container->removeDefinition('.zenstruck_foundry.maker.factory.odm_default_properties_guesser');
}
if (!isset($bundles['DoctrineBundle']) && !isset($bundles['DoctrineMongoDBBundle'])) {
$container->removeDefinition('.zenstruck_foundry.maker.factory.doctrine_scalar_fields_default_properties_guesser');
}
} else {
$configurator->import('../config/command_stubs.php');
}
if (isset($bundles['DoctrineBundle']) || isset($bundles['DoctrineMongoDBBundle'])) {
$configurator->import('../config/persistence.php');
}
if (isset($bundles['DoctrineBundle'])) {
$configurator->import('../config/orm.php');
$container->getDefinition('.zenstruck_foundry.persistence_strategy.orm')
->replaceArgument(1, $config['orm'])
;
$container->getDefinition('.zenstruck_foundry.persistence.database_resetter.orm.abstract')
->replaceArgument('$managers', $config['orm']['reset']['entity_managers'])
->replaceArgument('$connections', $config['orm']['reset']['connections'])
;
$container->getDefinition('.zenstruck_foundry.persistence.database_resetter.orm.migrate')
->replaceArgument('$configurations', $config['orm']['reset']['migrations']['configurations'])
;
/** @var ResetDatabaseMode $resetMode */
$resetMode = $config['orm']['reset']['mode'];
$toRemove = ResetDatabaseMode::SCHEMA === $resetMode ? ResetDatabaseMode::MIGRATE->value : ResetDatabaseMode::SCHEMA->value;
$container->removeDefinition(".zenstruck_foundry.persistence.database_resetter.orm.{$toRemove}.dama");
$container->removeDefinition(".zenstruck_foundry.persistence.database_resetter.orm.{$toRemove}");
$container->setAlias(OrmResetter::class, ".zenstruck_foundry.persistence.database_resetter.orm.{$resetMode->value}");
}
if (isset($bundles['DoctrineMongoDBBundle'])) {
$configurator->import('../config/mongo.php');
$container->getDefinition('.zenstruck_foundry.persistence_strategy.mongo')
->replaceArgument(1, $config['mongo'])
;
$container->getDefinition('.zenstruck_foundry.persistence.schema_resetter.mongo')
->replaceArgument(0, $config['mongo']['reset']['document_managers'])
;
$container->setAlias(MongoResetter::class, '.zenstruck_foundry.persistence.schema_resetter.mongo');
}
}
public function build(ContainerBuilder $container): void
{
parent::build($container);
$container->addCompilerPass($this);
}
public function process(ContainerBuilder $container): void
{
// faker providers
foreach ($container->findTaggedServiceIds('foundry.faker_provider') as $id => $tags) {
$container
->getDefinition('.zenstruck_foundry.faker')
->addMethodCall('addProvider', [new Reference($id)])
;
}
}
/**
* @param string[] $values
*/
private function configureGlobalState(array $values, ContainerBuilder $container): void
{
$values = \array_map(
static fn(string $v) => \is_a($v, Story::class, true) ? $v : new Reference($v),
$values
);
$container->getDefinition('.zenstruck_foundry.story_registry')
->replaceArgument(1, $values)
;
}
/**
* @param mixed[] $config
*/
private function configureInstantiator(array $config, ContainerBuilder $container): void
{
if ($config['service']) {
$container->setAlias('.zenstruck_foundry.instantiator', $config['service']);
return;
}
if (!$config['use_constructor']) {
$container->getDefinition('.zenstruck_foundry.instantiator')
->setFactory([Instantiator::class, 'withoutConstructor'])
;
}
if ($config['allow_extra_attributes']) {
$container->getDefinition('.zenstruck_foundry.instantiator')
->addMethodCall('allowExtra', returnsClone: true)
;
}
if ($config['always_force_properties']) {
$container->getDefinition('.zenstruck_foundry.instantiator')
->addMethodCall('alwaysForce', returnsClone: true)
;
}
}
/**
* @param mixed[] $config
*/
private function configureFaker(array $config, ContainerBuilder $container): void
{
if ($config['service']) {
$container->setAlias('.zenstruck_foundry.faker', $config['service']);
return;
}
$definition = $container->getDefinition('.zenstruck_foundry.faker');
if ($config['locale']) {
$definition->addArgument($config['locale']);
}
if ($config['seed']) {
$definition->addMethodCall('seed', [$config['seed']]);
}
}
}