Skip to content

Commit

Permalink
Merge pull request #15 from OskarStark/fix-user
Browse files Browse the repository at this point in the history
fix current user
  • Loading branch information
OskarStark authored Jun 13, 2018
2 parents fd3bc28 + 3b066fb commit 9920c54
Showing 1 changed file with 30 additions and 10 deletions.
40 changes: 30 additions & 10 deletions src/Context/SonataAdminContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ final class SonataAdminContext extends RawMinkContext implements CustomSnippetAc
{
const DEFAULT_USERNAME = '[email protected]';

/**
* @var UserInterface
*/
private $user;

/**
* @var UserManagerInterface
*/
Expand Down Expand Up @@ -316,6 +321,8 @@ public function iAmAnAuthenticatedUser()

$this->userManager->save($user);

$this->user = $user;

$this->createUserSession($user);
}

Expand All @@ -331,19 +338,13 @@ public function iAmAnAuthenticatedUser()
*/
public function iHaveRole($role)
{
$driver = $this->getSession()->getDriver();

$user = $this->userManager->findOneBy(['username' => self::DEFAULT_USERNAME]);
if (null === $user) {
throw new ExpectationException(
sprintf('User with username "%s" does not exist', self::DEFAULT_USERNAME),
$driver
);
}
$user = $this->getCurrentUser();

$user->setRoles([$role]);
$this->userManager->save($user);

$this->user = $user;

$this->createUserSession($user);
}

Expand All @@ -361,14 +362,16 @@ public function iAmAuthenticatedAsUser($username)
{
$driver = $this->getSession()->getDriver();

$user = $this->userManager->findOneBy(['username' => self::DEFAULT_USERNAME]);
$user = $this->userManager->findOneBy(['username' => $username]);
if (null === $user) {
throw new ExpectationException(
sprintf('User with username "%s" does not exist', $username),
$driver
);
}

$this->user = $user;

$this->createUserSession($user);
}

Expand Down Expand Up @@ -592,6 +595,23 @@ private function createUserSession(UserInterface $user)
$this->getSession()->setCookie($this->session->getName(), $this->session->getId());
}

private function getCurrentUser()
{
if (null != $this->user) {
return $this->user;
}

$user = $this->userManager->findOneBy(['username' => self::DEFAULT_USERNAME]);
if (null === $user) {
throw new ExpectationException(
sprintf('User with username "%s" does not exist', self::DEFAULT_USERNAME),
$this->getSession()->getDriver()
);
}

return $user;
}

/**
* Returns fixed step argument (with \\" replaced back to ").
*
Expand Down

0 comments on commit 9920c54

Please sign in to comment.