LockableTrait.php 1.9 KB

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