-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathManager.php
More file actions
1186 lines (1016 loc) · 37.6 KB
/
Manager.php
File metadata and controls
1186 lines (1016 loc) · 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Migrations\Migration;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use DateTime;
use Exception;
use InvalidArgumentException;
use Migrations\Config\ConfigInterface;
use Migrations\MigrationInterface;
use Migrations\SeedInterface;
use Migrations\Shim\MigrationAdapter;
use Migrations\Shim\SeedAdapter;
use Migrations\Util\Util;
use Phinx\Migration\MigrationInterface as PhinxMigrationInterface;
use Phinx\Seed\SeedInterface as PhinxSeedInterface;
use Psr\Container\ContainerInterface;
use RuntimeException;
class Manager
{
public const BREAKPOINT_TOGGLE = 1;
public const BREAKPOINT_SET = 2;
public const BREAKPOINT_UNSET = 3;
/**
* @var \Migrations\Config\ConfigInterface
*/
protected ConfigInterface $config;
/**
* @var \Cake\Console\ConsoleIo
*/
protected ConsoleIo $io;
/**
* @var \Migrations\Migration\Environment|null
*/
protected ?Environment $environment;
/**
* @var \Migrations\MigrationInterface[]|null
*/
protected ?array $migrations = null;
/**
* @var \Migrations\SeedInterface[]|null
*/
protected ?array $seeds = null;
/**
* @var \Psr\Container\ContainerInterface
*/
protected ContainerInterface $container;
/**
* @param \Migrations\Config\ConfigInterface $config Configuration Object
* @param \Cake\Console\ConsoleIo $io Console input/output
*/
public function __construct(ConfigInterface $config, ConsoleIo $io)
{
$this->setConfig($config);
$this->setIo($io);
}
/**
* Prints the specified environment's migration status.
*
* @param string|null $format format to print status in (either text, json, or null)
* @throws \RuntimeException
* @return array array indicating if there are any missing or down migrations
*/
public function printStatus(?string $format = null): array
{
$migrations = [];
$isJson = $format === 'json';
$defaultMigrations = $this->getMigrations();
if ($defaultMigrations) {
$env = $this->getEnvironment();
$versions = $env->getVersionLog();
foreach ($defaultMigrations as $migration) {
if (array_key_exists($migration->getVersion(), $versions)) {
$status = 'up';
unset($versions[$migration->getVersion()]);
} else {
$status = 'down';
}
$version = $migration->getVersion();
$migrationParams = [
'status' => $status,
'id' => $migration->getVersion(),
'name' => $migration->getName(),
];
$migrations[$version] = $migrationParams;
}
foreach ($versions as $missing) {
$version = $missing['version'];
$migrationParams = [
'status' => 'up',
'id' => $version,
'name' => $missing['migration_name'],
];
if (!$isJson) {
$migrationParams = [
'missing' => true,
] + $migrationParams;
}
$migrations[$version] = $migrationParams;
}
}
ksort($migrations);
return array_values($migrations);
}
/**
* Migrate to the version of the database on a given date.
*
* @param \DateTime $dateTime Date to migrate to
* @param bool $fake flag that if true, we just record running the migration, but not actually do the
* migration
* @return void
*/
public function migrateToDateTime(DateTime $dateTime, bool $fake = false): void
{
/** @var array<int> $versions */
$versions = array_keys($this->getMigrations());
$dateString = $dateTime->format('Ymdhis');
$versionToMigrate = null;
foreach ($versions as $version) {
if ($dateString > $version) {
$versionToMigrate = $version;
}
}
$io = $this->getIo();
if ($versionToMigrate === null) {
$io->out('No migrations to run');
return;
}
$io->out('Migrating to version ' . $versionToMigrate);
$this->migrate($versionToMigrate, $fake);
}
/**
* @inheritDoc
*/
public function rollbackToDateTime(DateTime $dateTime, bool $force = false): void
{
$env = $this->getEnvironment();
$versions = $env->getVersions();
$dateString = $dateTime->format('Ymdhis');
sort($versions);
$versions = array_reverse($versions);
if (!$versions || $dateString > $versions[0]) {
$this->getIo()->out('No migrations to rollback');
return;
}
if ($dateString < end($versions)) {
$this->getIo()->out('Rolling back all migrations');
$this->rollback(0);
return;
}
$index = 0;
foreach ($versions as $index => $version) {
if ($dateString > $version) {
break;
}
}
$versionToRollback = $versions[$index];
$this->getIo()->out('Rolling back to version ' . $versionToRollback);
$this->rollback($versionToRollback, $force);
}
/**
* Checks if the migration with version number $version as already been mark migrated
*
* @param int $version Version number of the migration to check
* @return bool
*/
public function isMigrated(int $version): bool
{
$adapter = $this->getEnvironment()->getAdapter();
/** @var array<int, mixed> $versions */
$versions = array_flip($adapter->getVersions());
return isset($versions[$version]);
}
/**
* Marks migration with version number $version migrated
*
* @param int $version Version number of the migration to check
* @param string $path Path where the migration file is located
* @return bool True if success
*/
public function markMigrated(int $version, string $path): bool
{
$adapter = $this->getEnvironment()->getAdapter();
$migrationFile = glob($path . DS . $version . '*');
if (!$migrationFile) {
throw new RuntimeException(
sprintf('A migration file matching version number `%s` could not be found', $version),
);
}
$migrationFile = $migrationFile[0];
/** @var class-string<\Phinx\Migration\MigrationInterface|\Migrations\MigrationInterface> $className */
$className = $this->getMigrationClassName($migrationFile);
require_once $migrationFile;
if (is_subclass_of($className, PhinxMigrationInterface::class)) {
$migration = new MigrationAdapter($className, $version);
} else {
$migration = new $className($version);
}
/** @var \Migrations\MigrationInterface $migration */
$config = $this->getConfig();
$migration->setConfig($config);
$time = date('Y-m-d H:i:s', time());
$adapter->migrated($migration, 'up', $time, $time);
return true;
}
/**
* Resolves a migration class name based on $path
*
* @param string $path Path to the migration file of which we want the class name
* @return string Migration class name
*/
protected function getMigrationClassName(string $path): string
{
$class = (string)preg_replace('/^[0-9]+_/', '', basename($path));
$class = str_replace('_', ' ', $class);
$class = ucwords($class);
$class = str_replace(' ', '', $class);
if (strpos($class, '.') !== false) {
$class = substr($class, 0, strpos($class, '.'));
}
return $class;
}
/**
* Decides which versions it should mark as migrated
*
* @param \Cake\Console\Arguments $args Console arguments will be extracted
* to determine which versions to be marked as migrated
* @return array<int> Array of versions that should be marked as migrated
* @throws \InvalidArgumentException If the `--exclude` or `--only` options are used without `--target`
* or version not found
*/
public function getVersionsToMark(Arguments $args): array
{
$migrations = $this->getMigrations();
$versions = array_keys($migrations);
$versionArg = null;
if ($args->hasArgument('version')) {
$versionArg = $args->getArgument('version');
}
$targetArg = $args->getOption('target');
$hasAllVersion = in_array($versionArg, ['all', '*'], true);
if ((!$versionArg && !$targetArg) || $hasAllVersion) {
return $versions;
}
$version = (int)$targetArg ?: (int)$versionArg;
if ($args->getOption('only') || $versionArg) {
if (!in_array($version, $versions)) {
throw new InvalidArgumentException("Migration `$version` was not found !");
}
return [$version];
}
$lengthIncrease = $args->getOption('exclude') ? 0 : 1;
$index = array_search($version, $versions);
if ($index === false) {
throw new InvalidArgumentException("Migration `$version` was not found !");
}
return array_slice($versions, 0, $index + $lengthIncrease);
}
/**
* Mark all migrations in $versions array found in $path as migrated
*
* It will start a transaction and rollback in case one of the operation raises an exception
*
* @param string $path Path where to look for migrations
* @param array<int> $versions Versions which should be marked
* @return list<string> Output from the operation
*/
public function markVersionsAsMigrated(string $path, array $versions): array
{
$adapter = $this->getEnvironment()->getAdapter();
$out = [];
if (!$versions) {
$out[] = '<info>No migrations were found. Nothing to mark as migrated.</info>';
return $out;
}
$adapter->beginTransaction();
foreach ($versions as $version) {
if ($this->isMigrated($version)) {
$out[] = sprintf('<info>Skipping migration `%s` (already migrated).</info>', $version);
continue;
}
try {
$this->markMigrated($version, $path);
$out[] = sprintf('<info>Migration `%s` successfully marked migrated !</info>', $version);
} catch (Exception $e) {
$adapter->rollbackTransaction();
$out[] = sprintf(
'<error>An error occurred while marking migration `%s` as migrated : %s</error>',
$version,
$e->getMessage(),
);
$out[] = '<error>All marked migrations during this process were unmarked.</error>';
return $out;
}
}
$adapter->commitTransaction();
return $out;
}
/**
* Migrate an environment to the specified version or by count of migrations.
*
* @param int|null $version version to migrate to
* @param bool $fake flag that if true, we just record running the migration, but not actually do the migration
* @param int|null $count Number of migrations to run, all migrations will be run if not set and no version is given.
* @return void
*/
public function migrate(?int $version = null, bool $fake = false, ?int $count = null): void
{
$migrations = $this->getMigrations();
$env = $this->getEnvironment();
$versions = $env->getVersions();
$current = $env->getCurrentVersion();
if (!$versions && !$migrations) {
return;
}
if ($version === null) {
$version = max(array_merge($versions, array_keys($migrations)));
} else {
if ($version != 0 && !isset($migrations[$version])) {
$this->getIo()->out(sprintf(
'<comment>warning</comment> %s is not a valid version',
$version,
));
return;
}
}
// are we migrating up or down?
$direction = $version > $current ? MigrationInterface::UP : MigrationInterface::DOWN;
if ($direction === MigrationInterface::DOWN) {
// run downs first
krsort($migrations);
foreach ($migrations as $migration) {
if ($migration->getVersion() <= $version) {
break;
}
if (in_array($migration->getVersion(), $versions)) {
$this->executeMigration($migration, MigrationInterface::DOWN, $fake);
}
}
}
ksort($migrations);
$done = 0;
foreach ($migrations as $migration) {
if ($migration->getVersion() > $version || ($count && $done >= $count)) {
break;
}
if (!in_array($migration->getVersion(), $versions)) {
$this->executeMigration($migration, MigrationInterface::UP, $fake);
$done++;
}
}
}
/**
* Execute a migration against the specified environment.
*
* @param \Migrations\MigrationInterface $migration Migration
* @param string $direction Direction
* @param bool $fake flag that if true, we just record running the migration, but not actually do the migration
* @return void
*/
public function executeMigration(MigrationInterface $migration, string $direction = MigrationInterface::UP, bool $fake = false): void
{
$this->getIo()->out('');
// Skip the migration if it should not be executed
if (!$migration->shouldExecute()) {
$this->printMigrationStatus($migration, 'skipped');
return;
}
$this->printMigrationStatus($migration, ($direction === MigrationInterface::UP ? 'migrating' : 'reverting'));
// Execute the migration and log the time elapsed.
$start = microtime(true);
$this->getEnvironment()->executeMigration($migration, $direction, $fake);
$end = microtime(true);
$this->printMigrationStatus(
$migration,
($direction === MigrationInterface::UP ? 'migrated' : 'reverted'),
sprintf('%.4fs', $end - $start),
);
}
/**
* Execute a seeder against the specified environment.
*
* @param \Migrations\SeedInterface $seed Seed
* @return void
*/
public function executeSeed(SeedInterface $seed): void
{
$this->getIo()->out('');
// Skip the seed if it should not be executed
if (!$seed->shouldExecute()) {
$this->printSeedStatus($seed, 'skipped');
return;
}
$this->printSeedStatus($seed, 'seeding');
// Execute the seeder and log the time elapsed.
$start = microtime(true);
$this->getEnvironment()->executeSeed($seed);
$end = microtime(true);
$this->printSeedStatus(
$seed,
'seeded',
sprintf('%.4fs', $end - $start),
);
}
/**
* Print Migration Status
*
* @param \Migrations\MigrationInterface $migration Migration
* @param string $status Status of the migration
* @param string|null $duration Duration the migration took to be executed
* @return void
*/
protected function printMigrationStatus(MigrationInterface $migration, string $status, ?string $duration = null): void
{
$this->printStatusOutput(
$migration->getVersion() . ' ' . $migration->getName(),
$status,
$duration,
);
}
/**
* Print Seed Status
*
* @param \Migrations\SeedInterface $seed Seed
* @param string $status Status of the seed
* @param string|null $duration Duration the seed took to be executed
* @return void
*/
protected function printSeedStatus(SeedInterface $seed, string $status, ?string $duration = null): void
{
$this->printStatusOutput(
$seed->getName(),
$status,
$duration,
);
}
/**
* Print Status in Output
*
* @param string $name Name of the migration or seed
* @param string $status Status of the migration or seed
* @param string|null $duration Duration the migration or seed took to be executed
* @return void
*/
protected function printStatusOutput(string $name, string $status, ?string $duration = null): void
{
$this->getIo()->out(
' ==' .
' <info>' . $name . ':</info>' .
' <comment>' . $status . ' ' . $duration . '</comment>',
);
}
/**
* Rollback an environment by a specific count of migrations.
*
* Note: If the count is greater than the number of migrations, it will rollback all migrations.
*
* @param int $count Count
* @param bool $force Force
* @param bool $fake Flag that if true, we just record running the migration, but not actually do the migration
* @return void
*/
public function rollbackByCount(int $count, bool $force = false, bool $fake = false): void
{
// note that the version log are also indexed by name with the proper ascending order according to the version order
$executedVersions = $this->getEnvironment()->getVersionLog();
$total = count($executedVersions);
$pos = 0;
while ($pos < $count && $pos < $total) {
array_pop($executedVersions);
$pos++;
}
if ($executedVersions) {
$last = end($executedVersions);
$target = $last['version'];
} else {
$target = 0;
}
$this->rollback($target, $force, false, $fake);
}
/**
* Rollback an environment to the specified version.
*
* @param int|string|null $target Target
* @param bool $force Force
* @param bool $targetMustMatchVersion Target must match version
* @param bool $fake Flag that if true, we just record running the migration, but not actually do the migration
* @return void
*/
public function rollback(int|string|null $target = null, bool $force = false, bool $targetMustMatchVersion = true, bool $fake = false): void
{
// note that the migrations are indexed by name (aka creation time) in ascending order
$migrations = $this->getMigrations();
// note that the version log are also indexed by name with the proper ascending order according to the version order
$executedVersions = $this->getEnvironment()->getVersionLog();
// get a list of migrations sorted in the opposite way of the executed versions
$sortedMigrations = [];
$io = $this->getIo();
foreach ($executedVersions as $versionCreationTime => &$executedVersion) {
// if we have a date (i.e. the target must not match a version) and we are sorting by execution time, we
// convert the version start time so we can compare directly with the target date
if (!$this->getConfig()->isVersionOrderCreationTime() && !$targetMustMatchVersion) {
/** @var \DateTime $dateTime */
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $executedVersion['start_time']);
$executedVersion['start_time'] = $dateTime->format('YmdHis');
}
if (isset($migrations[$versionCreationTime])) {
array_unshift($sortedMigrations, $migrations[$versionCreationTime]);
} else {
// this means the version is missing so we unset it so that we don't consider it when rolling back
// migrations (or choosing the last up version as target)
unset($executedVersions[$versionCreationTime]);
}
}
if ($target === 'all' || $target === '0') {
$target = 0;
} elseif (!is_numeric($target) && $target !== null) { // try to find a target version based on name
// search through the migrations using the name
$migrationNames = array_map(function ($item) {
return $item['migration_name'];
}, $executedVersions);
$found = array_search($target, $migrationNames, true);
// check on was found
if ($found !== false) {
$target = (string)$found;
} else {
$io->out("<error>No migration found with name ($target)</error>");
return;
}
}
// Check we have at least 1 migration to revert
$executedVersionCreationTimes = array_keys($executedVersions);
if (!$executedVersionCreationTimes || $target == end($executedVersionCreationTimes)) {
$io->out('<error>No migrations to rollback</error>');
return;
}
// If no target was supplied, revert the last migration
if ($target === null) {
// Get the migration before the last run migration
$prev = count($executedVersionCreationTimes) - 2;
$target = $prev >= 0 ? $executedVersionCreationTimes[$prev] : 0;
}
// If the target must match a version, check the target version exists
if ($targetMustMatchVersion && $target !== 0 && !isset($migrations[$target])) {
$io->out("<error>Target version ($target) not found</error>");
return;
}
// Rollback all versions until we find the wanted rollback target
$rollbacked = false;
foreach ($sortedMigrations as $migration) {
if ($targetMustMatchVersion && $migration->getVersion() == $target) {
break;
}
if (in_array($migration->getVersion(), $executedVersionCreationTimes)) {
$executedArray = $executedVersions[$migration->getVersion()];
if (!$targetMustMatchVersion) {
if (
($this->getConfig()->isVersionOrderCreationTime() && $executedArray['version'] <= $target) ||
(!$this->getConfig()->isVersionOrderCreationTime() && $executedArray['start_time'] <= $target)
) {
break;
}
}
if ($executedArray['breakpoint'] != 0 && !$force) {
$io->out('<error>Breakpoint reached. Further rollbacks inhibited.</error>');
break;
}
$this->executeMigration($migration, MigrationInterface::DOWN, $fake);
$rollbacked = true;
}
}
if (!$rollbacked) {
$this->getIo()->out('<error>No migrations to rollback</error>');
}
}
/**
* Run database seeders against an environment.
*
* @param string|null $seed Seeder
* @throws \InvalidArgumentException
* @return void
*/
public function seed(?string $seed = null): void
{
$seeds = $this->getSeeds();
if ($seed === null) {
// run all seeders
foreach ($seeds as $seeder) {
if (array_key_exists($seeder->getName(), $seeds)) {
$this->executeSeed($seeder);
}
}
} else {
// run only one seeder
if (array_key_exists($seed . 'Seed', $seeds)) {
$seed = $seed . 'Seed';
$this->executeSeed($seeds[$seed]);
} elseif (array_key_exists($seed, $seeds)) {
$this->executeSeed($seeds[$seed]);
} else {
throw new InvalidArgumentException(sprintf('The seed `%s` does not exist', $seed));
}
}
}
/**
* Gets the manager class for the given environment.
*
* @throws \InvalidArgumentException
* @return \Migrations\Migration\Environment
*/
public function getEnvironment(): Environment
{
if (isset($this->environment)) {
return $this->environment;
}
$config = $this->getConfig();
// create an environment instance and cache it
$envOptions = $config->getEnvironment();
assert(is_array($envOptions));
$environment = new Environment('default', $envOptions);
$environment->setIo($this->getIo());
$this->environment = $environment;
return $environment;
}
/**
* Set the io instance
*
* @param \Cake\Console\ConsoleIo $io The io instance to use
* @return $this
*/
public function setIo(ConsoleIo $io)
{
$this->io = $io;
return $this;
}
/**
* Get the io instance
*
* @return \Cake\Console\ConsoleIo $io The io instance to use
*/
public function getIo(): ConsoleIo
{
return $this->io;
}
/**
* Replace the environment
*
* @param \Migrations\Migration\Environment $environment
* @return $this
*/
public function setEnvironment(Environment $environment)
{
$this->environment = $environment;
return $this;
}
/**
* Sets the user defined PSR-11 container
*
* @param \Psr\Container\ContainerInterface $container Container
* @return $this
*/
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
return $this;
}
/**
* Sets the database migrations.
*
* @param \Migrations\MigrationInterface[] $migrations Migrations
* @return $this
*/
public function setMigrations(array $migrations)
{
$this->migrations = $migrations;
return $this;
}
/**
* Gets an array of the database migrations, indexed by migration name (aka creation time) and sorted in ascending
* order
*
* @throws \InvalidArgumentException
* @return \Migrations\MigrationInterface[]
*/
public function getMigrations(): array
{
if ($this->migrations === null) {
$phpFiles = $this->getMigrationFiles();
$io = $this->getIo();
$io->verbose('Migration file');
$io->verbose(
array_map(
function ($phpFile) {
return " <info>{$phpFile}</info>";
},
$phpFiles,
),
);
// filter the files to only get the ones that match our naming scheme
$fileNames = [];
/** @var \Migrations\MigrationInterface[] $versions */
$versions = [];
$io = $this->getIo();
foreach ($phpFiles as $filePath) {
if (Util::isValidMigrationFileName(basename($filePath))) {
$io->verbose("Valid migration file <info>{$filePath}</info>.");
$version = Util::getVersionFromFileName(basename($filePath));
if (isset($versions[$version])) {
throw new InvalidArgumentException(sprintf('Duplicate migration - "%s" has the same version as "%s"', $filePath, $versions[$version]->getVersion()));
}
// convert the filename to a class name
$class = Util::mapFileNameToClassName(basename($filePath));
if (isset($fileNames[$class])) {
throw new InvalidArgumentException(sprintf(
'Migration "%s" has the same name as "%s"',
basename($filePath),
$fileNames[$class],
));
}
$fileNames[$class] = basename($filePath);
$io->verbose("Loading class <info>$class</info> from <info>$filePath</info>.");
// load the migration file
$orig_display_errors_setting = ini_get('display_errors');
ini_set('display_errors', 'On');
/** @noinspection PhpIncludeInspection */
require_once $filePath;
ini_set('display_errors', $orig_display_errors_setting);
if (!class_exists($class)) {
throw new InvalidArgumentException(sprintf(
'Could not find class `%s` in file `%s`',
$class,
$filePath,
));
}
$io->verbose("Constructing <info>$class</info>.");
if (is_subclass_of($class, PhinxMigrationInterface::class)) {
$migration = new MigrationAdapter($class, $version);
} else {
$migration = new $class($version);
}
/** @var \Migrations\MigrationInterface $migration */
$config = $this->getConfig();
$migration->setConfig($config);
$migration->setIo($io);
$versions[$version] = $migration;
} else {
$io->verbose("Invalid migration file <error>{$filePath}</error>.");
}
}
ksort($versions);
$this->setMigrations($versions);
}
return (array)$this->migrations;
}
/**
* Returns a list of migration files found in the provided migration paths.
*
* @return string[]
*/
protected function getMigrationFiles(): array
{
return Util::getFiles($this->getConfig()->getMigrationPath());
}
/**
* Sets the database seeders.
*
* @param \Migrations\SeedInterface[] $seeds Seeders
* @return $this
*/
public function setSeeds(array $seeds)
{
$this->seeds = $seeds;
return $this;
}
/**
* Get seed dependencies instances from seed dependency array
*
* @param \Migrations\SeedInterface $seed Seed
* @return \Migrations\SeedInterface[]
*/
protected function getSeedDependenciesInstances(SeedInterface $seed): array
{
$dependenciesInstances = [];
$dependencies = $seed->getDependencies();
if ($dependencies && $this->seeds) {
foreach ($dependencies as $dependency) {
foreach ($this->seeds as $seed) {
$name = $seed->getName();
if ($name === $dependency) {
$dependenciesInstances[$name] = $seed;
}
}
}
}
return $dependenciesInstances;
}
/**
* Order seeds by dependencies
*
* @param \Migrations\SeedInterface[] $seeds Seeds
* @return \Migrations\SeedInterface[]
*/
protected function orderSeedsByDependencies(array $seeds): array
{
$orderedSeeds = [];
foreach ($seeds as $seed) {
$name = $seed->getName();
$orderedSeeds[$name] = $seed;
$dependencies = $this->getSeedDependenciesInstances($seed);
if ($dependencies) {
$orderedSeeds = array_merge($this->orderSeedsByDependencies($dependencies), $orderedSeeds);
}
}
return $orderedSeeds;
}
/**
* Gets an array of database seeders.
*
* @throws \InvalidArgumentException
* @return \Migrations\SeedInterface[]
*/
public function getSeeds(): array
{
if ($this->seeds === null) {
$phpFiles = $this->getSeedFiles();
// filter the files to only get the ones that match our naming scheme
$fileNames = [];
/** @var \Migrations\SeedInterface[] $seeds */
$seeds = [];
$config = $this->getConfig();
$io = $this->getIo();
foreach ($phpFiles as $filePath) {
if (Util::isValidSeedFileName(basename($filePath))) {
// convert the filename to a class name
$class = pathinfo($filePath, PATHINFO_FILENAME);
$fileNames[$class] = basename($filePath);
// load the seed file
/** @noinspection PhpIncludeInspection */
require_once $filePath;
if (!class_exists($class)) {
throw new InvalidArgumentException(sprintf(
'Could not find class `%s` in file `%s`',
$class,
$filePath,
));
}
// instantiate it