From 556487086b8abf0f33bcb1aa945e4e12ead7a264 Mon Sep 17 00:00:00 2001
From: Xapp73 <1post112@gmail.com>
Date: Thu, 19 Jan 2017 21:03:20 +0200
Subject: [PATCH 1/7] Broken version
---
src/Entity/Role.php | 63 +++++++++
src/Entity/User.php | 99 +++++++++-----
src/Form/UserForm.php | 259 ++++++++++++++++++++----------------
src/Service/UserManager.php | 33 ++++-
view/user/user/add.phtml | 12 +-
view/user/user/edit.phtml | 12 +-
6 files changed, 328 insertions(+), 150 deletions(-)
create mode 100644 src/Entity/Role.php
diff --git a/src/Entity/Role.php b/src/Entity/Role.php
new file mode 100644
index 0000000..b252d1e
--- /dev/null
+++ b/src/Entity/Role.php
@@ -0,0 +1,63 @@
+roleId;
+ }
+
+ /**
+ * Set the role id
+ * @param int $roleId
+ * @return void
+ */
+ public function setRoleId($roleId)
+ {
+ $this->roleId = (int) $roleId;
+ }
+
+ /**
+ * Get the role name
+ * @return string
+ */
+ public function getRoleName()
+ {
+ return $this->roleName;
+ }
+
+ /**
+ * Set the role name
+ * @param string $roleName
+ * @return void
+ */
+ public function setRoleName($roleName)
+ {
+ $this->roleName = $roleName;
+ }
+}
diff --git a/src/Entity/User.php b/src/Entity/User.php
index 2255b14..37978a9 100644
--- a/src/Entity/User.php
+++ b/src/Entity/User.php
@@ -1,19 +1,58 @@
roles = new ArrayCollection();
+ }
+
+ /**
+ * Get role.
+ * @return array
+ */
+ public function getRoles()
+ {
+ return $this->roles->getValues();
+ }
+
+ /**
+ * Add a role to the user.
+ * @param Role $role
+ * @return void
+ */
+ public function addRole($role)
+ {
+ $this->roles[] = $role;
+ }
+
/**
* @ORM\Id
* @ORM\Column(name="id", type="integer")
@@ -21,95 +60,95 @@ class User
*/
protected $id;
- /**
- * @ORM\Column(name="email")
+ /**
+ * @ORM\Column(name="email")
*/
protected $email;
-
- /**
- * @ORM\Column(name="full_name")
+
+ /**
+ * @ORM\Column(name="full_name")
*/
protected $fullName;
- /**
- * @ORM\Column(name="password")
+ /**
+ * @ORM\Column(name="password")
*/
protected $password;
- /**
- * @ORM\Column(name="status")
+ /**
+ * @ORM\Column(name="status")
*/
protected $status;
-
+
/**
- * @ORM\Column(name="date_created")
+ * @ORM\Column(name="date_created")
*/
protected $dateCreated;
-
+
/**
* @ORM\Column(name="pwd_reset_token", nullable=true)
*/
protected $passwordResetToken;
-
+
/**
* @ORM\Column(name="pwd_reset_token_creation_date", nullable=true)
*/
protected $passwordResetTokenCreationDate;
-
+
/**
* Returns user ID.
* @return integer
*/
- public function getId()
+ public function getId()
{
return $this->id;
}
/**
- * Sets user ID.
- * @param int $id
+ * Sets user ID.
+ * @param int $id
*/
- public function setId($id)
+ public function setId($id)
{
$this->id = $id;
}
/**
- * Returns email.
+ * Returns email.
* @return string
*/
- public function getEmail()
+ public function getEmail()
{
return $this->email;
}
/**
- * Sets email.
+ * Sets email.
* @param string $email
*/
- public function setEmail($email)
+ public function setEmail($email)
{
$this->email = $email;
}
-
+
/**
* Returns full name.
- * @return string
+ * @return string
*/
- public function getFullName()
+ public function getFullName()
{
return $this->fullName;
- }
+ }
/**
* Sets full name.
* @param string $fullName
*/
- public function setFullName($fullName)
+ public function setFullName($fullName)
{
$this->fullName = $fullName;
}
-
+
/**
* Returns status.
* @return int
diff --git a/src/Form/UserForm.php b/src/Form/UserForm.php
index 2db723a..33cd34f 100644
--- a/src/Form/UserForm.php
+++ b/src/Form/UserForm.php
@@ -1,12 +1,13 @@
setAttribute('method', 'post');
-
+
// Save parameters for internal use.
$this->scenario = $scenario;
$this->entityManager = $entityManager;
$this->user = $user;
-
+
$this->addElements();
- $this->addInputFilter();
+ $this->addInputFilter();
}
-
+
/**
* This method adds elements to form (input fields and submit button).
*/
- protected function addElements()
+ protected function addElements()
{
// Add "email" field
- $this->add([
- 'type' => 'text',
+ $this->add([
+ 'type' => 'text',
'name' => 'email',
'options' => [
'label' => 'E-mail',
],
]);
-
+
// Add "full_name" field
- $this->add([
- 'type' => 'text',
- 'name' => 'full_name',
+ $this->add([
+ 'type' => 'text',
+ 'name' => 'full_name',
'options' => [
'label' => 'Full Name',
],
]);
-
+
if ($this->scenario == 'create') {
-
+
// Add "password" field
- $this->add([
- 'type' => 'password',
+ $this->add([
+ 'type' => 'password',
'name' => 'password',
'options' => [
'label' => 'Password',
],
]);
-
+
// Add "confirm_password" field
- $this->add([
- 'type' => 'password',
+ $this->add([
+ 'type' => 'password',
'name' => 'confirm_password',
'options' => [
'label' => 'Confirm password',
],
]);
}
-
+
+ $roles = $this->entityManager->getRepository(Role::class)->findAll();
+ $hydrator = new \Zend\Hydrator\ClassMethods();
+ $rolesselector = [];
+ foreach ($roles as $role) {
+ $rolesarr = $hydrator->extract($role);
+ $rolesselector[$rolesarr['role_id']] = $rolesarr['role_name'];
+ }
+ ksort($rolesselector);
+
+ // checking for existing role if editing mode
+ $rolecurrent['role_id'] = 1;
+
+ if ($this->scenario != 'create') {
+ $role = $this->user->getRoles();
+ if (!empty($role)) {
+ $rolecurrent = $hydrator->extract($role[0]);
+ }
+ }
+
+ // Add role field selector here
+ $this->add([
+ 'type' => 'select',
+ 'name' => 'role',
+
+ 'options' => [
+ 'label' => 'Role',
+ 'value_options' => $rolesselector,
+
+ ],
+ 'attributes' => [
+ 'value' => $rolecurrent['role_id'],
+ ]
+ ]);
+
// Add "status" field
- $this->add([
- 'type' => 'select',
+ $this->add([
+ 'type' => 'select',
'name' => 'status',
'options' => [
'label' => 'Status',
'value_options' => [
1 => 'Active',
- 2 => 'Retired',
+ 2 => 'Retired',
]
],
]);
-
+
// Add the Submit button
$this->add([
- 'type' => 'submit',
+ 'type' => 'submit',
'name' => 'submit',
- 'attributes' => [
+ 'attributes' => [
'value' => 'Create'
],
]);
}
-
+
/**
* This method creates input filter (used for form filtering/validation).
*/
- private function addInputFilter()
+ private function addInputFilter()
{
// Create main input filter
- $inputFilter = new InputFilter();
+ $inputFilter = new InputFilter();
$this->setInputFilter($inputFilter);
-
+
// Add input for "email" field
$inputFilter->add([
- 'name' => 'email',
- 'required' => true,
- 'filters' => [
- ['name' => 'StringTrim'],
- ],
- 'validators' => [
- [
- 'name' => 'StringLength',
- 'options' => [
- 'min' => 1,
- 'max' => 128
- ],
+ 'name' => 'email',
+ 'required' => true,
+ 'filters' => [
+ ['name' => 'StringTrim'],
+ ],
+ 'validators' => [
+ [
+ 'name' => 'StringLength',
+ 'options' => [
+ 'min' => 1,
+ 'max' => 128
],
- [
- 'name' => 'EmailAddress',
- 'options' => [
- 'allow' => \Zend\Validator\Hostname::ALLOW_DNS,
- 'useMxCheck' => false,
- ],
+ ],
+ [
+ 'name' => 'EmailAddress',
+ 'options' => [
+ 'allow' => \Zend\Validator\Hostname::ALLOW_DNS,
+ 'useMxCheck' => false,
+ ],
+ ],
+ [
+ 'name' => UserExistsValidator::class,
+ 'options' => [
+ 'entityManager' => $this->entityManager,
+ 'user' => $this->user
],
- [
- 'name' => UserExistsValidator::class,
- 'options' => [
- 'entityManager' => $this->entityManager,
- 'user' => $this->user
- ],
- ],
],
- ]);
-
+ ],
+ ]);
+
// Add input for "full_name" field
$inputFilter->add([
- 'name' => 'full_name',
+ 'name' => 'full_name',
+ 'required' => true,
+ 'filters' => [
+ ['name' => 'StringTrim'],
+ ],
+ 'validators' => [
+ [
+ 'name' => 'StringLength',
+ 'options' => [
+ 'min' => 1,
+ 'max' => 512
+ ],
+ ],
+ ],
+ ]);
+
+ if ($this->scenario == 'create') {
+
+ // Add input for "password" field
+ $inputFilter->add([
+ 'name' => 'password',
'required' => true,
- 'filters' => [
- ['name' => 'StringTrim'],
- ],
+ 'filters' => [
+ ],
'validators' => [
[
- 'name' => 'StringLength',
+ 'name' => 'StringLength',
'options' => [
- 'min' => 1,
- 'max' => 512
+ 'min' => 6,
+ 'max' => 64
],
],
],
]);
-
- if ($this->scenario == 'create') {
-
- // Add input for "password" field
- $inputFilter->add([
- 'name' => 'password',
- 'required' => true,
- 'filters' => [
- ],
- 'validators' => [
- [
- 'name' => 'StringLength',
- 'options' => [
- 'min' => 6,
- 'max' => 64
- ],
- ],
- ],
- ]);
-
+
// Add input for "confirm_password" field
$inputFilter->add([
- 'name' => 'confirm_password',
- 'required' => true,
- 'filters' => [
- ],
- 'validators' => [
- [
- 'name' => 'Identical',
- 'options' => [
- 'token' => 'password',
- ],
+ 'name' => 'confirm_password',
+ 'required' => true,
+ 'filters' => [
+ ],
+ 'validators' => [
+ [
+ 'name' => 'Identical',
+ 'options' => [
+ 'token' => 'password',
],
],
- ]);
+ ],
+ ]);
}
-
+
// Add input for "status" field
$inputFilter->add([
- 'name' => 'status',
- 'required' => true,
- 'filters' => [
- ['name' => 'ToInt'],
- ],
- 'validators' => [
- ['name'=>'InArray', 'options'=>['haystack'=>[1, 2]]]
- ],
- ]);
- }
+ 'name' => 'status',
+ 'required' => true,
+ 'filters' => [
+ ['name' => 'ToInt'],
+ ],
+ 'validators' => [
+ ['name' => 'InArray', 'options' => ['haystack' => [1, 2]]]
+ ],
+ ]);
+ }
}
\ No newline at end of file
diff --git a/src/Service/UserManager.php b/src/Service/UserManager.php
index b907a15..483e784 100644
--- a/src/Service/UserManager.php
+++ b/src/Service/UserManager.php
@@ -1,6 +1,7 @@
setEmail($data['email']);
- $user->setFullName($data['full_name']);
+ $user->setFullName($data['full_name']);
+
+ // Get role object based on role Id from form
+ /** @var Role $role */
+ $role = $this->entityManager->find(Role::class, ['roleId' => $data['role']]);
+ // Set role to user
+ $user->addRole($role);
// Encrypt password and store the password in encrypted state.
$bcrypt = new Bcrypt();
@@ -49,7 +56,7 @@ public function addUser($data)
$currentDate = date('Y-m-d H:i:s');
$user->setDateCreated($currentDate);
-
+
// Add the entity to the entity manager.
$this->entityManager->persist($user);
@@ -58,11 +65,15 @@ public function addUser($data)
return $user;
}
-
+
/**
* This method updates data of an existing user.
+ * @param User $user
+ * @param $data
+ * @return bool
+ * @throws \Exception
*/
- public function updateUser($user, $data)
+ public function updateUser(User $user, $data)
{
// Do not allow to change user email if another user with such email already exits.
if($user->getEmail()!=$data['email'] && $this->checkUserExists($data['email'])) {
@@ -71,7 +82,13 @@ public function updateUser($user, $data)
$user->setEmail($data['email']);
$user->setFullName($data['full_name']);
- $user->setStatus($data['status']);
+ $user->setStatus($data['status']);
+
+ // Get role object based on role Id from form
+ /** @var Role $role */
+ $role = $this->entityManager->find(Role::class, ['roleId' => $data['role']]);
+ // Set role to user
+ $user->addRole($role);
// Apply changes to database.
$this->entityManager->flush();
@@ -95,7 +112,11 @@ public function createAdminUserIfNotExists()
$user->setPassword($passwordHash);
$user->setStatus(User::STATUS_ACTIVE);
$user->setDateCreated(date('Y-m-d H:i:s'));
-
+ // Get role object based on role Id from form
+ /** @var Role $role */
+ $role = $this->entityManager->find(Role::class, ['roleId' => 2]);
+ // Set role to user
+ $user->addRole($role);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
diff --git a/view/user/user/add.phtml b/view/user/user/add.phtml
index 6e2e1a0..07b5abf 100644
--- a/view/user/user/add.phtml
+++ b/view/user/user/add.phtml
@@ -19,6 +19,10 @@ $form->get('full_name')->setAttributes([
'placeholder'=>'John Doe'
]);
+$form->get('role')->setAttributes([
+ 'class'=>'form-control'
+]);
+
$form->get('status')->setAttributes([
'class'=>'form-control'
]);
@@ -69,7 +73,13 @@ $form->prepare();
= $this->formElement($form->get('confirm_password')); ?>
= $this->formElementErrors($form->get('confirm_password')); ?>
-
+
+
+ = $this->formLabel($form->get('role')); ?>
+ = $this->formElement($form->get('role')); ?>
+ = $this->formElementErrors($form->get('role')); ?>
+
+
= $this->formLabel($form->get('status')); ?>
= $this->formElement($form->get('status')); ?>
diff --git a/view/user/user/edit.phtml b/view/user/user/edit.phtml
index f7d1997..3959206 100644
--- a/view/user/user/edit.phtml
+++ b/view/user/user/edit.phtml
@@ -19,6 +19,10 @@ $form->get('full_name')->setAttributes([
'placeholder'=>'John Doe'
]);
+$form->get('role')->setAttributes([
+ 'class'=>'form-control'
+]);
+
$form->get('status')->setAttributes([
'class'=>'form-control'
]);
@@ -47,7 +51,13 @@ $form->prepare();
= $this->formElement($form->get('full_name')); ?>
= $this->formElementErrors($form->get('full_name')); ?>
-
+
+
+ = $this->formLabel($form->get('role')); ?>
+ = $this->formElement($form->get('role')); ?>
+ = $this->formElementErrors($form->get('role')); ?>
+
+
= $this->formLabel($form->get('status')); ?>
= $this->formElement($form->get('status')); ?>
From 9de15bfad1b8fd3e32f0590c3829e6b002092ec0 Mon Sep 17 00:00:00 2001
From: Xapp73 <1post112@gmail.com>
Date: Fri, 20 Jan 2017 17:53:51 +0200
Subject: [PATCH 2/7] Role system modification #1
---
src/Controller/UserController.php | 322 +++++++++++++++++-------------
src/Entity/User.php | 98 ++++-----
src/Form/UserForm.php | 44 ++--
src/Service/UserManager.php | 17 +-
view/user/user/index.phtml | 4 +-
5 files changed, 270 insertions(+), 215 deletions(-)
diff --git a/src/Controller/UserController.php b/src/Controller/UserController.php
index 1300da0..3e18604 100644
--- a/src/Controller/UserController.php
+++ b/src/Controller/UserController.php
@@ -1,6 +1,9 @@
entityManager = $entityManager;
$this->userManager = $userManager;
}
-
+
/**
- * This is the default "index" action of the controller. It displays the
+ * This is the default "index" action of the controller. It displays the
* list of users.
*/
- public function indexAction()
+ public function indexAction()
{
$users = $this->entityManager->getRepository(User::class)
- ->findBy([], ['id'=>'ASC']);
-
+ ->findBy([], ['id' => 'ASC']);
+
return new ViewModel([
'users' => $users
]);
- }
-
+ }
+
/**
* This action displays a page allowing to add a new user.
*/
public function addAction()
{
+ $rolesselector = $this->getRolesSelector();
+
// Create user form
- $form = new UserForm('create', $this->entityManager);
-
+ $form = new UserForm('create', $this->entityManager, null, $rolesselector, self::GUEST_ROLE_ID);
+
// Check if user has submitted the form
if ($this->getRequest()->isPost()) {
-
+
// Fill in the form with POST data
- $data = $this->params()->fromPost();
-
+ $data = $this->params()->fromPost();
+
$form->setData($data);
-
+
// Validate form
- if($form->isValid()) {
-
+ if ($form->isValid()) {
+
// Get filtered and validated data
$data = $form->getData();
-
+
// Add user.
$user = $this->userManager->addUser($data);
-
+
// Redirect to "view" page
- return $this->redirect()->toRoute('users',
- ['action'=>'view', 'id'=>$user->getId()]);
- }
- }
-
+ return $this->redirect()->toRoute('users',
+ ['action' => 'view', 'id' => $user->getId()]);
+ }
+ }
+
return new ViewModel([
- 'form' => $form
- ]);
+ 'form' => $form
+ ]);
}
-
+
/**
* The "view" action displays a page allowing to view user's details.
*/
- public function viewAction()
+ public function viewAction()
{
$id = (int)$this->params()->fromRoute('id', -1);
- if ($id<1) {
+ if ($id < 1) {
$this->getResponse()->setStatusCode(404);
return;
}
-
+
// Find a user with such ID.
$user = $this->entityManager->getRepository(User::class)
- ->find($id);
-
+ ->find($id);
+
if ($user == null) {
$this->getResponse()->setStatusCode(404);
return;
}
-
+
return new ViewModel([
'user' => $user
]);
}
-
+
/**
* The "edit" action displays a page allowing to edit user.
*/
- public function editAction()
+ public function editAction()
{
$id = (int)$this->params()->fromRoute('id', -1);
- if ($id<1) {
+ if ($id < 1) {
$this->getResponse()->setStatusCode(404);
return;
}
-
+
$user = $this->entityManager->getRepository(User::class)
- ->find($id);
-
+ ->find($id);
+
if ($user == null) {
$this->getResponse()->setStatusCode(404);
return;
}
-
+
+ $rolesselector = $this->getRolesSelector();
+
+ $rolecurrent = $this->getUserRole($user);
+
// Create user form
- $form = new UserForm('update', $this->entityManager, $user);
-
+ $form = new UserForm('update', $this->entityManager, $user, $rolesselector, $rolecurrent);
+
// Check if user has submitted the form
if ($this->getRequest()->isPost()) {
-
+
// Fill in the form with POST data
- $data = $this->params()->fromPost();
-
+ $data = $this->params()->fromPost();
+
$form->setData($data);
-
+
// Validate form
- if($form->isValid()) {
-
+ if ($form->isValid()) {
+
// Get filtered and validated data
$data = $form->getData();
-
+
// Update the user.
$this->userManager->updateUser($user, $data);
-
+
// Redirect to "view" page
- return $this->redirect()->toRoute('users',
- ['action'=>'view', 'id'=>$user->getId()]);
- }
+ return $this->redirect()->toRoute('users',
+ ['action' => 'view', 'id' => $user->getId()]);
+ }
} else {
$form->setData(array(
- 'full_name'=>$user->getFullName(),
- 'email'=>$user->getEmail(),
- 'status'=>$user->getStatus(),
- ));
+ 'full_name' => $user->getFullName(),
+ 'email' => $user->getEmail(),
+ 'status' => $user->getStatus(),
+ ));
}
-
+
return new ViewModel(array(
'user' => $user,
'form' => $form
));
}
-
+
/**
* This action displays a page allowing to change user's password.
*/
- public function changePasswordAction()
+ public function changePasswordAction()
{
$id = (int)$this->params()->fromRoute('id', -1);
- if ($id<1) {
+ if ($id < 1) {
$this->getResponse()->setStatusCode(404);
return;
}
-
+
$user = $this->entityManager->getRepository(User::class)
- ->find($id);
-
+ ->find($id);
+
if ($user == null) {
$this->getResponse()->setStatusCode(404);
return;
}
-
+
// Create "change password" form
$form = new PasswordChangeForm('change');
-
+
// Check if user has submitted the form
if ($this->getRequest()->isPost()) {
-
+
// Fill in the form with POST data
- $data = $this->params()->fromPost();
-
+ $data = $this->params()->fromPost();
+
$form->setData($data);
-
+
// Validate form
- if($form->isValid()) {
-
+ if ($form->isValid()) {
+
// Get filtered and validated data
$data = $form->getData();
-
+
// Try to change password.
if (!$this->userManager->changePassword($user, $data)) {
$this->flashMessenger()->addErrorMessage(
- 'Sorry, the old password is incorrect. Could not set the new password.');
+ 'Sorry, the old password is incorrect. Could not set the new password.');
} else {
$this->flashMessenger()->addSuccessMessage(
- 'Changed the password successfully.');
+ 'Changed the password successfully.');
}
-
+
// Redirect to "view" page
- return $this->redirect()->toRoute('users',
- ['action'=>'view', 'id'=>$user->getId()]);
- }
- }
-
+ return $this->redirect()->toRoute('users',
+ ['action' => 'view', 'id' => $user->getId()]);
+ }
+ }
+
return new ViewModel([
'user' => $user,
'form' => $form
]);
}
-
+
/**
* This action displays the "Reset Password" page.
*/
@@ -231,112 +244,147 @@ public function resetPasswordAction()
{
// Create form
$form = new PasswordResetForm();
-
+
// Check if user has submitted the form
if ($this->getRequest()->isPost()) {
-
+
// Fill in the form with POST data
- $data = $this->params()->fromPost();
-
+ $data = $this->params()->fromPost();
+
$form->setData($data);
-
+
// Validate form
- if($form->isValid()) {
-
+ if ($form->isValid()) {
+
// Look for the user with such email.
$user = $this->entityManager->getRepository(User::class)
- ->findOneByEmail($data['email']);
- if ($user!=null) {
+ ->findOneByEmail($data['email']);
+ if ($user != null) {
// Generate a new password for user and send an E-mail
// notification about that.
$this->userManager->generatePasswordResetToken($user);
-
+
// Redirect to "message" page
- return $this->redirect()->toRoute('users',
- ['action'=>'message', 'id'=>'sent']);
+ return $this->redirect()->toRoute('users',
+ ['action' => 'message', 'id' => 'sent']);
} else {
- return $this->redirect()->toRoute('users',
- ['action'=>'message', 'id'=>'invalid-email']);
+ return $this->redirect()->toRoute('users',
+ ['action' => 'message', 'id' => 'invalid-email']);
}
- }
- }
-
- return new ViewModel([
+ }
+ }
+
+ return new ViewModel([
'form' => $form
]);
}
-
+
/**
- * This action displays an informational message page.
+ * This action displays an informational message page.
* For example "Your password has been resetted" and so on.
*/
- public function messageAction()
+ public function messageAction()
{
// Get message ID from route.
$id = (string)$this->params()->fromRoute('id');
-
+
// Validate input argument.
- if($id!='invalid-email' && $id!='sent' && $id!='set' && $id!='failed') {
+ if ($id != 'invalid-email' && $id != 'sent' && $id != 'set' && $id != 'failed') {
throw new \Exception('Invalid message ID specified');
}
-
+
return new ViewModel([
'id' => $id
]);
}
-
+
/**
- * This action displays the "Reset Password" page.
+ * This action displays the "Reset Password" page.
*/
public function setPasswordAction()
{
$token = $this->params()->fromRoute('token', null);
-
+
// Validate token length
- if ($token!=null && (!is_string($token) || strlen($token)!=32)) {
+ if ($token != null && (!is_string($token) || strlen($token) != 32)) {
throw new \Exception('Invalid token type or length');
}
-
- if($token===null ||
- !$this->userManager->validatePasswordResetToken($token)) {
- return $this->redirect()->toRoute('user',
- ['action'=>'message', 'id'=>'failed']);
+
+ if ($token === null ||
+ !$this->userManager->validatePasswordResetToken($token)
+ ) {
+ return $this->redirect()->toRoute('user',
+ ['action' => 'message', 'id' => 'failed']);
}
-
+
// Create form
$form = new PasswordChangeForm('reset');
-
+
// Check if user has submitted the form
if ($this->getRequest()->isPost()) {
-
+
// Fill in the form with POST data
- $data = $this->params()->fromPost();
-
+ $data = $this->params()->fromPost();
+
$form->setData($data);
-
+
// Validate form
- if($form->isValid()) {
-
+ if ($form->isValid()) {
+
$data = $form->getData();
-
+
// Set new password for the user.
if ($this->userManager->setPasswordByToken($token, $data['password'])) {
-
+
// Redirect to "message" page
- return $this->redirect()->toRoute('user',
- ['action'=>'message', 'id'=>'set']);
+ return $this->redirect()->toRoute('user',
+ ['action' => 'message', 'id' => 'set']);
} else {
// Redirect to "message" page
- return $this->redirect()->toRoute('user',
- ['action'=>'message', 'id'=>'failed']);
+ return $this->redirect()->toRoute('user',
+ ['action' => 'message', 'id' => 'failed']);
}
- }
- }
-
- return new ViewModel([
+ }
+ }
+
+ return new ViewModel([
'form' => $form
]);
}
+
+ /**
+ * @return mixed
+ */
+ public function getRolesSelector()
+ {
+ $roles = $this->entityManager->getRepository(Role::class)->findAll();
+ $hydrator = new \Zend\Hydrator\ClassMethods();
+ $rolesselector = [];
+ foreach ($roles as $role) {
+ $rolesarr = $hydrator->extract($role);
+ $rolesselector[$rolesarr['role_id']] = $rolesarr['role_name'];
+ }
+ ksort($rolesselector);
+
+ return $rolesselector;
+ }
+
+ /**
+ * @param User $user
+ * @return int
+ */
+ public function getUserRole($user)
+ {
+ // checking for existing role if editing mode
+ $rolecurrent['role_id'] = self::GUEST_ROLE_ID;
+ $hydrator = new \Zend\Hydrator\ClassMethods();
+ $role = $user->getRole();
+ if (!empty($role)) {
+ $rolecurrent = $hydrator->extract($role);
+ }
+
+ return $rolecurrent['role_id'];
+ }
}
diff --git a/src/Entity/User.php b/src/Entity/User.php
index 37978a9..0daffd7 100644
--- a/src/Entity/User.php
+++ b/src/Entity/User.php
@@ -1,7 +1,6 @@
roles = new ArrayCollection();
+ return $this->role;
}
/**
- * Get role.
- * @return array
+ * Get Role Name.
+ * @return string
*/
- public function getRoles()
+ public function getRoleName()
{
- return $this->roles->getValues();
+ if(!empty($this->role)) {
+ return $this->role->getRoleName();
+ } else {
+ return 'N/A';
+ }
}
-
/**
* Add a role to the user.
* @param Role $role
@@ -50,7 +50,7 @@ public function getRoles()
*/
public function addRole($role)
{
- $this->roles[] = $role;
+ $this->role = $role;
}
/**
@@ -151,9 +151,9 @@ public function setFullName($fullName)
/**
* Returns status.
- * @return int
+ * @return int
*/
- public function getStatus()
+ public function getStatus()
{
return $this->status;
}
@@ -162,14 +162,14 @@ public function getStatus()
* Returns possible statuses as array.
* @return array
*/
- public static function getStatusList()
+ public static function getStatusList()
{
return [
self::STATUS_ACTIVE => 'Active',
self::STATUS_RETIRED => 'Retired'
];
- }
-
+ }
+
/**
* Returns user status as string.
* @return string
@@ -179,55 +179,55 @@ public function getStatusAsString()
$list = self::getStatusList();
if (isset($list[$this->status]))
return $list[$this->status];
-
+
return 'Unknown';
- }
-
+ }
+
/**
* Sets status.
- * @param int $status
+ * @param int $status
*/
- public function setStatus($status)
+ public function setStatus($status)
{
$this->status = $status;
- }
-
+ }
+
/**
* Returns password.
* @return string
*/
- public function getPassword()
+ public function getPassword()
{
- return $this->password;
+ return $this->password;
}
-
+
/**
- * Sets password.
+ * Sets password.
* @param string $password
*/
- public function setPassword($password)
+ public function setPassword($password)
{
$this->password = $password;
}
-
+
/**
* Returns the date of user creation.
- * @return string
+ * @return string
*/
- public function getDateCreated()
+ public function getDateCreated()
{
return $this->dateCreated;
}
-
+
/**
* Sets the date when this user was created.
- * @param string $dateCreated
+ * @param string $dateCreated
*/
- public function setDateCreated($dateCreated)
+ public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
- }
-
+ }
+
/**
* Returns password reset token.
* @return string
@@ -236,16 +236,16 @@ public function getResetPasswordToken()
{
return $this->passwordResetToken;
}
-
+
/**
* Sets password reset token.
* @param string $token
*/
- public function setPasswordResetToken($token)
+ public function setPasswordResetToken($token)
{
$this->passwordResetToken = $token;
}
-
+
/**
* Returns password reset token's creation date.
* @return string
@@ -254,12 +254,12 @@ public function getPasswordResetTokenCreationDate()
{
return $this->passwordResetTokenCreationDate;
}
-
+
/**
* Sets password reset token's creation date.
* @param string $date
*/
- public function setPasswordResetTokenCreationDate($date)
+ public function setPasswordResetTokenCreationDate($date)
{
$this->passwordResetTokenCreationDate = $date;
}
diff --git a/src/Form/UserForm.php b/src/Form/UserForm.php
index 33cd34f..39d2817 100644
--- a/src/Form/UserForm.php
+++ b/src/Form/UserForm.php
@@ -1,7 +1,9 @@
scenario = $scenario;
$this->entityManager = $entityManager;
$this->user = $user;
+ $this->rolesselector = $rolesselector;
+ $this->rolecurrent = $rolecurrent;
$this->addElements();
$this->addInputFilter();
@@ -95,25 +114,6 @@ protected function addElements()
]);
}
- $roles = $this->entityManager->getRepository(Role::class)->findAll();
- $hydrator = new \Zend\Hydrator\ClassMethods();
- $rolesselector = [];
- foreach ($roles as $role) {
- $rolesarr = $hydrator->extract($role);
- $rolesselector[$rolesarr['role_id']] = $rolesarr['role_name'];
- }
- ksort($rolesselector);
-
- // checking for existing role if editing mode
- $rolecurrent['role_id'] = 1;
-
- if ($this->scenario != 'create') {
- $role = $this->user->getRoles();
- if (!empty($role)) {
- $rolecurrent = $hydrator->extract($role[0]);
- }
- }
-
// Add role field selector here
$this->add([
'type' => 'select',
@@ -121,11 +121,11 @@ protected function addElements()
'options' => [
'label' => 'Role',
- 'value_options' => $rolesselector,
+ 'value_options' => $this->rolesselector,
],
'attributes' => [
- 'value' => $rolecurrent['role_id'],
+ 'value' => $this->rolecurrent,
]
]);
diff --git a/src/Service/UserManager.php b/src/Service/UserManager.php
index 483e784..2b9fd7b 100644
--- a/src/Service/UserManager.php
+++ b/src/Service/UserManager.php
@@ -12,6 +12,11 @@
*/
class UserManager
{
+ const ADMIN_ROLE_ID = 2;
+ const ADMIN_EMAIL = 'admin@example.com';
+ const ADMIN_NAME = 'Admin';
+ const ADMIN_PASSWORD = 'Secur1ty';
+
/**
* Doctrine entity manager.
* @var \Doctrine\ORM\EntityManager
@@ -43,7 +48,7 @@ public function addUser($data)
// Get role object based on role Id from form
/** @var Role $role */
- $role = $this->entityManager->find(Role::class, ['roleId' => $data['role']]);
+ $role = $this->entityManager->find(Role::class, $data['role']);
// Set role to user
$user->addRole($role);
@@ -86,7 +91,7 @@ public function updateUser(User $user, $data)
// Get role object based on role Id from form
/** @var Role $role */
- $role = $this->entityManager->find(Role::class, ['roleId' => $data['role']]);
+ $role = $this->entityManager->find(Role::class, $data['role']);
// Set role to user
$user->addRole($role);
@@ -105,16 +110,16 @@ public function createAdminUserIfNotExists()
$user = $this->entityManager->getRepository(User::class)->findOneBy([]);
if ($user==null) {
$user = new User();
- $user->setEmail('admin@example.com');
- $user->setFullName('Admin');
+ $user->setEmail(self::ADMIN_EMAIL);
+ $user->setFullName(self::ADMIN_NAME);
$bcrypt = new Bcrypt();
- $passwordHash = $bcrypt->create('Secur1ty');
+ $passwordHash = $bcrypt->create(self::ADMIN_PASSWORD);
$user->setPassword($passwordHash);
$user->setStatus(User::STATUS_ACTIVE);
$user->setDateCreated(date('Y-m-d H:i:s'));
// Get role object based on role Id from form
/** @var Role $role */
- $role = $this->entityManager->find(Role::class, ['roleId' => 2]);
+ $role = $this->entityManager->find(Role::class, self::ADMIN_ROLE_ID);
// Set role to user
$user->addRole($role);
$this->entityManager->persist($user);
diff --git a/view/user/user/index.phtml b/view/user/user/index.phtml
index 916fee7..f4edf0e 100644
--- a/view/user/user/index.phtml
+++ b/view/user/user/index.phtml
@@ -25,6 +25,7 @@ $this->pageBreadcrumbs()->setItems([
E-mail |
Full Name |
Date Created |
+
Role |
Status |
Actions |
@@ -40,7 +41,8 @@ $this->pageBreadcrumbs()->setItems([
= $this->escapeHtml($user->getFullName()); ?>
|
-
= $this->escapeHtml($user->getDateCreated()); ?> |
+
= $this->escapeHtml($user->getDateCreated()); ?> |
+
= $this->escapeHtml($user->getRoleName()); ?> |
= $this->escapeHtml($user->getStatusAsString()); ?> |
|