Completed
Push — master ( 774d12...7a0ba2 )
by Wanderson
02:14
created

UserDAO::updatePassword()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 3
nop 3
dl 0
loc 9
rs 8.8571
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
		$userClone = clone $user;
91
		$userClone->setLoginDate($now);
92
		return $this->save($userClone);
93
	}
94
95
	/**
96
	 * Gera/Atualiza um novo recoveryHash
97
	 * @param User $user
98
	 * @return string|null
99
	 */
100
	public function updateRecoveryHash(User $user) {
101
		$hash = md5($user->getEmail() . date('Y-m-d'));
102
		$user->setRecoreryHash($hash);
103
		return $this->save($user);
104
	}
105
106
	/**
107
	 * Atualiza a senha | É necessário informar a senha atual, ou então o recoveryHash
108
	 * @param User $user
109
	 * @param string $currentPassword
110
	 * @param string $recoveryHash
111
	 * @return string|null
112
	 */
113
	public function updatePassword($user, $currentPassword = null, $recoveryHash = null) {
114
		$savedUser = $this->fetchById($user->getId());
115
		if (!is_null($currentPassword) and $savedUser->getPasswordHash() != User::encryptPassword($currentPassword)) {
116
			return 'A senha atual não está correta.';
117
		} elseif (!is_null($recoveryHash) and $user->getRecoreryHash() !== $recoveryHash) {
118
			return 'O link de recuperação é inválido.';
119
		}
120
		return $this->save($user);
121
	}
122
123
	/**
124
	 * Retorna true se já existe este email no sistema 
125
	 * @return boolean
126
	 */
127
	public function emailIsUsed() {
128
		return $this->numRows(['email = ?' => $this->obj->getEmail(), 'person_id <> ?' => $this->obj->getId()]);
129
	}
130
131
	public function fetchByRecoveryHash($recoveryHash) {
132
		return $this->fetch(['recovery_hash = ?' => $recoveryHash]);
133
	}
134
135
	public function onDelete() {
136
		$this->obj->getImage()->remove();
137
	}
138
139
	/**
140
	 * Insere o primeiro admin
141
	 * @param User $user
142
	 * @return string|null
143
	 */
144
	public function insertFirst(User $user) {
145
		$user->setName('Administrador');
146
		$user->setAccessLevel(User::ACCESS_ADMIN);
147
		$user->setConfirmEmail($user->getEmail());
148
		$user->setConfirmPassword($user->getPassword());
149
150
		if ($this->numRows() === 0) {
151
			return $this->save($user);
152
		}
153
	}
154
155
}
156