Completed
Push — master ( df2561...efdf8d )
by Michael
03:00
created

AbstractActiveRecordSearch   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 11
c 3
b 0
f 1
lcom 1
cbo 2
dl 0
loc 62
ccs 0
cts 40
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B search() 0 26 3
C getSearchQuery() 0 23 8
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
	public function search($options = [])
24
	{
25
		$pdoStatement = $this->getPdo()->prepare($this->getSearchQuery($options));
26
		array_walk_recursive($options, function (&$value) use ($pdoStatement) {
27
			static $index = 1;
28
29
			$pdoStatement->bindParam($index++, $value);
30
		});
31
32
		$pdoStatement->execute();
33
		$result = [];
34
35
		while ($row = $pdoStatement->fetch()) {
36
			$new = new static($this->getPdo());
37
			$new->setId(intval($row['id']));
38
			$data = $new->getActiveRecordData();
39
40
			foreach ($data as $key => &$value) {
41
				$value = $row[$key];
42
			}
43
44
			$result[] = $new;
45
		}
46
47
		return $result;
48
	}
49
50
	/**
51
	 * Returns the search query with the given options.
52
	 *
53
	 * @param array $options = []
54
	 * @return string the search query with the given options.
55
	 */
56
	private function getSearchQuery($options = [])
57
	{
58
		$columns = array_keys($this->getActiveRecordData());
59
		$values = [];
60
61
		foreach ($options as $key => $value) {
62
			if (!in_array($key, $columns)) {
63
				throw new ActiveRecordException('Invalid option key.');
64
			}
65
66
			if (is_int($value)) {
67
				$values[] = $key . ' = ?';
68
			} elseif (is_string($value)) {
69
				$values[] = $key . ' LIKE ?';
70
			} elseif(is_array($value) && !empty($value)) {
71
				$values[] = $key . ' IN(' . implode(',', array_fill(0, count($value), '?')) . ')';
72
			} else {
73
				throw new ActiveRecordException('Invalid option value.');
74
			}
75
		}
76
77
		return sprintf('SELECT * FROM %s %s %s', $this->getActiveRecordName(), empty($values) ? '' : 'WHERE', implode(' AND ', $values));
78
	}
79
}
80