[Security] added SecurityContextInterface::getUser()

This changes helps the common use case of fetching the current user and better complies with the Law of Demeter (http://en.wikipedia.org/wiki/Law_of_Demeter).

Before (still works):

    $token = $context->getToken();
    $user = $token ? $token->getUser() : null;

After:

    $user = $context->getUser();
This commit is contained in:
Kris Wallsmith 2011-12-08 08:53:01 -08:00
parent 4730f4303b
commit 41872cd40e
3 changed files with 41 additions and 0 deletions

View File

@ -89,4 +89,18 @@ class SecurityContext implements SecurityContextInterface
{
$this->token = $token;
}
/**
* Returns the current user, if one exists.
*
* @return mixed Returns either an object which implements __toString(),
* or a primitive string if there is a token, otherwise
* returns null.
*/
public function getUser()
{
if ($this->token) {
return $this->token->getUser();
}
}
}

View File

@ -38,6 +38,15 @@ interface SecurityContextInterface
*/
function setToken(TokenInterface $token = null);
/**
* Returns the current user, if one exists.
*
* @return mixed Returns either an object which implements __toString(),
* or a primitive string if there is a token, otherwise
* returns null.
*/
function getUser();
/**
* Checks if the attributes are granted against the current authentication token and optionally supplied object.
*

View File

@ -89,4 +89,22 @@ class SecurityContextTest extends \PHPUnit_Framework_TestCase
$context->setToken($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
$this->assertSame($token, $context->getToken());
}
public function testGetUser()
{
$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token->expects($this->once())
->method('getUser')
->will($this->returnValue('foo'));
$context = new SecurityContext(
$this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
$this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')
);
$this->assertNull($context->getUser(), '->getUser() returns null when there is no token');
$context->setToken($token);
$this->assertEquals('foo', $context->getUser(), '->getUser() return the token user');
}
}