• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

j-schumann / symfony-addons / 38429079703

13 Oct 2026 04:15PM UTC coverage: 93.131%. Remained the same
38429079703

push

github

j-schumann
Audit the dependencies in CI, explain the MSSQL user variables

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

949 of 1019 relevant lines covered (93.13%)

48.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.22
/src/PHPUnit/RefreshDatabaseTrait.php
1
<?php
2

3
namespace Vrok\SymfonyAddons\PHPUnit;
4

5
use Doctrine\Bundle\FixturesBundle\Loader\SymfonyFixturesLoader;
6
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
7
use Doctrine\Common\DataFixtures\FixtureInterface;
8
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
9
use Doctrine\DBAL\DriverManager;
10
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
11
use Doctrine\DBAL\Platforms\AbstractPlatform;
12
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
13
use Doctrine\DBAL\Platforms\SQLitePlatform;
14
use Doctrine\DBAL\Platforms\SQLServerPlatform;
15
use Doctrine\DBAL\Schema\Name\UnqualifiedName;
16
use Doctrine\DBAL\Schema\SQLiteSchemaManager;
17
use Doctrine\ORM\EntityManagerInterface;
18
use Doctrine\ORM\Tools\SchemaTool;
19
use Doctrine\Persistence\ManagerRegistry;
20
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
21
use Symfony\Component\DependencyInjection\ContainerInterface;
22
use Symfony\Component\HttpKernel\KernelInterface;
23

24
/**
25
 * Idea from DoctrineTestBundle & hautelook/AliceBundle: We want to force the test DB to have the
26
 * current schema and load all test fixtures (group=test) so the DB is in a known state for each
27
 * test (meaning each time the kernel is booted).
28
 *
29
 * static::$fixtureGroups can be customized in setUpBeforeClass()
30
 *
31
 * The cleanup method for the database can be overridden by setting the ENV DB_CLEANUP_METHOD (e.g.
32
 * in phpunit.xml.dist).
33
 *
34
 * "purge" will update the DB schema once and afterward only purges all tables and resets the
35
 * identities. On SQLServer the tables are always emptied with DELETE, as TRUNCATE does not work there
36
 * with foreign keys; on MySQL/MariaDB DELETE is only the default and DB_PURGE_MODE switches back to
37
 * TRUNCATE.
38
 *
39
 * "dropSchema" will drop all tables (and indices) and recreate them before each test, use this when
40
 * a test requires a genuinely fresh schema.
41
 *
42
 * "dropDatabase" will drop the entire database and recreate it before each test.
43
 */
44
trait RefreshDatabaseTrait
45
{
46
    /**
47
     * @var string[] allowed values for the ENV DB_CLEANUP_METHOD
48
     */
49
    private const array CLEANUP_METHODS = ['purge', 'dropSchema', 'dropDatabase'];
50

51
    /**
52
     * @var string[] allowed values for the ENV DB_PURGE_MODE
53
     */
54
    private const array PURGE_MODES = ['delete', 'truncate'];
55

56
    /**
57
     * @var array<string> fixture group(s) to apply
58
     */
59
    protected static array $fixtureGroups = ['test'];
60

61
    /**
62
     * @var array<FixtureInterface>|null fixture cache
63
     */
64
    protected static ?array $fixtures = null;
65

66
    /**
67
     * Cache for the tables that have an auto-increment column.
68
     *
69
     * @var array<string, array{name: string, column: string}>|null
70
     */
71
    private static ?array $identityTables = null;
72

73
    /**
74
     * @var bool Flag whether the db setup is done (db exists, schema is up to date)
75
     */
76
    protected static bool $setupComplete = false;
77

78
    /**
79
     * Called on each test that calls bootKernel() or uses createClient().
80
     *
81
     * @param array<string, mixed> $options
82
     */
83
    protected static function bootKernel(array $options = []): KernelInterface
257 ✔
84
    {
85
        static::ensureKernelTestCase();
257 ✔
86

87
        $kernel = parent::bootKernel($options);
257 ✔
88
        $container = static::getContainer();
257 ✔
89
        /** @var ManagerRegistry $doctrine */
90
        $doctrine = $container->get('doctrine');
257 ✔
91
        /** @var EntityManagerInterface $entityManager */
92
        $entityManager = $doctrine->getManager();
257 ✔
93
        $executor = static::getExecutor($entityManager);
257 ✔
94

95
        $cleanupMethod = $_ENV['DB_CLEANUP_METHOD'] ?? 'purge';
257 ✔
96
        if (
97
            !\is_string($cleanupMethod)
257 ✔
98
            || !\in_array($cleanupMethod, self::CLEANUP_METHODS, true)
257 ✔
99
        ) {
100
            $given = \is_string($cleanupMethod) ? $cleanupMethod : get_debug_type($cleanupMethod);
5 ✔
101
            $allowed = implode(', ', self::CLEANUP_METHODS);
5 ✔
102
            throw new \InvalidArgumentException("Unknown DB_CLEANUP_METHOD '$given', allowed values are: $allowed");
5 ✔
103
        }
104

105
        switch ($cleanupMethod) {
106
            case 'dropDatabase':
252 ✔
107
                static::recreateDatabase($entityManager, true);
5 ✔
108
                static::updateSchema($entityManager);
5 ✔
109
                break;
5 ✔
110

111
            case 'dropSchema':
247 ✔
112
                if (!static::$setupComplete) {
5 ✔
113
                    static::recreateDatabase($entityManager);
×
114
                    static::$setupComplete = true;
×
115
                }
116

117
                static::updateSchema($entityManager, true);
5 ✔
118
                break;
5 ✔
119

120
            case 'purge':
242 ✔
121
                // only on the first test: make sure the db exists and the schema is up to date
122
                if (!static::$setupComplete) {
242 ✔
123
                    static::recreateDatabase($entityManager);
6 ✔
124
                    static::updateSchema($entityManager);
6 ✔
125
                    static::$setupComplete = true;
6 ✔
126
                }
127

128
                $connection = $executor->getObjectManager()->getConnection();
242 ✔
129
                $platform = $connection->getDatabasePlatform();
242 ✔
130
                $isMysql = $platform instanceof AbstractMySQLPlatform;
242 ✔
131
                $purgeMode = $_ENV['DB_PURGE_MODE'] ?? 'delete';
242 ✔
132
                if (!\is_string($purgeMode) || !\in_array($purgeMode, self::PURGE_MODES, true)) {
242 ✔
133
                    $given = \is_string($purgeMode) ? $purgeMode : get_debug_type($purgeMode);
5 ✔
134
                    $allowed = implode(', ', self::PURGE_MODES);
5 ✔
135
                    throw new \InvalidArgumentException("Unknown DB_PURGE_MODE '$given', allowed values are: $allowed");
5 ✔
136
                }
137

138
                // In MySQL/MariaDB we need to disable foreign key checks, as the automatic table
139
                // ordering does not help us when we have self-referencing tables.
140
                if ($isMysql) {
237 ✔
141
                    $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 0');
94 ✔
142
                }
143

144
                // SQLServer has no choice: TRUNCATE does not work with foreign keys there, and
145
                // "EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'" does not help
146
                // either. On MySQL/MariaDB it is a preference: TRUNCATE is a DDL operation, InnoDB
147
                // drops and recreates the tablespace file for each table and each test, which is
148
                // usually more expensive than emptying the tables with DELETE, so DELETE is the
149
                // default and DB_PURGE_MODE=truncate opts out of it. Either way, DELETE keeps the
150
                // auto-increment counters, so they have to be reset afterward.
151
                $purgeWithDelete = $platform instanceof SQLServerPlatform
237 ✔
152
                    || ($isMysql && 'truncate' !== $purgeMode);
237 ✔
153
                if ($purgeWithDelete) {
237 ✔
154
                    $purger = $executor->getPurger();
135 ✔
155
                    \assert($purger instanceof ORMPurger);
×
156
                    $purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
135 ✔
157
                }
158

159
                // Purge even when no fixtures are defined, e.g., for tests that require an empty
160
                // database, like import tests. Purge separately from inserting the fixtures, as
161
                // execute() would wrap the TRUNCATE in a transaction which MySQL auto-commits when
162
                // DDL queries are executed, which throws an exception in the
163
                // entityManager ("There is no active transaction",
164
                // @see https://github.com/doctrine/migrations/issues/1104) because it does not
165
                // check if a transaction is still open before calling commit().
166
                $executor->purge();
237 ✔
167

168
                // A TRUNCATE on MySQL/MariaDB is the only purge that resets the identity generators
169
                // for us. PostgreSQL keeps its sequences unless the TRUNCATE says RESTART IDENTITY,
170
                // SQLite empties the tables with DELETE whatever the purge mode says, and where we
171
                // purged with DELETE there was no TRUNCATE to reset anything. So everywhere else we
172
                // do it ourselves, as tests may rely on the generated IDs (e.g. when asserting on
173
                // IRIs like /items/1).
174
                $purgeResetIdentities = $isMysql && !$purgeWithDelete;
237 ✔
175
                if (!$purgeResetIdentities) {
237 ✔
176
                    static::resetIdentities($entityManager, $platform);
233 ✔
177
                }
178

179
                // Restore the default: the checks were only disabled for the purge, the fixtures
180
                // and the test itself should run with the same settings as the application, e.g.
181
                // for tests that assert that a foreign key violation occurs.
182
                if ($isMysql) {
237 ✔
183
                    $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 1');
94 ✔
184
                }
185

186
                break;
237 ✔
187
        }
188

189
        $fixtures = static::getFixtures($container);
247 ✔
190
        if ([] !== $fixtures) {
247 ✔
191
            $executor->execute($fixtures, true);
203 ✔
192
        }
193

194
        return $kernel;
247 ✔
195
    }
196

197
    protected static function ensureKernelTestCase(): void
257 ✔
198
    {
199
        // @phpstan-ignore function.alreadyNarrowedType (always true in the ApiPlatformTestCase, but the trait can be used elsewhere)
200
        if (!is_a(static::class, KernelTestCase::class, true)) {
257 ✔
201
            throw new \LogicException(\sprintf('The test class must extend "%s" to use "%s".', KernelTestCase::class, static::class));
×
202
        }
203
    }
204

205
    /**
206
     * (Drops and re-) creates the (test) database if it does not exist. This code tries to
207
     * duplicate the behavior of the doctrine:database:drop / doctrine:schema:create commands in the
208
     * DoctrineBundle.
209
     *
210
     * @param bool $drop if true, the method deletes an existing database before recreating it, else
211
     *                   the database is only created when it does not exist
212
     */
213
    protected static function recreateDatabase(
16 ✔
214
        EntityManagerInterface $em,
215
        bool $drop = false,
216
    ): void {
217
        $connection = $em->getConnection();
16 ✔
218
        $params = $connection->getParams();
16 ✔
219
        $params = $params['primary'] ?? $params;
16 ✔
220

221
        // name will already contain the dbname_suffix (and the TEST_TOKEN) if any is configured
222
        $dbName = $params['path'] ?? $params['dbname'] ?? false;
16 ✔
223
        if (!$dbName) {
16 ✔
224
            throw new \RuntimeException("Connection does not contain a 'dbname' or 'path' parameter, don't know how to proceed, aborting.");
×
225
        }
226

227
        unset($params['dbname'], $params['path']);
16 ✔
228
        $platform = $connection->getDatabasePlatform();
16 ✔
229
        if ($platform instanceof PostgreSQLPlatform) {
16 ✔
230
            // @phpstan-ignore nullCoalesce.offset (the doctrine-bundle passes its default_dbname option, DBAL's type omits it)
231
            $params['dbname'] = $params['default_dbname'] ?? 'postgres';
4 ✔
232
        } elseif ($platform instanceof AbstractMySQLPlatform) {
12 ✔
233
            // DBAL requires a database to introspect the database names on MySQL/MariaDB
234
            $params['dbname'] = 'information_schema';
6 ✔
235
        }
236

237
        $tempConnection = DriverManager::getConnection($params, $connection->getConfiguration());
16 ✔
238
        $schemaManager = $tempConnection->createSchemaManager();
16 ✔
239

240
        // SQLite does not support checking for existing / dropping / creating databases via
241
        // Doctrine -> special handling here
242
        if ($schemaManager instanceof SQLiteSchemaManager) {
16 ✔
243
            if ($drop && file_exists($dbName)) {
3 ✔
244
                unlink($dbName);
2 ✔
245
            }
246

247
            // the database file will be automatically created on first use, no need to create now
248
            return;
3 ✔
249
        }
250

251
        $dbExists = array_any(
13 ✔
252
            $schemaManager->introspectDatabaseNames(),
13 ✔
253
            static fn (UnqualifiedName $n): bool => $n->getIdentifier()->getValue() === $dbName,
13 ✔
254
        );
13 ✔
255

256
        if ($drop && $dbExists) {
13 ✔
257
            // close the current connection in the em, it would be invalid anyway after the drop
258
            $connection->close();
8 ✔
259

260
            // For Postgres, closing the old connection is not enough to prevent: 'ERROR: database
261
            // "db_test" is being accessed by other users'
262
            if ($tempConnection->getDatabasePlatform() instanceof PostgreSQLPlatform) {
8 ✔
263
                $tempConnection->executeStatement(
2 ✔
264
                    'SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = ? AND pid <> pg_backend_pid()',
2 ✔
265
                    [$dbName]
2 ✔
266
                );
2 ✔
267
            }
268

269
            if ($tempConnection->getDatabasePlatform() instanceof SQLServerPlatform) {
8 ✔
270
                $tempConnection->executeStatement(
2 ✔
271
                    "USE master; ALTER DATABASE $dbName SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
2 ✔
272
                );
2 ✔
273
            }
274

275
            $schemaManager->dropDatabase($dbName);
8 ✔
276

277
            $dbExists = false;
8 ✔
278
        }
279

280
        if (!$dbExists) {
13 ✔
281
            $schemaManager->createDatabase($dbName);
8 ✔
282
        }
283

284
        $tempConnection->close();
13 ✔
285
    }
286

287
    /**
288
     * Brings the db schema to the newest version.
289
     *
290
     * @param bool $drop if true, the method drops the current schema first, e.g. to reset all data
291
     */
292
    protected static function updateSchema(
21 ✔
293
        EntityManagerInterface $em,
294
        bool $drop = false,
295
    ): void {
296
        $metadatas = $em->getMetadataFactory()->getAllMetadata();
21 ✔
297
        if ([] === $metadatas) {
21 ✔
298
            return;
×
299
        }
300

301
        $schemaTool = new SchemaTool($em);
21 ✔
302

303
        if ($drop) {
21 ✔
304
            // The method name is misleading; it only drops the elements within the database, not
305
            // the db itself...
306
            $schemaTool->dropDatabase();
5 ✔
307
        }
308

309
        $schemaTool->updateSchema($metadatas);
21 ✔
310
    }
311

312
    /**
313
     * Use a static fixture cache as we need them before each test.
314
     *
315
     * @return array<FixtureInterface>
316
     */
317
    protected static function getFixtures(ContainerInterface $container): array
247 ✔
318
    {
319
        if ([] === static::$fixtureGroups) {
247 ✔
320
            // the fixture loader returns all possible fixtures if called with an empty array ->
321
            // catch here
322
            return [];
44 ✔
323
        }
324

325
        if (\is_array(static::$fixtures)) {
203 ✔
326
            return static::$fixtures;
191 ✔
327
        }
328

329
        /** @var SymfonyFixturesLoader $fixturesLoader */
330
        $fixturesLoader = $container->get('doctrine.fixtures.loader');
12 ✔
331
        $fixtures = $fixturesLoader->getFixtures(static::$fixtureGroups);
12 ✔
332
        static::$fixtures = $fixtures;
12 ✔
333

334
        return $fixtures;
12 ✔
335
    }
336

337
    /**
338
     * Returns a new executor instance, we need it before each test execution.
339
     */
340
    protected static function getExecutor(EntityManagerInterface $em): ORMExecutor
257 ✔
341
    {
342
        $purger = new ORMPurger($em);
257 ✔
343
        $purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE);
257 ✔
344

345
        // don't use a static Executor, it contains the EM which could be closed through (expected)
346
        // exceptions and would not work
347
        return new ORMExecutor($em, $purger);
257 ✔
348
    }
349

350
    /**
351
     * Resets the identity generators of all tables that have one, so the records created in the
352
     * tests always receive the same IDs.
353
     *
354
     * Must be called after the purge and before the fixtures are loaded.
355
     */
356
    protected static function resetIdentities(
233 ✔
357
        EntityManagerInterface $em,
358
        AbstractPlatform $platform,
359
    ): void {
360
        $identityTables = static::getIdentityTables($em, $platform);
233 ✔
361
        if ([] === $identityTables) {
233 ✔
362
            return;
×
363
        }
364

365
        $connection = $em->getConnection();
233 ✔
366

367
        if ($platform instanceof AbstractMySQLPlatform) {
233 ✔
368
            foreach (array_keys($identityTables) as $table) {
90 ✔
369
                // the value is clamped to MAX(id) + 1, so this is a no-op for a table that was
370
                // excluded from the purge and still has rows
371
                $connection->executeStatement("ALTER TABLE $table AUTO_INCREMENT = 1");
90 ✔
372
            }
373

374
            return;
90 ✔
375
        }
376

377
        if ($platform instanceof PostgreSQLPlatform) {
143 ✔
378
            // TRUNCATE keeps the sequences, only "TRUNCATE ... RESTART IDENTITY" would reset them
379
            foreach ($identityTables as $table => $meta) {
53 ✔
380
                // is_called = false lets the next record use the value itself. The table name is
381
                // passed quoted, as pg_get_serial_sequence treats its first argument as a
382
                // (potentially qualified) name and would lowercase an unquoted one.
383
                $connection->executeQuery(
53 ✔
384
                    'SELECT setval(pg_get_serial_sequence(?, ?), 1, false)',
53 ✔
385
                    [$table, $meta['column']]
53 ✔
386
                );
53 ✔
387
            }
388

389
            return;
53 ✔
390
        }
391

392
        if ($platform instanceof SQLServerPlatform) {
90 ✔
393
            foreach (array_keys($identityTables) as $table) {
45 ✔
394
                // DBCC CHECKIDENT makes the *next* record use RESEED + 1, but only for a table that
395
                // was inserted into before: for a table that was never used, the first record uses
396
                // the reseed value itself, which would be 0. So we only reseed tables that have a
397
                // current identity value.
398
                $connection->executeStatement(
45 ✔
399
                    'DECLARE @table NVARCHAR(776) = ?;
45 ✔
400
                     IF EXISTS (
401
                         SELECT 1 FROM sys.identity_columns
402
                         WHERE object_id = OBJECT_ID(@table) AND last_value IS NOT NULL
403
                     )
404
                         DBCC CHECKIDENT (@table, RESEED, 0) WITH NO_INFOMSGS',
45 ✔
405
                    [$table]
45 ✔
406
                );
45 ✔
407
            }
408

409
            return;
45 ✔
410
        }
411

412
        if ($platform instanceof SQLitePlatform) {
45 ✔
413
            // SQLite stores the counters of all AUTOINCREMENT columns in this table, it only exists
414
            // when at least one such column is used
415
            $sequenceTableExists = (bool) $connection->fetchOne(
45 ✔
416
                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_sequence'"
45 ✔
417
            );
45 ✔
418
            if (!$sequenceTableExists) {
45 ✔
419
                return;
×
420
            }
421

422
            foreach ($identityTables as $meta) {
45 ✔
423
                // the counters are stored with the unquoted table name
424
                $connection->executeStatement(
45 ✔
425
                    'DELETE FROM sqlite_sequence WHERE name = ?',
45 ✔
426
                    [$meta['name']]
45 ✔
427
                );
45 ✔
428
            }
429
        }
430
    }
431

432
    /**
433
     * Returns all tables that have an identity / auto-increment column, in the order in which the
434
     * mapping defines them.
435
     *
436
     * @return array<string, array{name: string, column: string}>
437
     */
438
    protected static function getIdentityTables(
233 ✔
439
        EntityManagerInterface $em,
440
        AbstractPlatform $platform,
441
    ): array {
442
        if (null !== self::$identityTables) {
233 ✔
443
            return self::$identityTables;
232 ✔
444
        }
445

446
        $quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
6 ✔
447
        $tables = [];
6 ✔
448

449
        foreach ($em->getMetadataFactory()->getAllMetadata() as $meta) {
6 ✔
450
            if ($meta->isMappedSuperclass || $meta->isEmbeddedClass) {
6 ✔
451
                continue;
6 ✔
452
            }
453

454
            // Only the root class of a hierarchy owns the identity column: With SINGLE_TABLE the
455
            // children share the table of the root, with JOINED they have their own table, but its
456
            // primary key is a foreign key to the root and not auto-increment. The children inherit
457
            // generatorType = IDENTITY in both cases,
458
            // @see ClassMetadataFactory::inheritIdGeneratorMapping()
459
            if ($meta->name !== $meta->rootEntityName) {
6 ✔
460
                continue;
6 ✔
461
            }
462

463
            // the conditions under which the SchemaTool sets autoincrement=true
464
            $identifierFields = $meta->getIdentifierFieldNames();
6 ✔
465
            if (!$meta->isIdGeneratorIdentity() || 1 !== \count($identifierFields)) {
6 ✔
466
                continue;
6 ✔
467
            }
468

469
            // multiple entities can be mapped to the same table -> deduplicate
470
            $tables[$quoteStrategy->getTableName($meta, $platform)] = [
6 ✔
471
                'name'   => $meta->getTableName(),
6 ✔
472
                'column' => $meta->getColumnName($identifierFields[0]),
6 ✔
473
            ];
6 ✔
474
        }
475

476
        return self::$identityTables = $tables;
6 ✔
477
    }
478

479
    protected static function fixtureCleanup(): void
×
480
    {
481
        static::$fixtures = null;
×
482
    }
483
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc