LockableTrait.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. /**
  24. * @var \Symfony\Component\Lock\LockInterface|null
  25. */
  26. private $lock;
  27. /**
  28. * Locks a command.
  29. * @param string|null $name
  30. * @param bool $blocking
  31. */
  32. private function lock($name = null, $blocking = false)
  33. {
  34. if (!class_exists(SemaphoreStore::class)) {
  35. throw new LogicException('To enable the locking feature you must install the symfony/lock component. Try running "composer require symfony/lock".');
  36. }
  37. if (null !== $this->lock) {
  38. throw new LogicException('A lock is already in place.');
  39. }
  40. if (SemaphoreStore::isSupported()) {
  41. $store = new SemaphoreStore();
  42. } else {
  43. $store = new FlockStore();
  44. }
  45. $this->lock = (new LockFactory($store))->createLock($name ?: $this->getName());
  46. if (!$this->lock->acquire($blocking)) {
  47. $this->lock = null;
  48. return false;
  49. }
  50. return true;
  51. }
  52. /**
  53. * Releases the command lock if there is one.
  54. */
  55. private function release()
  56. {
  57. if ($this->lock) {
  58. $this->lock->release();
  59. $this->lock = null;
  60. }
  61. }
  62. }