Completed
Push — master ( 6e739b...0f594c )
by Asmir
22s queued 12s
created

DependencyFactory::getMigrationRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 7
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\Migrations\Configuration\Configuration;
9
use Doctrine\Migrations\Configuration\Connection\ConnectionLoader;
10
use Doctrine\Migrations\Configuration\EntityManager\EntityManagerLoader;
11
use Doctrine\Migrations\Configuration\Migration\ConfigurationLoader;
12
use Doctrine\Migrations\Exception\FrozenDependencies;
13
use Doctrine\Migrations\Exception\MissingDependency;
14
use Doctrine\Migrations\Finder\GlobFinder;
15
use Doctrine\Migrations\Finder\MigrationFinder;
16
use Doctrine\Migrations\Finder\RecursiveRegexFinder;
17
use Doctrine\Migrations\Generator\ClassNameGenerator;
18
use Doctrine\Migrations\Generator\ConcatenationFileBuilder;
19
use Doctrine\Migrations\Generator\DiffGenerator;
20
use Doctrine\Migrations\Generator\FileBuilder;
21
use Doctrine\Migrations\Generator\Generator;
22
use Doctrine\Migrations\Generator\SqlGenerator;
23
use Doctrine\Migrations\Metadata\Storage\MetadataStorage;
24
use Doctrine\Migrations\Metadata\Storage\TableMetadataStorage;
25
use Doctrine\Migrations\Metadata\Storage\TableMetadataStorageConfiguration;
26
use Doctrine\Migrations\Provider\DBALSchemaDiffProvider;
27
use Doctrine\Migrations\Provider\LazySchemaDiffProvider;
28
use Doctrine\Migrations\Provider\OrmSchemaProvider;
29
use Doctrine\Migrations\Provider\SchemaDiffProvider;
30
use Doctrine\Migrations\Provider\SchemaProvider;
31
use Doctrine\Migrations\Tools\Console\ConsoleInputMigratorConfigurationFactory;
32
use Doctrine\Migrations\Tools\Console\Helper\MigrationStatusInfosHelper;
33
use Doctrine\Migrations\Tools\Console\MigratorConfigurationFactory;
34
use Doctrine\Migrations\Version\AliasResolver;
35
use Doctrine\Migrations\Version\AlphabeticalComparator;
36
use Doctrine\Migrations\Version\Comparator;
37
use Doctrine\Migrations\Version\CurrentMigrationStatusCalculator;
38
use Doctrine\Migrations\Version\DbalExecutor;
39
use Doctrine\Migrations\Version\DbalMigrationFactory;
40
use Doctrine\Migrations\Version\DefaultAliasResolver;
41
use Doctrine\Migrations\Version\Executor;
42
use Doctrine\Migrations\Version\MigrationFactory;
43
use Doctrine\Migrations\Version\MigrationPlanCalculator;
44
use Doctrine\Migrations\Version\MigrationStatusCalculator;
45
use Doctrine\Migrations\Version\SortedMigrationPlanCalculator;
46
use Doctrine\ORM\EntityManagerInterface;
47
use Psr\Log\LoggerInterface;
48
use Psr\Log\NullLogger;
49
use Symfony\Component\Stopwatch\Stopwatch;
50
use function array_key_exists;
51
use function preg_quote;
52
use function sprintf;
53
54
/**
55
 * The DependencyFactory is responsible for wiring up and managing internal class dependencies.
56
 */
57
class DependencyFactory
58
{
59
    /** @var Configuration */
60
    private $configuration;
61
62
    /** @var object[]|callable[] */
63
    private $dependencies = [];
64
65
    /** @var Connection */
66
    private $connection;
67
68
    /** @var EntityManagerInterface|null */
69
    private $em;
70
71
    /** @var bool */
72
    private $frozen = false;
73
74
    /** @var ConfigurationLoader */
75
    private $configurationLoader;
76
77
    /** @var ConnectionLoader */
78
    private $connectionLoader;
79
80
    /** @var EntityManagerLoader|null */
81
    private $emLoader;
82
83 57
    public static function fromConnection(
84
        ConfigurationLoader $configurationLoader,
85
        ConnectionLoader $connectionLoader,
86
        ?LoggerInterface $logger = null
87
    ) : self {
88 57
        $dependencyFactory                      = new self($logger);
89 57
        $dependencyFactory->configurationLoader = $configurationLoader;
90 57
        $dependencyFactory->connectionLoader    = $connectionLoader;
91
92 57
        return $dependencyFactory;
93
    }
94
95 1
    public static function fromEntityManager(
96
        ConfigurationLoader $configurationLoader,
97
        EntityManagerLoader $emLoader,
98
        ?LoggerInterface $logger = null
99
    ) : self {
100 1
        $dependencyFactory                      = new self($logger);
101 1
        $dependencyFactory->configurationLoader = $configurationLoader;
102 1
        $dependencyFactory->emLoader            = $emLoader;
103
104 1
        return $dependencyFactory;
105
    }
106
107 58
    private function __construct(?LoggerInterface $logger)
108
    {
109 58
        if ($logger === null) {
110 43
            return;
111
        }
112
113 15
        $this->setService(LoggerInterface::class, $logger);
114 15
    }
115
116 53
    public function isFrozen() : bool
117
    {
118 53
        return $this->frozen;
119
    }
120
121 55
    public function freeze() : void
122
    {
123 55
        $this->frozen = true;
124 55
        $this->getConfiguration()->freeze();
125 55
    }
126
127 39
    private function assertNotFrozen() : void
128
    {
129 39
        if ($this->frozen) {
130 1
            throw FrozenDependencies::new();
131
        }
132 38
    }
133
134 34
    public function hasEntityManager() : bool
135
    {
136 34
        return $this->emLoader !== null;
137
    }
138
139 2
    public function setConfigurationLoader(ConfigurationLoader $configurationLoader) : void
140
    {
141 2
        $this->assertNotFrozen();
142 2
        $this->configurationLoader = $configurationLoader;
143 2
    }
144
145 55
    public function getConfiguration() : Configuration
146
    {
147 55
        if ($this->configuration === null) {
148 55
            $this->configuration = $this->configurationLoader->getConfiguration();
149 55
            $this->freeze();
150
        }
151
152 55
        return $this->configuration;
153
    }
154
155 34
    public function getConnection() : Connection
156
    {
157 34
        if ($this->connection === null) {
158 34
            $this->connection = $this->hasEntityManager()
159 1
                ? $this->getEntityManager()->getConnection()
160 33
                : $this->connectionLoader->getConnection();
161 34
            $this->freeze();
162
        }
163
164 34
        return $this->connection;
165
    }
166
167 2
    public function getEntityManager() : EntityManagerInterface
168
    {
169 2
        if ($this->em === null) {
170 2
            if ($this->emLoader === null) {
171 1
                throw MissingDependency::noEntityManager();
172
            }
173
174 1
            $this->em = $this->emLoader->getEntityManager();
175 1
            $this->freeze();
176
        }
177
178 1
        return $this->em;
179
    }
180
181 31
    public function getVersionComparator() : Comparator
182
    {
183
        return $this->getDependency(Comparator::class, static function () : AlphabeticalComparator {
184 31
            return new AlphabeticalComparator();
185 31
        });
186
    }
187
188 37
    public function getLogger() : LoggerInterface
189
    {
190
        return $this->getDependency(LoggerInterface::class, static function () : LoggerInterface {
191 14
            return new NullLogger();
192 37
        });
193
    }
194
195 1
    public function getEventDispatcher() : EventDispatcher
196
    {
197
        return $this->getDependency(EventDispatcher::class, function () : EventDispatcher {
198 1
            return new EventDispatcher(
199 1
                $this->getConnection(),
200 1
                $this->getConnection()->getEventManager()
201
            );
202 1
        });
203
    }
204
205
    public function getClassNameGenerator() : ClassNameGenerator
206
    {
207
        return $this->getDependency(ClassNameGenerator::class, static function () : ClassNameGenerator {
208
            return new ClassNameGenerator();
209
        });
210
    }
211
212
    public function getSchemaDumper() : SchemaDumper
213
    {
214
        return $this->getDependency(SchemaDumper::class, function () : SchemaDumper {
215
            $excludedTables = [];
216
217
            $metadataConfig = $this->getConfiguration()->getMetadataStorageConfiguration();
218
            if ($metadataConfig instanceof TableMetadataStorageConfiguration) {
219
                $excludedTables[] = sprintf('/^%s$/', preg_quote($metadataConfig->getTableName(), '/'));
220
            }
221
222
            return new SchemaDumper(
223
                $this->getConnection()->getDatabasePlatform(),
224
                $this->getConnection()->getSchemaManager(),
225
                $this->getMigrationGenerator(),
226
                $this->getMigrationSqlGenerator(),
227
                $excludedTables
228
            );
229
        });
230
    }
231
232
    private function getSchemaProvider() : SchemaProvider
233
    {
234
        return $this->getDependency(SchemaProvider::class, function () : SchemaProvider {
235
            return new OrmSchemaProvider($this->getEntityManager());
236
        });
237
    }
238
239
    public function getDiffGenerator() : DiffGenerator
240
    {
241
        return $this->getDependency(DiffGenerator::class, function () : DiffGenerator {
242
            return new DiffGenerator(
243
                $this->getConnection()->getConfiguration(),
244
                $this->getConnection()->getSchemaManager(),
245
                $this->getSchemaProvider(),
246
                $this->getConnection()->getDatabasePlatform(),
247
                $this->getMigrationGenerator(),
248
                $this->getMigrationSqlGenerator()
249
            );
250
        });
251
    }
252
253 1
    public function getSchemaDiffProvider() : SchemaDiffProvider
254
    {
255
        return $this->getDependency(SchemaDiffProvider::class, function () : LazySchemaDiffProvider {
256 1
            return LazySchemaDiffProvider::fromDefaultProxyFactoryConfiguration(
257 1
                new DBALSchemaDiffProvider(
258 1
                    $this->getConnection()->getSchemaManager(),
259 1
                    $this->getConnection()->getDatabasePlatform()
260
                )
261
            );
262 1
        });
263
    }
264
265
    private function getFileBuilder() : FileBuilder
266
    {
267
        return $this->getDependency(FileBuilder::class, static function () : FileBuilder {
268
            return new ConcatenationFileBuilder();
269
        });
270
    }
271
272 1
    private function getParameterFormatter() : ParameterFormatter
273
    {
274
        return $this->getDependency(ParameterFormatter::class, function () : ParameterFormatter {
275 1
            return new InlineParameterFormatter($this->getConnection());
276 1
        });
277
    }
278
279 34
    public function getMigrationsFinder() : MigrationFinder
280
    {
281
        return $this->getDependency(MigrationFinder::class, function () : MigrationFinder {
282 34
            $configs              = $this->getConfiguration();
283 34
            $needsRecursiveFinder = $configs->areMigrationsOrganizedByYear() || $configs->areMigrationsOrganizedByYearAndMonth();
284
285 34
            return $needsRecursiveFinder ? new RecursiveRegexFinder() : new GlobFinder();
286 34
        });
287
    }
288
289 43
    public function getMigrationRepository() : MigrationsRepository
290
    {
291
        return $this->getDependency(MigrationsRepository::class, function () : MigrationsRepository {
292 31
            return new FilesystemMigrationsRepository(
293 31
                $this->getConfiguration()->getMigrationClasses(),
294 31
                $this->getConfiguration()->getMigrationDirectories(),
295 31
                $this->getMigrationsFinder(),
296 31
                $this->getMigrationFactory(),
297 31
                $this->getVersionComparator()
298
            );
299 43
        });
300
    }
301
302 31
    public function getMigrationFactory() : MigrationFactory
303
    {
304
        return $this->getDependency(MigrationFactory::class, function () : MigrationFactory {
305 31
            return new DbalMigrationFactory($this->getConnection(), $this->getLogger());
306 31
        });
307
    }
308
309
    /**
310
     * @param object|callable $service
311
     */
312 38
    public function setService(string $id, $service) : void
313
    {
314 38
        $this->assertNotFrozen();
315 37
        $this->dependencies[$id] = $service;
316 37
    }
317
318 43
    public function getMetadataStorage() : MetadataStorage
319
    {
320
        return $this->getDependency(MetadataStorage::class, function () : MetadataStorage {
321 31
            return new TableMetadataStorage(
322 31
                $this->getConnection(),
323 31
                $this->getConfiguration()->getMetadataStorageConfiguration(),
324 31
                $this->getMigrationRepository()
325
            );
326 43
        });
327
    }
328
329 1
    private function getVersionExecutor() : Executor
330
    {
331
        return $this->getDependency(Executor::class, function () : Executor {
332 1
            return new DbalExecutor(
333 1
                $this->getMetadataStorage(),
334 1
                $this->getEventDispatcher(),
335 1
                $this->getConnection(),
336 1
                $this->getSchemaDiffProvider(),
337 1
                $this->getLogger(),
338 1
                $this->getParameterFormatter(),
339 1
                $this->getStopwatch()
340
            );
341 1
        });
342
    }
343
344 4
    public function getQueryWriter() : QueryWriter
345
    {
346
        return $this->getDependency(QueryWriter::class, function () : QueryWriter {
347
            return new FileQueryWriter(
348
                $this->getFileBuilder(),
349
                $this->getLogger()
350
            );
351 4
        });
352
    }
353
354 19
    public function getVersionAliasResolver() : AliasResolver
355
    {
356
        return $this->getDependency(AliasResolver::class, function () : AliasResolver {
357 19
            return new DefaultAliasResolver(
358 19
                $this->getMigrationRepository(),
359 19
                $this->getMetadataStorage(),
360 19
                $this->getMigrationStatusCalculator()
361
            );
362 19
        });
363
    }
364
365 25
    public function getMigrationStatusCalculator() : MigrationStatusCalculator
366
    {
367
        return $this->getDependency(MigrationStatusCalculator::class, function () : MigrationStatusCalculator {
368 25
            return new CurrentMigrationStatusCalculator(
369 25
                $this->getMigrationRepository(),
370 25
                $this->getMetadataStorage()
371
            );
372 25
        });
373
    }
374
375 14
    public function getMigrationPlanCalculator() : MigrationPlanCalculator
376
    {
377
        return $this->getDependency(MigrationPlanCalculator::class, function () : MigrationPlanCalculator {
378 10
            return new SortedMigrationPlanCalculator(
379 10
                $this->getMigrationRepository(),
380 10
                $this->getMetadataStorage()
381
            );
382 14
        });
383
    }
384
385
    public function getMigrationGenerator() : Generator
386
    {
387
        return $this->getDependency(Generator::class, function () : Generator {
388
            return new Generator($this->getConfiguration());
389
        });
390
    }
391
392
    public function getMigrationSqlGenerator() : SqlGenerator
393
    {
394
        return $this->getDependency(SqlGenerator::class, function () : SqlGenerator {
395
            return new SqlGenerator(
396
                $this->getConfiguration(),
397
                $this->getConnection()->getDatabasePlatform()
398
            );
399
        });
400
    }
401
402 20
    public function getConsoleInputMigratorConfigurationFactory() : MigratorConfigurationFactory
403
    {
404
        return $this->getDependency(MigratorConfigurationFactory::class, function () : MigratorConfigurationFactory {
405 20
            return new ConsoleInputMigratorConfigurationFactory(
406 20
                $this->getConfiguration()
407
            );
408 20
        });
409
    }
410
411 3
    public function getMigrationStatusInfosHelper() : MigrationStatusInfosHelper
412
    {
413
        return $this->getDependency(MigrationStatusInfosHelper::class, function () : MigrationStatusInfosHelper {
414 3
            return new MigrationStatusInfosHelper(
415 3
                $this->getConfiguration(),
416 3
                $this->getConnection(),
417 3
                $this->getVersionAliasResolver(),
418 3
                $this->getMigrationRepository(),
419 3
                $this->getMetadataStorage()
420
            );
421 3
        });
422
    }
423
424 10
    public function getMigrator() : Migrator
425
    {
426
        return $this->getDependency(Migrator::class, function () : Migrator {
427 1
            return new DbalMigrator(
428 1
                $this->getConnection(),
429 1
                $this->getEventDispatcher(),
430 1
                $this->getVersionExecutor(),
431 1
                $this->getLogger(),
432 1
                $this->getStopwatch()
433
            );
434 10
        });
435
    }
436
437 1
    public function getStopwatch() : Stopwatch
438
    {
439
        return $this->getDependency(Stopwatch::class, static function () : Stopwatch {
440 1
            return new Stopwatch(true);
441 1
        });
442
    }
443
444
    public function getRollup() : Rollup
445
    {
446
        return $this->getDependency(Rollup::class, function () : Rollup {
447
            return new Rollup(
448
                $this->getMetadataStorage(),
449
                $this->getMigrationRepository()
450
            );
451
        });
452
    }
453
454
    /**
455
     * @return mixed
456
     */
457 52
    private function getDependency(string $id, callable $callback)
458
    {
459 52
        if (! array_key_exists($id, $this->dependencies)) {
460 50
            $this->dependencies[$id] = $callback();
461
        }
462
463 52
        return $this->dependencies[$id];
464
    }
465
}
466