LockableTrait.php 1.7 KB

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