Completed
Push — develop ( 8109ce...b15e90 )
by Alejandro
17s queued 12s
created

AbstractLockedCommand::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\CLI\Command\Util;
6
7
use Shlinkio\Shlink\CLI\Util\ExitCodes;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Lock\LockFactory;
12
13
use function sprintf;
14
15
abstract class AbstractLockedCommand extends Command
16
{
17
    private LockFactory $locker;
18
19 19
    public function __construct(LockFactory $locker)
20
    {
21 19
        parent::__construct();
22 19
        $this->locker = $locker;
23 19
    }
24
25 16
    final protected function execute(InputInterface $input, OutputInterface $output): ?int
26
    {
27 16
        $lockConfig = $this->getLockConfig();
28 16
        $lock = $this->locker->createLock($lockConfig->lockName(), $lockConfig->ttl(), $lockConfig->isBlocking());
29
30 16
        if (! $lock->acquire($lockConfig->isBlocking())) {
31 1
            $output->writeln(
32 1
                sprintf('<comment>Command "%s" is already in progress. Skipping.</comment>', $lockConfig->lockName()),
33
            );
34 1
            return ExitCodes::EXIT_WARNING;
35
        }
36
37
        try {
38 15
            return $this->lockedExecute($input, $output);
39
        } finally {
40 15
            $lock->release();
41
        }
42
    }
43
44
    abstract protected function lockedExecute(InputInterface $input, OutputInterface $output): int;
45
46
    abstract protected function getLockConfig(): LockedCommandConfig;
47
}
48