forked from api-platform/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecreateSchemaTrait.php
More file actions
90 lines (73 loc) · 2.73 KB
/
RecreateSchemaTrait.php
File metadata and controls
90 lines (73 loc) · 2.73 KB
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
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Tests;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\SchemaTool;
trait RecreateSchemaTrait
{
/**
* @param class-string[] $classes
*/
private function recreateSchema(array $classes = []): void
{
$manager = $this->getManager();
if ($manager instanceof DocumentManager) {
$schemaManager = $manager->getSchemaManager();
foreach ($classes as $c) {
$class = str_contains($c, 'Entity') ? str_replace('Entity', 'Document', $c) : $c;
$schemaManager->dropDocumentDatabase($class);
}
return;
}
/** @var ClassMetadata[] $metadataCollection */
$metadataCollection = [];
$processedClasses = [];
foreach ($classes as $class) {
$this->addMetadataWithDependencies($manager, $class, $metadataCollection, $processedClasses);
}
$schemaTool = new SchemaTool($manager);
@$schemaTool->dropDatabase();
@$schemaTool->createSchema($metadataCollection);
}
/**
* @param array<ClassMetadata> $metadataCollection
* @param array<string, bool> $processedClasses
*
* @param-out array<ClassMetadata> $metadataCollection
* @param-out array<string, bool> $processedClasses
*/
private function addMetadataWithDependencies(EntityManagerInterface $manager, string $class, array &$metadataCollection, array &$processedClasses): void
{
if (isset($processedClasses[$class])) {
return;
}
$metadata = $manager->getMetadataFactory()->getMetadataFor($class);
$metadataCollection[] = $metadata;
$processedClasses[$class] = true;
foreach ($metadata->getAssociationMappings() as $associationMapping) {
$this->addMetadataWithDependencies($manager, $associationMapping->targetEntity, $metadataCollection, $processedClasses);
}
}
private function isMongoDB(): bool
{
return 'mongodb' === static::getContainer()->getParameter('kernel.environment');
}
private function isPostgres(): bool
{
return 'postgres' === static::getContainer()->getParameter('kernel.environment');
}
private function getManager(): EntityManagerInterface|DocumentManager
{
return static::getContainer()->get($this->isMongoDB() ? 'doctrine_mongodb' : 'doctrine')->getManager();
}
}