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

j-schumann / symfony-addons / 38279079843

12 Oct 2026 04:40PM UTC coverage: 82.227% (+18.4%) from 63.806%
38279079843

push

github

web-flow
Prepare 4.0: API Platform 5 only, QueryParameter filters, remove obsolete subscribers (#85)

123 of 125 new or added lines in 10 files covered. (98.4%)

3 existing lines in 3 files now uncovered.

842 of 1024 relevant lines covered (82.23%)

29.44 hits per line

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

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

3
namespace Vrok\SymfonyAddons\PHPUnit;
4

5
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
6
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
7
use Doctrine\DBAL\DriverManager;
8
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
9
use Doctrine\DBAL\Platforms\AbstractPlatform;
10
use Doctrine\DBAL\Platforms\MariaDBPlatform;
11
use Doctrine\DBAL\Platforms\MySQLPlatform;
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 Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21
use Symfony\Component\HttpKernel\KernelInterface;
22

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

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

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

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

65
    /**
66
     * @var array|null cache for the tables that have an auto-increment column
67
     */
68
    private static ?array $identityTables = null;
69

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

75
    /**
76
     * Called on each test that calls bootKernel() or uses createClient().
77
     */
78
    protected static function bootKernel(array $options = []): KernelInterface
177 ✔
79
    {
80
        static::ensureKernelTestCase();
177 ✔
81

82
        $kernel = parent::bootKernel($options);
177 ✔
83
        $container = static::getContainer();
177 ✔
84
        $entityManager = $container->get('doctrine')->getManager();
177 ✔
85
        $executor = static::getExecutor($entityManager);
177 ✔
86

87
        $cleanupMethod = $_ENV['DB_CLEANUP_METHOD'] ?? 'purge';
177 ✔
88
        if (!\is_string($cleanupMethod) || !\in_array($cleanupMethod, self::CLEANUP_METHODS, true)) {
177 ✔
89
            $given = \is_string($cleanupMethod) ? $cleanupMethod : get_debug_type($cleanupMethod);
5 ✔
90
            $allowed = implode(', ', self::CLEANUP_METHODS);
5 ✔
91
            throw new \InvalidArgumentException("Unknown DB_CLEANUP_METHOD '$given', allowed values are: $allowed");
5 ✔
92
        }
93

94
        switch ($cleanupMethod) {
95
            case 'dropDatabase':
172 ✔
96
                static::recreateDatabase($entityManager, true);
5 ✔
97
                static::updateSchema($entityManager);
5 ✔
98
                break;
5 ✔
99

100
            case 'dropSchema':
167 ✔
101
                if (!static::$setupComplete) {
5 ✔
102
                    static::recreateDatabase($entityManager);
×
103
                    static::$setupComplete = true;
×
104
                }
105

106
                static::updateSchema($entityManager, true);
5 ✔
107
                break;
5 ✔
108

109
            case 'purge':
162 ✔
110
                // only on the first test: make sure the db exists and the schema is up to date
111
                if (!static::$setupComplete) {
162 ✔
112
                    static::recreateDatabase($entityManager);
6 ✔
113
                    static::updateSchema($entityManager);
6 ✔
114
                    static::$setupComplete = true;
6 ✔
115
                }
116

117
                $connection = $executor->getObjectManager()->getConnection();
162 ✔
118
                $platform = $connection->getDatabasePlatform();
162 ✔
119
                $isMysql = $platform instanceof MySQLPlatform || $platform instanceof MariaDBPlatform;
162 ✔
120
                $purgeMode = $_ENV['DB_PURGE_MODE'] ?? 'delete';
162 ✔
121
                if (!\is_string($purgeMode) || !\in_array($purgeMode, self::PURGE_MODES, true)) {
162 ✔
122
                    $given = \is_string($purgeMode) ? $purgeMode : get_debug_type($purgeMode);
5 ✔
123
                    $allowed = implode(', ', self::PURGE_MODES);
5 ✔
124
                    throw new \InvalidArgumentException("Unknown DB_PURGE_MODE '$given', allowed values are: $allowed");
5 ✔
125
                }
126

127
                // In MySQL/MariaDB we need to disable foreign key checks, as the automatic table
128
                // ordering does not help us when we have self-referencing tables.
129
                if ($isMysql) {
157 ✔
130
                    $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 0');
62 ✔
131
                }
132

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

148
                // Purge even when no fixtures are defined, e.g., for tests that require an empty
149
                // database, like import tests. Fix for PHP8: purge separately from inserting the
150
                // fixtures, as execute() would wrap the TRUNCATE in a transaction which MySQL
151
                // auto-commits when DDL queries are executed, which throws an exception in the
152
                // entityManager ("There is no active transaction",
153
                // @see https://github.com/doctrine/migrations/issues/1104) because it does not
154
                // check if a transaction is still open before calling commit().
155
                $executor->purge();
157 ✔
156

157
                // A TRUNCATE on MySQL/MariaDB is the only purge that resets the identity generators
158
                // for us. PostgreSQL keeps its sequences unless the TRUNCATE says RESTART IDENTITY,
159
                // SQLite empties the tables with DELETE whatever the purge mode says, and where we
160
                // purged with DELETE there was no TRUNCATE to reset anything. So everywhere else we
161
                // do it ourselves, as tests may rely on the generated IDs (e.g. when asserting on
162
                // IRIs like /items/1).
163
                $purgeResetIdentities = $isMysql && !$purgeWithDelete;
157 ✔
164
                if (!$purgeResetIdentities) {
157 ✔
165
                    static::resetIdentities($entityManager, $platform);
153 ✔
166
                }
167

168
                // Restore the default: the checks were only disabled for the purge, the fixtures
169
                // and the test itself should run with the same settings as the application, e.g.
170
                // for tests that assert that a foreign key violation occurs.
171
                if ($isMysql) {
157 ✔
172
                    $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 1');
62 ✔
173
                }
174

175
                break;
157 ✔
176
        }
177

178
        // now load any fixtures configured for "test" (or overwritten groups)
179
        $fixtures = static::getFixtures($container);
167 ✔
180
        if ([] !== $fixtures) {
167 ✔
181
            $executor->execute($fixtures, true);
128 ✔
182
        }
183

184
        return $kernel;
167 ✔
185
    }
186

187
    protected static function ensureKernelTestCase(): void
177 ✔
188
    {
189
        // @phpstan-ignore function.alreadyNarrowedType (always true in the ApiPlatformTestCase, but the trait can be used elsewhere)
190
        if (!is_a(static::class, KernelTestCase::class, true)) {
177 ✔
191
            throw new \LogicException(\sprintf('The test class must extend "%s" to use "%s".', KernelTestCase::class, static::class));
×
192
        }
193
    }
194

195
    /**
196
     * (Drops and re-) creates the (test) database if it does not exist. This code tries to
197
     * duplicate the behavior of the doctrine:database:drop / doctrine:schema:create commands in the
198
     * DoctrineBundle.
199
     *
200
     * @param bool $drop if true, the method deletes an existing database before recreating it, else
201
     *                   the database is only created when it does not exist
202
     */
203
    protected static function recreateDatabase(
11 ✔
204
        EntityManagerInterface $em,
205
        bool $drop = false,
206
    ): void {
207
        $connection = $em->getConnection();
11 ✔
208
        $params = $connection->getParams();
11 ✔
209
        $params = $params['primary'] ?? $params;
11 ✔
210

211
        // name will already contain the dbname_suffix (and the TEST_TOKEN) if any is configured
212
        $dbName = $params['path'] ?? $params['dbname'] ?? false;
11 ✔
213
        if (!$dbName) {
11 ✔
214
            throw new \RuntimeException("Connection does not contain a 'dbname' or 'path' parameter, don't know how to proceed, aborting.");
×
215
        }
216

217
        unset($params['dbname'], $params['path']);
11 ✔
218
        $platform = $connection->getDatabasePlatform();
11 ✔
219
        if ($platform instanceof PostgreSQLPlatform) {
11 ✔
220
            // @phpstan-ignore nullCoalesce.offset (the doctrine-bundle passes its default_dbname option, DBAL's type omits it)
221
            $params['dbname'] = $params['default_dbname'] ?? 'postgres';
3 ✔
222
        } elseif ($platform instanceof AbstractMySQLPlatform) {
8 ✔
223
            // DBAL requires a database to introspect the database names on MySQL/MariaDB
224
            $params['dbname'] = 'information_schema';
4 ✔
225
        }
226

227
        $tempConnection = DriverManager::getConnection($params, $connection->getConfiguration());
11 ✔
228
        $schemaManager = $tempConnection->createSchemaManager();
11 ✔
229

230
        // SQLite does not support checking for existing / dropping / creating databases via
231
        // Doctrine -> special handling here
232
        if ($schemaManager instanceof SQLiteSchemaManager) {
11 ✔
233
            if ($drop && file_exists($dbName)) {
2 ✔
234
                unlink($dbName);
1 ✔
235
            }
236

237
            // the database file will be automatically created on first use, no need to create now
238
            return;
2 ✔
239
        }
240

241
        $dbExists = array_any(
9 ✔
242
            $schemaManager->introspectDatabaseNames(),
9 ✔
243
            static fn (UnqualifiedName $name): bool => $name->getIdentifier()->getValue() === $dbName,
9 ✔
244
        );
9 ✔
245

246
        if ($drop && $dbExists) {
9 ✔
247
            // close the current connection in the em, it would be invalid anyway after the drop
248
            $connection->close();
4 ✔
249

250
            // For Postgres, closing the old connection is not enough to prevent: 'ERROR: database
251
            // "db_test" is being accessed by other users'
252
            if ($tempConnection->getDatabasePlatform() instanceof PostgreSQLPlatform) {
4 ✔
253
                $tempConnection->executeStatement(
1 ✔
254
                    'SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = ? AND pid <> pg_backend_pid()',
1 ✔
255
                    [$dbName]
1 ✔
256
                );
1 ✔
257
            }
258

259
            if ($tempConnection->getDatabasePlatform() instanceof SQLServerPlatform) {
4 ✔
260
                $tempConnection->executeStatement(
1 ✔
261
                    "USE master; ALTER DATABASE $dbName SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
1 ✔
262
                );
1 ✔
263
            }
264

265
            $schemaManager->dropDatabase($dbName);
4 ✔
266

267
            $dbExists = false;
4 ✔
268
        }
269

270
        // Create the database only if it doesn't already exist. Skip for SQLite as it creates
271
        // database files automatically and this call would throw an exception.
272
        if (!$dbExists) {
9 ✔
273
            $schemaManager->createDatabase($dbName);
4 ✔
274
        }
275

276
        $tempConnection->close();
9 ✔
277
    }
278

279
    /**
280
     * Brings the db schema to the newest version.
281
     *
282
     * @param bool $drop if true, the method drops the current schema first, e.g. to reset all data
283
     */
284
    protected static function updateSchema(
16 ✔
285
        EntityManagerInterface $em,
286
        bool $drop = false,
287
    ): void {
288
        $metadatas = $em->getMetadataFactory()->getAllMetadata();
16 ✔
289
        if ([] === $metadatas) {
16 ✔
290
            return;
×
291
        }
292

293
        $schemaTool = new SchemaTool($em);
16 ✔
294

295
        if ($drop) {
16 ✔
296
            // The method name is misleading; it only drops the elements within the database, not
297
            // the db itself...
298
            $schemaTool->dropDatabase();
5 ✔
299
        }
300

301
        $schemaTool->updateSchema($metadatas);
16 ✔
302
    }
303

304
    /**
305
     * Use a static fixture cache as we need them before each test.
306
     */
307
    protected static function getFixtures(ContainerInterface $container): array
167 ✔
308
    {
309
        if ([] === static::$fixtureGroups) {
167 ✔
310
            // the fixture loader returns all possible fixtures if called with an empty array ->
311
            // catch here
312
            return [];
39 ✔
313
        }
314

315
        if (\is_array(static::$fixtures)) {
128 ✔
316
            return static::$fixtures;
116 ✔
317
        }
318

319
        $fixturesLoader = $container->get('doctrine.fixtures.loader');
12 ✔
320
        static::$fixtures = $fixturesLoader->getFixtures(static::$fixtureGroups);
12 ✔
321

322
        return static::$fixtures;
12 ✔
323
    }
324

325
    /**
326
     * Returns a new executor instance, we need it before each test execution.
327
     */
328
    protected static function getExecutor(EntityManagerInterface $em): ORMExecutor
177 ✔
329
    {
330
        $purger = new ORMPurger($em);
177 ✔
331
        $purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE);
177 ✔
332

333
        // don't use a static Executor, it contains the EM which could be closed through (expected)
334
        // exceptions and would not work
335
        return new ORMExecutor($em, $purger);
177 ✔
336
    }
337

338
    /**
339
     * Resets the identity generators of all tables that have one, so the records created in the
340
     * tests always receive the same IDs.
341
     *
342
     * Must be called after the purge and before the fixtures are loaded.
343
     */
344
    protected static function resetIdentities(
153 ✔
345
        EntityManagerInterface $em,
346
        AbstractPlatform $platform,
347
    ): void {
348
        $identityTables = static::getIdentityTables($em, $platform);
153 ✔
349
        if ([] === $identityTables) {
153 ✔
350
            return;
×
351
        }
352

353
        $connection = $em->getConnection();
153 ✔
354

355
        if ($platform instanceof MySQLPlatform || $platform instanceof MariaDBPlatform) {
153 ✔
356
            foreach (array_keys($identityTables) as $table) {
58 ✔
357
                // the value is clamped to MAX(id) + 1, so this is a no-op for a table that was
358
                // excluded from the purge and still has rows
359
                $connection->executeStatement("ALTER TABLE $table AUTO_INCREMENT = 1");
58 ✔
360
            }
361

362
            return;
58 ✔
363
        }
364

365
        if ($platform instanceof PostgreSQLPlatform) {
95 ✔
366
            // TRUNCATE keeps the sequences, only "TRUNCATE ... RESTART IDENTITY" would reset them,
367
            // @see Vrok\DoctrineAddons\DBAL\Platforms\PostgreSQLTestPlatform
368
            foreach ($identityTables as $table => $meta) {
37 ✔
369
                // is_called = false lets the next record use the value itself. The table name is
370
                // passed quoted, as pg_get_serial_sequence treats its first argument as a
371
                // (potentially qualified) name and would lowercase an unquoted one.
372
                $connection->executeQuery(
37 ✔
373
                    'SELECT setval(pg_get_serial_sequence(?, ?), 1, false)',
37 ✔
374
                    [$table, $meta['column']]
37 ✔
375
                );
37 ✔
376
            }
377

378
            return;
37 ✔
379
        }
380

381
        if ($platform instanceof SQLServerPlatform) {
58 ✔
382
            foreach (array_keys($identityTables) as $table) {
29 ✔
383
                // DBCC CHECKIDENT makes the *next* record use RESEED + 1, but only for a table that
384
                // was inserted into before: for a table that was never used, the first record uses
385
                // the reseed value itself, which would be 0. So we only reseed tables that have a
386
                // current identity value.
387
                $connection->executeStatement(
29 ✔
388
                    'DECLARE @table NVARCHAR(776) = ?;
29 ✔
389
                     IF EXISTS (
390
                         SELECT 1 FROM sys.identity_columns
391
                         WHERE object_id = OBJECT_ID(@table) AND last_value IS NOT NULL
392
                     )
393
                         DBCC CHECKIDENT (@table, RESEED, 0) WITH NO_INFOMSGS',
29 ✔
394
                    [$table]
29 ✔
395
                );
29 ✔
396
            }
397

398
            return;
29 ✔
399
        }
400

401
        if ($platform instanceof SQLitePlatform) {
29 ✔
402
            // SQLite stores the counters of all AUTOINCREMENT columns in this table, it only exists
403
            // when at least one such column is used
404
            $sequenceTableExists = (bool) $connection->fetchOne(
29 ✔
405
                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_sequence'"
29 ✔
406
            );
29 ✔
407
            if (!$sequenceTableExists) {
29 ✔
408
                return;
×
409
            }
410

411
            foreach ($identityTables as $meta) {
29 ✔
412
                // the counters are stored with the unquoted table name
413
                $connection->executeStatement(
29 ✔
414
                    'DELETE FROM sqlite_sequence WHERE name = ?',
29 ✔
415
                    [$meta['name']]
29 ✔
416
                );
29 ✔
417
            }
418
        }
419
    }
420

421
    /**
422
     * Returns all tables that have an identity / auto-increment column, in the order in which the
423
     * mapping defines them.
424
     *
425
     * @return array<string, array{name: string, column: string}>
426
     */
427
    protected static function getIdentityTables(
153 ✔
428
        EntityManagerInterface $em,
429
        AbstractPlatform $platform,
430
    ): array {
431
        if (null !== self::$identityTables) {
153 ✔
432
            return self::$identityTables;
152 ✔
433
        }
434

435
        $quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
6 ✔
436
        $tables = [];
6 ✔
437

438
        foreach ($em->getMetadataFactory()->getAllMetadata() as $meta) {
6 ✔
439
            if ($meta->isMappedSuperclass || $meta->isEmbeddedClass) {
6 ✔
440
                continue;
6 ✔
441
            }
442

443
            // Only the root class of a hierarchy owns the identity column: With SINGLE_TABLE the
444
            // children share the table of the root, with JOINED they have their own table, but its
445
            // primary key is a foreign key to the root and not auto-increment. The children inherit
446
            // generatorType = IDENTITY in both cases,
447
            // @see ClassMetadataFactory::inheritIdGeneratorMapping()
448
            if ($meta->name !== $meta->rootEntityName) {
6 ✔
449
                continue;
6 ✔
450
            }
451

452
            // the conditions under which the SchemaTool sets autoincrement=true
453
            $identifierFields = $meta->getIdentifierFieldNames();
6 ✔
454
            if (!$meta->isIdGeneratorIdentity() || 1 !== \count($identifierFields)) {
6 ✔
455
                continue;
6 ✔
456
            }
457

458
            // multiple entities can be mapped to the same table -> deduplicate
459
            $tables[$quoteStrategy->getTableName($meta, $platform)] = [
6 ✔
460
                'name'   => $meta->getTableName(),
6 ✔
461
                'column' => $meta->getColumnName($identifierFields[0]),
6 ✔
462
            ];
6 ✔
463
        }
464

465
        return self::$identityTables = $tables;
6 ✔
466
    }
467

UNCOV
468
    protected static function fixtureCleanup(): void
×
469
    {
470
        static::$fixtures = null;
×
471
    }
472
}
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