Add user manager & user manipulator

This commit is contained in:
Nicolas Le Goff
2013-08-27 16:31:26 +02:00
parent f4428d2ff4
commit 1f03451bfc
18 changed files with 1442 additions and 200 deletions

View File

@@ -90,6 +90,7 @@ use Alchemy\Geonames\GeonamesServiceProvider;
use Alchemy\Phrasea\Core\Provider\InstallerServiceProvider; use Alchemy\Phrasea\Core\Provider\InstallerServiceProvider;
use Alchemy\Phrasea\Core\Provider\JMSSerializerServiceProvider; use Alchemy\Phrasea\Core\Provider\JMSSerializerServiceProvider;
use Alchemy\Phrasea\Core\Provider\LocaleServiceProvider; use Alchemy\Phrasea\Core\Provider\LocaleServiceProvider;
use Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider;
use Alchemy\Phrasea\Core\Provider\NotificationDelivererServiceProvider; use Alchemy\Phrasea\Core\Provider\NotificationDelivererServiceProvider;
use Alchemy\Phrasea\Core\Provider\ORMServiceProvider; use Alchemy\Phrasea\Core\Provider\ORMServiceProvider;
use Alchemy\Phrasea\Core\Provider\PhraseanetServiceProvider; use Alchemy\Phrasea\Core\Provider\PhraseanetServiceProvider;
@@ -296,6 +297,7 @@ class Application extends SilexApplication
$this->register(new ValidatorServiceProvider()); $this->register(new ValidatorServiceProvider());
$this->register(new XPDFServiceProvider()); $this->register(new XPDFServiceProvider());
$this->register(new FileServeServiceProvider()); $this->register(new FileServeServiceProvider());
$this->register(new ManipulatorServiceProvider());
$this['phraseanet.exception_handler'] = $this->share(function ($app) { $this['phraseanet.exception_handler'] = $this->share(function ($app) {
return PhraseaExceptionHandler::register($app['debug']); return PhraseaExceptionHandler::register($app['debug']);

View File

@@ -0,0 +1,35 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Provider;
use Alchemy\Phrasea\Model\Manipulator\UserManipulator;
use Alchemy\Phrasea\Model\Manager\UserManager;
use Silex\Application;
use Silex\ServiceProviderInterface;
class ManipulatorServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['user.manipulator'] = $app->share(function($app) {
return new UserManipulator($app['user.manager'], $app['EM']);
});
$app['user.manager'] = $app->share(function($app) {
return new UserManager($app['auth.password-encoder'], $app['geonames.connector'], $app['EM'], $app['phraseanet.appbox']);
});
}
public function boot(Application $app)
{
}
}

View File

@@ -0,0 +1,40 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Model\Manager;
/**
* This class is responsible of handling logic and complex stuff before the
* entity is persisted by the ORM.
*/
interface ManagerInterface
{
/**
* Returns an empty instance of the managed entity.
*/
public function create();
/**
* Updates the given entity.
*
* @param $entity
* @param boolean $flush Whether to flush the changes or not (default true).
*/
public function update($entity, $flush = true);
/**
* Deletes the given entity.
*
* @param User $entity
* @param boolean $flush Whether to flush the changes or not (default true).
*/
public function delete($entity, $flush = true);
}

View File

@@ -0,0 +1,190 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Model\Manager;
use Alchemy\Geonames\Connector as GeonamesConnector;
use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Entities\User;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
class UserManager implements ManagerInterface
{
/** @var \appbox */
protected $appbox;
/** @var ObjectManager */
protected $objectManager;
/** @var PasswordEncoderInterface */
protected $passwordEncoder;
/** @var GeonamesConnector */
private $geonamesConnector;
/**
* Constructor
*
* @param PasswordEncoderInterface $passwordEncoder
* @param GeonamesConnector $connector
* @param ObjectManager $om
* @param \appbox $appbox
*/
public function __construct(PasswordEncoderInterface $passwordEncoder, GeonamesConnector $connector, ObjectManager $om, \appbox $appbox)
{
$this->appbox = $appbox;
$this->objectManager = $om;
$this->passwordEncoder = $passwordEncoder;
$this->geonamesConnector = $connector;
}
/**
* @{inheritdoc}
*/
public function create()
{
return new User();
}
/**
* @{inheritdoc}
*/
public function delete($user, $flush = true)
{
$user->setDeleted(true);
$user->setEmail(null);
$user->setLogin(sprintf('(#deleted_%s', $user->getLogin()));
$this->cleanRelations($user);
$this->objectManager->persist($user);
if ($flush) {
$this->objectManager->flush();
}
}
/**
* @{inheritdoc}
*/
public function update($user, $flush = true)
{
$this->objectManager->persist($user);
if ($flush) {
$this->objectManager->flush();
}
}
/**
* Updates the modelOf field from the template field value.
*
* @param UserInterface $user
*/
public function onUpdateModel(User $user)
{
$user->getFtpCredential()->resetCredentials();
$this->cleanSettings($user);
$user->reset();
}
/**
* Updates the password field from the plain password field value.
*
* @param UserInterface $user
*/
public function onUpdatePassword(User $user)
{
$user->setNonce(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36));
$user->setPassword($this->passwordEncoder->encodePassword($user->getPassword(), $user->getNonce()));
}
/**
* Updates the country fields for a user according to the current geoname id field value.
*
* @param User $user
*/
public function onUpdateGeonameId(User $user)
{
if (null !== $user->getGeonameId()) {
try {
$country = $this->geonamesConnector
->geoname($user->getGeonameId())
->get('country');
if (isset($country['name'])) {
$user->setCountry($country['name']);
}
} catch (GeonamesExceptionInterface $e) {
}
}
}
/**
* Removes user settings.
*
* @param User $user
*/
public function cleanSettings(User $user)
{
foreach($user->getNotificationSettings() as $userNotificatonSetting) {
$userNotificatonSetting->setUser(null);
}
$user->getNotificationSettings()->clear();
foreach($user->getSettings() as $userSetting) {
$userSetting->setUser(null);
}
$user->getSettings()->clear();
}
/**
* Removes user queries.
*
* @param User $user
*/
public function cleanQueries(User $user)
{
foreach($user->getQueries() as $userQuery) {
$userQuery->setUser(null);
}
$user->getQueries()->clear();
}
/**
* Removes all user's relations.
*
* @todo Removes order relationship, it is now a doctrine entity.
*
* @param User $user
*/
private function cleanRelations(User $user)
{
$conn = $this->appbox->get_connection();
foreach(array(
'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);
}
}

View File

@@ -0,0 +1,27 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Model\Manipulator;
use Doctrine\ORM\EntityRepository;
/**
* This class is responsible of manipulating entities.
*/
interface ManipulatorInterface
{
/**
* Returns the entitiy repository
*
* @return EntityRepository
*/
public function getRepository();
}

View File

@@ -0,0 +1,271 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Model\Manipulator;
use Alchemy\Geonames\Connector as GeonamesConnector;
use Alchemy\Phrasea\Model\Manager\UserManager;
use Alchemy\Phrasea\Exception\RuntimeException;
use Doctrine\Common\Persistence\ObjectManager;
use Entities\User;
use Repositories\UserRepository;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
/**
* Manages common operations for the users.
*/
class UserManipulator implements ManipulatorInterface
{
/** @var UserManager */
private $manager;
/** @var UserRepository */
private $repository;
/** @var ObjectManager */
private $om;
/**
* Constructor
*
* @param PasswordEncoderInterface $passwordEncoder
* @param GeonamesConnector $connector
* @param ObjectManager $om
* @param \appbox $appbox
*/
public function __construct(UserManager $manager, ObjectManager $om)
{
$this->manager = $manager;
$this->om = $om;
$this->repository = $om->getRepository('Entities\User');
}
/**
* @{inheritdoc}
*/
public function getRepository()
{
return $this->repository;
}
/**
* Creates a user and returns it.
*
* @param string $login
* @param string $password
* @param string $email
* @param Boolean $active
* @param Boolean $login
* @param Boolean $template
*
* @return User
*
* @throws InvalidArgument if login, email or password is not valid.
* @throws RuntimeException if login or email already exists.
*/
public function createUser($login, $password, $email = null, $admin = false)
{
$user = $this->manager->create();
$this->setLogin($user, $login);
$this->setEmail($user, $email);
$this->setPassword($user, $password);
$user->setAdmin($admin);
$this->manager->update($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.
*
* @param string $name
* @param User $template
*
* @return User
*
* @throws InvalidArgument if name is not valid.
* @throws RuntimeException if name already exists.
*/
public function createTemplate($name, User $template)
{
$user = $this->manager->create();
$this->setLogin($user, $name);
$this->setPassword($user, substr(uniqid ('', true), -6));
$this->setModelOf($user, $template);
$this->manager->update($user);
return $user;
}
/**
* Sets the password for the given user.
*
* @param user $user
* @param string $password
*
* @throws InvalidArgument if password is not valid.
*/
public function setPassword(User $user, $password)
{
$user->setPassword($password);
$this->manager->onUpdatePassword($user);
}
/**
* Sets the template for the given user.
*
* @param User $user
* @param User $template
*
* @throws InvalidArgument if user and template are the same.
*/
public function setModelOf(User $user, User $template)
{
$user->setModelOf($template);
$this->manager->onUpdateModel($user);
}
/**
* Sets the geonameid for the given user.
*
* @param User $user
* @param integer $geonameid
*
* @throws InvalidArgument if geonameid is not valid.
*/
public function setGeonameId(User $user, $geonameid)
{
$user->setGeonameId($geonameid);
$this->manager->onUpdateGeonameId($user);
}
/**
* Sets the login for the given user.
*
* @param User $user
* @param sring $login
*
* @throws InvalidArgument if login is not valid.
* @throws RuntimeException if login already exists.
*/
public function setLogin(User $user, $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
*
* @throws InvalidArgument if email is not valid or already exists.
* @throws RuntimeException if email already exists.
*/
public function setEmail(User $user, $email)
{
if (null !== $this->repository->findByEmail($email)) {
throw new RuntimeException(sprintf('User with email %s already exists.', $email));
}
$user->setEmail($email);
}
/**
* Promotes the given users.
*
* @param User|array $user
*/
public function promote($users)
{
if (!is_array($users)) {
$users = array($users);
}
foreach ($users as $user) {
$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

@@ -29,10 +29,16 @@ class FtpCredential
private $id; private $id;
/** /**
* @ORM\Column(type="integer") * @ORM\Column(type="integer", nullable=true)
*/ */
private $usrId; private $usrId;
/**
* @ORM\OneToOne(targetEntity="User", inversedBy="ftpCredential")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
**/
private $user;
/** /**
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
*/ */
@@ -93,15 +99,7 @@ class FtpCredential
} }
/** /**
* @return \User_Adapter * @return integer
*/
public function getUser(Application $app)
{
return \User_Adapter::getInstance($this->usrId, $app);
}
/**
* @return \User_Adapter
*/ */
public function getUsrId() public function getUsrId()
{ {
@@ -116,6 +114,26 @@ class FtpCredential
$this->usrId = $usrId; $this->usrId = $usrId;
} }
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @param User $user
*
* @return FtpCredential
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/** /**
* @return boolean * @return boolean
*/ */
@@ -126,10 +144,14 @@ class FtpCredential
/** /**
* @param boolean $active * @param boolean $active
*
* @return FtpCredential
*/ */
public function setActive($active) public function setActive($active)
{ {
$this->active = (Boolean) $active; $this->active = (Boolean) $active;
return $this;
} }
/** /**
@@ -142,10 +164,14 @@ class FtpCredential
/** /**
* @param string $address * @param string $address
*
* @return FtpCredential
*/ */
public function setAddress($address) public function setAddress($address)
{ {
$this->address = $address; $this->address = $address;
return $this;
} }
/** /**
@@ -158,10 +184,14 @@ class FtpCredential
/** /**
* @param string $login * @param string $login
*
* @return FtpCredential
*/ */
public function setLogin($login) public function setLogin($login)
{ {
$this->login = $login; $this->login = $login;
return $this;
} }
/** /**
@@ -174,10 +204,14 @@ class FtpCredential
/** /**
* @param string $password * @param string $password
*
* @return FtpCredential
*/ */
public function setPassword($password) public function setPassword($password)
{ {
$this->password = $password; $this->password = $password;
return $this;
} }
/** /**
@@ -190,10 +224,14 @@ class FtpCredential
/** /**
* @param string $receptionFolder * @param string $receptionFolder
*
* @return FtpCredential
*/ */
public function setReceptionFolder($receptionFolder) public function setReceptionFolder($receptionFolder)
{ {
$this->receptionFolder = $receptionFolder; $this->receptionFolder = $receptionFolder;
return $this;
} }
/** /**
@@ -206,10 +244,14 @@ class FtpCredential
/** /**
* @param string $repositoryPrefixName * @param string $repositoryPrefixName
*
* @return FtpCredential
*/ */
public function setRepositoryPrefixName($repositoryPrefixName) public function setRepositoryPrefixName($repositoryPrefixName)
{ {
$this->repositoryPrefixName = $repositoryPrefixName; $this->repositoryPrefixName = $repositoryPrefixName;
return $this;
} }
/** /**
@@ -222,10 +264,14 @@ class FtpCredential
/** /**
* @param string $passive * @param string $passive
*
* @return FtpCredential
*/ */
public function setPassive($passive) public function setPassive($passive)
{ {
$this->passive = (Boolean) $passive; $this->passive = (Boolean) $passive;
return $this;
} }
/** /**
@@ -238,10 +284,14 @@ class FtpCredential
/** /**
* @param string $ssl * @param string $ssl
*
* @return FtpCredential
*/ */
public function setSsl($ssl) public function setSsl($ssl)
{ {
$this->ssl = (Boolean) $ssl; $this->ssl = (Boolean) $ssl;
return $this;
} }
/** /**
@@ -254,10 +304,14 @@ class FtpCredential
/** /**
* @param string $maxRetry * @param string $maxRetry
*
* @return FtpCredential
*/ */
public function setMaxRetry($maxRetry) public function setMaxRetry($maxRetry)
{ {
$this->maxRetry = $maxRetry; $this->maxRetry = $maxRetry;
return $this;
} }
/** /**
@@ -270,9 +324,31 @@ class FtpCredential
/** /**
* @param \DateTime $updated * @param \DateTime $updated
*
* @return FtpCredential
*/ */
public function setUpdated(\DateTime $updated) public function setUpdated(\DateTime $updated)
{ {
$this->updated = $updated; $this->updated = $updated;
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

@@ -14,6 +14,7 @@ namespace Entities;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
/** /**
@@ -39,6 +40,38 @@ class User
const GENDER_MRS = 'mrs'; const GENDER_MRS = 'mrs';
const GENDER_MISS = 'miss'; const GENDER_MISS = 'miss';
const USER_GUEST = 'guest';
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
@@ -144,7 +177,7 @@ class User
/** /**
* @ORM\Column(type="string", length=32) * @ORM\Column(type="string", length=32)
*/ */
private $fax= ''; private $fax = '';
/** /**
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
@@ -171,11 +204,6 @@ class User
*/ */
private $ldapCreated = false; private $ldapCreated = false;
/**
* @ORM\Column(type="integer", name="model_of", nullable=true)
*/
private $modelOf;
/** /**
* @ORM\Column(type="string", length=64, name="last_model", nullable=true) * @ORM\Column(type="string", length=64, name="last_model", nullable=true)
*/ */
@@ -223,11 +251,49 @@ class User
*/ */
private $updated; private $updated;
/**
* @ORM\OneToOne(targetEntity="User")
* @ORM\JoinColumn(name="model_of", referencedColumnName="id")
**/
private $modelOf;
/**
* @ORM\OneToOne(targetEntity="FtpCredential", mappedBy="user", cascade={"all"})
**/
private $ftpCredential;
/**
* @ORM\OneToMany(targetEntity="UserQuery", mappedBy="user", cascade={"all"})
**/
private $queries;
/**
* @ORM\OneToMany(targetEntity="UserSetting", mappedBy="user", cascade={"all"})
**/
private $settings;
/**
* @ORM\OneToMany(targetEntity="UserNotificationSetting", mappedBy="user", cascade={"all"})
**/
private $notificationSettings;
/** /**
* @var \ACL * @var \ACL
*/ */
private $acl; private $acl;
/**
* Constructor
*/
public function __construct()
{
$this->setFtpCredential(new FtpCredential());
$this->queries = new ArrayCollection();
$this->notificationSettings = new ArrayCollection();
$this->setDefaultSettings();
$this->nonce = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/** /**
* @return integer * @return integer
*/ */
@@ -249,6 +315,10 @@ class User
*/ */
public function setLogin($login) public function setLogin($login)
{ {
if (trim($login) === '') {
throw new InvalidArgumentException('Invalid login.');
}
$this->login = $login; $this->login = $login;
} }
@@ -265,6 +335,10 @@ class User
*/ */
public function setEmail($email) public function setEmail($email)
{ {
if (null !== $email && !preg_match('/.+@.+\..+/', trim($email))) {
throw new InvalidArgumentException('Invalid email.');
}
$this->email = $email; $this->email = $email;
} }
@@ -282,6 +356,10 @@ class User
*/ */
public function setPassword($password) public function setPassword($password)
{ {
if (trim($password) === '') {
throw new InvalidArgumentException('Invalid password.');
}
$this->password = $password; $this->password = $password;
} }
@@ -659,7 +737,7 @@ class User
} }
/** /**
* @return integer * @return User
*/ */
public function getModelOf() public function getModelOf()
{ {
@@ -667,11 +745,15 @@ class User
} }
/** /**
* @param integer $modelOf * @param User $user
*/ */
public function setModelOf($modelOf) public function setModelOf(User $user)
{ {
$this->modelOf = $modelOf; if ($this->isUser($user)) {
throw new InvalidArgumentException(sprintf('Can not set same user %s as template.', $this->getLogin()));
}
$this->modelOf = $user;
} }
/** /**
@@ -819,10 +901,89 @@ class User
*/ */
public function setUpdated(\Datetime $updated) public function setUpdated(\Datetime $updated)
{ {
$this->updated = $updated; $this->updated = $updated;
} }
/**
* @return FtpCredential
*/
public function getFtpCredential()
{
return $this->ftpCredential;
}
/**
* @param FtpCredential $ftpCredential
*
* @return User
*/
public function setFtpCredential(FtpCredential $ftpCredential)
{
$this->ftpCredential = $ftpCredential;
return $this;
}
/**
* @return ArrayCollection
*/
public function getQueries()
{
return $this->queries;
}
/**
* @param ArrayCollection $queries
*
* @return User
*/
public function setQueries(ArrayCollection $queries)
{
$this->queries = $queries;
return $this;
}
/**
* @return ArrayCollection
*/
public function getSettings()
{
return $this->settings;
}
/**
* @param ArrayCollection $settings
*
* @return User
*/
public function setSettings(ArrayCollection $settings)
{
$this->settings = $settings;
return $this;
}
/**
* @return ArrayCollection
*/
public function getNotificationSettings()
{
return $this->notificationSettings;
}
/**
* @param ArrayCollection $notificationSettings
*
* @return User
*/
public function setNotificationSettings(ArrayCollection $notificationSettings)
{
$this->notificationSettings = $notificationSettings;
return $this;
}
/** /**
* @param Application $app * @param Application $app
* *
@@ -837,6 +998,16 @@ class User
return $this->acl; return $this->acl;
} }
/**
* @param User $user
*
* @return boolean
*/
public function isUser(User $user = null)
{
return null !== $user && $this->getLogin() === $user->getLogin();
}
/** /**
* @return boolean * @return boolean
*/ */
@@ -850,7 +1021,7 @@ class User
*/ */
public function isSpecial() public function isSpecial()
{ {
return in_array($this->login, array('invite', 'autoregister')); return in_array($this->login, array(self::USER_GUEST, self::USER_AUTOREGISTER));
} }
/** /**
@@ -872,4 +1043,49 @@ 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;
}
/**
* @return User
*/
private function setDefaultSettings()
{
$this->settings = new ArrayCollection();
foreach(self::$defaultUserSettings as $name => $value) {
$setting = new UserSetting();
$setting->setName($name);
$setting->setValue($value);
$this->settings->add($setting);
};
return $this;
}
} }

View File

@@ -18,7 +18,7 @@ use Gedmo\Mapping\Annotation as Gedmo;
/** /**
* @ORM\Table(name="UserNotificationSettings", * @ORM\Table(name="UserNotificationSettings",
* uniqueConstraints={ * uniqueConstraints={
* @ORM\UniqueConstraint(name="unique_index",columns={"usr_id", "name"}) * @ORM\UniqueConstraint(name="unique_index",columns={"user_id", "name"})
* } * }
* ) * )
* @ORM\Entity(repositoryClass="Repositories\UserNotificaionSettingRepository") * @ORM\Entity(repositoryClass="Repositories\UserNotificaionSettingRepository")
@@ -33,9 +33,10 @@ class UserNotificationSetting
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User", inversedBy="notificationSettings")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
private $usrId; **/
private $user;
/** /**
* @ORM\Column(type="string", length=64) * @ORM\Column(type="string", length=64)
@@ -68,43 +69,21 @@ class UserNotificationSetting
} }
/** /**
* @return integer * @return User
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usrId; return $this->user;
} }
/** /**
* @param integer $usrId * @param User $user
* *
* @return UserNotificationSetting * @return UserNotificationSetting
*/ */
public function setUsrId($usrId) public function setUser(User $user = null)
{ {
$this->usrId = $usrId; $this->user = $user;
return $this;
}
/**
* @param Application $app
*
* @return \User_Adapter
*/
public function getUser(Application $app)
{
return \User_Adapter::getInstance($this->usrId, $app);
}
/**
* @param \User_Adapter $user
*
* @return UserNotificationSetting
*/
public function setUser(\User_Adapter $user)
{
$this->setUsrId($user->get_id());
return $this; return $this;
} }

View File

@@ -29,10 +29,16 @@ class UserQuery
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\Column(type="integer", nullable=true)
*/ */
private $usrId; private $usrId;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="queries")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
**/
private $user;
/** /**
* @ORM\Column(type="string", length=256) * @ORM\Column(type="string", length=256)
*/ */
@@ -62,34 +68,28 @@ class UserQuery
/** /**
* @param integer $usrId * @param integer $usrId
*
* @return UserQuery
*/ */
public function setUsrId($usrId) public function setUsrId($usrId)
{ {
$this->usrId = $usrId; $this->usrId = $usrId;
return $this;
} }
/** /**
* @param Application $app * @return User
*
* @return \User_Adapter
*/ */
public function getUser(Application $app) public function getUser()
{ {
return \User_Adapter::getInstance($this->usrId, $app); return $this->user;
} }
/** /**
* @param \User_Adapter $user * @param User $user
* *
* @return UserQuery * @return UserQuery
*/ */
public function setUser(\User_Adapter $user) public function setUser(User $user = null)
{ {
$this->setUsrId($user->get_id()); $this->user = $user;
return $this; return $this;
} }

View File

@@ -18,7 +18,7 @@ use Gedmo\Mapping\Annotation as Gedmo;
/** /**
* @ORM\Table(name="UserSettings", * @ORM\Table(name="UserSettings",
* uniqueConstraints={ * uniqueConstraints={
* @ORM\UniqueConstraint(name="unique_setting",columns={"usr_id", "name"}) * @ORM\UniqueConstraint(name="unique_setting",columns={"user_id", "name"})
* } * }
* ) * )
* @ORM\Entity(repositoryClass="Repositories\UserSettingRepository") * @ORM\Entity(repositoryClass="Repositories\UserSettingRepository")
@@ -33,9 +33,10 @@ class UserSetting
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User", inversedBy="settings")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
private $usrId; **/
private $user;
/** /**
* @ORM\Column(type="string", length=64) * @ORM\Column(type="string", length=64)
@@ -68,43 +69,21 @@ class UserSetting
} }
/** /**
* @return integer * @return User
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usrId; return $this->user;
} }
/** /**
* @param integer $usrId * @param User $user
* *
* @return UserSetting * @return UserSetting
*/ */
public function setUsrId($usrId) public function setUser(User $user = null)
{ {
$this->usrId = $usrId; $this->user = $user;
return $this;
}
/**
* @param \Alchemy\Phrasea\Application $app
*
* @return string
*/
public function getUser(Application $app)
{
return \User_Adapter::getInstance($this->usrId, $app);
}
/**
* @param \User_Adapter $user
*
* @return UserSetting
*/
public function setUser(\User_Adapter $user)
{
$this->setUsrId($user->get_id());
return $this; return $this;
} }

View File

@@ -23,7 +23,7 @@ use Entities\User;
class UserRepository extends EntityRepository class UserRepository extends EntityRepository
{ {
/** /**
* Finds admins * Finds admins.
* *
* @return array * @return array
*/ */
@@ -39,47 +39,7 @@ class UserRepository extends EntityRepository
} }
/** /**
* Sets a selection of user * Finds a user by login.
*
* @param array $users An array of user
*
* @return integer The number of processed rows
*/
public function setAdmins(array $users)
{
$qb = $this->createQueryBuilder('u');
$qb->update('Entities\User', 'u')
->set('u.admin', $qb->expr()->literal(true))
->where($qb->expr()->in('u.id', array_map(function($value) {
if ($value instanceof User) {
return $value->getId();
}
return (int) $value;
}, $users)));
return $qb->getQuery()->execute();
}
/**
* Resets all admins
*
* @return integer The number of processed rows
*/
public function resetAdmins()
{
$qb = $this->createQueryBuilder('u');
$qb->update('Entities\User', 'u')
->set('u.admin', $qb->expr()->literal(false))
->where($qb->expr()->eq('u.admin', $qb->expr()->literal(true)));
return $qb->getQuery()->execute();
}
/**
* Finds a user by login
* *
* @param string $login * @param string $login
* *
@@ -91,7 +51,7 @@ class UserRepository extends EntityRepository
} }
/** /**
* Finds a user by email * Finds a user by email.
* *
* @param string $email * @param string $email
* *
@@ -101,7 +61,7 @@ class UserRepository extends EntityRepository
{ {
$qb = $this->createQueryBuilder('u'); $qb = $this->createQueryBuilder('u');
$qb->where($qb->expr()->eq('u.email', $email)) $qb->where($qb->expr()->eq('u.email', $qb->expr()->literal($email)))
->andWhere($qb->expr()->isNotNull('u.email')) ->andWhere($qb->expr()->isNotNull('u.email'))
->andWhere($qb->expr()->eq('u.deleted', $qb->expr()->literal(false))); ->andWhere($qb->expr()->eq('u.deleted', $qb->expr()->literal(false)));

View File

@@ -10,6 +10,7 @@
*/ */
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Doctrine\ORM\EntityManager;
use Entities\User; use Entities\User;
use Gedmo\Timestampable\TimestampableListener; use Gedmo\Timestampable\TimestampableListener;
@@ -56,17 +57,30 @@ class patch_3902 implements patchInterface
$stmt->closeCursor(); $stmt->closeCursor();
$conn = $app['phraseanet.appbox']->get_connection(); $conn = $app['phraseanet.appbox']->get_connection();
$em = $app['EM'];
$em->getEventManager()->removeEventSubscriber(new TimestampableListener());
$this->updateUsers($em, $conn);
$this->updateModels($em, $conn);
$em->getEventManager()->addEventSubscriber(new TimestampableListener());
}
/**
* Sets user entity from usr table.
*/
private function updateUsers(EntityManager $em, $conn)
{
$sql = 'SELECT * FROM usr'; $sql = 'SELECT * FROM usr';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute(); $stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor(); $stmt->closeCursor();
$n = 0; $n = 0;
$em = $app['EM'];
$em->getEventManager()->removeEventSubscriber(new TimestampableListener());
foreach ($rs as $row) { foreach ($rows as $row) {
$user = new User(); $user = new User();
$user->setActivity($row['activite']); $user->setActivity($row['activite']);
$user->setAddress($row['adresse']); $user->setAddress($row['adresse']);
@@ -101,7 +115,6 @@ class patch_3902 implements patchInterface
$user->setMailLocked(!!$row['mail_locked']); $user->setMailLocked(!!$row['mail_locked']);
$user->setMailNotificationsActivated(!!$row['mail_notifications']); $user->setMailNotificationsActivated(!!$row['mail_notifications']);
$user->setModelOf($row['model_of']);
$user->setNonce($row['nonce']); $user->setNonce($row['nonce']);
$user->setPassword($row['usr_password']); $user->setPassword($row['usr_password']);
$user->setPushList($row['push_list']); $user->setPushList($row['push_list']);
@@ -141,7 +154,49 @@ class patch_3902 implements patchInterface
$em->flush(); $em->flush();
$em->clear(); $em->clear();
}
/**
* Sets model from usr table.
*/
private function updateModels(EntityManager $em, $conn)
{
$sql = 'SELECT model_of, usr_login FROM usr WHERE model_of > 0 AND usr_login IS NOT NULL';
$stmt = $conn->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$em->getEventManager()->addEventSubscriber(new TimestampableListener()); $n = 0;
$repository = $em->getRepository('Entities\User');
foreach ($rows as $row) {
$user = $repository->findOneByLogin($row['usr_login']);
if (null === $user) {
continue;
}
$template = $repository->find($row['model_of']);
if (null === $template) {
continue;
}
$user->setModelOf($template);
$em->persist($user);
$n++;
if ($n % 100 === 0) {
$em->flush();
$em->clear();
}
}
$em->flush();
$em->clear();
} }
} }

View File

@@ -0,0 +1,14 @@
<?php
namespace Alchemy\Tests\Phrasea\Core\Provider;
class ManipulatorServiceProviderTest extends ServiceProviderTestCase
{
public function provideServiceDescription()
{
return array(
array('Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider', 'user.manipulator', '\Alchemy\Phrasea\Model\Manipulator\UserManipulator'),
array('Alchemy\Phrasea\Core\Provider\ManipulatorServiceProvider', 'user.manager', '\Alchemy\Phrasea\Model\Manager\UserManager'),
);
}
}

View File

@@ -0,0 +1,144 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Tests\Phrasea\Model\Manipulator;
use Doctrine\Common\Collections\ArrayCollection;
use Alchemy\Phrasea\Model\Manager\UserManager;
use Entities\UserQuery;
class UserManagerTest extends \PhraseanetPHPUnitAbstract
{
public function testNewUser()
{
$user = self::$DI['app']['user.manager']->create();
$this->assertInstanceOf('\Entities\User', $user);
}
public function testDeleteUser()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'password');
self::$DI['app']['user.manager']->update($user);
self::$DI['app']['user.manager']->delete($user);
$this->assertTrue($user->isDeleted());
$this->assertNull($user->getEmail());
$this->assertEquals('(#deleted_', substr($user->getLogin(), 0, 10));
}
public function testUpdateUser()
{
$template = self::$DI['app']['user.manipulator']->createUser('template', 'password');
self::$DI['app']['user.manager']->update($template);
$user = self::$DI['app']['user.manipulator']->createUser('login', 'password');
$user->setModelOf($template);
self::$DI['app']['user.manager']->update($user);
$this->assertNotNull($user->getPassword());
$this->assertNotNull($user->getModelOf());
}
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');
$user->setModelOf($template);
self::$DI['app']['user.manager']->onUpdateModel($user);
}
public function testUpdatePassword()
{
$user = self::$DI['app']['user.manager']->create();
$user->setPassword($hashPass = uniqid());
$nonce = $user->getNonce();
self::$DI['app']['user.manager']->onUpdatePassword($user);
$this->assertNotNull($user->getPassword());
$this->assertNotEquals($hashPass, $user->getPassword());
$this->assertNotEquals($nonce, $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('name' => 'france')));
$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']['user.manager']->create();
$user->setGeonameId(4);
$userManager->onUpdateGeonameId($user);
$this->assertEquals('france', $user->getCountry());
}
public function testCleanSettings()
{
self::$DI['app']['user.manipulator']->createUser('login', 'toto');
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertGreaterThan(0, $user->getSettings()->count());
self::$DI['app']['user.manager']->cleanSettings($user);
self::$DI['app']['user.manager']->update($user);
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertEquals(0, $user->getSettings()->count());
}
public function testCleanQueries()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'toto');
$userQuery = new UserQuery();
$userQuery->setUser($user);
$userQuery->setQuery('blabla');
$user->setQueries(new ArrayCollection(array($userQuery)));
self::$DI['app']['user.manager']->update($user);
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertGreaterThan(0, $user->getQueries()->count());
self::$DI['app']['user.manager']->cleanQueries($user);
self::$DI['app']['user.manager']->update($user);
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertEquals(0, $user->getQueries()->count());
}
}

View File

@@ -0,0 +1,125 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Tests\Phrasea\Model\Manipulator;
use Doctrine\Common\Collections\ArrayCollection;
use Alchemy\Phrasea\Model\Manipulator\UserManipulator;
use Entities\User;
class UserManipulatorTest extends \PhraseanetPHPUnitAbstract
{
public function testCreateUser()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'pass');
$this->assertInstanceOf('\Entities\User', self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login'));
}
public function testCreateAdminUser()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'pass', 'admin@admin.com', true);
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertTrue($user->isAdmin());
$this->assertNotNull($user->getEmail());
}
public function testCreateGuest()
{
$user = self::$DI['app']['user.manipulator']->createGuest();
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin(User::USER_GUEST);
$this->assertTrue($user->isSpecial());
}
public function testCreateAutoRegister()
{
$user = self::$DI['app']['user.manipulator']->createAutoRegister();
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin(User::USER_AUTOREGISTER);
$this->assertTrue($user->isSpecial());
}
public function testCreateTemplate()
{
$template = self::$DI['app']['user.manipulator']->createUser('login', 'pass');
$user = self::$DI['app']['user.manipulator']->createTemplate('test', $template);
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('test');
$this->assertTrue($user->isTemplate());
}
public function testSetPassword()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'password');
$curPassword = $user->getPassword();
self::$DI['app']['user.manipulator']->setPassword($user, 'toto');
$this->assertNotEquals($curPassword, $user->getPassword());
}
public function testSetGeonameId()
{
$manager = $this->getMockBuilder('Alchemy\Phrasea\Model\Manager\UserManager')
->disableOriginalConstructor()
->getMock();
$manager->expects($this->once())
->method('onUpdateGeonameId');
$user = self::$DI['app']['user.manipulator']->createUser('login', 'password');
$manipulator = new UserManipulator($manager, self::$DI['app']['EM']);
$manipulator->setGeonameId($user, 4);
$this->assertEquals(4, $user->getGeonameId());
}
public function testPromote()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'toto');
$this->assertFalse($user->isAdmin());
$user2 = self::$DI['app']['user.manipulator']->createUser('login2', 'toto');
$this->assertFalse($user2->isAdmin());
self::$DI['app']['user.manipulator']->promote(array($user, $user2));
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertTrue($user->isAdmin());
$user2 = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertTrue($user2->isAdmin());
}
public function testDemote()
{
$user = self::$DI['app']['user.manipulator']->createUser('login', 'toto', null, true);
$this->assertTrue($user->isAdmin());
self::$DI['app']['user.manipulator']->demote($user);
$user = self::$DI['app']['user.manipulator']->getRepository()->findOneByLogin('login');
$this->assertFalse($user->isAdmin());
}
public function testSetLogin()
{
self::$DI['app']['user.manipulator']->createUser('login', 'password');
$user2 = self::$DI['app']['user.manipulator']->createUser('login2', 'password');
$this->setExpectedException(
'Alchemy\Phrasea\Exception\RuntimeException',
'User with login login already exists.'
);
self::$DI['app']['user.manipulator']->setLogin($user2, 'login');
}
public function testSetEmail()
{
self::$DI['app']['user.manipulator']->createUser('login', 'password', 'test@test.fr');
$user2 = self::$DI['app']['user.manipulator']->createUser('login2', 'password', 'test2@test.fr');
$this->setExpectedException(
'Alchemy\Phrasea\Exception\RuntimeException',
'User with email test@test.fr already exists.'
);
self::$DI['app']['user.manipulator']->setEmail($user2, 'test@test.fr');
}
}

View File

@@ -14,15 +14,27 @@ namespace Doctrine\Tests\Entities;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Entities\User; use Entities\User;
class UserTest extends \PHPUnit_Framework_TestCase class UserTest extends \PhraseanetPHPUnitAbstract
{ {
private $user; private $user;
public function setUp() public function setUp()
{ {
parent::setUp();
$this->user = new User(); $this->user = new User();
} }
public function testConstructor()
{
$this->assertNotNull($this->user->getNonce());
$this->assertInstanceOf('\Entities\FtpCredential', $this->user->getFtpCredential());
$this->assertInstanceOf('\Doctrine\Common\Collections\ArrayCollection', $this->user->getQueries());
$this->assertInstanceOf('\Doctrine\Common\Collections\ArrayCollection', $this->user->getNotificationSettings());
$settings = $this->user->getSettings();
$this->assertInstanceOf('\Doctrine\Common\Collections\ArrayCollection', $settings);
$this->assertGreaterThan(0, $settings->count());
}
/** /**
* @dataProvider genderProvider * @dataProvider genderProvider
*/ */
@@ -81,6 +93,39 @@ class UserTest extends \PHPUnit_Framework_TestCase
$this->user->setGeonameId(-1); $this->user->setGeonameId(-1);
} }
public function testInvalidLogin()
{
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid login.'
);
$this->user->setLogin('');
}
public function testInvalidEmail()
{
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid email.'
);
$this->user->setEmail('');
}
public function testValidEmail()
{
$this->user->setEmail('aa@aa.fr');
$this->assertEquals('aa@aa.fr', $this->user->getEmail());
}
public function testInvalidPassword()
{
$this->setExpectedException(
'Alchemy\Phrasea\Exception\InvalidArgumentException',
'Invalid password.'
);
$this->user->setPassword('');
}
public function testGetDisplayName() public function testGetDisplayName()
{ {
$this->user->setLogin('login'); $this->user->setLogin('login');
@@ -101,7 +146,11 @@ class UserTest extends \PHPUnit_Framework_TestCase
public function testIsTemplate() public function testIsTemplate()
{ {
$this->assertFalse($this->user->isTemplate()); $this->assertFalse($this->user->isTemplate());
$this->user->setModelOf(1); $template = new User();
$template->setLogin('login2');
$template->setPassword('toto');
$this->insertOneUser($template);
$this->user->setModelOf($template);
$this->assertTrue($this->user->isTemplate()); $this->assertTrue($this->user->isTemplate());
} }
@@ -109,14 +158,85 @@ class UserTest extends \PHPUnit_Framework_TestCase
{ {
$this->user->setLogin('login'); $this->user->setLogin('login');
$this->assertFalse($this->user->isSpecial()); $this->assertFalse($this->user->isSpecial());
$this->user->setLogin('invite'); $this->user->setLogin(User::USER_AUTOREGISTER);
$this->assertTrue($this->user->isSpecial()); $this->assertTrue($this->user->isSpecial());
$this->user->setLogin('login'); $this->user->setLogin('login');
$this->assertFalse($this->user->isSpecial()); $this->assertFalse($this->user->isSpecial());
$this->user->setLogin('autoregister'); $this->user->setLogin(User::USER_GUEST);
$this->assertTrue($this->user->isSpecial()); $this->assertTrue($this->user->isSpecial());
} }
public function testIsUSer()
{
$this->user->setLogin('login');
$this->user->setPassword('toto');
$this->assertFalse($this->user->isUser(null));
$this->insertOneUser($this->user);
$user = new User();
$user->setLogin('login2');
$user->setPassword('toto');
$this->insertOneUser($user);
$this->assertFalse($user->isUser($this->user));
$this->asserttrue($this->user->isUser($this->user));
}
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()
{
$this->user->setLogin('login');
$this->user->setPassword('toto');
$user = new User();
$user->setLogin('login2');
$user->setPassword('toto');
$this->insertOneUser($this->user);
$this->insertOneUser($user);
$this->user->setModelOf($user);
$this->assertEquals('login2', $this->user->getModelOf()->getLogin());
$this->setExpectedException('Alchemy\Phrasea\Exception\InvalidArgumentException');
$this->user->setModelOf($this->user);
}
public function genderProvider() public function genderProvider()
{ {
return array( return array(

View File

@@ -15,58 +15,54 @@ use Entities\User;
class UserRepositoryTest extends \PhraseanetPHPUnitAbstract class UserRepositoryTest extends \PhraseanetPHPUnitAbstract
{ {
public function testFindAdmins() public function testFindAdminsWithNoAdmins()
{
$this->markTestSkipped('missing deleted field');
$user = new User();
$user->setLogin('login');
$user->setPassword('toto');
$this->insertOneUser($user);
$users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
$this->assertEquals(0, count($users));
$user->setAdmin(true);
$this->insertOneUser($user);
$users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
$this->assertEquals(1, count($users));
$user->setModelOf(1);
$this->insertOneUser($user);
$users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
$this->assertEquals(0, count($users));
$user->setModelOf(null);
$user->setModelOf(true);
$this->insertOneUser($user);
$users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
$this->assertEquals(0, count($users));
}
public function testSetAdmins()
{ {
$user = new User(); $user = new User();
$user->setLogin('login'); $user->setLogin('login');
$user->setPassword('toto'); $user->setPassword('toto');
$this->insertOneUser($user); $this->insertOneUser($user);
$this->assertFalse($user->isAdmin()); $users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
self::$DI['app']['EM']->getRepository('Entities\User')->setAdmins(array($user)); $this->assertEquals(0, count($users));
$user = self::$DI['app']['EM']->getReference('Entities\User', $user->getId());
self::$DI['app']['EM']->refresh($user);
$this->assertTrue($user->isAdmin());
} }
public function testResetAdmins() public function testFindAdminsWithOneAdmin()
{ {
$user = new User(); $user = new User();
$user->setLogin('login'); $user->setLogin('login');
$user->setPassword('toto'); $user->setPassword('toto');
$user->setAdmin(true); $user->setAdmin(true);
$this->insertOneUser($user); $this->insertOneUser($user);
$this->assertTrue($user->isAdmin()); $users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
self::$DI['app']['EM']->getRepository('Entities\User')->resetAdmins(); $this->assertEquals(1, count($users));
$user = self::$DI['app']['EM']->getReference('Entities\User', $user->getId()); }
self::$DI['app']['EM']->refresh($user);
$this->assertFalse($user->isAdmin()); public function testFindAdminsWithOneAdminButTemplate()
{
$user = new User();
$user->setLogin('login');
$user->setPassword('toto');
$user->setAdmin(true);
$template = new User();
$template->setLogin('logint');
$template->setPassword('totot');
$user->setModelOf($template);
$users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
$this->assertEquals(0, count($users));
}
public function testFindAdminsWithOneAdminButDeleted()
{
$user = new User();
$user->setLogin('login');
$user->setPassword('toto');
$user->setAdmin(true);
$user->setDeleted(true);
$users = self::$DI['app']['EM']->getRepository('Entities\User')->findAdmins();
$this->assertEquals(0, count($users));
} }
public function testFindByLogin() public function testFindByLogin()
@@ -80,25 +76,38 @@ class UserRepositoryTest extends \PhraseanetPHPUnitAbstract
$this->assertNull(self::$DI['app']['EM']->getRepository('Entities\User')->findByLogin('wrong-login')); $this->assertNull(self::$DI['app']['EM']->getRepository('Entities\User')->findByLogin('wrong-login'));
} }
public function testFindByEmail() public function testFindUserByEmail()
{ {
$this->markTestSkipped('missing deleted field');
$user = new User(); $user = new User();
$user->setLogin('login'); $user->setLogin('login');
$user->setPassword('toto'); $user->setPassword('toto');
$user->setEmail('toto@toto.to'); $user->setEmail('toto@toto.to');
$this->insertOneUser($user); $this->insertOneUser($user);
$userFound = self::$DI['app']['EM']->getRepository('Entities\User')->findByEmail('toto@toto.to'); $user = self::$DI['app']['EM']->getRepository('Entities\User')->findByEmail('toto@toto.to');
$this->assertInstanceOf('Entities\User', $userFound); $this->assertInstanceOf('Entities\User', $user);
}
public function testFindUserByEmailButDeleted()
{
$user = new User();
$user->setLogin('login');
$user->setPassword('toto');
$user->setEmail('toto@toto.to');
$user->setDeleted(true); $user->setDeleted(true);
$this->insertOneUser($user); $this->insertOneUser($user);
$userFound = self::$DI['app']['EM']->getRepository('Entities\User')->findByEmail('toto@toto.to'); $user = self::$DI['app']['EM']->getRepository('Entities\User')->findByEmail('toto@toto.to');
$this->assertNull($userFound); $this->assertNull($user);
}
public function testFindUserByEmailButNullEmail()
{
$user = new User();
$user->setLogin('login');
$user->setPassword('toto');
$user->setEmail(null); $user->setEmail(null);
$user->setDeleted(true);
$this->insertOneUser($user); $this->insertOneUser($user);
$userFound = self::$DI['app']['EM']->getRepository('Entities\User')->findByEmail(null); $user = self::$DI['app']['EM']->getRepository('Entities\User')->findByEmail('toto@toto.to');
$this->assertNull($userFound); $this->assertNull($user);
} }
} }