Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Console\Command; Chris@0: Chris@0: use Symfony\Component\Console\Exception\LogicException; Chris@0: use Symfony\Component\Console\Exception\RuntimeException; Chris@14: use Symfony\Component\Lock\Factory; Chris@14: use Symfony\Component\Lock\Lock; Chris@14: use Symfony\Component\Lock\Store\FlockStore; Chris@14: use Symfony\Component\Lock\Store\SemaphoreStore; Chris@0: Chris@0: /** Chris@0: * Basic lock feature for commands. Chris@0: * Chris@0: * @author Geoffrey Brier Chris@0: */ Chris@0: trait LockableTrait Chris@0: { Chris@14: /** @var Lock */ Chris@14: private $lock; Chris@0: Chris@0: /** Chris@0: * Locks a command. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function lock($name = null, $blocking = false) Chris@0: { Chris@14: if (!class_exists(SemaphoreStore::class)) { Chris@14: throw new RuntimeException('To enable the locking feature you must install the symfony/lock component.'); Chris@0: } Chris@0: Chris@14: if (null !== $this->lock) { Chris@0: throw new LogicException('A lock is already in place.'); Chris@0: } Chris@0: Chris@14: if (SemaphoreStore::isSupported($blocking)) { Chris@14: $store = new SemaphoreStore(); Chris@14: } else { Chris@14: $store = new FlockStore(); Chris@14: } Chris@0: Chris@14: $this->lock = (new Factory($store))->createLock($name ?: $this->getName()); Chris@14: if (!$this->lock->acquire($blocking)) { Chris@14: $this->lock = null; Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Releases the command lock if there is one. Chris@0: */ Chris@0: private function release() Chris@0: { Chris@14: if ($this->lock) { Chris@14: $this->lock->release(); Chris@14: $this->lock = null; Chris@0: } Chris@0: } Chris@0: }