Completed
Push — master ( dd5c07...b4647f )
by Wanderson
02:12
created

UserDAO::clearRecoveryHash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
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 (!$this->obj->accessIsDenied() && strlen($this->obj->getEmail()) == 0) {
27
			return 'O campo E-mail deve ser preenchido.';
28
		} elseif (!$this->obj->accessIsDenied() && !filter_var($this->obj->getEmail(), FILTER_VALIDATE_EMAIL)) {
29
			return 'O campo E-mail deve ser um e-mail válido.';
30
		} elseif (!$this->obj->accessIsDenied() && $this->obj->getConfirmEmail() !== null && $this->obj->getConfirmEmail() != $this->obj->getEmail()) {
31
			return 'O campo E-mail deve ser informado duas vezes iguais.';
32
		} elseif (strlen($this->obj->getEmail()) > 0 and $this->emailIsUsed()) {
33
			return 'Já existe um usuário com este e-mail.';
34
		} elseif (!$this->obj->accessIsDenied() && $this->obj->getPassword() !== null && strlen($this->obj->getPassword()) < 4) {
35
			return 'A senha deve possuir pelo menos 4 caracteres.';
36
		} elseif ($this->obj->getConfirmPassword() != $this->obj->getPassword()) {
37
			return 'O campo Senha deve ser informado duas vezes iguais.';
38
		}
39
		return null;
40
	}
41
42
	/**
43
	 * @param array $row
44
	 * @return User
45
	 */
46
	public static function mapObject($row) {
47
		$obj = new User();
48
		$obj->setId($row['person_id']);
49
		$obj->setEnabled($row['is_enabled']);
50
		$obj->setAccessLevel($row['access_level']);
51
		//$obj->setGroupId($row['group_id']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
90% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
52
		$obj->setName($row['name']);
53
		$obj->setEmail($row['email']);
54
		$obj->setConfirmEmail($row['email']);
55
		$obj->setPasswordHash($row['password_hash']);
56
		$obj->setRecoreryHash($row['recovery_hash']);
57
		$obj->getImage()->setName($row['image']);
58
		$obj->setLoginDate(new Date($row['login_date']));
59
		return $obj;
60
	}
61
62
	/**
63
	 * @param User $obj
64
	 * @return mixed[]
65
	 */
66
	public static function mapRow($obj) {
67
		$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...
68
		$row['is_enabled'] = (int) $obj->isEnabled();
69
		$row['access_level'] = $obj->getAccessLevel();
70
		$row['name'] = strClear($obj->getName());
71
		$row['email'] = strClear($obj->getEmail());
72
		$row['image'] = $obj->getImage()->getName();
73
		$row['login_date'] = $obj->getLoginDate()->toSql();
74
		if (!is_null($obj->getPasswordHash())) {
75
			$row['password_hash'] = $obj->getPasswordHash();
76
		}
77
		if (!is_null($obj->getRecoreryHash())) {
78
			$row['recovery_hash'] = $obj->getRecoreryHash();
79
		}
80
		return $row;
81
	}
82
83
	/**
84
	 * Atualiza data ultimo login
85
	 * @param User $user
86
	 * @return string|null
87
	 */
88
	public function updateLoginDate(User $user) {
89
		$now = new Date();
90
		$user->setLoginDate($now);
91
		return $this->save($user);
92
	}
93
94
	/**
95
	 * Gera/Atualiza um novo recoveryHash
96
	 * @param User $user
97
	 * @return string|null
98
	 */
99
	public function updateRecoveryHash(User $user) {
100
		$hash = md5($user->getEmail() . date('Y-m-d'));
101
		$user->setRecoreryHash($hash);
102
		return $this->save($user);
103
	}
104
105
	/**
106
	 * Limpa o recoveryHash
107
	 * @param User $user
108
	 * @return string|null
109
	 */
110
	public function clearRecoveryHash(User $user) {
111
		$user->setRecoreryHash('');
112
		return $this->save($user);
113
	}
114
115
	/**
116
	 * Atualiza a senha | É necessário informar a senha atual, ou então o recoveryHash
117
	 * @param User $user
118
	 * @param string $currentPassword
119
	 * @param string $recoveryHash
120
	 * @return string|null
121
	 */
122
	public function updatePassword($user, $currentPassword = null, $recoveryHash = null) {
123
		$savedUser = $this->fetchById($user->getId());
124
		if (!is_null($currentPassword) and $savedUser->getPasswordHash() != User::encryptPassword($currentPassword)) {
125
			return 'A senha atual não está correta.';
126
		} elseif (!is_null($recoveryHash) and $user->getRecoreryHash() !== $recoveryHash) {
127
			return 'O link de recuperação é inválido.';
128
		}
129
		return $this->save($user);
130
	}
131
132
	/**
133
	 * Retorna true se já existe este email no sistema 
134
	 * @return boolean
135
	 */
136
	public function emailIsUsed() {
137
		return $this->numRows(['email = ?' => $this->obj->getEmail(), 'person_id <> ?' => $this->obj->getId()]);
138
	}
139
140
	public function fetchByRecoveryHash($recoveryHash) {
141
		return $this->fetch(['recovery_hash = ?' => $recoveryHash]);
142
	}
143
144
	public function onDelete() {
145
		$this->obj->getImage()->remove();
146
	}
147
148
	/**
149
	 * Insere o primeiro admin
150
	 * @param User $user
151
	 * @return string|null
152
	 */
153
	public function insertFirst(User $user) {
154
		$user->setName('Administrador');
155
		$user->setAccessLevel(User::ACCESS_ADMIN);
156
		$user->setConfirmEmail($user->getEmail());
157
		$user->setConfirmPassword($user->getPassword());
158
159
		if ($this->numRows() === 0) {
160
			return $this->save($user);
161
		}
162
	}
163
164
}
165