LockableTrait.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\Lock;
  13. use Symfony\Component\Lock\LockFactory;
  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. /** @var Lock */
  24. private $lock;
  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.');
  32. }
  33. if (null !== $this->lock) {
  34. throw new LogicException('A lock is already in place.');
  35. }
  36. if (SemaphoreStore::isSupported()) {
  37. $store = new SemaphoreStore();
  38. } else {
  39. $store = new FlockStore();
  40. }
  41. $this->lock = (new LockFactory($store))->createLock($name ?: $this->getName());
  42. if (!$this->lock->acquire($blocking)) {
  43. $this->lock = null;
  44. return false;
  45. }
  46. return true;
  47. }
  48. /**
  49. * Releases the command lock if there is one.
  50. */
  51. private function release()
  52. {
  53. if ($this->lock) {
  54. $this->lock->release();
  55. $this->lock = null;
  56. }
  57. }
  58. }