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 ( 513f1e...e33bd5 )
by Robert
12s
created

AbstractCommand::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
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\Exception\RuntimeException;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Output\OutputInterface;
12
13
abstract class AbstractCommand extends Console\Command\Command
14
{
15
    /**
16
     * @var OutputInterface
17
     */
18
    protected $output;
19
20
    /**
21
     * {@inheritdoc}
22
     */
23 14
    protected function initialize(InputInterface $input, OutputInterface $output)
24
    {
25 14
        $this->output = $output;
26 14
    }
27
28
    /**
29
     * @param string[] $directories
30
     * @return MongoDbMigrations\MigrationInterface[]
31
     */
32 14
    protected function getMigrations(array $directories): array
33
    {
34 14
        foreach ($directories as $directory) {
35 14
            if (! is_dir($directory)) {
36 2
                throw new Console\Exception\InvalidArgumentException("'{$directory}' is no valid directory");
37
            }
38
39 14
            $this->output->writeln("<comment>Iterating '{$directory}' for potential migrations classes</comment>", OutputInterface::VERBOSITY_DEBUG);
40 14
            $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory), \RecursiveIteratorIterator::LEAVES_ONLY);
41
42
            /** @var \SplFileInfo $file */
43 14
            foreach ($iterator as $file) {
44 14
                if ($file->getBasename('.php') === $file->getBasename()) {
45 14
                    continue;
46
                }
47
48 14
                require_once $file->getRealPath();
49
50 14
                $this->output->writeln("<comment>Loaded potential migration '{$file->getRealPath()}'</comment>", OutputInterface::VERBOSITY_DEBUG);
51
            }
52
        }
53
54
        /** @var MongoDbMigrations\MigrationInterface[] $migrations */
55 12
        $migrations = [];
56 12
        foreach (get_declared_classes() as $className) {
57 12
            $reflectionClass = new \ReflectionClass($className);
58
59 12
            if ($reflectionClass->implementsInterface(MongoDbMigrations\MigrationInterface::class)) {
60
                /** @var MongoDbMigrations\MigrationInterface $newInstance */
61 12
                $newInstance = $reflectionClass->newInstance();
62 12
                $id = md5($newInstance->getId());
63
64 12
                if (isset($migrations[$id])) {
65 1
                    $existingMigrationClass = get_class($migrations[$id]);
66 1
                    throw new RuntimeException("Found a non unique migration id '{$newInstance->getId()}' in '{$reflectionClass->getName()}', already defined by migration class '{$existingMigrationClass}'");
67
                }
68
69 12
                $migrations[$id] = $newInstance;
70
71 12
                $this->output->writeln("<comment>Found valid migration class '{$reflectionClass->getName()}'</comment>", OutputInterface::VERBOSITY_DEBUG);
72
            }
73
        }
74
75 11
        $migrationClassesCount = count($migrations);
76 11
        $this->output->writeln("<info>✓ Found {$migrationClassesCount} valid migration classes</info>", OutputInterface::VERBOSITY_VERBOSE);
77
78 11
        uasort($migrations, function (MongoDbMigrations\MigrationInterface $a, MongoDbMigrations\MigrationInterface $b) {
79 11
            if ($a->getCreateDate() === $b->getCreateDate()) {
80
                return 0;
81
            }
82
83 11
            return $a->getCreateDate() < $b->getCreateDate() ? -1 : 1;
84 11
        });
85
86 11
        $this->output->writeln("<info>✓ Reordered all migration classes according to their create date</info>", OutputInterface::VERBOSITY_VERBOSE);
87
88 11
        return $migrations;
89
    }
90
91
    /**
92
     * @param string $server
93
     * @param string $database
94
     * @return Database
95
     */
96 11
    protected function connect(string $server, string $database): Database
97
    {
98 11
        $client = new MongoDB\Client($server);
99 11
        $db = $client->selectDatabase($database);
100 11
        $this->output->writeln("<info>✓ Successfully established database connection</info>", OutputInterface::VERBOSITY_VERBOSE);
101
102 11
        return $db;
103
    }
104
105
    /**
106
     * @param Database $db
107
     *
108
     * @throws RuntimeException If there is already a running command
109
     */
110 11
    protected function acquireLock(Database $db)
111
    {
112 11
        $databaseMigrationsLockCollection = $db->selectCollection('DATABASE_MIGRATIONS_LOCK');
113 11
        $databaseMigrationsLockCollection->createIndex(['locked' => 1]);
114
115 11
        $currentLock = $databaseMigrationsLockCollection->findOneAndReplace(['locked' => ['$exists' => true]], ['locked' => true, 'last_locked_date' => new MongoDB\BSON\UTCDatetime((new \DateTime())->getTimestamp() * 1000)], ['upsert' => true]);
116 11
        if ($currentLock !== null && $currentLock->locked === true) {
117 2
            throw new RuntimeException('Concurrent migrations are not allowed');
118
        }
119
120 9
        $this->output->writeln("<info>✓ Successfully acquired migration lock</info>", OutputInterface::VERBOSITY_VERBOSE);
121 9
    }
122
123
    /**
124
     * @param Database $db
125
     */
126 9
    protected function releaseLock(Database $db)
127
    {
128 9
        $databaseMigrationsLockCollection = $db->selectCollection('DATABASE_MIGRATIONS_LOCK');
129 9
        $databaseMigrationsLockCollection->updateOne(['locked' => true], ['$set' => ['locked' => false]]);
130 9
        $this->output->writeln("<info>✓ Successfully released migration lock</info>", OutputInterface::VERBOSITY_VERBOSE);
131 9
    }
132
133
    /**
134
     * @param Database $db
135
     * @return MongoDB\Collection
136
     */
137 9
    protected function getMigrationsCollection(Database $db): MongoDB\Collection
138
    {
139 9
        $databaseMigrationsCollection = $db->selectCollection('DATABASE_MIGRATIONS');
140 9
        $databaseMigrationsCollection->createIndex(['migration_id' => 1], ['unique' => true, 'background' => false]);
141
142 9
        return $databaseMigrationsCollection;
143
    }
144
}
145