Passed
Push — master ( 3b5a7c...0f24e7 )
by Jean-Christophe
05:29
created

DatabaseOperationsTrait::prepareAndFetchAll()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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