Completed
Push — master ( c7b167...faaa80 )
by Wanderson
02:08
created

UserDAO::validateNewPassword()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 7.7777
c 0
b 0
f 0
cc 8
eloc 10
nc 5
nop 5
1
<?php
2
3
namespace Win\Authentication;
4
5
use Win\DAO\DAO;
6
use Win\Authentication\User;
7
use Win\Calendar\Date;
8
9
/**
10
 * User DAO
11
 */
12
class UserDAO extends DAO implements UserDAOInterface {
13
14
	const TABLE = 'person';
15
	const ALIAS = 'Usuário';
16
17
	/** @var User */
18
	protected $obj;
19
20
	/**
21
	 * @return string|null
22
	 */
23
	protected function validate() {
24
		if (strlen($this->obj->getName()) < 2) {
25
			return 'O campo Nome deve possuir pelo menos 2 caracteres.';
26
		} elseif (strlen($this->obj->getEmail()) == 0) {
27
			return 'O campo E-mail deve ser preenchido.';
28
		} elseif (!filter_var($this->obj->getEmail(), FILTER_VALIDATE_EMAIL)) {
29
			return 'O campo E-mail deve ser um e-mail válido.';
30
		} elseif (strlen($this->obj->getEmail()) > 0 and $this->obj->emailIsDuplicated()) {
31
			return 'Já existe um usuário com este e-mail.';
32
		} elseif ($this->obj->getPassword() != null and strlen($this->obj->getPassword()) < 4) {
33
			return 'A senha deve possuir pelo menos 4 caracteres.';
34
		}
35
		return null;
36
	}
37
38
	/**
39
	 * @param array $row
40
	 * @return User
41
	 */
42
	protected function mapObject($row) {
43
		$obj = new User();
44
		$obj->setId($row['person_id']);
45
		$obj->setEnabled($row['is_enabled']);
46
		$obj->setAccessLevel($row['access_level']);
47
		$obj->setGroupId($row['group_id']);
48
		$obj->setName($row['name']);
49
		$obj->setEmail($row['email']);
50
		$obj->setPasswordHash($row['password_hash']);
51
		$obj->setRecoreryHash($row['recovery_hash']);
52
		$obj->getImage()->setName($row['image']);
53
		if (!is_null($row['login_date'])) {
54
			$obj->setLoginDate(new Date($row['login_date']));
55
		}
56
		return $obj;
57
	}
58
59
	/**
60
	 * @param User $obj
61
	 * @return mixed[]
62
	 */
63
	protected function mapRow($obj) {
64
		$row['person_id'] = $obj->getId();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$row was never initialized. Although not strictly required by PHP, it is generally a good practice to add $row = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
65
		$row['is_enabled'] = $obj->isEnabled();
66
		$row['access_level'] = $obj->getAccessLevel();
67
		$row['group_id'] = $obj->getGroupId();
68
		$row['name'] = $obj->getName();
69
		$row['email'] = $obj->getEmail();
70
		if ($obj->getPassword() != null) {
71
			$row['password_hash'] = $obj->getPasswordHash();
72
		}
73
		if ($obj->getRecoreryHash() != null) {
74
			$row['recovery_hash'] = $obj->getRecoreryHash();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $row['recovery_hash'] is correct as $obj->getRecoreryHash() (which targets Win\Authentication\User::getRecoreryHash()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
75
		}
76
		$row['image'] = $obj->getImage()->getName();
77
		$row['login_date'] = $obj->getLoginDate()->toSql();
78
		return $row;
79
	}
80
81
	/**
82
	 * Insere o primeiro usuario
83
	 * @param User $user
84
	 * @return string|null
85
	 */
86
	public function insertFirst(User $user) {
87
		if ($this->totalUsers() === 0) {
88
			$user->setAccessLevel(User::ACCESS_ADMIN);
89
			$user->setName('Administrador');
90
			return $this->save($user);
91
		}
92
	}
93
94
	/**
95
	 * Retorna total usuarios
96
	 * @return int
97
	 */
98
	public function totalUsers() {
99
		return (int) $this->numRows();
100
	}
101
102
	/**
103
	 * Atualiza data ultimo login
104
	 * @param User $user
105
	 * @return string|null
106
	 */
107
	public function updateLoginDate(User $user) {
108
		$now = new Date();
109
		$userClone = clone $user;
110
		$userClone->setLoginDate($now);
111
		return $this->save($userClone);
112
	}
113
114
	/**
115
	 * Gera/Atualiza um novo recoveryHash
116
	 * @param User $user
117
	 * @return string|null
118
	 */
119
	public function updateRecoveryHash(User $user) {
120
		$hash = md5($user->getEmail() . date('Y-m-d'));
121
		$user->setRecoreryHash($hash);
122
		return $this->save($user);
123
	}
124
125
	/**
126
	 * Atualiza a senha | É necessário informar a senha atual, ou então o recoveryHash
127
	 * @param int $userId
128
	 * @param string $newPassword1
129
	 * @param string $newPassword2
130
	 * @param string $currentPassword
131
	 * @param string $recoveryHash
132
	 * @return string erro
133
	 */
134
	public function updatePassword($userId, $newPassword1, $newPassword2, $currentPassword = null, $recoveryHash = null) {
135
		$user = $this->fetchById($userId);
136
		$error = $this->validateNewPassword($user, $newPassword1, $newPassword2, $currentPassword, $recoveryHash);
137
138
		if (!$error) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
139
			$user->setPassword($newPassword1);
140
			$error = $this->save($user);
141
		}
142
		return $error;
143
	}
144
145
	/**
146
	 * Valida se está apto a alterar a senha
147
	 * @param User $user
148
	 * @param string $newPassword1
149
	 * @param string $newPassword2
150
	 * @param string $currentPassword
151
	 * @param string $recoveryHash
152
	 * @return string|null
153
	 */
154
	private function validateNewPassword($user, $newPassword1, $newPassword2, $currentPassword, $recoveryHash) {
155
		if (!is_null($currentPassword) and $user->getPasswordHash() != User::encryptPassword($currentPassword)) {
156
			return 'A senha atual não está correta.';
157
		} elseif (!is_null($recoveryHash) and $user->getRecoreryHash() !== $recoveryHash) {
158
			return 'O link de recuperação é inválido.';
159
		} elseif (!is_null($user->getPassword()) and strlen($newPassword1) < 4) {
160
			return 'A nova senha deve possuir pelo menos 4 caracteres.';
161
		} elseif ($newPassword1 != $newPassword2) {
162
			return 'A nova senha deve ser informada duas vezes iguais.';
163
		}
164
		return null;
165
	}
166
167
	public function fetchByRecoveryHash($recoveryHash) {
168
		return $this->fetch(['recovery_hash = ?' => $recoveryHash]);
169
	}
170
171
	/** @param User $obj */
172
	public function delete($obj) {
173
		$obj->getImage()->remove();
174
		parent::delete($obj);
175
	}
176
177
}
178