LockableTrait.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\Filesystem\LockHandler;
  14. /**
  15. * Basic lock feature for commands.
  16. *
  17. * @author Geoffrey Brier <geoffrey.brier@gmail.com>
  18. */
  19. trait LockableTrait
  20. {
  21. private $lockHandler;
  22. /**
  23. * Locks a command.
  24. *
  25. * @return bool
  26. */
  27. private function lock($name = null, $blocking = false)
  28. {
  29. if (!class_exists(LockHandler::class)) {
  30. throw new RuntimeException('To enable the locking feature you must install the symfony/filesystem component.');
  31. }
  32. if (null !== $this->lockHandler) {
  33. throw new LogicException('A lock is already in place.');
  34. }
  35. $this->lockHandler = new LockHandler($name ?: $this->getName());
  36. if (!$this->lockHandler->lock($blocking)) {
  37. $this->lockHandler = null;
  38. return false;
  39. }
  40. return true;
  41. }
  42. /**
  43. * Releases the command lock if there is one.
  44. */
  45. private function release()
  46. {
  47. if ($this->lockHandler) {
  48. $this->lockHandler->release();
  49. $this->lockHandler = null;
  50. }
  51. }
  52. }