1 | <?php |
||
2 | namespace App\BxConsole; |
||
3 | |||
4 | use Symfony\Component\Console\Exception\LogicException; |
||
5 | use Symfony\Component\Lock\Lock; |
||
6 | use Symfony\Component\Lock\LockFactory; |
||
7 | use Symfony\Component\Lock\Store\FlockStore; |
||
8 | |||
9 | trait LockableTrait { |
||
10 | |||
11 | /** @var Lock */ |
||
12 | private $_lock; |
||
13 | |||
14 | protected function lock($blocking = false) { |
||
15 | |||
16 | if (null !== $this->_lock) { |
||
17 | throw new LogicException('A lock is already in place.'); |
||
18 | } |
||
19 | |||
20 | $lockStore = new FlockStore(pathinfo(EnvHelper::getCrontabFile(), PATHINFO_DIRNAME)); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
21 | $lockFactory = new LockFactory($lockStore); |
||
22 | |||
23 | $this->_lock = $lockFactory->createLock($this->getLockName($this->getName()), EnvHelper::getCrontabTimeout()); |
||
24 | |||
25 | if (!$this->_lock->acquire($blocking)) { |
||
26 | $this->_lock = null; |
||
27 | |||
28 | return false; |
||
29 | } |
||
30 | |||
31 | return true; |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * Releases the command lock if there is one. |
||
36 | */ |
||
37 | protected function release() |
||
38 | { |
||
39 | if ($this->_lock) { |
||
40 | $this->_lock->release(); |
||
41 | $this->_lock = null; |
||
42 | } |
||
43 | } |
||
44 | |||
45 | protected function getLockName($cmd) { |
||
46 | |||
47 | return preg_replace('/[^a-z\d ]/i', '_', $cmd); |
||
48 | } |
||
49 | } |