LockableTrait.php 1.7KB

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\Console\Exception\RuntimeException;
  13. use Symfony\Component\Lock\Factory;
  14. use Symfony\Component\Lock\Lock;
  15. use Symfony\Component\Lock\Store\FlockStore;
  16. use Symfony\Component\Lock\Store\SemaphoreStore;
  17. /**
  18. * Basic lock feature for commands.
  19. *
  20. * @author Geoffrey Brier <geoffrey.brier@gmail.com>
  21. */
  22. trait LockableTrait
  23. {
  24. /** @var Lock */
  25. private $lock;
  26. /**
  27. * Locks a command.
  28. *
  29. * @return bool
  30. */
  31. private function lock($name = null, $blocking = false)
  32. {
  33. if (!class_exists(SemaphoreStore::class)) {
  34. throw new RuntimeException('To enable the locking feature you must install the symfony/lock component.');
  35. }
  36. if (null !== $this->lock) {
  37. throw new LogicException('A lock is already in place.');
  38. }
  39. if (SemaphoreStore::isSupported()) {
  40. $store = new SemaphoreStore();
  41. } else {
  42. $store = new FlockStore();
  43. }
  44. $this->lock = (new Factory($store))->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()
  55. {
  56. if ($this->lock) {
  57. $this->lock->release();
  58. $this->lock = null;
  59. }
  60. }
  61. }