Completed
Push — master ( 94e1e6...1341d4 )
by Alejandro
16s queued 11s
created

AbstractLockedCommand::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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