feature #18471 [Console] Add Lockable trait (geoffrey-brier)

This PR was merged into the 3.2-dev branch.

Discussion
----------

[Console] Add Lockable trait

| Q             | A
| ------------- | ---
| Branch?       | "master"
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | none
| License       | MIT
| Doc PR        | none for the moment :)

Hi there,

Since the 2.6 the `LockHandler` class was added to ease concurrency problems. There was a nice post about [using it in your commands](http://symfony.com/blog/new-in-symfony-2-6-lockhandler).

From my humble experience, I find it a bit unpleasant/time consuming to always copy/paste the same code. So here is my proposal:

Before:

```php
class UpdateContentsCommand extends Command
{
    protected function configure()
    {
        // ...
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // create the lock
        $lock = new LockHandler('update:contents');
        if (!$lock->lock()) {
            $output->writeln('The command is already running in another process.');

            return 0;
        }

      // Your code

        $lock->release();
    }
}
```

After:

```php
class MyCommand extends Command
{
    use LockableTrait;

    protected function execute(InputInterface $input, OutputInterface $output)
    {
         if (!$this->lock()) {
             // Here you can handle locking errors
         }
        // Your code
        // The lock release is still optionnal
         $this->release();
    }
}
```
In addition, you can optionally pass two arguments:
- a string argument to change the lock name
- a boolean argument to indicate if you want to wait until the requested lock is released

Commits
-------

b57a83f [Console] Add Lockable trait
This commit is contained in:
Fabien Potencier 2016-06-23 13:46:59 +02:00
commit 43f9514db5
6 changed files with 179 additions and 0 deletions

View File

@ -7,6 +7,7 @@ CHANGELOG
* added `setInputs()` method to CommandTester for ease testing of commands expecting inputs
* added `setStream()` and `getStream()` methods to Input (implement StreamableInputInterface)
* added StreamableInputInterface
* added LockableTrait
3.1.0
-----

View File

@ -0,0 +1,63 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Filesystem\LockHandler;
/**
* Basic lock feature for commands.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait LockableTrait
{
protected $lockHandler;
/**
* Locks a command.
*
* @return bool
*/
protected function lock($name = null, $blocking = false)
{
if (!class_exists(LockHandler::class)) {
throw new RuntimeException('To enable the locking feature you must install the symfony/filesystem component.');
}
if (null !== $this->lockHandler) {
throw new LogicException('A lock is already in place.');
}
$this->lockHandler = new LockHandler($name ?: $this->getName());
if (!$this->lockHandler->lock($blocking)) {
$this->lockHandler = null;
return false;
}
return true;
}
/**
* Releases the command lock if there is one.
*/
protected function release()
{
if ($this->lockHandler) {
$this->lockHandler->release();
$this->lockHandler = null;
}
}
}

View File

@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Tests\Command;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Filesystem\LockHandler;
class LockableTraitTest extends \PHPUnit_Framework_TestCase
{
protected static $fixturesPath;
public static function setUpBeforeClass()
{
self::$fixturesPath = __DIR__.'/../Fixtures/';
require_once self::$fixturesPath.'/FooLockCommand.php';
require_once self::$fixturesPath.'/FooLock2Command.php';
}
public function testLockIsReleased()
{
$command = new \FooLockCommand();
$tester = new CommandTester($command);
$this->assertSame(2, $tester->execute(array()));
$this->assertSame(2, $tester->execute(array()));
}
public function testLockReturnsFalseIfAlreadyLockedByAnotherCommand()
{
$command = new \FooLockCommand();
$lock = new LockHandler($command->getName());
$lock->lock();
$tester = new CommandTester($command);
$this->assertSame(1, $tester->execute(array()));
$lock->release();
$this->assertSame(2, $tester->execute(array()));
}
public function testMultipleLockCallsThrowLogicException()
{
$command = new \FooLock2Command();
$tester = new CommandTester($command);
$this->assertSame(1, $tester->execute(array()));
}
}

View File

@ -0,0 +1,28 @@
<?php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class FooLock2Command extends Command
{
use LockableTrait;
protected function configure()
{
$this->setName('foo:lock2');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
try {
$this->lock();
$this->lock();
} catch (LogicException $e) {
return 1;
}
return 2;
}
}

View File

@ -0,0 +1,27 @@
<?php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class FooLockCommand extends Command
{
use LockableTrait;
protected function configure()
{
$this->setName('foo:lock');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (!$this->lock()) {
return 1;
}
$this->release();
return 2;
}
}

View File

@ -21,11 +21,13 @@
},
"require-dev": {
"symfony/event-dispatcher": "~2.8|~3.0",
"symfony/filesystem": "~2.8|~3.0",
"symfony/process": "~2.8|~3.0",
"psr/log": "~1.0"
},
"suggest": {
"symfony/event-dispatcher": "",
"symfony/filesystem": "",
"symfony/process": "",
"psr/log": "For using the console logger"
},