Passed
Push — master ( c0dc60...96b474 )
by Jean-Christophe
08:33
created

DatabaseOperationsTrait::query()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 2
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Ubiquity\db\traits;
4
5
use Ubiquity\log\Logger;
6
use Ubiquity\cache\database\DbCache;
7
use Ubiquity\exceptions\CacheException;
8
9
/**
10
 * Ubiquity\db\traits$DatabaseOperationsTrait
11
 * This class is part of Ubiquity
12
 *
13
 * @author jcheron <[email protected]>
14
 * @version 1.0.1
15
 * @property \PDO $pdoObject
16
 * @property mixed $cache
17
 * @property array $options
18
 */
19
trait DatabaseOperationsTrait {
20
	private $statements = [ ];
21
22
	abstract public function getDSN();
23
24 2
	public function getPdoObject() {
25 2
		return $this->pdoObject;
26
	}
27
28 99
	public function _connect() {
29 99
		$this->options [\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION;
30 99
		$this->pdoObject = new \PDO ( $this->getDSN (), $this->user, $this->password, $this->options );
31 99
	}
32
33
	/**
34
	 * Executes an SQL statement, returning a result set as a PDOStatement object
35
	 *
36
	 * @param string $sql
37
	 * @return \PDOStatement|boolean
38
	 */
39 7
	public function query($sql) {
40 7
		return $this->pdoObject->query ( $sql );
41
	}
42
43
	/**
44
	 *
45
	 * @param string $tableName
46
	 * @param string $condition
47
	 * @param array|string $fields
48
	 * @param array $parameters
49
	 * @param boolean|null $useCache
50
	 * @return array
51
	 */
52 59
	public function prepareAndExecute($tableName, $condition, $fields, $parameters = null, $useCache = NULL) {
53 59
		$cache = ((DbCache::$active && $useCache !== false) || (! DbCache::$active && $useCache === true));
54 59
		$result = false;
55 59
		if ($cache) {
56 18
			$cKey = $condition;
57 18
			if (is_array ( $parameters )) {
58 15
				$cKey .= implode ( ",", $parameters );
59
			}
60
			try {
61 18
				$result = $this->cache->fetch ( $tableName, $cKey );
62 17
				Logger::info ( "Cache", "fetching cache for table {$tableName} with condition : {$condition}", "Database::prepareAndExecute", $parameters );
63 1
			} catch ( \Exception $e ) {
64
				throw new CacheException ( "Cache is not created in Database constructor" );
65
			}
66
		}
67 59
		if ($result === false) {
68 57
			$result = $this->prepareAndFetchAll ( "SELECT {$fields} FROM `" . $tableName . "`" . $condition, $parameters );
69 57
			if ($cache) {
70 15
				$this->cache->store ( $tableName, $cKey, $result );
71
			}
72
		}
73 59
		return $result;
74
	}
75
76 58
	public function prepareAndFetchAll($sql, $parameters = null) {
77 58
		$statement = $this->getStatement ( $sql );
78 58
		if ($statement->execute ( $parameters )) {
79 58
			Logger::info ( "Database", $sql, "prepareAndFetchAll", $parameters );
80 58
			return $statement->fetchAll ();
81
		}
82
		return false;
83
	}
84
85 1
	public function prepareAndFetchAllColumn($sql, $parameters = null, $column = null) {
86 1
		$statement = $this->getStatement ( $sql );
87 1
		if ($statement->execute ( $parameters )) {
88 1
			Logger::info ( "Database", $sql, "prepareAndFetchAllColumn", $parameters );
89 1
			return $statement->fetchAll ( \PDO::FETCH_COLUMN, $column );
90
		}
91
		return false;
92
	}
93
94 22
	public function prepareAndFetchColumn($sql, $parameters = null, $columnNumber = null) {
95 22
		$statement = $this->getStatement ( $sql );
96 22
		if ($statement->execute ( $parameters )) {
97 22
			Logger::info ( "Database", $sql, "prepareAndFetchColumn", $parameters );
98 22
			return $statement->fetchColumn ( $columnNumber );
99
		}
100
		return false;
101
	}
102
103
	/**
104
	 *
105
	 * @param string $sql
106
	 * @return \PDOStatement
107
	 */
108 68
	private function getStatement($sql) {
109 68
		if (! isset ( $this->statements [$sql] )) {
110 68
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
111 68
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
112
		}
113 68
		return $this->statements [$sql];
114
	}
115
116
	/**
117
	 * Execute an SQL statement and return the number of affected rows (INSERT, UPDATE or DELETE)
118
	 *
119
	 * @param string $sql
120
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
121
	 */
122 2
	public function execute($sql) {
123 2
		return $this->pdoObject->exec ( $sql );
124
	}
125
126
	/**
127
	 * Prepares a statement for execution and returns a statement object
128
	 *
129
	 * @param String $sql
130
	 * @return \PDOStatement|boolean
131
	 */
132 16
	public function prepareStatement($sql) {
133 16
		return $this->pdoObject->prepare ( $sql );
134
	}
135
136
	/**
137
	 * Sets $value to $parameter
138
	 *
139
	 * @param \PDOStatement $statement
140
	 * @param String $parameter
141
	 * @param mixed $value
142
	 * @return boolean
143
	 */
144 1
	public function bindValueFromStatement(\PDOStatement $statement, $parameter, $value) {
145 1
		return $statement->bindValue ( ":" . $parameter, $value );
146
	}
147
148
	/**
149
	 * Returns the last insert id
150
	 *
151
	 * @return string
152
	 */
153 12
	public function lastInserId() {
154 12
		return $this->pdoObject->lastInsertId ();
155
	}
156
157 3
	public function getTablesName() {
158 3
		$sql = 'SHOW TABLES';
159 3
		$query = $this->pdoObject->query ( $sql );
160 3
		return $query->fetchAll ( \PDO::FETCH_COLUMN );
161
	}
162
163
	/**
164
	 * Returns the number of records in $tableName that respects the condition passed as a parameter
165
	 *
166
	 * @param string $tableName
167
	 * @param string $condition Part following the WHERE of an SQL statement
168
	 */
169 1
	public function count($tableName, $condition = '') {
170 1
		if ($condition != '')
171 1
			$condition = " WHERE " . $condition;
172 1
		return $this->query ( "SELECT COUNT(*) FROM " . $tableName . $condition )->fetchColumn ();
173
	}
174
175 4
	public function queryColumn($query, $columnNumber = null) {
176 4
		return $this->query ( $query )->fetchColumn ( $columnNumber );
177
	}
178
179 1
	public function fetchAll($query) {
180 1
		return $this->query ( $query )->fetchAll ();
181
	}
182
183 21
	public function isConnected() {
184 21
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping ());
185
	}
186
187 7
	public function ping() {
188 7
		return ($this->pdoObject && 1 === intval ( $this->pdoObject->query ( 'SELECT 1' )->fetchColumn ( 0 ) ));
189
	}
190
}
191
192