Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 /*
|
Chris@0
|
4 * This file is part of the Symfony package.
|
Chris@0
|
5 *
|
Chris@0
|
6 * (c) Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
7 *
|
Chris@0
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@0
|
9 * file that was distributed with this source code.
|
Chris@0
|
10 */
|
Chris@0
|
11
|
Chris@0
|
12 namespace Symfony\Component\Console\Command;
|
Chris@0
|
13
|
Chris@0
|
14 use Symfony\Component\Console\Exception\LogicException;
|
Chris@0
|
15 use Symfony\Component\Console\Exception\RuntimeException;
|
Chris@14
|
16 use Symfony\Component\Lock\Factory;
|
Chris@14
|
17 use Symfony\Component\Lock\Lock;
|
Chris@14
|
18 use Symfony\Component\Lock\Store\FlockStore;
|
Chris@14
|
19 use Symfony\Component\Lock\Store\SemaphoreStore;
|
Chris@0
|
20
|
Chris@0
|
21 /**
|
Chris@0
|
22 * Basic lock feature for commands.
|
Chris@0
|
23 *
|
Chris@0
|
24 * @author Geoffrey Brier <geoffrey.brier@gmail.com>
|
Chris@0
|
25 */
|
Chris@0
|
26 trait LockableTrait
|
Chris@0
|
27 {
|
Chris@14
|
28 /** @var Lock */
|
Chris@14
|
29 private $lock;
|
Chris@0
|
30
|
Chris@0
|
31 /**
|
Chris@0
|
32 * Locks a command.
|
Chris@0
|
33 *
|
Chris@0
|
34 * @return bool
|
Chris@0
|
35 */
|
Chris@0
|
36 private function lock($name = null, $blocking = false)
|
Chris@0
|
37 {
|
Chris@14
|
38 if (!class_exists(SemaphoreStore::class)) {
|
Chris@14
|
39 throw new RuntimeException('To enable the locking feature you must install the symfony/lock component.');
|
Chris@0
|
40 }
|
Chris@0
|
41
|
Chris@14
|
42 if (null !== $this->lock) {
|
Chris@0
|
43 throw new LogicException('A lock is already in place.');
|
Chris@0
|
44 }
|
Chris@0
|
45
|
Chris@14
|
46 if (SemaphoreStore::isSupported($blocking)) {
|
Chris@14
|
47 $store = new SemaphoreStore();
|
Chris@14
|
48 } else {
|
Chris@14
|
49 $store = new FlockStore();
|
Chris@14
|
50 }
|
Chris@0
|
51
|
Chris@14
|
52 $this->lock = (new Factory($store))->createLock($name ?: $this->getName());
|
Chris@14
|
53 if (!$this->lock->acquire($blocking)) {
|
Chris@14
|
54 $this->lock = null;
|
Chris@0
|
55
|
Chris@0
|
56 return false;
|
Chris@0
|
57 }
|
Chris@0
|
58
|
Chris@0
|
59 return true;
|
Chris@0
|
60 }
|
Chris@0
|
61
|
Chris@0
|
62 /**
|
Chris@0
|
63 * Releases the command lock if there is one.
|
Chris@0
|
64 */
|
Chris@0
|
65 private function release()
|
Chris@0
|
66 {
|
Chris@14
|
67 if ($this->lock) {
|
Chris@14
|
68 $this->lock->release();
|
Chris@14
|
69 $this->lock = null;
|
Chris@0
|
70 }
|
Chris@0
|
71 }
|
Chris@0
|
72 }
|