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

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