Completed
Push — master ( 281aaa...7f49f2 )
by Michael
03:22
created

AbstractActiveRecord::searchOne()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.4285
cc 3
eloc 10
nc 5
nop 2
crap 3
1
<?php
2
3
/**
4
 * This file is part of the miBadger package.
5
 *
6
 * @author Michael Webbers <[email protected]>
7
 * @license http://opensource.org/licenses/Apache-2.0 Apache v2 License
8
 * @version 1.0.0
9
 */
10
11
namespace miBadger\ActiveRecord;
12
13
use miBadger\Query\Query;
14
15
/**
16
 * The abstract active record class.
17
 *
18
 * @since 1.0.0
19
 */
20
abstract class AbstractActiveRecord implements ActiveRecordInterface
21
{
22
	/** @var \PDO The PDO object. */
23
	private $pdo;
24
25
	/** @var null|int The ID. */
26
	private $id;
27
28
	/**
29
	 * Construct an abstract pdo active record with the given pdo.
30
	 *
31
	 * @param \PDO $pdo
32
	 */
33 31
	public function __construct(\PDO $pdo)
34
	{
35 31
		$pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
36 31
		$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
37
38 31
		$this->setPdo($pdo);
39 31
	}
40
41
	/**
42
	 * {@inheritdoc}
43
	 */
44 4
	public function create()
45
	{
46
		try {
47 4
			(new Query($this->getPdo(), $this->getActiveRecordTable()))
48 4
				->insert($this->getActiveRecordColumns())
49 4
				->execute();
50
51 2
			$this->setId(intval($this->getPdo()->lastInsertId()));
52 4
		} catch (\PDOException $e) {
53 2
			throw new ActiveRecordException($e->getMessage(), 0, $e);
54
		}
55
56 2
		return $this;
57
	}
58
59
	/**
60
	 * {@inheritdoc}
61
	 */
62 9
	public function read($id)
63
	{
64
		try {
65 9
			$result = (new Query($this->getPdo(), $this->getActiveRecordTable()))
66 9
				->select()
67 9
				->where('id', '=', $id)
68 9
				->execute()
69 8
				->fetch();
70
71 8
			if ($result === false) {
72 1
				throw new ActiveRecordException(sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getActiveRecordTable()));
73
			}
74
75 7
			$this->fill($result);
76 6
			$this->setId($id);
77 9
		} catch (\PDOException $e) {
78 1
			throw new ActiveRecordException($e->getMessage(), 0, $e);
79
		}
80
81 6
		return $this;
82
	}
83
84
	/**
85
	 * {@inheritdoc}
86
	 */
87 5 View Code Duplication
	public function update()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
88
	{
89 5
		if (!$this->exists()) {
90 1
			throw new ActiveRecordException(sprintf('Can not update a non-existent active record entry to the `%s` table.', $this->getActiveRecordTable()));
91
		}
92
93
		try {
94 4
			(new Query($this->getPdo(), $this->getActiveRecordTable()))
95 4
				->update($this->getActiveRecordColumns())
96 4
				->where('id', '=', $this->getId())
97 4
				->execute();
98 4
		} catch (\PDOException $e) {
99 2
			throw new ActiveRecordException($e->getMessage(), 0, $e);
100
		}
101
102 2
		return $this;
103
	}
104
105
	/**
106
	 * {@inheritdoc}
107
	 */
108 4 View Code Duplication
	public function delete()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
	{
110 4
		if (!$this->exists()) {
111 1
			throw new ActiveRecordException(sprintf('Can not delete a non-existent active record entry from the `%s` table.', $this->getActiveRecordTable()));
112
		}
113
114
		try {
115 3
			(new Query($this->getPdo(), $this->getActiveRecordTable()))
116 3
				->delete()
117 3
				->where('id', '=', $this->getId())
118 3
				->execute();
119
120 2
			$this->setId(null);
121 3
		} catch (\PDOException $e) {
122 1
			throw new ActiveRecordException($e->getMessage(), 0, $e);
123
		}
124
125 2
		return $this;
126
	}
127
128
	/**
129
	 * {@inheritdoc}
130
	 */
131 2
	public function sync()
132
	{
133 2
		if (!$this->exists()) {
134 1
			return $this->create();
135
		}
136
137 1
		return $this->update();
138
	}
139
140
	/**
141
	 * {@inheritdoc}
142
	 */
143 10
	public function exists()
144
	{
145 10
		return $this->getId() !== null;
146
	}
147
148
	/**
149
	 * Fill the active record
150
	 *
151
	 * @param array $fetch
152
	 * @return null
153
	 */
154 17
	public function fill(array $fetch)
155
	{
156 17
		$data = $this->getActiveRecordColumns();
157
158 17
		foreach ($data as $key => &$value) {
159 17
			if (!array_key_exists($key, $fetch)) {
160 1
				throw new ActiveRecordException(sprintf('Can not read the expected column `%s`. It\'s not returnd by the `%s` table', $key, $this->getActiveRecordTable()));
161
			}
162
163 17
			$value = $fetch[$key];
164 17
		}
165 16
	}
166
167
	/**
168
	 * {@inheritdoc}
169
	 */
170 28
	public function searchOne(array $where = [], array $orderBy = [])
171
	{
172
		try {
173 3
			$result = $this->getSearchQueryResult($where, $orderBy, 1)->fetch();
174
175 2
			if ($result === false) {
176 1
				throw new ActiveRecordException(sprintf('Can not search one non-existent entry from the `%s` table.', $this->getActiveRecordTable()));
177
			}
178
179 1
			$this->fill($result);
180 28
			$this->setId(intval($result['id']));
181
182 1
			return $this;
183 3
		} catch (\PDOException $e) {
184 1
			throw new ActiveRecordException($e->getMessage(), 0, $e);
185
		}
186
	}
187
188
	/**
189
	 * {@inheritdoc}
190
	 */
191 10
	public function search(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
192
	{
193
		try {
194 10
			$queryResult = $this->getSearchQueryResult($where, $orderBy, $limit, $offset);
195 8
			$result = [];
196
197 8
			foreach ($queryResult as $fetch) {
198 8
				$new = new static($this->getPdo());
199
200 8
				$new->setId(intval($fetch['id']));
201 8
				$new->fill($fetch);
202
203 8
				$result[] = $new;
204 8
			}
205
206 8
			return $result;
207 2
		} catch (\PDOException $e) {
208 2
			throw new ActiveRecordException($e->getMessage(), 0, $e);
209
		}
210
	}
211
212
	/**
213
	 * Returns the search query result with the given where, order by, limit and offset clauses.
214
	 *
215
	 * @param array $where = []
216
	 * @param array $orderBy = []
217
	 * @param int $limit = -1
218
	 * @param int $offset = 0
219
	 * @return \miBadger\Query\QueryResult the search query result with the given where, order by, limit and offset clauses.
220
	 */
221 13
	private function getSearchQueryResult(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
222
	{
223 13
		$query = (new Query($this->getPdo(), $this->getActiveRecordTable()))
224 13
			->select();
225
226 13
		$this->getSearchQueryWhere($query, $where);
227 13
		$this->getSearchQueryOrderBy($query, $orderBy);
228 13
		$this->getSearchQueryLimit($query, $limit, $offset);
229
230 13
		return $query->execute();
231
	}
232
233
	/**
234
	 * Returns the given query after adding the given where conditions.
235
	 *
236
	 * @param \miBadger\Query\Query $query
237
	 * @param array $where
238
	 * @return \miBadger\Query\Query the given query after adding the given where conditions.
239
	 */
240 13
	private function getSearchQueryWhere($query, $where)
241
	{
242 13
		foreach ($where as $key => $value) {
243 7
			$query->where($value[0], $value[1], $value[2]);
244 13
		}
245
246 13
		return $query;
247
	}
248
249
	/**
250
	 * Returns the given query after adding the given order by conditions.
251
	 *
252
	 * @param \miBadger\Query\Query $query
253
	 * @param array $orderBy
254
	 * @return \miBadger\Query\Query the given query after adding the given order by conditions.
255
	 */
256 13
	private function getSearchQueryOrderBy($query, $orderBy)
257
	{
258 13
		foreach ($orderBy as $key => $value) {
259 1
			$query->orderBy($key, $value);
260 13
		}
261
262 13
		return $query;
263
	}
264
265
	/**
266
	 * Returns the given query after adding the given limit and offset conditions.
267
	 *
268
	 * @param \miBadger\Query\Query $query
269
	 * @param int $limit
270
	 * @param int $offset
271
	 * @return \miBadger\Query\Query the given query after adding the given limit and offset conditions.
272
	 */
273 13
	private function getSearchQueryLimit($query, $limit, $offset)
274
	{
275 13
		if ($limit > -1) {
276 5
			$query->limit($limit);
277 5
			$query->offset($offset);
278 5
		}
279
280 13
		return $query;
281
	}
282
283
	/**
284
	 * Returns the PDO.
285
	 *
286
	 * @return \PDO the PDO.
287
	 */
288 28
	public function getPdo()
289
	{
290 28
		return $this->pdo;
291
	}
292
293
	/**
294
	 * Set the PDO.
295
	 *
296
	 * @param \PDO $pdo
297
	 * @return $this
298
	 */
299 31
	protected function setPdo($pdo)
300
	{
301 31
		$this->pdo = $pdo;
302
303 31
		return $this;
304
	}
305
306
	/**
307
	 * Returns the ID.
308
	 *
309
	 * @return null|int The ID.
310
	 */
311 9
	public function getId()
312
	{
313 9
		return $this->id;
314
	}
315
316
	/**
317
	 * Set the ID.
318
	 *
319
	 * @param int $id
320
	 * @return $this
321
	 */
322 16
	protected function setId($id)
323
	{
324 16
		$this->id = $id;
325
326 16
		return $this;
327
	}
328
329
	/**
330
	 * Returns the active record table.
331
	 *
332
	 * @return string the active record table.
333
	 */
334
	abstract protected function getActiveRecordTable();
335
336
	/**
337
	 * Returns the active record columns.
338
	 *
339
	 * @return array the active record columns.
340
	 */
341
	abstract protected function getActiveRecordColumns();
342
}
343