Skip to content

Instantly share code, notes, and snippets.

@elnur
Created May 14, 2014 12:48
Show Gist options
  • Select an option

  • Save elnur/d5c0040e1a308ec9d867 to your computer and use it in GitHub Desktop.

Select an option

Save elnur/d5c0040e1a308ec9d867 to your computer and use it in GitHub Desktop.
<?php
namespace Example\Manager;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;
use Example\Model\User;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
/**
* @Service("user_manager")
*/
class UserManager
{
/**
* @var EncoderFactoryInterface
*/
private $encoderFactory;
/**
* @InjectParams({
* "encoderFactory" = @Inject("security.encoder_factory")
* })
*
* @param EncoderFactoryInterface $encoderFactory
*/
public function __construct(EncoderFactoryInterface $encoderFactory)
{
$this->encoderFactory = $encoderFactory;
}
/**
* @param User $user
*/
public function save(User $user)
{
$encoder = $this->encoderFactory->getEncoder($user);
$password = $encoder->encodePassword($user->getPlainPassword(), $user->getSalt());
$user->setPassword($password);
}
}
<?php
namespace Example\Manager;
use PHPUnit_Framework_TestCase;
use Example\Model\User;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
class UserManagerTest extends PHPUnit_Framework_TestCase
{
const PLAIN_PASSWORD = 'password';
const ENCODED_PASSWORD = 'encoded-password';
/**
* @test
*/
public function shouldEncodePasswordIfPlainPasswordIsSet()
{
$encoderFactory = $this->getMock(EncoderFactoryInterface::class);
$userManager = new UserManager($encoderFactory);
$encoder = $this->getMock(PasswordEncoderInterface::class);
$user = new User([
'plainPassword' => self::PLAIN_PASSWORD,
]);
$encoderFactory
->expects($this->once())
->method('getEncoder')
->with($user)
->willReturn($encoder);
$encoder
->expects($this->once())
->method('encodePassword')
->with(self::PLAIN_PASSWORD, $user->getSalt())
->willReturn(self::ENCODED_PASSWORD);
$userManager->save($user);
$this->assertEquals(self::ENCODED_PASSWORD, $user->getPassword());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment