Skip to content

Commit

Permalink
[Security] added SecurityContextInterface::getUser()
Browse files Browse the repository at this point in the history
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();
  • Loading branch information
kriswallsmith committed Dec 8, 2011
1 parent 4730f43 commit 41872cd
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Symfony/Component/Security/Core/SecurityContext.php
Expand Up @@ -89,4 +89,18 @@ public function setToken(TokenInterface $token = null)
{
$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();
}
}
}
Expand Up @@ -38,6 +38,15 @@ function getToken();
*/
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.
*
Expand Down
Expand Up @@ -89,4 +89,22 @@ public function testGetSetToken()
$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');
}
}

0 comments on commit 41872cd

Please sign in to comment.