GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( bb2de9...e7a4b9 )
by Robert
18s
created

VersionsCommand::deleteMigrations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
crap 2
1
<?php declare(strict_types=1);
2
3
namespace Gruberro\MongoDbMigrations\Console\Command;
4
5
use Gruberro\MongoDbMigrations;
6
use MongoDB;
7
use MongoDB\Database;
8
use Symfony\Component\Console;
9
use Symfony\Component\Console\Input\InputArgument;
10
use Symfony\Component\Console\Input\InputOption;
11
12
class VersionsCommand extends AbstractCommand
13
{
14
    /**
15
     * {@inheritdoc}
16
     */
17 5
    protected function configure()
18
    {
19
        $this
20 5
            ->setName('php-mongodb-migrations:version')
21 5
            ->setDescription('Manually add and delete migrations from the version collection.')
22 5
            ->addOption(
23 5
                'server',
24 5
                's',
25 5
                InputOption::VALUE_REQUIRED,
26 5
                'The connection string (e.g. mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db)',
27 5
                'mongodb://localhost:27017'
28
            )
29 5
            ->addArgument(
30 5
                'database',
31 5
                InputArgument::REQUIRED,
32 5
                'The database to connect to'
33
            )
34 5
            ->addArgument(
35 5
                'migration-directories',
36 5
                InputArgument::IS_ARRAY,
37 5
                'List of directories containing migration classes',
38 5
                []
39
            )
40 5
            ->addOption(
41 5
                'id',
42 5
                null,
43 5
                InputOption::VALUE_REQUIRED,
44 5
                'The migration id to add or delete'
45
            )
46 5
            ->addOption(
47 5
                'add',
48 5
                null,
49 5
                InputOption::VALUE_NONE,
50 5
                'Add the specified migration id'
51
            )
52 5
            ->addOption(
53 5
                'delete',
54 5
                null,
55 5
                InputOption::VALUE_NONE,
56 5
                'Delete the specified migration id'
57
            )
58 5
            ->addOption(
59 5
                'all',
60 5
                null,
61 5
                InputOption::VALUE_NONE,
62 5
                'Apply to all the migrations'
63
            )
64 5
            ->setHelp(<<<EOT
65 5
The <info>%command.name%</info> command allows you to manually add, delete or synchronize migrations from the version collection:
66
67
    <info>%command.full_name% DATABASE_NAME /path/to/migrations --id=MIGRATION_ID --add</info>
68
69
If you want to delete a version you can use the <comment>--delete</comment> option:
70
71
    <info>%command.full_name% DATABASE_NAME /path/to/migrations --id=MIGRATION_ID --delete</info>
72
73
If you want to synchronize by adding or deleting all migrations available in the version collection you can use the <comment>--all</comment> option:
74
75
    <info>%command.full_name% DATABASE_NAME /path/to/migrations --add --all</info>
76
    <info>%command.full_name% DATABASE_NAME /path/to/migrations --delete --all</info>
77
EOT
78
            );
79
        ;
80 5
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85 7
    protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
86
    {
87 7
        $id = $input->getOption('id');
88 7
        $directories = $input->getArgument('migration-directories');
89 7
        $migrations = $this->getMigrations($directories);
90 6
        $db = $this->connect($input->getOption('server'), $input->getArgument('database'));
91
92 6
        $add = $input->getOption('add');
93 6
        $delete = $input->getOption('delete');
94 6
        $all = $input->getOption('all');
95
96
        // Assume add is the default behavior
97 6
        if ($add === false && $delete === false) {
98 5
            $add = true;
99
        }
100
101 6
        if ($add === true && $delete === true) {
102
            throw new Console\Exception\RuntimeException("--add and --delete is not allowed to be set both");
103
        }
104
105 6
        if (!$all && $id === null) {
106 1
            throw new Console\Exception\RuntimeException("Specify --all or a single migration id");
107
        }
108
109 5
        $this->acquireLock($db);
110
111
        try {
112 4
            if ($all) {
113 3
                $id = null;
114
            }
115
116 4
            if ($id !== null) {
117 1
                $migrations = array_filter($migrations, function (MongoDbMigrations\MigrationInterface $migration) use ($id): bool {
118 1
                    return $migration->getId() === $id;
119 1
                });
120
121 1
                if (count($migrations) === 0) {
122
                    throw new Console\Exception\RuntimeException("No migration for id '{$id}' found");
123
                }
124
            }
125
126 4
            if ($add) {
127 3
                $this->addMigrations($migrations, $db);
128 2
            } elseif ($delete) {
129 4
                $this->deleteMigrations($migrations, $db);
130
            }
131
        } catch (\Exception $e) {
132
            throw new Console\Exception\RuntimeException('Error while executing migrations', $e->getCode(), $e);
133 4
        } finally {
134 4
            $this->releaseLock($db);
135
        }
136 4
    }
137
138
    /**
139
     * @param array $migrations
140
     * @param Database $db
141
     */
142 3
    private function addMigrations(array $migrations, Database $db)
143
    {
144 3
        $databaseMigrationsCollection = $this->getMigrationsCollection($db);
145
146 3
        foreach ($migrations as $id => $migration) {
147
            $migrationInfo = [
148 3
                'migration_id' => $id,
149 3
                'migration_class' => get_class($migration),
150 3
                'last_execution_date' => new MongoDB\BSON\UTCDatetime((new \DateTime())->getTimestamp() * 1000),
151 3
                'run_always' => $migration instanceof MongoDbMigrations\RunAlwaysMigrationInterface,
152
            ];
153
154 3
            if ($migration instanceof MongoDbMigrations\ContextualMigrationInterface) {
155 2
                $migrationInfo['contexts'] = $migration->getContexts();
156
            }
157
158 3
            $databaseMigrationsCollection->updateOne(
159 3
                ['migration_id' => $id],
160 3
                ['$set' => $migrationInfo],
161 3
                ['upsert' => true]
162
            );
163
        }
164
165 3
        $addedMigrations = count($migrations);
166 3
        $this->output->writeln("<info>✓ Successfully added {$addedMigrations} migrations to version collection</info>");
167 3
    }
168
169
    /**
170
     * @param array $migrations
171
     * @param Database $db
172
     */
173 2
    private function deleteMigrations(array $migrations, Database $db)
174
    {
175 2
        $databaseMigrationsCollection = $this->getMigrationsCollection($db);
176
177 2
        foreach ($migrations as $id => $migration) {
178 2
            $databaseMigrationsCollection->deleteOne(['migration_id' => $id]);
179
        }
180
181 2
        $deletedMigrations = count($migrations);
182 2
        $this->output->writeln("<info>✓ Successfully deleted {$deletedMigrations} migrations from version collection</info>");
183 2
    }
184
}
185