Completed
Push — develop ( 32f6c0...7995ec )
by Michael
03:11
created

AbstractActiveRecordSearch::getSearchQuery()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 9

Importance

Changes 5
Bugs 0 Features 3
Metric Value
c 5
b 0
f 3
dl 0
loc 26
ccs 19
cts 19
cp 1
rs 4.909
cc 9
eloc 18
nc 7
nop 1
crap 9
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
/**
14
 * The abstract active record search class.
15
 *
16
 * @since 1.0.0
17
 */
18
abstract class AbstractActiveRecordSearch extends AbstractActiveRecord
19
{
20
	/**
21
	 * {@inheritdoc}
22
	 */
23 8
	public function search($options = [])
24
	{
25
		try {
26 8
			$pdoStatement = $this->getPdo()->prepare($this->getSearchQuery($options));
27 5
			array_walk_recursive($options, function(&$value) use ($pdoStatement) {
28 4
				static $index = 1;
29
30 4
				$pdoStatement->bindParam($index++, $value);
31 5
			});
32
33 5
			$pdoStatement->execute();
34 5
			$result = [];
35
36 5
			while ($fetch = $pdoStatement->fetch()) {
37 3
				$new = new static($this->getPdo());
38
39 3
				$new->setId(intval($fetch['id']));
40 3
				$new->setActiveRecordData($fetch);
41
42 3
				$result[] = $new;
43 3
			}
44
45 5
			return $result;
46 3
		} catch (\PDOException $e) {
47 1
			throw new ActiveRecordException(sprintf('Can not search the record in the `%s` table.', $this->getActiveRecordName()), 0, $e);
48
		}
49
	}
50
51
	/**
52
	 * Returns the search query with the given options.
53
	 *
54
	 * @param array $options = []
55
	 * @return string the search query with the given options.
56
	 */
57 8
	private function getSearchQuery($options = [])
58
	{
59 8
		$columns = array_keys($this->getActiveRecordData());
60 8
		$columns[] = 'id';
61 8
		$values = [];
62
63 8
		foreach ($options as $key => $value) {
64 6
			if (!in_array($key, $columns)) {
65 1
				throw new ActiveRecordException(sprintf('Search option key `%s` does not exists.', $key));
66
			}
67
68 5
			if (is_numeric($value)) {
69 1
				$values[] = '`' . $key . '` = ?';
70 5
			} elseif (is_string($value)) {
71 1
				$values[] = '`' . $key . '` LIKE ?';
72 4
			} elseif (is_null($value)) {
73 1
				$values[] = '`' . $key . '` IS ?';
74 3
			} elseif (is_array($value) && !empty($value)) {
75 1
				$values[] = '`' . $key . '` IN(' . implode(',', array_fill(0, count($value), '?')) . ')';
76 1
			} else {
77 1
				throw new ActiveRecordException(sprintf('Search option value of key `%s` is not supported.', $this->getActiveRecordName()));
78
			}
79 6
		}
80
81 6
		return sprintf('SELECT * FROM `%s` %s', $this->getActiveRecordName(), empty($values) ? '' : 'WHERE ' . implode(' AND ', $values));
82
	}
83
}
84