Passed
Pull Request — master (#439)
by Alejandro
11:54
created

LockMigrationsSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Migrations;
5
6
use Doctrine\Common\EventSubscriber;
7
use Doctrine\Migrations\Events;
8
use Shlinkio\Shlink\Common\Exception\MigrationsException;
9
use Symfony\Component\Lock\Factory as Locker;
10
use Symfony\Component\Lock\Lock;
11
12
class LockMigrationsSubscriber implements EventSubscriber
13
{
14
    private const MIGRATIONS_LOCK_NAME = 'migrations';
15
    private const MIGRATIONS_LOCK_TTL = 90; // 1.5 minutes
16
17
    /** @var Locker */
18
    private $locker;
19
    /** @var Lock */
20
    private $lock;
21
22 4
    public function __construct(Locker $locker)
23
    {
24 4
        $this->locker = $locker;
25
    }
26
27 1
    public function getSubscribedEvents(): array
28
    {
29 1
        return [Events::onMigrationsMigrating, Events::onMigrationsMigrated];
30
    }
31
32 2
    public function onMigrationsMigrating(): void
33
    {
34 2
        $this->lock = $this->locker->createLock(self::MIGRATIONS_LOCK_NAME, self::MIGRATIONS_LOCK_TTL);
35 2
        $migrationInProgress = ! $this->lock->acquire();
36
37 2
        if ($migrationInProgress) {
38 1
            throw MigrationsException::migrationInProgress();
39
        }
40
    }
41
42 1
    public function onMigrationsMigrated(): void
43
    {
44 1
        $this->lock !== null && $this->lock->release();
45
    }
46
}
47