Completed
Push — master ( c823eb...e0ab14 )
by Wanderson
02:54
created

DAO   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 186
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 22
c 1
b 0
f 1
lcom 1
cbo 2
dl 0
loc 186
rs 10

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A setPDO() 0 3 1
mapObject() 0 1 ?
mapRow() 0 1 ?
A save() 0 9 2
A insert() 0 10 1
A update() 0 14 2
A delete() 0 3 1
A deleteById() 0 6 1
A fetchById() 0 3 1
A fetchByField() 0 3 1
A fetch() 0 11 2
A fetchAll() 0 16 3
A selectSQL() 0 4 1
A whereSQL() 0 3 2
A objExists() 0 3 1
A validateObject() 0 5 2
1
<?php
2
3
namespace Win\DesignPattern;
4
5
/**
6
 * Data Access Object
7
 */
8
abstract class DAO {
9
10
	/** @var \PDO */
11
	protected $pdo;
12
13
	/** Inicia o DAO */
14
	public function __construct() {
15
		$this->pdo = \Win\Connection\MySQL::instance()->getPDO();
16
	}
17
18
	/**
19
	 * Define uma conexão manualmente
20
	 * @param \PDO $pdo
21
	 */
22
	public function setPDO($pdo) {
23
		$this->pdo = $pdo;
24
	}
25
26
	/**
27
	 * Retorna um objeto a partir da linha da tabela
28
	 * @param mixed[] $row
29
	 */
30
	abstract public function mapObject(array $row);
31
32
	/** Retorna a linha da tabela a partir de um objeto
33
	 * @param object $obj
34
	 */
35
	abstract public function mapRow($obj);
36
37
	/**
38
	 * Salva o registro
39
	 * @param object $obj
40
	 */
41
	public function save($obj) {
42
		$this->obj = $obj;
0 ignored issues
show
Bug introduced by
The property obj does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
43
		if (!$this->objExists()) {
44
			$this->insert();
45
			$this->obj->setId($this->pdo->lastInsertId());
46
		} else {
47
			$this->update();
48
		}
49
	}
50
51
	/** Insere registro no banco de dados */
52
	protected function insert() {
53
		$mapRow = $this->mapRow($this->obj);
54
		$keys = array_keys($mapRow);
55
		$values = array_values($mapRow);
56
		$params = str_split(str_repeat('?', count($keys)));
57
58
		$sql = 'INSERT INTO ' . static::TABLE . ' (' . implode(',', $keys) . ') VALUES (' . implode(', ', $params) . ') ';
59
		$stmt = $this->pdo->prepare($sql);
60
		$stmt->execute($values);
61
	}
62
63
	/** Atualiza registro no banco de dados */
64
	protected function update() {
65
		$mapRow = $this->mapRow($this->obj);
66
		$keys = array_keys($mapRow);
67
		$values = array_values($mapRow);
68
		$params = [];
69
		foreach ($keys as $key):
70
			$params[] = $key . ' = ?';
71
		endforeach;
72
		$values[] = $this->obj->getId();
73
74
		$sql = 'UPDATE ' . static::TABLE . ' SET ' . implode(', ', $params) . ' WHERE id = ? ';
75
		$stmt = $this->pdo->prepare($sql);
76
		$stmt->execute($values);
77
	}
78
79
	/**
80
	 * Exclui o registro
81
	 * @param mixed $obj
82
	 */
83
	public function delete($obj) {
84
		$this->deleteById($obj->getId());
85
	}
86
87
	/**
88
	 * Exclui o registro por Id
89
	 * @param int $id
90
	 */
91
	public function deleteById($id) {
92
		$sql = 'DELETE FROM ' . static::TABLE . ' WHERE id = :id';
93
		$stmt = $this->pdo->prepare($sql);
94
		$stmt->bindValue(':id', $id);
95
		$stmt->execute();
96
	}
97
98
	/**
99
	 * Busca o objeto pelo id
100
	 * @param int $id
101
	 * @return mixed
102
	 */
103
	public function fetchById($id) {
104
		return $this->fetchByField('id', $id);
105
	}
106
107
	/**
108
	 * Busca o objeto por um campo específico
109
	 * @param string $fieldName
110
	 * @param mixed $fieldValue
111
	 * @return mixed
112
	 */
113
	public function fetchByField($fieldName, $fieldValue) {
114
		return $this->fetch([$fieldName . ' = ?' => $fieldValue]);
115
	}
116
117
	/**
118
	 * Busca o objeto pelo filtro
119
	 * @param string $fieldName
0 ignored issues
show
Bug introduced by
There is no parameter named $fieldName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
120
	 * @param mixed $fieldValue
0 ignored issues
show
Bug introduced by
There is no parameter named $fieldValue. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
121
	 * @return mixed
122
	 */
123
	public function fetch($filter) {
124
		if (!is_array($filter)):
125
			throw new \Exception("Filter: '{$filter}' must be a array");
126
		endif;
127
		$sql = $this->selectSQL($filter);
128
		$stmt = $this->pdo->prepare($sql);
129
		$stmt->execute(array_values($filter));
130
131
		$result = $stmt->fetch();
132
		return $this->mapObject($result);
133
	}
134
135
	/**
136
	 * Retorna todos os registros
137
	 *
138
	 * É possivel utilizar filtragem
139
	 * @example fetchAll(['id = ?' => 10, 'data > ?' => '2010-01-01'])
140
	 * 
141
	 * @param string[] $filter Array com filtros
142
	 * @return object[] Array de objetos
143
	 */
144
	public function fetchAll($filter = []) {
145
		if (!is_array($filter)):
146
			throw new \Exception("Filter: '{$filter}' must be a array");
147
		endif;
148
149
		$sql = $this->selectSQL($filter);
150
		$stmt = $this->pdo->prepare($sql);
151
		$stmt->execute(array_values($filter));
152
153
		$results = $stmt->fetchAll();
154
		$array = [];
155
		foreach ($results as $result):
156
			$array[] = $this->mapObject($result);
157
		endforeach;
158
		return $array;
159
	}
160
161
	/** Retorna comando Select */
162
	protected function selectSQL(&$filter) {
163
		$keys = array_keys($filter);
164
		return 'SELECT * FROM ' . static::TABLE . ' ' . $this->whereSQL($keys) . '';
165
	}
166
167
	/**
168
	 * Retorna WHERE com base nas keys
169
	 * @param string[] $keys
170
	 * @return string
171
	 */
172
	private function whereSQL(&$keys) {
173
		return ($keys) ? 'WHERE ' . implode(' AND ', $keys) : '';
174
	}
175
176
	/**
177
	 * Retorna true se objeto existe
178
	 * @return boolean
179
	 */
180
	public function objExists() {
181
		return ($this->obj->getId() > 0);
182
	}
183
184
	/**
185
	 * Define pagina 404 se objeto não existir
186
	 */
187
	public function validateObject() {
188
		if ($this->obj->getId() == 0) {
189
			\Win\Mvc\Application::app()->pageNotFound();
190
		}
191
	}
192
193
}
194