Completed
Push — master ( a7b0c2...fe24f6 )
by Wanderson
02:20
created

UserDAO::onDelete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
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
		
25
		if (strlen($this->obj->name) < 2) {
26
			return 'O campo Nome deve possuir pelo menos 2 caracteres.';
27
		} elseif (!$this->obj->accessIsDenied() && strlen($this->obj->getEmail()) == 0) {
28
			return 'O campo E-mail deve ser preenchido.';
29
		} elseif (!$this->obj->accessIsDenied() && !filter_var($this->obj->getEmail(), FILTER_VALIDATE_EMAIL)) {
30
			return 'O campo E-mail deve ser um e-mail válido.';
31
		} elseif (!$this->obj->accessIsDenied() && $this->obj->confirmEmail()) {
32
			return 'O campo E-mail deve ser informado duas vezes iguais.';
33
		} elseif (strlen($this->obj->getEmail()) > 0 and $this->emailIsUsed()) {
34
			return 'Já existe um usuário com este e-mail.';
35
		} elseif (!$this->obj->accessIsDenied() && ($this->obj->getPassword() !== null || $this->obj->getId() === 0) && strlen($this->obj->getPassword()) < 4) {
36
			return 'A senha deve possuir pelo menos 4 caracteres.';
37
		} elseif (!$this->obj->confirmPassword()) {
38
			return 'O campo Senha deve ser informado duas vezes iguais.';
39
		}
40
		return null;
41
	}
42
43
	/**
44
	 * @param array $row
45
	 * @return User
46
	 */
47
	public static function mapObject($row) {
48
		$obj = new User();
49
		$obj->id = $row['person_id'];
50
		$obj->isEnabled = $row['is_enabled'];
51
		$obj->accessLevel = $row['access_level'];
52
		//$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...
53
		$obj->name = $row['name'];
54
		$obj->setEmail($row['email']);
55
		$obj->passwordHash = $row['password_hash'];
56
		$obj->recoreryHash = $row['recovery_hash'];
57
		$obj->image->setName($row['image']);
58
		$obj->loginDate = 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->id;
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->accessLevel;
70
		$row['name'] = strClear($obj->name);
71
		$row['email'] = strClear($obj->getEmail());
72
		//$row['image'] = $obj->image->getName();
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
73
		$row['login_date'] = $obj->loginDate->toSql();
74
		if (!is_null($obj->passwordHash)) {
75
			$row['password_hash'] = $obj->passwordHash;
76
		}
77
		if (!is_null($obj->recoreryHash)) {
78
			$row['recovery_hash'] = $obj->recoreryHash;
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
		$user->loginDate = new Date();
90
		return $this->save($user);
91
	}
92
93
	/**
94
	 * Atualiza a senha | É necessário informar a senha atual, ou então o recoveryHash
95
	 * @param User $user
96
	 * @param string $currentPassword
97
	 * @param string $recoveryHash
98
	 * @return string|null
99
	 */
100
	public function updatePassword($user, $currentPassword = null, $recoveryHash = null) {
101
		$savedUser = $this->fetchById($user->getId());
102
		if (!is_null($currentPassword) and $savedUser->passwordHash != Password::encrypt($currentPassword)) {
103
			return 'A senha atual não está correta.';
104
		} elseif (!is_null($recoveryHash) and $user->recoreryHash !== $recoveryHash) {
105
			return 'O link de recuperação é inválido.';
106
		}
107
		return $this->save($user);
108
	}
109
110
	/**
111
	 * Retorna true se já existe este email no sistema 
112
	 * @return boolean
113
	 */
114
	public function emailIsUsed() {
115
		return $this->numRows(['email = ?' => $this->obj->getEmail(), 'person_id <> ?' => $this->obj->id]);
116
	}
117
118
	public function fetchByRecoveryHash($recoveryHash) {
119
		return $this->fetch(['recovery_hash = ?' => $recoveryHash]);
120
	}
121
122
	public function onDelete() {
123
		$this->obj->image->remove();
124
	}
125
126
	/**
127
	 * Insere o primeiro admin
128
	 * @param User $user
129
	 * @return string|null
130
	 */
131
	public function insertFirst(User $user) {
132
		$user->name = 'Administrador';
133
		$user->accessLevel = User::ACCESS_ADMIN;
134
135
		if ($this->numRows() === 0) {
136
			return $this->save($user);
137
		}
138
	}
139
140
}
141