Adress comments

This commit is contained in:
Nicolas Le Goff
2013-10-09 11:11:33 +02:00
parent d5ff2f03e4
commit b45bc31135
15 changed files with 467 additions and 638 deletions

View File

@@ -20,12 +20,12 @@ class ManipulatorServiceProvider implements ServiceProviderInterface
{ {
public function register(Application $app) public function register(Application $app)
{ {
$app['model.user-manipulator'] = $app->share(function($app) { $app['manipulator.user'] = $app->share(function($app) {
return new UserManipulator($app['model.user-manager'], $app['EM']); return new UserManipulator($app['model.user-manager'], $app['auth.password-encoder'], $app['geonames.connector']);
}); });
$app['model.user-manager'] = $app->share(function($app) { $app['model.user-manager'] = $app->share(function($app) {
return new UserManager($app['auth.password-encoder'], $app['geonames.connector'], $app['EM'], $app['phraseanet.appbox']); return new UserManager($app['EM'], $app['phraseanet.appbox']->get_connection());
}); });
} }

View File

@@ -11,92 +11,48 @@
namespace Alchemy\Phrasea\Model\Manager; namespace Alchemy\Phrasea\Model\Manager;
use Alchemy\Geonames\Connector as GeonamesConnector;
use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectManager;
use Entities\EntityInterface;
use Entities\User; use Entities\User;
use Entities\UserSetting; use Entities\UserSetting;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
class UserManager class UserManager
{ {
/** @var \appbox */
protected $appbox;
/** @var ObjectManager */ /** @var ObjectManager */
protected $objectManager; protected $objectManager;
/** @var PasswordEncoderInterface */ /** @var \PDO */
protected $passwordEncoder; protected $appboxConnection;
/** @var GeonamesConnector */
private $geonamesConnector;
/** public function __construct(ObjectManager $om, \PDO $appboxConnection)
* The default user setting values.
*
* @var array
*/
private static $defaultUserSettings = array(
'view' => 'thumbs',
'images_per_page' => '20',
'images_size' => '120',
'editing_images_size' => '134',
'editing_top_box' => '180px',
'editing_right_box' => '400px',
'editing_left_box' => '710px',
'basket_sort_field' => 'name',
'basket_sort_order' => 'ASC',
'warning_on_delete_story' => 'true',
'client_basket_status' => '1',
'css' => '000000',
'start_page_query' => 'last',
'start_page' => 'QUERY',
'rollover_thumbnail' => 'caption',
'technical_display' => '1',
'doctype_display' => '1',
'bask_val_order' => 'nat',
'basket_caption_display' => '0',
'basket_status_display' => '0',
'basket_title_display' => '0'
);
public function __construct(PasswordEncoderInterface $passwordEncoder, GeonamesConnector $connector, ObjectManager $om, \appbox $appbox)
{ {
$this->appbox = $appbox;
$this->objectManager = $om; $this->objectManager = $om;
$this->passwordEncoder = $passwordEncoder; $this->appboxConnection = $appboxConnection;
$this->geonamesConnector = $connector;
} }
/** /**
* Creates a new user.
*
* @return User * @return User
*/ */
public function create() public function create()
{ {
$user = new User(); return new User();
foreach(self::$defaultUserSettings as $name => $value) {
$setting = new UserSetting();
$setting->setName($name);
$setting->setValue($value);
$user->getSettings()->add($setting);
};
return $user;
} }
/** /**
* @{inheritdoc} * Deletes an user.
*
* @param User $user
* @param type $flush
*/ */
public function delete(EntityInterface $user, $flush = true) public function delete(User $user, $flush = true)
{ {
$this->checkEntity($user);
$user->setDeleted(true); $user->setDeleted(true);
$user->setEmail(null); $user->setEmail(null);
$user->setLogin(sprintf('(#deleted_%s', $user->getLogin())); $user->setLogin(sprintf('(#deleted_%s', $user->getLogin()));
$this->cleanRelations($user); $this->cleanProperties($user);
$this->cleanRights($user);
$this->objectManager->persist($user); $this->objectManager->persist($user);
if ($flush) { if ($flush) {
@@ -105,68 +61,27 @@ class UserManager
} }
/** /**
* @{inheritdoc} * Updates an user.
*/
public function update(EntityInterface $user, $flush = true)
{
$this->checkEntity($user);
$this->objectManager->persist($user);
if ($flush) {
$this->objectManager->flush();
}
}
/**
* Updates the modelOf field from the template field value.
*
* @param UserInterface $user
* @param UserInterface $template
*/
public function onUpdateModel(User $user, User $template)
{
$user->setModelOf($template);
if (null !== $credential = $user->getFtpCredential()) {
$credential->resetCredentials();
}
$this->cleanSettings($user);
$user->reset();
}
/**
* Sets the given password.
*
* @param UserInterface $user
* @param password $password
*/
public function onUpdatePassword(User $user, $password)
{
$user->setNonce(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36));
$user->setPassword($this->passwordEncoder->encodePassword($password, $user->getNonce()));
}
/**
* Updates the country fields for a user according to the current geoname id field value.
* *
* @param User $user * @param User $user
* @param type $flush
*/ */
public function onUpdateGeonameId(User $user) public function update(User $user, $flush = true)
{ {
if (null === $user->getGeonameId()) { $this->objectManager->persist($user);
return; if ($flush) {
$this->objectManager->flush();
} }
}
try { /**
$country = $this->geonamesConnector * Gets the object manager.
->geoname($user->getGeonameId()) *
->get('country'); * @return ObjectManager
*/
if (isset($country['code'])) { public function getObjectManager()
$user->setCountry($country['code']); {
} return $this->objectManager;
} catch (GeonamesExceptionInterface $e) {
}
} }
/** /**
@@ -174,16 +89,16 @@ class UserManager
* *
* @param User $user * @param User $user
*/ */
public function cleanSettings(User $user) private function cleanSettings(User $user)
{ {
foreach($user->getNotificationSettings() as $userNotificatonSetting) { foreach($user->getNotificationSettings() as $userNotificationSetting) {
$userNotificatonSetting->setUser(null); $this->objectManager->remove($userNotificationSetting);
} }
$user->getNotificationSettings()->clear(); $user->getNotificationSettings()->clear();
foreach($user->getSettings() as $userSetting) { foreach($user->getSettings() as $userSetting) {
$userSetting->setUser(null); $this->objectManager->remove($userSetting);
} }
$user->getSettings()->clear(); $user->getSettings()->clear();
@@ -194,55 +109,95 @@ class UserManager
* *
* @param User $user * @param User $user
*/ */
public function cleanQueries(User $user) private function cleanQueries(User $user)
{ {
foreach($user->getQueries() as $userQuery) { foreach($user->getQueries() as $userQuery) {
$userQuery->setUser(null); $this->objectManager->remove($userQuery);
} }
$user->getQueries()->clear(); $user->getQueries()->clear();
} }
/** /**
* Removes all user's relations. * Removes user ftp credentials.
*
* @todo Removes order relationship, it is now a doctrine entity.
* *
* @param User $user * @param User $user
*/ */
private function cleanRelations(User $user) private function cleanFtpCredentials(User $user)
{ {
$conn = $this->appbox->get_connection(); if (null !== $credential = $user->getFtpCredential()) {
foreach(array( $this->objectManager->remove($credential);
'basusr',
'sbasusr',
'edit_presets',
'ftp_export',
'order',
'sselnew',
'tokens',
) as $table) {
$stmt = $conn->prepare('DELETE FROM `' .$table. '` WHERE usr_id = :usr_id');
$stmt->execute(array(':usr_id' => $user->getId()));
$stmt->closeCursor();
} }
unset($stmt);
$this->cleanSettings($user);
$this->cleanQueries($user);
} }
/** /**
* Checks whether given entity is an User one. * Removes user ftp export.
* *
* @param EntityInterface $entity * @param User $user
*
* @throws InvalidArgumentException If provided entity is not an User one.
*/ */
private function checkEntity(EntityInterface $entity) private function cleanFtpExports(User $user)
{ {
if (!$entity instanceof User) { $elements = $this->objectManager->getRepository('Entities\FtpExport')
throw new InvalidArgumentException(sprintf('Entity of type `%s` should be a `Entities\User` entity.', get_class($entity))); ->findBy(array('usrId' => $user->getId()));
foreach($elements as $element) {
$this->objectManager->remove($element);
}
}
/**
* Removes user orders.
*
* @param User $user
*/
private function cleanOrders(User $user)
{
$orders = $this->objectManager->getRepository('Entities\Order')
->findBy(array('usrId' => $user->getId()));
foreach($orders as $order) {
$this->objectManager->remove($order);
}
}
/**
* Removes all user's properties.
*
* @param User $user
*/
private function cleanProperties(User $user)
{
foreach(array(
'edit_presets',
'sselnew',
'tokens',
) as $table) {
$stmt = $this->appboxConnection->prepare('DELETE FROM `' .$table. '` WHERE usr_id = :usr_id');
$stmt->execute(array(':usr_id' => $user->getId()));
$stmt->closeCursor();
}
$this->cleanSettings($user);
$this->cleanQueries($user);
$this->cleanFtpCredentials($user);
$this->cleanOrders($user);
$this->cleanFtpExports($user);
}
/**
* Removes all user's rights.
*
* @param User $user
*/
private function cleanRights(User $user)
{
foreach(array(
'basusr',
'sbasusr',
) as $table) {
$stmt = $this->appboxConnection->prepare('DELETE FROM `' .$table. '` WHERE usr_id = :usr_id');
$stmt->execute(array(':usr_id' => $user->getId()));
$stmt->closeCursor();
} }
} }
} }

View File

@@ -19,7 +19,7 @@ use Doctrine\ORM\EntityRepository;
interface ManipulatorInterface interface ManipulatorInterface
{ {
/** /**
* Returns the entitiy repository. * Returns the entity repository.
* *
* @return EntityRepository * @return EntityRepository
*/ */

View File

@@ -12,12 +12,14 @@
namespace Alchemy\Phrasea\Model\Manipulator; namespace Alchemy\Phrasea\Model\Manipulator;
use Alchemy\Geonames\Connector as GeonamesConnector; use Alchemy\Geonames\Connector as GeonamesConnector;
use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface;
use Alchemy\Phrasea\Model\Manager\UserManager; use Alchemy\Phrasea\Model\Manager\UserManager;
use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectManager;
use Entities\User; use Entities\User;
use Repositories\UserRepository; use Repositories\UserRepository;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
/** /**
* Manages common operations for the users. * Manages common operations for the users.
@@ -26,16 +28,16 @@ class UserManipulator implements ManipulatorInterface
{ {
/** @var UserManager */ /** @var UserManager */
private $manager; private $manager;
/** @var UserRepository */ /** @var PasswordEncoderInterface */
private $repository; protected $passwordEncoder;
/** @var ObjectManager */ /** @var GeonamesConnector */
private $om; private $geonamesConnector;
public function __construct(UserManager $manager, ObjectManager $om) public function __construct(UserManager $manager, PasswordEncoderInterface $passwordEncoder, GeonamesConnector $connector)
{ {
$this->manager = $manager; $this->manager = $manager;
$this->om = $om; $this->passwordEncoder = $passwordEncoder;
$this->repository = $om->getRepository('Entities\User'); $this->geonamesConnector = $connector;
} }
/** /**
@@ -43,7 +45,7 @@ class UserManipulator implements ManipulatorInterface
*/ */
public function getRepository() public function getRepository()
{ {
return $this->repository; return $this->manager->getObjectManager()->getRepository('Entities\User');
} }
/** /**
@@ -56,151 +58,87 @@ class UserManipulator implements ManipulatorInterface
* *
* @return User * @return User
* *
* @throws InvalidArgumentException if login, email or password is not valid. * @throws InvalidArgumentException if login or email is not valid.
* @throws RuntimeException if login or email already exists. * @throws RuntimeException if login or email already exists.
*/ */
public function createUser($login, $password, $email = null, $admin = false) public function createUser($login, $password, $email = null, $admin = false)
{ {
$user = $this->manager->create(); $user = $this->manager->create();
$this->setLogin($user, $login); $this->doSetLogin($user, $login);
$this->setEmail($user, $email); $this->doSetEmail($user, $email);
$this->setPassword($user, $password); $this->doSetPassword($user, $password);
$user->setAdmin($admin); $user->setAdmin($admin);
$this->manager->update($user); $this->manager->update($user);
return $user; return $user;
} }
/**
* Creates a guest user and returns it.
*
* @return User
*
* @throws RuntimeException if guest already exists.
*/
public function createGuest()
{
$user = $this->manager->create();
$this->setLogin($user, User::USER_GUEST);
$this->setPassword($user, substr(uniqid ('', true), -6));
$this->manager->update($user);
return $user;
}
/**
* Creates an auto register user and returns it.
*
* @return User
*
* @throws RuntimeException if autoregister already exists.
*/
public function createAutoRegister()
{
$user = $this->manager->create();
$this->setLogin($user, User::USER_AUTOREGISTER);
$this->setPassword($user, substr(uniqid ('', true), -6));
$this->manager->update($user);
return $user;
}
/** /**
* Creates a template user and returns it. * Creates a template user and returns it.
* *
* @param string $name * @param string $login
* @param User $template * @param User $owner
* *
* @return User * @return User The template
* *
* @throws InvalidArgumentException if name is not valid. * @throws InvalidArgumentException if login is not valid.
* @throws RuntimeException if name already exists. * @throws RuntimeException if login already exists.
*/ */
public function createTemplate($name, User $template) public function createTemplate($login, User $owner)
{ {
$user = $this->manager->create(); $user = $this->manager->create();
$this->setLogin($user, $name); $this->doSetLogin($user, $login);
$this->setPassword($user, substr(uniqid ('', true), -6)); $user->setModelOf($owner);
$this->setModelOf($user, $template);
$this->manager->update($user); $this->manager->update($user);
return $user; return $user;
} }
/** /**
* Sets the password for the given user. * Sets the password for an user.
* *
* @param user $user * @param user $user
* @param string $password * @param string $password
*
* @throws InvalidArgumentException if password is not valid.
*/ */
public function setPassword(User $user, $password) public function setPassword(User $user, $password)
{ {
if (trim($password) === '') { $this->doSetPassword($user, $password);
throw new InvalidArgumentException('Invalid password.'); $this->manager->update($user);
}
$this->manager->onUpdatePassword($user, $password);
} }
/** /**
* Sets the template for the given user. * Sets the geonameid for an user.
* *
* @param User $user * @param User $user
* @param User $template
*
* @throws InvalidArgumentException if user and template are the same.
*/
public function setModelOf(User $user, User $template)
{
if ($user->getLogin() === $template->getLogin()) {
throw new InvalidArgumentException(sprintf('Can not set same user %s as template.', $user->getLogin()));
}
$this->manager->onUpdateModel($user, $template);
}
/**
* Sets the geonameid for the given user.
*
* @param User $user
* @param integer $geonameid * @param integer $geonameid
* *
* @throws InvalidArgumentException if geonameid is not valid. * @throws InvalidArgumentException if geonameid is not valid.
*/ */
public function setGeonameId(User $user, $geonameid) public function setGeonameId(User $user, $geonameid)
{ {
$user->setGeonameId($geonameid); if (null === $geonameid) {
$this->manager->onUpdateGeonameId($user); return;
}
try {
$country = $this->geonamesConnector->geoname($geonameid)->get('country');
$user->setGeonameId($geonameid);
if (isset($country['code'])) {
$user->setCountry($country['code']);
}
} catch (GeonamesExceptionInterface $e) {
$user->setCountry(null);
}
$this->manager->update($user);
} }
/** /**
* Sets the login for the given user. * Sets email for an user.
* *
* @param User $user * @param User $user
* @param sring $login
*
* @throws InvalidArgumentException if login is not valid.
* @throws RuntimeException if login already exists.
*/
public function setLogin(User $user, $login)
{
if (trim($login) === '') {
throw new InvalidArgumentException('Invalid login.');
}
if (null !== $this->repository->findByLogin($login)) {
throw new RuntimeException(sprintf('User with login %s already exists.', $login));
}
$user->setLogin($login);
}
/**
* Sets email for given user.
*
* @param User $user
* @param string $email * @param string $email
* *
* @throws InvalidArgumentException if email is not valid or already exists. * @throws InvalidArgumentException if email is not valid or already exists.
@@ -208,11 +146,82 @@ class UserManipulator implements ManipulatorInterface
*/ */
public function setEmail(User $user, $email) public function setEmail(User $user, $email)
{ {
if (null !== $email && !preg_match('/.+@.+\..+/', trim($email))) { $this->doSetEmail($user, $email);
throw new InvalidArgumentException('Invalid email.'); $this->manager->update($user);
}
/**
* Promotes users.
*
* @param User|User[] $users
*/
public function promote($users)
{
foreach ($this->makeTraversable($users) as $user) {
$user->setAdmin(true);
$this->manager->update($user);
}
}
/**
* Demotes users.
*
* @param User|User[] $users
*/
public function demote($users)
{
foreach ($this->makeTraversable($users) as $user) {
$user->setAdmin(false);
$this->manager->update($user);
}
}
/**
* Sets the password for an user.
*
* @param user $user
* @param string $password
*/
private function doSetPassword(User $user, $password)
{
$user->setNonce(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36));
$user->setPassword($this->passwordEncoder->encodePassword($password, $user->getNonce()));
}
/**
* Sets the login for an user.
*
* @param User $user
* @param sring $login
*
* @throws InvalidArgumentException if login is not valid.
* @throws RuntimeException if login already exists.
*/
private function doSetLogin(User $user, $login)
{
if (null !== $this->getRepository()->findByLogin($login)) {
throw new RuntimeException(sprintf('User with login %s already exists.', $login));
} }
if (null !== $this->repository->findByEmail($email)) { $user->setLogin($login);
}
/**
* Sets email for an user.
*
* @param User $user
* @param string $email
*
* @throws InvalidArgumentException if email is not valid or already exists.
* @throws RuntimeException if email already exists.
*/
private function doSetEmail(User $user, $email)
{
if (null !== $email && false === (Boolean) \Swift_Validate::email($email)) {
throw new InvalidArgumentException(sprintf('Email %s is not legal.', $email));
}
if (null !== $this->getRepository()->findByEmail($email)) {
throw new RuntimeException(sprintf('User with email %s already exists.', $email)); throw new RuntimeException(sprintf('User with email %s already exists.', $email));
} }
@@ -220,56 +229,18 @@ class UserManipulator implements ManipulatorInterface
} }
/** /**
* Promotes the given users. * Makes given variable traversable.
* *
* @param User|array $user * @param mixed $var
*
* @return array
*/ */
public function promote($users) private function makeTraversable($var)
{ {
if (!is_array($users)) { if (!is_array($var) && !$var instanceof \Traversable) {
$users = array($users); return array($var);
} }
foreach ($users as $user) { return $var;
$this->doPromoteUser($user);
}
}
/**
* Demotes the given users.
*
* @param User|array $users
*/
public function demote($users)
{
if (!is_array($users)) {
$users = array($users);
}
foreach ($users as $user) {
$this->doDemoteUser($user);
}
}
/**
* Promove given user.
*
* @param User $user
*/
private function doDemoteUser(User $user)
{
$user->setAdmin(false);
$this->manager->update($user);
}
/**
* Demotes given user.
*
* @param User $user
*/
private function doPromoteUser(User $user)
{
$user->setAdmin(true);
$this->manager->update($user);
} }
} }

View File

@@ -333,22 +333,4 @@ class FtpCredential
return $this; return $this;
} }
/**
* @return FtpCredential
*/
public function resetCredentials()
{
$this->active = false;
$this->address = '';
$this->login = '';
$this->maxRetry = 5;
$this->passive = false;
$this->password = '';
$this->receptionFolder = '';
$this->repositoryPrefixName = '';
$this->ssl = false;
return $this;
}
} }

View File

@@ -43,6 +43,35 @@ class User
const USER_GUEST = 'guest'; const USER_GUEST = 'guest';
const USER_AUTOREGISTER = 'autoregister'; const USER_AUTOREGISTER = 'autoregister';
/**
* The default user setting values.
*
* @var array
*/
private static $defaultUserSettings = array(
'view' => 'thumbs',
'images_per_page' => '20',
'images_size' => '120',
'editing_images_size' => '134',
'editing_top_box' => '180px',
'editing_right_box' => '400px',
'editing_left_box' => '710px',
'basket_sort_field' => 'name',
'basket_sort_order' => 'ASC',
'warning_on_delete_story' => 'true',
'client_basket_status' => '1',
'css' => '000000',
'start_page_query' => 'last',
'start_page' => 'QUERY',
'rollover_thumbnail' => 'caption',
'technical_display' => '1',
'doctype_display' => '1',
'bask_val_order' => 'nat',
'basket_caption_display' => '0',
'basket_status_display' => '0',
'basket_title_display' => '0'
);
/** /**
* @ORM\Column(type="integer") * @ORM\Column(type="integer")
* @ORM\Id * @ORM\Id
@@ -61,7 +90,7 @@ class User
private $email; private $email;
/** /**
* @ORM\Column(type="string", length=128) * @ORM\Column(type="string", length=128, nullable=true)
*/ */
private $password; private $password;
@@ -225,26 +254,36 @@ class User
/** /**
* @ORM\OneToOne(targetEntity="User") * @ORM\OneToOne(targetEntity="User")
* @ORM\JoinColumn(name="model_of", referencedColumnName="id") * @ORM\JoinColumn(name="model_of", referencedColumnName="id")
*
* @var User
**/ **/
private $modelOf; private $modelOf;
/** /**
* @ORM\OneToOne(targetEntity="FtpCredential", mappedBy="user", cascade={"all"}) * @ORM\OneToOne(targetEntity="FtpCredential", mappedBy="user", cascade={"all"})
*
* @var FtpCredential
**/ **/
private $ftpCredential; private $ftpCredential;
/** /**
* @ORM\OneToMany(targetEntity="UserQuery", mappedBy="user", cascade={"all"}) * @ORM\OneToMany(targetEntity="UserQuery", mappedBy="user", cascade={"all"})
*
* @var UserQuery[]
**/ **/
private $queries; private $queries;
/** /**
* @ORM\OneToMany(targetEntity="UserSetting", mappedBy="user", cascade={"all"}) * @ORM\OneToMany(targetEntity="UserSetting", mappedBy="user", cascade={"all"})
*
* @var UserSetting[]
**/ **/
private $settings; private $settings;
/** /**
* @ORM\OneToMany(targetEntity="UserNotificationSetting", mappedBy="user", cascade={"all"}) * @ORM\OneToMany(targetEntity="UserNotificationSetting", mappedBy="user", cascade={"all"})
*
* @var UserNotificationSetting[]
**/ **/
private $notificationSettings; private $notificationSettings;
@@ -253,6 +292,11 @@ class User
*/ */
private $acl; private $acl;
/**
* @var ArrayCollection
*/
private $cachedSettings;
/** /**
* Constructor * Constructor
*/ */
@@ -702,11 +746,11 @@ class User
} }
/** /**
* @param User $user * @param User $owner
*/ */
public function setModelOf(User $user) public function setModelOf(User $owner)
{ {
$this->modelOf = $user; $this->modelOf = $owner;
} }
/** /**
@@ -870,7 +914,7 @@ class User
* *
* @return User * @return User
*/ */
public function setFtpCredential(FtpCredential $ftpCredential) public function setFtpCredential(FtpCredential $ftpCredential = null)
{ {
$this->ftpCredential = $ftpCredential; $this->ftpCredential = $ftpCredential;
@@ -886,13 +930,13 @@ class User
} }
/** /**
* @param ArrayCollection $queries * @param UserQuery $query
* *
* @return User * @return User
*/ */
public function setQueries(ArrayCollection $queries) public function AddQuery(UserQuery $query)
{ {
$this->queries = $queries; $this->queries->add($query);
return $this; return $this;
} }
@@ -906,13 +950,42 @@ class User
} }
/** /**
* @param ArrayCollection $settings * Retrieves user setting value.
*
* @param string $name
* @param mixed $default
*
* @return string
*/
public function getSettingValue($name, $default = null)
{
if (null === $this->cachedSettings) {
$settings = self::$defaultUserSettings;
foreach ($this->settings as $setting) {
$settings[$setting->getName()] = $setting->getValue();
}
$this->cachedSettings = $settings;
}
// checks for stored settings
if (array_key_exists($name, $this->cachedSettings)) {
return $this->cachedSettings[$name];
}
return $default;
}
/**
* @param UserSetting $setting
* *
* @return User * @return User
*/ */
public function setSettings(ArrayCollection $settings) public function addSetting(UserSetting $setting)
{ {
$this->settings = $settings; $this->cachedSettings = null;
$this->settings->add($setting);
return $this; return $this;
} }
@@ -926,13 +999,13 @@ class User
} }
/** /**
* @param ArrayCollection $notificationSettings * @param UserNotificationSetting $notificationSetting
* *
* @return User * @return User
*/ */
public function setNotificationSettings(ArrayCollection $notificationSettings) public function addNotificationSettings(UserNotificationSetting $notificationSetting)
{ {
$this->notificationSettings = $notificationSettings; $this->notificationSettings->add($notificationSetting);
return $this; return $this;
} }
@@ -986,32 +1059,4 @@ class User
return _('Unnamed user'); return _('Unnamed user');
} }
/**
* Reset user informations.
*
* @return User
*/
public function reset()
{
$this->setCity('');
$this->setAddress('');
$this->setCountry('');
$this->setZipCode('');
$this->setTimezone('');
$this->setCompany('');
$this->setEmail(null);
$this->setFax('');
$this->setPhone('');
$this->setFirstName('');
$this->setGender(null);
$this->setGeonameId(null);
$this->setJob('');
$this->setActivity('');
$this->setLastName('');
$this->setMailNotificationsActivated(false);
$this->setRequestNotificationsActivated(false);
return $this;
}
} }

View File

@@ -33,7 +33,7 @@ class UserNotificationSetting
private $id; private $id;
/** /**
* @ORM\Column(type="integer", nullable=true, name="usr_id") * @ORM\Column(type="integer", name="usr_id")
*/ */
private $usrId; private $usrId;

View File

@@ -29,7 +29,7 @@ class UserQuery
private $id; private $id;
/** /**
* @ORM\Column(type="integer", nullable=true, name="usr_id") * @ORM\Column(type="integer", name="usr_id")
*/ */
private $usrId; private $usrId;

View File

@@ -33,7 +33,7 @@ class UserSetting
private $id; private $id;
/** /**
* @ORM\Column(type="integer", nullable=true) * @ORM\Column(type="integer", name="usr_id")
*/ */
private $usrId; private $usrId;

View File

@@ -58,21 +58,25 @@ class patch_3902 implements patchInterface
$conn = $app['phraseanet.appbox']->get_connection(); $conn = $app['phraseanet.appbox']->get_connection();
$em = $app['EM']; $em = $app['EM'];
$em->getEventManager()->removeEventSubscriber(new TimestampableListener()); $em->getEventManager()->removeEventSubscriber(new TimestampableListener());
$this->updateUsers($em, $conn); $this->updateUsers($em, $conn);
$this->updateModels($em, $conn); $this->updateModels($em, $conn);
$em->getEventManager()->addEventSubscriber(new TimestampableListener()); $em->getEventManager()->addEventSubscriber(new TimestampableListener());
} }
/** /**
* Sets user entity from usr table. * Sets user entity from usr table.
*/ */
private function updateUsers(EntityManager $em, $conn) private function updateUsers(EntityManager $em, $conn)
{ {
$sql = 'SELECT * FROM usr'; $sql = 'SELECT activite, adresse, create_db, canchgftpprofil, canchgprofil, ville,
societe, pays, usr_mail, fax, usr_prenom, geonameid, invite, fonction, last_conn, lastModel,
usr_nom, ldap_created, locale, usr_login, mail_locked, mail_notifications, nonce, usr_password, push_list,
request_notifications, salted_password, usr_sexe, tel, timezone, cpostal, usr_creationdate, usr_modificationdate
FROM usr WHERE model_of = 0';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute(); $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
@@ -155,34 +159,33 @@ class patch_3902 implements patchInterface
$em->flush(); $em->flush();
$em->clear(); $em->clear();
} }
/** /**
* Sets model from usr table. * Sets model from usr table.
*/ */
private function updateModels(EntityManager $em, $conn) private function updateModels(EntityManager $em, $conn)
{ {
$sql = 'SELECT model_of, usr_login FROM usr WHERE model_of > 0 AND usr_login IS NOT NULL'; $sql = "SELECT model_of, usr_login
FROM usr
WHERE model_of > 0";
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute(); $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor(); $stmt->closeCursor();
$n = 0; $n = 0;
$repository = $em->getRepository('Entities\User'); $repository = $em->getRepository('Entities\User');
foreach ($rows as $row) { foreach ($rows as $row) {
if (null === $user = $repository->findOneByLogin($row['usr_login'])) { $user = $repository->findOneByLogin($row['usr_login']);
continue;
}
if (null === $template = $repository->find($row['model_of'])) { if (null === $template = $repository->find($row['model_of'])) {
continue; $em->remove($user);
} else {
$user->setModelOf($template);
$em->persist($user);
} }
$user->setModelOf($template);
$em->persist($user);
$n++; $n++;

View File

@@ -7,7 +7,7 @@ class ManipulatorServiceProviderTest extends ServiceProviderTestCase
public function provideServiceDescription() public function provideServiceDescription()
{ {
return array( return array(
array('Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider', 'model.user-manipulator', '\Alchemy\Phrasea\Model\Manipulator\UserManipulator'), array('Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider', 'manipulator.user', '\Alchemy\Phrasea\Model\Manipulator\UserManipulator'),
array('Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider', 'model.user-manager', '\Alchemy\Phrasea\Model\Manager\UserManager'), array('Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider', 'model.user-manager', '\Alchemy\Phrasea\Model\Manager\UserManager'),
); );
} }

View File

@@ -11,9 +11,10 @@
namespace Alchemy\Tests\Phrasea\Model\Manipulator; namespace Alchemy\Tests\Phrasea\Model\Manipulator;
use Doctrine\Common\Collections\ArrayCollection;
use Alchemy\Phrasea\Model\Manager\UserManager; use Alchemy\Phrasea\Model\Manager\UserManager;
use Entities\UserNotificationSetting;
use Entities\UserQuery; use Entities\UserQuery;
use Entities\UserSetting;
class UserManagerTest extends \PhraseanetPHPUnitAbstract class UserManagerTest extends \PhraseanetPHPUnitAbstract
{ {
@@ -25,139 +26,43 @@ class UserManagerTest extends \PhraseanetPHPUnitAbstract
public function testDeleteUser() public function testDeleteUser()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'password');
$query = new UserQuery();
$query->setUser($user);
$query->setQuery('a query');
$query->setUsrId(1);
$user->addQuery($query);
$setting = new UserSetting();
$setting->setUsrId(1);
$setting->setUser($user);
$setting->setName('setting');
$setting->setValue(0);
$user->addSetting($setting);
$setting = new UserNotificationSetting();
$setting->setUsrId(1);
$setting->setUser($user);
$setting->setName('setting');
$setting->setValue(0);
$user->addNotificationSettings($setting);
self::$DI['app']['model.user-manager']->update($user); self::$DI['app']['model.user-manager']->update($user);
self::$DI['app']['model.user-manager']->delete($user); self::$DI['app']['model.user-manager']->delete($user);
$this->assertTrue($user->isDeleted()); $this->assertTrue($user->isDeleted());
$this->assertNull($user->getEmail()); $this->assertNull($user->getEmail());
$this->assertEquals('(#deleted_', substr($user->getLogin(), 0, 10)); $this->assertEquals('(#deleted_', substr($user->getLogin(), 0, 10));
} $user = self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('(#deleted_login');
$this->assertEquals(0, $user->getSettings()->count());
public function testInvalidDeleteUser() $this->assertEquals(0, $user->getNotificationSettings()->count());
{ $this->assertEquals(0, $user->getQueries()->count());
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Entity of type `Entities\UserQuery` should be a `Entities\User` entity.'
);
$wrongEntity = new UserQuery();
self::$DI['app']['model.user-manager']->delete($wrongEntity);
} }
public function testUpdateUser() public function testUpdateUser()
{ {
$template = self::$DI['app']['model.user-manipulator']->createUser('template', 'password'); $template = self::$DI['app']['manipulator.user']->createUser('template', 'password');
self::$DI['app']['model.user-manager']->update($template); self::$DI['app']['model.user-manager']->update($template);
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'password');
$user->setModelOf($template); $user->setModelOf($template);
self::$DI['app']['model.user-manager']->update($user); self::$DI['app']['model.user-manager']->update($user);
$this->assertNotNull($user->getPassword()); $this->assertNotNull($user->getPassword());
$this->assertNotNull($user->getModelOf()); $this->assertNotNull($user->getModelOf());
} }
public function testInvalidUpdateUser()
{
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Entity of type `Entities\UserQuery` should be a `Entities\User` entity.'
);
$wrongEntity = new UserQuery();
self::$DI['app']['model.user-manager']->update($wrongEntity);
}
public function testUpdateTemplate()
{
$user = $this->getMock('Entities\User', array('getId', 'setModelOf', 'reset'));
$user->expects($this->any())->method('getId')->will($this->returnValue(1));
$ftpCredential = $this->getMock('Entities\FtpCredential');
$ftpCredential->expects($this->once())->method('resetCredentials');
$user->setFtpCredential($ftpCredential);
$settings = $this->getMock('Doctrine\Common\Collections\ArrayCollection', array('clear'));
$settings->expects($this->once())->method('clear');
$user->setSettings($settings);
$notifSettings = $this->getMock('Doctrine\Common\Collections\ArrayCollection', array('clear'));
$notifSettings->expects($this->once())->method('clear');
$user->setNotificationSettings($notifSettings);
$template = $this->getMock('Entities\User', array('getId'));
$template->expects($this->any())->method('getId')->will($this->returnValue(2));
$user->expects($this->once())->method('reset');
self::$DI['app']['model.user-manager']->onUpdateModel($user, $template);
}
public function testUpdatePassword()
{
$user = self::$DI['app']['model.user-manager']->create();
self::$DI['app']['model.user-manager']->onUpdatePassword($user, $hashPass = uniqid());
$this->assertNotNull($user->getPassword());
$this->assertNotEquals($hashPass, $user->getPassword());
$this->assertNotNull($user->getNonce());
}
public function testUpdateCountry()
{
$geonamesConnector = $this->getMockBuilder('Alchemy\Geonames\Connector')
->disableOriginalConstructor()
->getMock();
$geoname = $this->getMockBuilder('Alchemy\Geonames\Geoname')
->disableOriginalConstructor()
->getMock();
$geoname->expects($this->once())
->method('get')
->with($this->equalTo('country'))
->will($this->returnValue(array('code' => 'fr')));
$geonamesConnector->expects($this->once())
->method('geoname')
->will($this->returnValue($geoname));
$userManager = new UserManager(
$this->getMock('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface'),
$geonamesConnector,
self::$DI['app']['EM'],
self::$DI['app']['phraseanet.appbox']
);
$user = self::$DI['app']['model.user-manager']->create();
$user->setGeonameId(4);
$userManager->onUpdateGeonameId($user);
$this->assertEquals('fr', $user->getCountry());
}
public function testCleanSettings()
{
self::$DI['app']['model.user-manipulator']->createUser('login', 'toto');
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login');
$this->assertGreaterThan(0, $user->getSettings()->count());
self::$DI['app']['model.user-manager']->cleanSettings($user);
self::$DI['app']['model.user-manager']->update($user);
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login');
$this->assertEquals(0, $user->getSettings()->count());
}
public function testCleanQueries()
{
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'toto');
$userQuery = new UserQuery();
$userQuery->setUser($user);
$userQuery->setQuery('blabla');
$user->setQueries(new ArrayCollection(array($userQuery)));
self::$DI['app']['model.user-manager']->update($user);
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login');
$this->assertGreaterThan(0, $user->getQueries()->count());
self::$DI['app']['model.user-manager']->cleanQueries($user);
self::$DI['app']['model.user-manager']->update($user);
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login');
$this->assertEquals(0, $user->getQueries()->count());
}
} }

View File

@@ -13,51 +13,38 @@ namespace Alchemy\Tests\Phrasea\Model\Manipulator;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Alchemy\Phrasea\Model\Manipulator\UserManipulator; use Alchemy\Phrasea\Model\Manipulator\UserManipulator;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Entities\User; use Entities\User;
class UserManipulatorTest extends \PhraseanetPHPUnitAbstract class UserManipulatorTest extends \PhraseanetPHPUnitAbstract
{ {
public function testCreateUser() public function testCreateUser()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'pass'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'pass');
$this->assertInstanceOf('\Entities\User', self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login')); $this->assertInstanceOf('\Entities\User', self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('login'));
} }
public function testCreateAdminUser() public function testCreateAdminUser()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'pass', 'admin@admin.com', true); $user = self::$DI['app']['manipulator.user']->createUser('login', 'pass', 'admin@admin.com', true);
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login'); $user = self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('login');
$this->assertTrue($user->isAdmin()); $this->assertTrue($user->isAdmin());
$this->assertNotNull($user->getEmail()); $this->assertNotNull($user->getEmail());
} }
public function testCreateGuest()
{
$user = self::$DI['app']['model.user-manipulator']->createGuest();
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin(User::USER_GUEST);
$this->assertTrue($user->isSpecial());
}
public function testCreateAutoRegister()
{
$user = self::$DI['app']['model.user-manipulator']->createAutoRegister();
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin(User::USER_AUTOREGISTER);
$this->assertTrue($user->isSpecial());
}
public function testCreateTemplate() public function testCreateTemplate()
{ {
$template = self::$DI['app']['model.user-manipulator']->createUser('login', 'pass'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'pass');
$user = self::$DI['app']['model.user-manipulator']->createTemplate('test', $template); $template = self::$DI['app']['manipulator.user']->createTemplate('test', $user);
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('test'); $user = self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('test');
$this->assertTrue($user->isTemplate()); $this->assertTrue($user->isTemplate());
} }
public function testSetPassword() public function testSetPassword()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'password');
$curPassword = $user->getPassword(); $curPassword = $user->getPassword();
self::$DI['app']['model.user-manipulator']->setPassword($user, 'toto'); self::$DI['app']['manipulator.user']->setPassword($user, 'toto');
$this->assertNotEquals($curPassword, $user->getPassword()); $this->assertNotEquals($curPassword, $user->getPassword());
} }
@@ -67,11 +54,29 @@ class UserManipulatorTest extends \PhraseanetPHPUnitAbstract
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$manager->expects($this->once()) $geoname = $this->getMockBuilder('Alchemy\Geonames\Geoname')
->method('onUpdateGeonameId'); ->disableOriginalConstructor()
->getMock();
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password'); $geoname->expects($this->once())
$manipulator = new UserManipulator($manager, self::$DI['app']['EM']); ->method('get')
->with($this->equalTo('country'))
->will($this->returnValue(array('code' => 'fr')));
$geonamesConnector = $this->getMockBuilder('Alchemy\Geonames\Connector')
->disableOriginalConstructor()
->getMock();
$geonamesConnector->expects($this->once())
->method('geoname')
->with($this->equalTo(4))
->will($this->returnValue($geoname));
$passwordInterface = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')
->getMock();
$user = self::$DI['app']['manipulator.user']->createUser('login', 'password');
$manipulator = new UserManipulator($manager, $passwordInterface, $geonamesConnector);
$manipulator->setGeonameId($user, 4); $manipulator->setGeonameId($user, 4);
$this->assertEquals(4, $user->getGeonameId()); $this->assertEquals(4, $user->getGeonameId());
@@ -79,56 +84,65 @@ class UserManipulatorTest extends \PhraseanetPHPUnitAbstract
public function testPromote() public function testPromote()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'toto'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'toto');
$this->assertFalse($user->isAdmin()); $this->assertFalse($user->isAdmin());
$user2 = self::$DI['app']['model.user-manipulator']->createUser('login2', 'toto'); $user2 = self::$DI['app']['manipulator.user']->createUser('login2', 'toto');
$this->assertFalse($user2->isAdmin()); $this->assertFalse($user2->isAdmin());
self::$DI['app']['model.user-manipulator']->promote(array($user, $user2)); self::$DI['app']['manipulator.user']->promote(array($user, $user2));
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login'); $user = self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('login');
$this->assertTrue($user->isAdmin()); $this->assertTrue($user->isAdmin());
$user2 = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login'); $user2 = self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('login');
$this->assertTrue($user2->isAdmin()); $this->assertTrue($user2->isAdmin());
} }
public function testDemote() public function testDemote()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'toto', null, true); $user = self::$DI['app']['manipulator.user']->createUser('login', 'toto', null, true);
$this->assertTrue($user->isAdmin()); $this->assertTrue($user->isAdmin());
self::$DI['app']['model.user-manipulator']->demote($user); self::$DI['app']['manipulator.user']->demote($user);
$user = self::$DI['app']['model.user-manipulator']->getRepository()->findOneByLogin('login'); $user = self::$DI['app']['manipulator.user']->getRepository()->findOneByLogin('login');
$this->assertFalse($user->isAdmin()); $this->assertFalse($user->isAdmin());
} }
public function testSetLogin()
{
self::$DI['app']['model.user-manipulator']->createUser('login', 'password');
$user = self::$DI['app']['model.user-manipulator']->createUser('login2', 'password');
$this->setExpectedException(
'Alchemy\Phrasea\Exception\RuntimeException',
'User with login login already exists.'
);
self::$DI['app']['model.user-manipulator']->setLogin($user, 'login');
}
public function testSetEmail() public function testSetEmail()
{ {
self::$DI['app']['model.user-manipulator']->createUser('login', 'password', 'test@test.fr'); self::$DI['app']['manipulator.user']->createUser('login', 'password', 'test@test.fr');
$user = self::$DI['app']['model.user-manipulator']->createUser('login2', 'password', 'test2@test.fr'); $user = self::$DI['app']['manipulator.user']->createUser('login2', 'password', 'test2@test.fr');
$this->setExpectedException( $this->setExpectedException(
'Alchemy\Phrasea\Exception\RuntimeException', 'Alchemy\Phrasea\Exception\RuntimeException',
'User with email test@test.fr already exists.' 'User with email test@test.fr already exists.'
); );
self::$DI['app']['model.user-manipulator']->setEmail($user, 'test@test.fr'); self::$DI['app']['manipulator.user']->setEmail($user, 'test@test.fr');
} }
public function testInvalidGeonamedId() public function testInvalidGeonamedId()
{ {
$manager = $this->getMockBuilder('Alchemy\Phrasea\Model\Manager\UserManager') $manager = $this->getMockBuilder('Alchemy\Phrasea\Model\Manager\UserManager')
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password');
$manipulator = new UserManipulator($manager, self::$DI['app']['EM']); $geoname = $this->getMockBuilder('Alchemy\Geonames\Geoname')
->disableOriginalConstructor()
->getMock();
$geoname->expects($this->once())
->method('get')
->with($this->equalTo('country'))
->will($this->returnValue(array('code' => 'fr')));
$geonamesConnector = $this->getMockBuilder('Alchemy\Geonames\Connector')
->disableOriginalConstructor()
->getMock();
$geonamesConnector->expects($this->once())
->method('geoname')
->with($this->equalTo(-1))
->will($this->returnValue($geoname));
$passwordInterface = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')
->getMock();
$user = self::$DI['app']['manipulator.user']->createUser('login', 'password');
$manipulator = new UserManipulator($manager, $passwordInterface, $geonamesConnector);
$this->setExpectedException( $this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException', 'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid geonameid -1.' 'Invalid geonameid -1.'
@@ -136,42 +150,24 @@ class UserManipulatorTest extends \PhraseanetPHPUnitAbstract
$manipulator->setGeonameId($user, -1); $manipulator->setGeonameId($user, -1);
} }
public function testInvalidLogin()
{
self::$DI['app']['model.user-manipulator']->createUser('login', 'password');
$user = self::$DI['app']['model.user-manipulator']->createUser('login2', 'password');
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid login.'
);
self::$DI['app']['model.user-manipulator']->setLogin($user, '');
}
public function testInvalidEmail() public function testInvalidEmail()
{ {
self::$DI['app']['model.user-manipulator']->createUser('login', 'password', 'test@test.fr'); self::$DI['app']['manipulator.user']->createUser('login', 'password', 'test@test.fr');
$user = self::$DI['app']['model.user-manipulator']->createUser('login2', 'password', 'test2@test.fr'); $user = self::$DI['app']['manipulator.user']->createUser('login2', 'password', 'test2@test.fr');
$this->setExpectedException( $this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException', 'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid email.' 'Email testtest.fr is not legal.'
); );
self::$DI['app']['model.user-manipulator']->setEmail($user, 'testtest.fr'); self::$DI['app']['manipulator.user']->setEmail($user, 'testtest.fr');
} }
public function testInvalidPassword()
{
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password');
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid password.'
);
self::$DI['app']['model.user-manipulator']->setPassword($user, '');
}
public function testInvalidSetModelOf() public function testInvalidSetModelOf()
{ {
$user = self::$DI['app']['model.user-manipulator']->createUser('login', 'password'); $user = self::$DI['app']['manipulator.user']->createUser('login', 'password');
$this->setExpectedException('Alchemy\Phrasea\Exception\InvalidArgumentException'); $this->setExpectedException(
self::$DI['app']['model.user-manipulator']->setModelOf($user, $user); 'Alchemy\Phrasea\Exception\RuntimeException',
'User with login login already exists.'
);
self::$DI['app']['manipulator.user']->createTemplate('login', $user);
} }
} }

View File

@@ -13,6 +13,7 @@ namespace Doctrine\Tests\Entities;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Entities\User; use Entities\User;
use Entities\UserSetting;
class UserTest extends \PhraseanetPHPUnitAbstract class UserTest extends \PhraseanetPHPUnitAbstract
{ {
@@ -126,47 +127,6 @@ class UserTest extends \PhraseanetPHPUnitAbstract
$this->assertTrue($this->user->isSpecial()); $this->assertTrue($this->user->isSpecial());
} }
public function testReset()
{
$this->user->setCity('city');
$this->user->setAddress('address');
$this->user->setCountry('country');
$this->user->setZipCode('zipcode');
$this->user->setTimezone('timezone');
$this->user->setCompany('company');
$this->user->setEmail('email@email.com');
$this->user->setFax('fax');
$this->user->setPhone('phone');
$this->user->setFirstName('firstname');
$this->user->setGender(User::GENDER_MR);
$this->user->setGeonameId(1);
$this->user->setJob('job');
$this->user->setActivity('activity');
$this->user->setLastName('lastname');
$this->user->setMailNotificationsActivated(true);
$this->user->setRequestNotificationsActivated(true);
$this->user->reset();
$this->assertEmpty($this->user->getCity());
$this->assertEmpty($this->user->getAddress());
$this->assertEmpty($this->user->getCountry());
$this->assertEmpty($this->user->getZipCode());
$this->assertEmpty($this->user->getTimezone());
$this->assertEmpty($this->user->getCompany());
$this->assertEmpty($this->user->getFax());
$this->assertEmpty($this->user->getPhone());
$this->assertEmpty($this->user->getFirstName());
$this->assertEmpty($this->user->getJob());
$this->assertEmpty($this->user->getActivity());
$this->assertEmpty($this->user->getLastName());
$this->assertNull($this->user->getEmail());
$this->assertNull($this->user->getGeonameId());
$this->assertNull($this->user->getGender());
$this->assertFalse($this->user->hasMailNotificationsActivated());
$this->assertFalse($this->user->hasRequestNotificationsActivated());
}
public function testSetModelOf() public function testSetModelOf()
{ {
$this->user->setLogin('login'); $this->user->setLogin('login');
@@ -199,4 +159,16 @@ class UserTest extends \PhraseanetPHPUnitAbstract
array('madame') array('madame')
); );
} }
public function testGetSettingValue()
{
$setting = new UserSetting();
$setting->setName('titi');
$setting->setValue('a_value');
$this->user->addSetting($setting);
$this->assertEquals('a_value', $this->user->getSettingValue('titi'));
$this->assertEquals('000000', $this->user->getSettingValue('css'));
$this->assertEquals('toto', $this->user->getSettingValue('not_found', 'toto'));
}
} }

Binary file not shown.