Passed
Pull Request — master (#1939)
by
unknown
02:40
created

Manager::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
ccs 0
cts 0
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace Phinx\Migration;
9
10
use DateTime;
11
use InvalidArgumentException;
12
use Phinx\Config\Config;
13
use Phinx\Config\ConfigInterface;
14
use Phinx\Config\NamespaceAwareInterface;
15
use Phinx\Console\Command\AbstractCommand;
16
use Phinx\Migration\Manager\Environment;
17
use Phinx\Seed\AbstractSeed;
18
use Phinx\Seed\SeedInterface;
19
use Phinx\Util\Util;
20
use Psr\Container\ContainerInterface;
21
use RuntimeException;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Output\OutputInterface;
24
25
class Manager
26
{
27
    public const BREAKPOINT_TOGGLE = 1;
28
    public const BREAKPOINT_SET = 2;
29
    public const BREAKPOINT_UNSET = 3;
30
31
    /**
32
     * @var \Phinx\Config\ConfigInterface
33
     */
34
    protected $config;
35
36
    /**
37
     * @var \Symfony\Component\Console\Input\InputInterface
38
     */
39
    protected $input;
40
41
    /**
42
     * @var \Symfony\Component\Console\Output\OutputInterface
43
     */
44
    protected $output;
45
46
    /**
47
     * @var \Phinx\Migration\Manager\Environment[]
48
     */
49
    protected $environments = [];
50
51
    /**
52
     * @var \Phinx\Migration\AbstractMigration[]|null
53
     */
54
    protected $migrations;
55
56
    /**
57
     * @var \Phinx\Seed\AbstractSeed[]|null
58
     */
59
    protected $seeds;
60
61
    /**
62
     * @var \Psr\Container\ContainerInterface
63
     */
64
    protected $container;
65
66
    /**
67
     * @param \Phinx\Config\ConfigInterface $config Configuration Object
68
     * @param \Symfony\Component\Console\Input\InputInterface $input Console Input
69
     * @param \Symfony\Component\Console\Output\OutputInterface $output Console Output
70
     */
71
    public function __construct(ConfigInterface $config, InputInterface $input, OutputInterface $output)
72
    {
73
        $this->setConfig($config);
74
        $this->setInput($input);
75
        $this->setOutput($output);
76
    }
77
78
    /**
79
     * Prints the specified environment's migration status.
80
     *
81
     * @param string $environment environment to print status of
82
     * @param string|null $format format to print status in (either text, json, or null)
83
     *
84
     * @throws \RuntimeException
85
     *
86
     * @return array array indicating if there are any missing or down migrations
87
     */
88
    public function printStatus($environment, $format = null)
89 432
    {
90
        $output = $this->getOutput();
91 432
        $hasDownMigration = false;
92 432
        $hasMissingMigration = false;
93 432
        $migrations = $this->getMigrations($environment);
94 432
        $migrationCount = 0;
95
        $missingCount = 0;
96
        $pendingMigrationCount = 0;
97
        $finalMigrations = [];
98
        $verbosity = $output->getVerbosity();
99
        if ($format === 'json') {
100
            $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
101
        }
102
        if (count($migrations)) {
103 22
            // rewrite using Symfony Table Helper as we already have this library
104
            // included and it will fix formatting issues (e.g drawing the lines)
105 22
            $output->writeln('');
106 22
107 22
            switch ($this->getConfig()->getVersionOrder()) {
108 22
                case Config::VERSION_ORDER_CREATION_TIME:
109 22
                    $migrationIdAndStartedHeader = "<info>[Migration ID]</info>  Started            ";
110 22
                    break;
111
                case Config::VERSION_ORDER_EXECUTION_TIME:
112
                    $migrationIdAndStartedHeader = "Migration ID    <info>[Started          ]</info>";
113 21
                    break;
114
                default:
115 21
                    throw new RuntimeException('Invalid version_order configuration option');
116 21
            }
117 19
118 19
            $output->writeln(" Status  $migrationIdAndStartedHeader  Finished             Migration Name ");
119 2
            $output->writeln('----------------------------------------------------------------------------------');
120 1
121 1
            $env = $this->getEnvironment($environment);
122 1
            $versions = $env->getVersionLog();
123 1
124 21
            $maxNameLength = $versions ? max(array_map(function ($version) {
125
                return strlen($version['migration_name']);
126 20
            }, $versions)) : 0;
127 20
128
            $missingVersions = array_diff_key($versions, $migrations);
129 20
            $missingCount = count($missingVersions);
130 20
131
            $hasMissingMigration = !empty($missingVersions);
132
133 17
            // get the migrations sorted in the same way as the versions
134 20
            /** @var \Phinx\Migration\AbstractMigration[] $sortedMigrations */
135
            $sortedMigrations = [];
136 20
137
            foreach ($versions as $versionCreationTime => $version) {
138 20
                if (isset($migrations[$versionCreationTime])) {
139
                    array_push($sortedMigrations, $migrations[$versionCreationTime]);
140
                    unset($migrations[$versionCreationTime]);
141 20
                }
142
            }
143 20
144 17
            if (empty($sortedMigrations) && !empty($missingVersions)) {
145 13
                // this means we have no up migrations, so we write all the missing versions already so they show up
146 13
                // before any possible down migration
147 13
                foreach ($missingVersions as $missingVersionCreationTime => $missingVersion) {
148 20
                    $this->printMissingVersion($missingVersion, $maxNameLength);
149
150 20
                    unset($missingVersions[$missingVersionCreationTime]);
151
                }
152
            }
153 4
154 4
            // any migration left in the migrations (ie. not unset when sorting the migrations by the version order) is
155
            // a migration that is down, so we add them to the end of the sorted migrations list
156 4
            if (!empty($migrations)) {
157 4
                $sortedMigrations = array_merge($sortedMigrations, $migrations);
158 4
            }
159
160
            $migrationCount = count($sortedMigrations);
161
            foreach ($sortedMigrations as $migration) {
162 20
                $version = array_key_exists($migration->getVersion(), $versions) ? $versions[$migration->getVersion()] : false;
163 13
                if ($version) {
164 13
                    // check if there are missing versions before this version
165
                    foreach ($missingVersions as $missingVersionCreationTime => $missingVersion) {
166 20
                        if ($this->getConfig()->isVersionOrderCreationTime()) {
167 20
                            if ($missingVersion['version'] > $version['version']) {
168 20
                                break;
169
                            }
170 13
                        } else {
171 6
                            if ($missingVersion['start_time'] > $version['start_time']) {
172 6
                                break;
173 4
                            } elseif (
174
                                $missingVersion['start_time'] == $version['start_time'] &&
175 3
                                $missingVersion['version'] > $version['version']
176
                            ) {
177
                                break;
178
                            }
179
                        }
180
181
                        $this->printMissingVersion($missingVersion, $maxNameLength);
182
183
                        unset($missingVersions[$missingVersionCreationTime]);
184 3
                    }
185
186 3
                    $status = '     <info>up</info> ';
187 13
                } else {
188
                    $pendingMigrationCount++;
189 13
                    $hasDownMigration = true;
190 13
                    $status = '   <error>down</error> ';
191 13
                }
192 13
                $maxNameLength = max($maxNameLength, strlen($migration->getName()));
193
194 20
                $output->writeln(sprintf(
195
                    '%s %14.0f  %19s  %19s  <comment>%s</comment>',
196 20
                    $status,
197 20
                    $migration->getVersion(),
198 20
                    ($version ? $version['start_time'] : ''),
199 20
                    ($version ? $version['end_time'] : ''),
200 20
                    $migration->getName()
201 20
                ));
202 20
203 20
                if ($version && $version['breakpoint']) {
204
                    $output->writeln('         <error>BREAKPOINT SET</error>');
205 20
                }
206 1
207 1
                $finalMigrations[] = ['migration_status' => trim(strip_tags($status)), 'migration_id' => sprintf('%14.0f', $migration->getVersion()), 'migration_name' => $migration->getName()];
208
                unset($versions[$migration->getVersion()]);
209 20
            }
210 20
211 20
            // and finally add any possibly-remaining missing migrations
212
            foreach ($missingVersions as $missingVersionCreationTime => $missingVersion) {
213
                $this->printMissingVersion($missingVersion, $maxNameLength);
214 20
215 4
                unset($missingVersions[$missingVersionCreationTime]);
216
            }
217 4
        } else {
218 20
            // there are no migrations
219 20
            $output->writeln('');
220
            $output->writeln('There are no available migrations. Try creating one using the <info>create</info> command.');
221 1
        }
222 1
223
        // write an empty line
224
        $output->writeln('');
225
226 21
        if ($format !== null) {
227 21
            switch ($format) {
228
                case AbstractCommand::FORMAT_JSON:
229
                    $output->setVerbosity($verbosity);
230
                    $output->writeln(json_encode(
231
                        [
232
                            'pending_count' => $pendingMigrationCount,
233
                            'missing_count' => $missingCount,
234
                            'total_count' => $migrationCount + $missingCount,
235
                            'migrations' => $finalMigrations,
236
                        ]
237
                    ));
238
                    break;
239
                default:
240
                    $output->writeln('<info>Unsupported format: ' . $format . '</info>');
241
            }
242 21
        }
243 10
244 11
        return [
245 6
            'hasMissingMigration' => $hasMissingMigration,
246
            'hasDownMigration' => $hasDownMigration,
247 5
        ];
248
    }
249
250
    /**
251
     * Print Missing Version
252
     *
253
     * @param array $version The missing version to print (in the format returned by Environment.getVersionLog).
254
     * @param int $maxNameLength The maximum migration name length.
255
     *
256
     * @return void
257 10
     */
258
    protected function printMissingVersion($version, $maxNameLength)
259 10
    {
260 10
        $this->getOutput()->writeln(sprintf(
261 10
            '     <error>up</error>  %14.0f  %19s  %19s  <comment>%s</comment>  <error>** MISSING MIGRATION FILE **</error>',
262 10
            $version['version'],
263 10
            $version['start_time'],
264 10
            $version['end_time'],
265 10
            str_pad($version['migration_name'], $maxNameLength, ' ')
266
        ));
267 10
268 1
        if ($version && $version['breakpoint']) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $version of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
269 1
            $this->getOutput()->writeln('         <error>BREAKPOINT SET</error>');
270 10
        }
271
    }
272
273
    /**
274
     * Migrate to the version of the database on a given date.
275
     *
276
     * @param string $environment Environment
277
     * @param \DateTime $dateTime Date to migrate to
278
     * @param bool $fake flag that if true, we just record running the migration, but not actually do the
279
     *                               migration
280 4
     *
281
     * @return void
282 4
     */
283 4
    public function migrateToDateTime($environment, DateTime $dateTime, $fake = false)
284
    {
285
        $versions = array_keys($this->getMigrations($environment));
286 4
        $dateString = $dateTime->format('YmdHis');
287 4
288
        $outstandingMigrations = array_filter($versions, function ($version) use ($dateString) {
289 4
            return $version <= $dateString;
290 3
        });
291 3
292 3
        if (count($outstandingMigrations) > 0) {
293 3
            $migration = max($outstandingMigrations);
294 4
            $this->getOutput()->writeln('Migrating to version ' . $migration);
295
            $this->migrate($environment, $migration, $fake);
296
        }
297
    }
298
299
    /**
300
     * Migrate an environment to the specified version.
301
     *
302
     * @param string $environment Environment
303 8
     * @param int|null $version version to migrate to
304
     * @param bool $fake flag that if true, we just record running the migration, but not actually do the migration
305 8
     *
306 8
     * @return void
307 8
     */
308 8
    public function migrate($environment, $version = null, $fake = false)
309
    {
310 8
        $migrations = $this->getMigrations($environment);
311
        $env = $this->getEnvironment($environment);
312
        $versions = $env->getVersions();
313
        $current = $env->getCurrentVersion();
314 8
315 5
        if (empty($versions) && empty($migrations)) {
316 5
            return;
317 3
        }
318
319
        if ($version === null) {
320
            $version = max(array_merge($versions, array_keys($migrations)));
321
        } else {
322
            if ($version != 0 && !isset($migrations[$version])) {
323
                $this->output->writeln(sprintf(
324
                    '<comment>warning</comment> %s is not a valid version',
325
                    $version
326
                ));
327 8
328
                return;
329 8
            }
330
        }
331
332
        // are we migrating up or down?
333
        $direction = $version > $current ? MigrationInterface::UP : MigrationInterface::DOWN;
334
335
        if ($direction === MigrationInterface::DOWN) {
336
            // run downs first
337
            krsort($migrations);
338
            foreach ($migrations as $migration) {
339
                if ($migration->getVersion() <= $version) {
340
                    break;
341
                }
342
343 8
                if (in_array($migration->getVersion(), $versions)) {
344 8
                    $this->executeMigration($environment, $migration, MigrationInterface::DOWN, $fake);
345 8
                }
346 2
            }
347
        }
348
349 8
        ksort($migrations);
350 5
        foreach ($migrations as $migration) {
351 5
            if ($migration->getVersion() > $version) {
352 8
                break;
353 8
            }
354
355
            if (!in_array($migration->getVersion(), $versions)) {
356
                $this->executeMigration($environment, $migration, MigrationInterface::UP, $fake);
357
            }
358
        }
359
    }
360
361
    /**
362
     * Execute a migration against the specified environment.
363 119
     *
364
     * @param string $name Environment Name
365 119
     * @param \Phinx\Migration\MigrationInterface $migration Migration
366 119
     * @param string $direction Direction
367
     * @param bool $fake flag that if true, we just record running the migration, but not actually do the migration
368 119
     *
369 119
     * @return void
370 119
     */
371
    public function executeMigration($name, MigrationInterface $migration, $direction = MigrationInterface::UP, $fake = false)
372
    {
373 119
        $this->getOutput()->writeln('');
374 119
375 119
        // Skip the migration if it should not be executed
376
        if (!$migration->shouldExecute()) {
377 119
            $this->printMigrationStatus($migration, 'skipped');
378
379 119
            return;
380 119
        }
381 119
382 119
        $this->printMigrationStatus($migration, ($direction === MigrationInterface::UP ? 'migrating' : 'reverting'));
383 119
384
        // Execute the migration and log the time elapsed.
385
        $start = microtime(true);
386
        $this->getEnvironment($name)->executeMigration($migration, $direction, $fake);
387
        $end = microtime(true);
388
389
        $this->printMigrationStatus(
390
            $migration,
391
            ($direction === MigrationInterface::UP ? 'migrated' : 'reverted'),
392 6
            sprintf('%.4fs', $end - $start)
393
        );
394 6
    }
395 6
396
    /**
397 6
     * Execute a seeder against the specified environment.
398 6
     *
399 6
     * @param string $name Environment Name
400
     * @param \Phinx\Seed\SeedInterface $seed Seed
401
     *
402 6
     * @return void
403 6
     */
404 6
    public function executeSeed($name, SeedInterface $seed)
405
    {
406 6
        $this->getOutput()->writeln('');
407
        $this->printSeedStatus($seed, 'seeding');
408 6
409 6
        // Execute the seeder and log the time elapsed.
410 6
        $start = microtime(true);
411 6
        $this->getEnvironment($name)->executeSeed($seed);
412 6
        $end = microtime(true);
413
414
        $this->printSeedStatus(
415
            $seed,
416
            'seeded',
417
            sprintf('%.4fs', $end - $start)
418
        );
419
    }
420
421
    /**
422
     * Print Migration Status
423 349
     *
424
     * @param \Phinx\Migration\MigrationInterface $migration Migration
425
     * @param string $status Status of the migration
426 349
     * @param string|null $duration Duration the migration took the be executed
427
     *
428
     * @return void
429 349
     */
430
    protected function printMigrationStatus(MigrationInterface $migration, $status, $duration = null)
431
    {
432 349
        $this->printStatusOutput(
433
            $migration->getVersion() . ' ' . $migration->getName(),
434 349
            $status,
435
            $duration
436
        );
437 349
    }
438 48
439 48
    /**
440 48
     * Print Seed Status
441
     *
442 349
     * @param \Phinx\Seed\SeedInterface $seed Seed
443 349
     * @param string $status Status of the seed
444 349
     * @param string|null $duration Duration the seed took the be executed
445
     *
446
     * @return void
447 47
     */
448
    protected function printSeedStatus(SeedInterface $seed, $status, $duration = null)
449 349
    {
450
        $this->printStatusOutput(
451 349
            $seed->getName(),
452 23
            $status,
453 349
            $duration
454
        );
455 20
    }
456 20
457 20
    /**
458 20
     * Print Status in Output
459
     *
460
     * @param string $name Name of the migration or seed
461 20
     * @param string $status Status of the migration or seed
462 20
     * @param string|null $duration Duration the migration or seed took the be executed
463 20
     *
464
     * @return void
465
     */
466
    protected function printStatusOutput($name, $status, $duration = null)
467 20
    {
468
        $this->getOutput()->writeln(
469
            ' ==' .
470 349
            ' <info>' . $name . ':</info>' .
471 349
            ' <comment>' . $status . ' ' . $duration . '</comment>'
472 53
        );
473 53
    }
474
475
    /**
476
     * Rollback an environment to the specified version.
477 296
     *
478
     * @param string $environment Environment
479 94
     * @param int|string|null $target Target
480 94
     * @param bool $force Force
481 94
     * @param bool $targetMustMatchVersion Target must match version
482
     * @param bool $fake Flag that if true, we just record running the migration, but not actually do the migration
483
     *
484 296
     * @return void
485 46
     */
486 46
    public function rollback($environment, $target = null, $force = false, $targetMustMatchVersion = true, $fake = false)
487
    {
488
        // note that the migrations are indexed by name (aka creation time) in ascending order
489
        $migrations = $this->getMigrations($environment);
490 250
491
        // note that the version log are also indexed by name with the proper ascending order according to the version order
492 250
        $executedVersions = $this->getEnvironment($environment)->getVersionLog();
493 250
494 70
        // get a list of migrations sorted in the opposite way of the executed versions
495
        $sortedMigrations = [];
496
497 250
        foreach ($executedVersions as $versionCreationTime => &$executedVersion) {
498 250
            // if we have a date (ie. the target must not match a version) and we are sorting by execution time, we
499
            // convert the version start time so we can compare directly with the target date
500 250
            if (!$this->getConfig()->isVersionOrderCreationTime() && !$targetMustMatchVersion) {
501 96
                $dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $executedVersion['start_time']);
502 96
                $executedVersion['start_time'] = $dateTime->format('YmdHis');
503 42
            }
504
505 68
            if (isset($migrations[$versionCreationTime])) {
506
                array_unshift($sortedMigrations, $migrations[$versionCreationTime]);
507 222
            } else {
508 121
                // this means the version is missing so we unset it so that we don't consider it when rolling back
509 121
                // migrations (or choosing the last up version as target)
510
                unset($executedVersions[$versionCreationTime]);
511 117
            }
512 117
        }
513 117
514 250
        if ($target === 'all' || $target === '0') {
515
            $target = 0;
516 250
        } elseif (!is_numeric($target) && $target !== null) { // try to find a target version based on name
517 133
            // search through the migrations using the name
518 133
            $migrationNames = array_map(function ($item) {
519 250
                return $item['migration_name'];
520
            }, $executedVersions);
521
            $found = array_search($target, $migrationNames, true);
522
523
            // check on was found
524
            if ($found !== false) {
525
                $target = (string)$found;
526
            } else {
527
                $this->getOutput()->writeln("<error>No migration found with name ($target)</error>");
528 9
529
                return;
530 9
            }
531
        }
532 9
533
        // Check we have at least 1 migration to revert
534 3
        $executedVersionCreationTimes = array_keys($executedVersions);
535 3
        if (empty($executedVersionCreationTimes) || $target == end($executedVersionCreationTimes)) {
536 3
            $this->getOutput()->writeln('<error>No migrations to rollback</error>');
537 3
538 3
            return;
539 3
        }
540
541 6
        // If no target was supplied, revert the last migration
542 3
        if ($target === null) {
543 3
            // Get the migration before the last run migration
544 3
            $prev = count($executedVersionCreationTimes) - 2;
545
            $target = $prev >= 0 ? $executedVersionCreationTimes[$prev] : 0;
546
        }
547 6
548
        // If the target must match a version, check the target version exists
549
        if ($targetMustMatchVersion && $target !== 0 && !isset($migrations[$target])) {
550
            $this->getOutput()->writeln("<error>Target version ($target) not found</error>");
551
552
            return;
553
        }
554
555 381
        // Rollback all versions until we find the wanted rollback target
556
        $rollbacked = false;
557 381
558 381
        foreach ($sortedMigrations as $migration) {
559
            if ($targetMustMatchVersion && $migration->getVersion() == $target) {
560
                break;
561
            }
562
563
            if (in_array($migration->getVersion(), $executedVersionCreationTimes)) {
564
                $executedVersion = $executedVersions[$migration->getVersion()];
565
566
                if (!$targetMustMatchVersion) {
567
                    if (
568 382
                        ($this->getConfig()->isVersionOrderCreationTime() && $executedVersion['version'] <= $target) ||
569
                        (!$this->getConfig()->isVersionOrderCreationTime() && $executedVersion['start_time'] <= $target)
570 382
                    ) {
571 380
                        break;
572
                    }
573
                }
574
575 7
                if ($executedVersion['breakpoint'] != 0 && !$force) {
576 1
                    $this->getOutput()->writeln('<error>Breakpoint reached. Further rollbacks inhibited.</error>');
577 1
                    break;
578
                }
579 1
                $this->executeMigration($environment, $migration, MigrationInterface::DOWN, $fake);
580
                $rollbacked = true;
581
            }
582
        }
583 6
584 6
        if (!$rollbacked) {
0 ignored issues
show
introduced by
The condition $rollbacked is always false.
Loading history...
585
            $this->getOutput()->writeln('<error>No migrations to rollback</error>');
586 6
        }
587 6
    }
588 6
589 6
    /**
590
     * Run database seeders against an environment.
591 6
     *
592
     * @param string $environment Environment
593
     * @param string|null $seed Seeder
594
     *
595
     * @throws \InvalidArgumentException
596
     *
597
     * @return void
598
     */
599
    public function seed($environment, $seed = null)
600 400
    {
601
        $seeds = $this->getSeeds();
602 400
603 400
        if ($seed === null) {
604
            // run all seeders
605
            foreach ($seeds as $seeder) {
606
                if (array_key_exists($seeder->getName(), $seeds)) {
607
                    $this->executeSeed($environment, $seeder);
608
                }
609
            }
610
        } else {
611 393
            // run only one seeder
612
            if (array_key_exists($seed, $seeds)) {
613 393
                $this->executeSeed($environment, $seeds[$seed]);
614
            } else {
615
                throw new InvalidArgumentException(sprintf('The seed class "%s" does not exist', $seed));
616
            }
617
        }
618
    }
619
620
    /**
621
     * Sets the environments.
622 400
     *
623
     * @param \Phinx\Migration\Manager\Environment[] $environments Environments
624 400
     *
625 400
     * @return $this
626
     */
627
    public function setEnvironments($environments = [])
628
    {
629
        $this->environments = $environments;
630
631
        return $this;
632
    }
633 395
634
    /**
635 395
     * Gets the manager class for the given environment.
636
     *
637
     * @param string $name Environment Name
638
     *
639
     * @throws \InvalidArgumentException
640
     *
641
     * @return \Phinx\Migration\Manager\Environment
642
     */
643
    public function getEnvironment($name)
644 379
    {
645
        if (isset($this->environments[$name])) {
646 379
            return $this->environments[$name];
647 379
        }
648
649
        // check the environment exists
650
        if (!$this->getConfig()->hasEnvironment($name)) {
651
            throw new InvalidArgumentException(sprintf(
652
                'The environment "%s" does not exist',
653
                $name
654
            ));
655
        }
656
657 388
        // create an environment instance and cache it
658
        $envOptions = $this->getConfig()->getEnvironment($name);
659 388
        $envOptions['version_order'] = $this->getConfig()->getVersionOrder();
660 388
        $envOptions['data_domain'] = $this->getConfig()->getDataDomain();
661
662
        $environment = new Environment($name, $envOptions);
663 388
        $this->environments[$name] = $environment;
664
        $environment->setInput($this->getInput());
665 388
        $environment->setOutput($this->getOutput());
666
667 388
        return $environment;
668 387
    }
669 387
670
    /**
671 387
     * Sets the user defined PSR-11 container
672 3
     *
673
     * @param \Psr\Container\ContainerInterface $container Container
674
     *
675 387
     * @return void
676 387
     */
677
    public function setContainer(ContainerInterface $container)
678
    {
679 387
        $this->container = $container;
680
    }
681 387
682 2
    /**
683 2
     * Sets the console input.
684 2
     *
685 2
     * @param \Symfony\Component\Console\Input\InputInterface $input Input
686 2
     *
687
     * @return $this
688
     */
689 387
    public function setInput(InputInterface $input)
690
    {
691
        $this->input = $input;
692
693 387
        return $this;
694 387
    }
695 2
696 2
    /**
697 2
     * Gets the console input.
698
     *
699 2
     * @return \Symfony\Component\Console\Input\InputInterface
700
     */
701
    public function getInput()
702
    {
703 385
        return $this->input;
704
    }
705 385
706 2
    /**
707 2
     * Sets the console output.
708 2
     *
709
     * @param \Symfony\Component\Console\Output\OutputInterface $output Output
710 2
     *
711
     * @return $this
712
     */
713 383
    public function setOutput(OutputInterface $output)
714 383
    {
715 384
        $this->output = $output;
716
717 379
        return $this;
718 379
    }
719 379
720
    /**
721 379
     * Gets the console output.
722
     *
723
     * @return \Symfony\Component\Console\Output\OutputInterface
724
     */
725
    public function getOutput()
726
    {
727
        return $this->output;
728
    }
729 388
730
    /**
731 388
     * Sets the database migrations.
732 388
     *
733 388
     * @param \Phinx\Migration\AbstractMigration[] $migrations Migrations
734
     *
735 388
     * @return $this
736 388
     */
737 388
    public function setMigrations(array $migrations)
738 388
    {
739 388
        $this->migrations = $migrations;
740 388
741
        return $this;
742 388
    }
743
744
    /**
745
     * Gets an array of the database migrations, indexed by migration name (aka creation time) and sorted in ascending
746
     * order
747
     *
748
     * @param string $environment Environment
749
     *
750
     * @throws \InvalidArgumentException
751 11
     *
752
     * @return \Phinx\Migration\AbstractMigration[]
753 11
     */
754 11
    public function getMigrations($environment)
755
    {
756
        if ($this->migrations === null) {
757
            $phpFiles = $this->getMigrationFiles();
758
759
            if ($this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
760
                $this->getOutput()->writeln('Migration file');
761
                $this->getOutput()->writeln(
762
                    array_map(
763 11
                        function ($phpFile) {
764
                            return "    <info>{$phpFile}</info>";
765 11
                        },
766 11
                        $phpFiles
767
                    )
768
                );
769 11
            }
770
771 11
            // filter the files to only get the ones that match our naming scheme
772
            $fileNames = [];
773 11
            /** @var \Phinx\Migration\AbstractMigration[] $versions */
774 11
            $versions = [];
775 11
776 11
            foreach ($phpFiles as $filePath) {
777
                if (Util::isValidMigrationFileName(basename($filePath))) {
778
                    if ($this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
779 11
                        $this->getOutput()->writeln("Valid migration file <info>{$filePath}</info>.");
780 11
                    }
781
782
                    $version = Util::getVersionFromFileName(basename($filePath));
783
784 11
                    if (isset($versions[$version])) {
785 11
                        throw new InvalidArgumentException(sprintf('Duplicate migration - "%s" has the same version as "%s"', $filePath, $versions[$version]->getVersion()));
786
                    }
787
788
                    $config = $this->getConfig();
789
                    $namespace = $config instanceof NamespaceAwareInterface ? $config->getMigrationNamespaceByPath(dirname($filePath)) : null;
790
791
                    // convert the filename to a class name
792
                    $class = ($namespace === null ? '' : $namespace . '\\') . Util::mapFileNameToClassName(basename($filePath));
793
794 11
                    if (isset($fileNames[$class])) {
795
                        throw new InvalidArgumentException(sprintf(
796 11
                            'Migration "%s" has the same name as "%s"',
797
                            basename($filePath),
798
                            $fileNames[$class]
799
                        ));
800
                    }
801
802
                    $fileNames[$class] = basename($filePath);
803
804 11
                    if ($this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
805 11
                        $this->getOutput()->writeln("Loading class <info>$class</info> from <info>$filePath</info>.");
806 11
                    }
807
808 11
                    // load the migration file
809 11
                    $orig_display_errors_setting = ini_get('display_errors');
810 11
                    ini_set('display_errors', 'On');
811
                    /** @noinspection PhpIncludeInspection */
812 11
                    require_once $filePath;
813
                    ini_set('display_errors', $orig_display_errors_setting);
814
                    if (!class_exists($class)) {
815
                        throw new InvalidArgumentException(sprintf(
816
                            'Could not find class "%s" in file "%s"',
817
                            $class,
818
                            $filePath
819
                        ));
820 11
                    }
821
822 11
                    if ($this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
823 11
                        $this->getOutput()->writeln("Running <info>$class</info>.");
824 11
                    }
825
826 11
                    // instantiate it
827 11
                    $migration = new $class($environment, $version, $this->getInput(), $this->getOutput());
828 11
829 11
                    if (!($migration instanceof AbstractMigration)) {
830 11
                        throw new InvalidArgumentException(sprintf(
831 11
                            'The class "%s" in file "%s" must extend \Phinx\Migration\AbstractMigration',
832
                            $class,
833 11
                            $filePath
834
                        ));
835
                    }
836
837
                    $versions[$version] = $migration;
838
                } else {
839
                    if ($this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
840
                        $this->getOutput()->writeln("Invalid migration file <error>{$filePath}</error>.");
841
                    }
842 400
                }
843
            }
844 400
845 400
            ksort($versions);
846
            $this->setMigrations($versions);
847
        }
848
849
        return $this->migrations;
850
    }
851
852
    /**
853 399
     * Returns a list of migration files found in the provided migration paths.
854
     *
855 399
     * @return string[]
856
     */
857
    protected function getMigrationFiles()
858
    {
859
        return Util::getFiles($this->getConfig()->getMigrationPaths());
860
    }
861
862
    /**
863
     * Sets the database seeders.
864
     *
865 2
     * @param \Phinx\Seed\AbstractSeed[] $seeds Seeders
866
     *
867 2
     * @return $this
868 2
     */
869 2
    public function setSeeds(array $seeds)
870 2
    {
871
        $this->seeds = $seeds;
872 2
873
        return $this;
874
    }
875
876 2
    /**
877 1
     * Get seed dependencies instances from seed dependency array
878 1
     *
879 1
     * @param \Phinx\Seed\AbstractSeed $seed Seed
880
     *
881 2
     * @return \Phinx\Seed\AbstractSeed[]
882 1
     */
883 1
    protected function getSeedDependenciesInstances(AbstractSeed $seed)
884
    {
885 1
        $dependenciesInstances = [];
886 1
        $dependencies = $seed->getDependencies();
887
        if (!empty($dependencies)) {
888
            foreach ($dependencies as $dependency) {
889 1
                foreach ($this->seeds as $seed) {
890
                    if (get_class($seed) === $dependency) {
891 1
                        $dependenciesInstances[get_class($seed)] = $seed;
892
                    }
893 1
                }
894 1
            }
895 1
        }
896 1
897 1
        return $dependenciesInstances;
898 1
    }
899
900
    /**
901
     * Order seeds by dependencies
902
     *
903
     * @param \Phinx\Seed\AbstractSeed[] $seeds Seeds
904
     *
905
     * @return \Phinx\Seed\AbstractSeed[]
906 1
     */
907
    protected function orderSeedsByDependencies(array $seeds)
908 1
    {
909 1
        $orderedSeeds = [];
910 1
        foreach ($seeds as $seed) {
911 1
            $key = get_class($seed);
912 1
            $dependencies = $this->getSeedDependenciesInstances($seed);
913
            if (!empty($dependencies)) {
914
                $orderedSeeds[$key] = $seed;
915
                $orderedSeeds = array_merge($this->orderSeedsByDependencies($dependencies), $orderedSeeds);
916
            } else {
917
                $orderedSeeds[$key] = $seed;
918
            }
919
        }
920
921
        return $orderedSeeds;
922
    }
923
924
    /**
925
     * Gets an array of database seeders.
926
     *
927
     * @throws \InvalidArgumentException
928
     *
929
     * @return \Phinx\Seed\AbstractSeed[]
930
     */
931
    public function getSeeds()
932
    {
933
        if ($this->seeds === null) {
934
            $phpFiles = $this->getSeedFiles();
935
936
            // filter the files to only get the ones that match our naming scheme
937
            $fileNames = [];
938
            /** @var \Phinx\Seed\AbstractSeed[] $seeds */
939
            $seeds = [];
940
941
            foreach ($phpFiles as $filePath) {
942
                if (Util::isValidSeedFileName(basename($filePath))) {
943
                    $config = $this->getConfig();
944
                    $namespace = $config instanceof NamespaceAwareInterface ? $config->getSeedNamespaceByPath(dirname($filePath)) : null;
945
946
                    // convert the filename to a class name
947
                    $class = ($namespace === null ? '' : $namespace . '\\') . pathinfo($filePath, PATHINFO_FILENAME);
948
                    $fileNames[$class] = basename($filePath);
949
950
                    // load the seed file
951
                    /** @noinspection PhpIncludeInspection */
952
                    require_once $filePath;
953
                    if (!class_exists($class)) {
954
                        throw new InvalidArgumentException(sprintf(
955
                            'Could not find class "%s" in file "%s"',
956
                            $class,
957
                            $filePath
958
                        ));
959
                    }
960
961
                    // instantiate it
962
                    /** @var \Phinx\Seed\AbstractSeed $seed */
963
                    if ($this->container !== null) {
964
                        $seed = $this->container->get($class);
965
                    } else {
966
                        $seed = new $class();
967
                    }
968
                    $input = $this->getInput();
969
                    if ($input !== null) {
970
                        $seed->setInput($input);
971
                    }
972
                    $output = $this->getOutput();
973
                    if ($output !== null) {
974
                        $seed->setOutput($output);
975
                    }
976
977
                    if (!($seed instanceof AbstractSeed)) {
978
                        throw new InvalidArgumentException(sprintf(
979
                            'The class "%s" in file "%s" must extend \Phinx\Seed\AbstractSeed',
980
                            $class,
981
                            $filePath
982
                        ));
983
                    }
984
985
                    $seeds[$class] = $seed;
986
                }
987
            }
988
989
            ksort($seeds);
990
            $this->setSeeds($seeds);
991
        }
992
993
        $this->seeds = $this->orderSeedsByDependencies($this->seeds);
994
995
        return $this->seeds;
996
    }
997
998
    /**
999
     * Returns a list of seed files found in the provided seed paths.
1000
     *
1001
     * @return string[]
1002
     */
1003
    protected function getSeedFiles()
1004
    {
1005
        return Util::getFiles($this->getConfig()->getSeedPaths());
1006
    }
1007
1008
    /**
1009
     * Sets the config.
1010
     *
1011
     * @param \Phinx\Config\ConfigInterface $config Configuration Object
1012
     *
1013
     * @return $this
1014
     */
1015
    public function setConfig(ConfigInterface $config)
1016
    {
1017
        $this->config = $config;
1018
1019
        return $this;
1020
    }
1021
1022
    /**
1023
     * Gets the config.
1024
     *
1025
     * @return \Phinx\Config\ConfigInterface
1026
     */
1027
    public function getConfig()
1028
    {
1029
        return $this->config;
1030
    }
1031
1032
    /**
1033
     * Toggles the breakpoint for a specific version.
1034
     *
1035
     * @param string $environment Environment name
1036
     * @param int|null $version Version
1037
     *
1038
     * @return void
1039
     */
1040
    public function toggleBreakpoint($environment, $version)
1041
    {
1042
        $this->markBreakpoint($environment, $version, self::BREAKPOINT_TOGGLE);
1043
    }
1044
1045
    /**
1046
     * Updates the breakpoint for a specific version.
1047
     *
1048
     * @param string $environment The required environment
1049
     * @param int|null $version The version of the target migration
1050
     * @param int $mark The state of the breakpoint as defined by self::BREAKPOINT_xxxx constants.
1051
     *
1052
     * @return void
1053
     */
1054
    protected function markBreakpoint($environment, $version, $mark)
1055
    {
1056
        $migrations = $this->getMigrations($environment);
1057
        $this->getMigrations($environment);
1058
        $env = $this->getEnvironment($environment);
1059
        $versions = $env->getVersionLog();
1060
1061
        if (empty($versions) || empty($migrations)) {
1062
            return;
1063
        }
1064
1065
        if ($version === null) {
1066
            $lastVersion = end($versions);
1067
            $version = $lastVersion['version'];
1068
        }
1069
1070
        if ($version != 0 && (!isset($versions[$version]) || !isset($migrations[$version]))) {
1071
            $this->output->writeln(sprintf(
1072
                '<comment>warning</comment> %s is not a valid version',
1073
                $version
1074
            ));
1075
1076
            return;
1077
        }
1078
1079
        switch ($mark) {
1080
            case self::BREAKPOINT_TOGGLE:
1081
                $env->getAdapter()->toggleBreakpoint($migrations[$version]);
1082
                break;
1083
            case self::BREAKPOINT_SET:
1084
                if ($versions[$version]['breakpoint'] == 0) {
1085
                    $env->getAdapter()->setBreakpoint($migrations[$version]);
1086
                }
1087
                break;
1088
            case self::BREAKPOINT_UNSET:
1089
                if ($versions[$version]['breakpoint'] == 1) {
1090
                    $env->getAdapter()->unsetBreakpoint($migrations[$version]);
1091
                }
1092
                break;
1093
        }
1094
1095
        $versions = $env->getVersionLog();
1096
1097
        $this->getOutput()->writeln(
1098
            ' Breakpoint ' . ($versions[$version]['breakpoint'] ? 'set' : 'cleared') .
1099
            ' for <info>' . $version . '</info>' .
1100
            ' <comment>' . $migrations[$version]->getName() . '</comment>'
1101
        );
1102
    }
1103
1104
    /**
1105
     * Remove all breakpoints
1106
     *
1107
     * @param string $environment The required environment
1108
     *
1109
     * @return void
1110
     */
1111
    public function removeBreakpoints($environment)
1112
    {
1113
        $this->getOutput()->writeln(sprintf(
1114
            ' %d breakpoints cleared.',
1115
            $this->getEnvironment($environment)->getAdapter()->resetAllBreakpoints()
1116
        ));
1117
    }
1118
1119
    /**
1120
     * Set the breakpoint for a specific version.
1121
     *
1122
     * @param string $environment The required environment
1123
     * @param int|null $version The version of the target migration
1124
     *
1125
     * @return void
1126
     */
1127
    public function setBreakpoint($environment, $version)
1128
    {
1129
        $this->markBreakpoint($environment, $version, self::BREAKPOINT_SET);
1130
    }
1131
1132
    /**
1133
     * Unset the breakpoint for a specific version.
1134
     *
1135
     * @param string $environment The required environment
1136
     * @param int|null $version The version of the target migration
1137
     *
1138
     * @return void
1139
     */
1140
    public function unsetBreakpoint($environment, $version)
1141
    {
1142
        $this->markBreakpoint($environment, $version, self::BREAKPOINT_UNSET);
1143
    }
1144
}
1145