Debian Codegraph @

vendor/symfony/console/Command/LockableTrait.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Command;
13
14 use Symfony\Component\Console\Attribute\AsCommand;
15 use Symfony\Component\Console\Exception\LogicException;
16 use Symfony\Component\Lock\LockFactory;
17 use Symfony\Component\Lock\LockInterface;
18 use Symfony\Component\Lock\Store\FlockStore;
19 use Symfony\Component\Lock\Store\SemaphoreStore;
20
21 /**
22 * Basic lock feature for commands.
23 *
24 * @author Geoffrey Brier <[email protected]>
25 */
26 trait LockableTrait
27 {
28 private ?LockInterface $lock = null;
29
30 private ?LockFactory $lockFactory = null;
31
32 /**
33 * Locks a command.
34 */
35 private function lock(?string $name = null, bool $blocking = false): bool
36 {
37 if (!class_exists(SemaphoreStore::class)) {
38 throw new LogicException('To enable the locking feature you must install the symfony/lock component. Try running "composer require symfony/lock".');
39 }
40
41 if (null !== $this->lock) {
42 throw new LogicException('A lock is already in place.');
43 }
44
45 if (null === $this->lockFactory) {
46 if (SemaphoreStore::isSupported()) {
47 $store = new SemaphoreStore();
48 } else {
49 $store = new FlockStore();
50 }
51
52 $this->lockFactory = new LockFactory($store);
53 }
54
55 if (!$name) {
56 if ($this instanceof Command) {
57 $name = $this->getName();
58 } elseif ($attribute = (new \ReflectionClass($this::class))->getAttributes(AsCommand::class)) {
59 $name = $attribute[0]->newInstance()->name;
60 } else {
61 throw new LogicException(\sprintf('Lock name missing: provide it via "%s()", #[AsCommand] attribute, or by extending Command class.', __METHOD__));
62 }
63 }
64
65 $this->lock = $this->lockFactory->createLock($name);
66 if (!$this->lock->acquire($blocking)) {
67 $this->lock = null;
68
69 return false;
70 }
71
72 return true;
73 }
74
75 /**
76 * Releases the command lock if there is one.
77 */
78 private function release(): void
79 {
80 if ($this->lock) {
81 $this->lock->release();
82 $this->lock = null;
83 }
84 }
85 }