Completed
Push — master ( efdf8d...2fd22e )
by Michael
02:24
created

AbstractActiveRecordSearch   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 11
c 4
b 0
f 1
lcom 1
cbo 2
dl 0
loc 64
ccs 34
cts 34
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B search() 0 27 3
C getSearchQuery() 0 24 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 7
	public function search($options = [])
24
	{
25
		try {
26 7
			$pdoStatement = $this->getPdo()->prepare($this->getSearchQuery($options));
27 4
			array_walk_recursive($options, function (&$value) use ($pdoStatement) {
28 3
				static $index = 1;
29
30 3
				$pdoStatement->bindParam($index++, $value);
31 4
			});
32
33 4
			$pdoStatement->execute();
34 4
			$result = [];
35
36 4
			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 4
			return $result;
46 3
		} catch (\PDOException $e) {
47 1
			throw new ActiveRecordException('Can\'t search the record.', 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 7
	private function getSearchQuery($options = [])
58
	{
59 7
		$columns = array_keys($this->getActiveRecordData());
60 7
		$columns[] = 'id';
61 7
		$values = [];
62
63 7
		foreach ($options as $key => $value) {
64 5
			if (!in_array($key, $columns)) {
65 1
				throw new ActiveRecordException(sprintf('Option key "%s" doesn\'t exists.', $key));
66
			}
67
68 4
			if (is_numeric($value)) {
69 1
				$values[] = $key . ' = ?';
70 4
			} elseif (is_string($value)) {
71 1
				$values[] = $key . ' LIKE ?';
72 3
			} elseif(is_array($value) && !empty($value)) {
73 1
				$values[] = $key . ' IN(' . implode(',', array_fill(0, count($value), '?')) . ')';
74 1
			} else {
75 1
				throw new ActiveRecordException('Option value not supported.');
76
			}
77 5
		}
78
79 5
		return sprintf('SELECT * FROM %s %s %s', $this->getActiveRecordName(), empty($values) ? '' : 'WHERE', implode(' AND ', $values));
80
	}
81
}
82