Passed
Push — master ( 882bf7...838b77 )
by Jean-Christophe
10:10 queued 10s
created

DAO::getCache()   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 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 2
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Ubiquity\orm;
4
5
use Ubiquity\db\Database;
6
use Ubiquity\log\Logger;
7
use Ubiquity\db\SqlUtils;
8
use Ubiquity\orm\traits\DAOUpdatesTrait;
9
use Ubiquity\orm\traits\DAORelationsTrait;
10
use Ubiquity\orm\parser\ConditionParser;
11
use Ubiquity\orm\traits\DAOUQueries;
12
use Ubiquity\orm\traits\DAOCoreTrait;
13
use Ubiquity\orm\traits\DAORelationsPrepareTrait;
14
use Ubiquity\exceptions\DAOException;
15
use Ubiquity\orm\traits\DAORelationsAssignmentsTrait;
16
use Ubiquity\orm\traits\DAOTransactionsTrait;
17
use Ubiquity\controllers\Startup;
18
use Ubiquity\cache\CacheManager;
19
use Ubiquity\orm\traits\DAOPooling;
20
use Ubiquity\orm\traits\DAOBulkUpdatesTrait;
21
use Ubiquity\orm\traits\DAOPreparedTrait;
22
use Ubiquity\cache\dao\AbstractDAOCache;
23
24
/**
25
 * Gateway class between database and object model.
26
 * This class is part of Ubiquity
27
 *
28
 * @author jcheron <[email protected]>
29
 * @version 1.2.5
30
 *
31
 */
32
class DAO {
33
	use DAOCoreTrait,DAOUpdatesTrait,DAORelationsTrait,DAORelationsPrepareTrait,DAORelationsAssignmentsTrait,
34
	DAOUQueries,DAOTransactionsTrait,DAOPooling,DAOBulkUpdatesTrait,DAOPreparedTrait;
35
36
	/**
37
	 *
38
	 * @var Database
39
	 */
40
	public static $db;
41
	public static $useTransformers = false;
42
	public static $transformerOp = 'transform';
43
	private static $conditionParsers = [ ];
44
	protected static $modelsDatabase = [ ];
45
	/**
46
	 *
47
	 * @var AbstractDAOCache
48
	 */
49
	protected static $cache;
50
51 87
	public static function getDb($model) {
52 87
		return self::getDatabase ( self::$modelsDatabase [$model] ?? 'default');
53
	}
54
55
	/**
56
	 * Returns an array of $className objects from the database
57
	 *
58
	 * @param string $className class name of the model to load
59
	 * @param string $condition Part following the WHERE of an SQL statement
60
	 * @param boolean|array $included if true, loads associate members with associations, if array, example : ['client.*','commands']
61
	 * @param array|null $parameters
62
	 * @param boolean $useCache use the active cache if true
63
	 * @return array
64
	 */
65 33
	public static function getAll($className, $condition = '', $included = true, $parameters = null, $useCache = NULL) {
66 33
		$db = self::getDb ( $className );
67 33
		return static::_getAll ( $db, $className, new ConditionParser ( $condition, null, $parameters ), $included, $useCache );
68
	}
69
70 3
	public static function paginate($className, $page = 1, $rowsPerPage = 20, $condition = null, $included = true) {
71 3
		return self::getAll ( $className, ($condition ?? '1=1') . ' LIMIT ' . $rowsPerPage . ' OFFSET ' . (($page - 1) * $rowsPerPage), $included );
72
	}
73
74 3
	public static function getRownum($className, $ids) {
75 3
		$tableName = OrmUtils::getTableName ( $className );
76 3
		$db = self::getDb ( $className );
77 3
		$quote = $db->quote;
78 3
		self::parseKey ( $ids, $className, $quote );
79 3
		$condition = SqlUtils::getCondition ( $ids, $className );
80 3
		$keyFields = OrmUtils::getKeyFields ( $className );
81 3
		if (\is_array ( $keyFields )) {
82 3
			$keys = \implode ( ',', $keyFields );
83
		} else {
84
			$keys = '1';
85
		}
86 3
		return $db->getRowNum ( $tableName, $keys, $condition );
87
	}
88
89
	/**
90
	 * Returns the number of objects of $className from the database respecting the condition possibly passed as parameter
91
	 *
92
	 * @param string $className complete classname of the model to load
93
	 * @param string $condition Part following the WHERE of an SQL statement
94
	 * @param array|null $parameters The query parameters
95
	 * @return int|false count of objects
96
	 */
97 20
	public static function count($className, $condition = '', $parameters = null) {
98 20
		$tableName = OrmUtils::getTableName ( $className );
99 20
		if ($condition != '') {
100 9
			$condition = ' WHERE ' . $condition;
101
		}
102 20
		$db = self::getDb ( $className );
103 20
		$quote = $db->quote;
104 20
		return $db->prepareAndFetchColumn ( 'SELECT COUNT(*) FROM ' . $quote . $tableName . $quote . $condition, $parameters );
105
	}
106
107
	/**
108
	 * Tests the existence of objects of $className from the database respecting the condition possibly passed as parameter
109
	 *
110
	 * @param string $className complete classname of the model to load
111
	 * @param string $condition Part following the WHERE of an SQL statement
112
	 * @param array|null $parameters The query parameters
113
	 * @return boolean
114
	 */
115 1
	public static function exists($className, $condition = '', $parameters = null) {
116 1
		$tableName = OrmUtils::getTableName ( $className );
117 1
		if ($condition != '') {
118 1
			$condition = ' WHERE ' . $condition;
119
		}
120 1
		$db = self::getDb ( $className );
121 1
		$quote = $db->quote;
122 1
		return (1 == $db->prepareAndFetchColumn ( "SELECT EXISTS(SELECT 1 FROM {$quote}{$tableName}{$quote}{$condition})", $parameters ));
123
	}
124
125
	/**
126
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key or with a condition
127
	 *
128
	 * @param String $className complete classname of the model to load
129
	 * @param Array|string $condition condition or primary key values
130
	 * @param boolean|array $included if true, charges associate members with association
131
	 * @param array|null $parameters the request parameters
132
	 * @param boolean|null $useCache use cache if true
133
	 * @return object the instance loaded or null if not found
134
	 */
135 18
	public static function getOne($className, $condition, $included = true, $parameters = null, $useCache = NULL) {
136 18
		$db = self::getDb ( $className );
137 18
		$conditionParser = new ConditionParser ();
138 18
		if (! isset ( $parameters )) {
139 18
			$conditionParser->addKeyValues ( $condition, $className );
140 1
		} elseif (! is_array ( $condition )) {
141 1
			$conditionParser->setCondition ( $condition );
142 1
			$conditionParser->setParams ( $parameters );
143
		} else {
144
			throw new DAOException ( "The \$condition parameter should not be an array if \$parameters is not null" );
145
		}
146 18
		return static::_getOne ( $db, $className, $conditionParser, $included, $useCache );
147
	}
148
149
	/**
150
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key
151
	 *
152
	 * @param String $className complete classname of the model to load
153
	 * @param Array|string $keyValues primary key values or condition
154
	 * @param boolean|array $included if true, charges associate members with association
155
	 * @param array|null $parameters the request parameters
156
	 * @param boolean|null $useCache use cache if true
157
	 * @return object the instance loaded or null if not found
158
	 */
159 28
	public static function getById($className, $keyValues, $included = true, $useCache = NULL) {
160 28
		return static::_getOne ( self::getDatabase ( self::$modelsDatabase [$className] ?? 'default'), $className, self::getConditionParser ( $className, $keyValues ), $included, $useCache );
161
	}
162
163 28
	protected static function getConditionParser($className, $keyValues): ConditionParser {
164 28
		if (! isset ( self::$conditionParsers [$className] )) {
165 15
			$conditionParser = new ConditionParser ();
166 15
			$conditionParser->addKeyValues ( $keyValues, $className );
167 15
			self::$conditionParsers [$className] = $conditionParser;
168
		} else {
169 16
			self::$conditionParsers [$className]->setKeyValues ( $keyValues );
170
		}
171 28
		return self::$conditionParsers [$className];
172
	}
173
174
	/**
175
	 * Establishes the connection to the database using the past parameters
176
	 *
177
	 * @param string $offset
178
	 * @param string $wrapper
179
	 * @param string $dbType
180
	 * @param string $dbName
181
	 * @param string $serverName
182
	 * @param string $port
183
	 * @param string $user
184
	 * @param string $password
185
	 * @param array $options
186
	 * @param boolean $cache
187
	 */
188 87
	public static function connect($offset, $wrapper, $dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [ ], $cache = false) {
189 87
		self::$db [$offset] = new Database ( $wrapper, $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache, self::$pool );
190
		try {
191 87
			self::$db [$offset]->connect ();
192
		} catch ( \Exception $e ) {
193
			Logger::error ( "DAO", $e->getMessage () );
194
			throw new DAOException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
195
		}
196 87
	}
197
198
	/**
199
	 * Establishes the connection to the database using the $config array
200
	 *
201
	 * @param array $config the config array (Startup::getConfig())
202
	 */
203 22
	public static function startDatabase(&$config, $offset = null) {
204 22
		$db = $offset ? ($config ['database'] [$offset] ?? ($config ['database'] ?? [ ])) : ($config ['database'] ['default'] ?? $config ['database']);
205 22
		if ($db ['dbName'] !== '') {
206 22
			self::connect ( $offset ?? 'default', $db ['wrapper'] ?? \Ubiquity\db\providers\pdo\PDOWrapper::class, $db ['type'], $db ['dbName'], $db ['serverName'] ?? '127.0.0.1', $db ['port'] ?? 3306, $db ['user'] ?? 'root', $db ['password'] ?? '', $db ['options'] ?? [ ], $db ['cache'] ?? false);
207
		}
208 22
	}
209
210 133
	public static function getDbOffset(&$config, $offset = null) {
211 133
		return $offset ? ($config ['database'] [$offset] ?? ($config ['database'] ?? [ ])) : ($config ['database'] ['default'] ?? $config ['database']);
212
	}
213
214
	/**
215
	 * Returns true if the connection to the database is established
216
	 *
217
	 * @return boolean
218
	 */
219 5
	public static function isConnected($offset = 'default') {
220 5
		$db = self::$db [$offset] ?? false;
221 5
		return $db && ($db instanceof Database) && $db->isConnected ();
222
	}
223
224
	/**
225
	 * Sets the transformer operation
226
	 *
227
	 * @param string $op
228
	 */
229
	public static function setTransformerOp($op) {
230
		self::$transformerOp = $op;
231
	}
232
233
	/**
234
	 * Closes the active pdo connection to the database
235
	 */
236 41
	public static function closeDb($offset = 'default') {
237 41
		$db = self::$db [$offset] ?? false;
238 41
		if ($db !== false) {
239 40
			$db->close ();
240
		}
241 41
	}
242
243
	/**
244
	 * Defines the database connection to use for $model class
245
	 *
246
	 * @param string $model a model class
247
	 * @param string $database a database connection defined in config.php
248
	 */
249 9
	public static function setModelDatabase($model, $database = 'default') {
250 9
		self::$modelsDatabase [$model] = $database;
251 9
	}
252
253
	/**
254
	 * Defines the database connections to use for models classes
255
	 *
256
	 * @param array $modelsDatabase
257
	 */
258
	public static function setModelsDatabases($modelsDatabase) {
259
		self::$modelsDatabase = $modelsDatabase;
260
	}
261
262
	/**
263
	 * Returns the database instance defined at $offset key in config
264
	 *
265
	 * @param string $offset
266
	 * @return \Ubiquity\db\Database
267
	 */
268 89
	public static function getDatabase($offset = 'default') {
269 89
		if (! isset ( self::$db [$offset] )) {
270 20
			self::startDatabase ( Startup::$config, $offset );
271
		}
272 89
		SqlUtils::$quote = self::$db [$offset]->quote;
273 89
		return self::$db [$offset];
274
	}
275
276 5
	public static function getDatabases() {
277 5
		$config = Startup::getConfig ();
278 5
		if (isset ( $config ['database'] )) {
279 5
			if (isset ( $config ['database'] ['dbName'] )) {
280
				return [ 'default' ];
281
			} else {
282 5
				return \array_keys ( $config ['database'] );
283
			}
284
		}
285
		return [ ];
286
	}
287
288
	public static function updateDatabaseParams(array &$config, array $parameters, $offset = 'default') {
289
		if ($offset === 'default') {
290
			if (isset ( $config ['database'] [$offset] )) {
291
				foreach ( $parameters as $k => $param ) {
292
					$config ['database'] [$offset] [$k] = $param;
293
				}
294
			} else {
295
				foreach ( $parameters as $k => $param ) {
296
					$config ['database'] [$k] = $param;
297
				}
298
			}
299
		} else {
300
			if (isset ( $config ['database'] [$offset] )) {
301
				foreach ( $parameters as $k => $param ) {
302
					$config ['database'] [$offset] [$k] = $param;
303
				}
304
			}
305
		}
306
	}
307
308 37
	public static function start() {
309 37
		self::$modelsDatabase = CacheManager::getModelsDatabases ();
310 37
	}
311
312
	public static function getDbCacheInstance($model) {
313
		$db = static::$db [self::$modelsDatabase [$model] ?? 'default'];
314
		return $db->getCacheInstance ();
315
	}
316
317 2
	public static function warmupCache($className, $condition = '', $included = false, $parameters = [ ]) {
318 2
		$objects = self::getAll ( $className, $condition, $included, $parameters );
319 2
		foreach ( $objects as $o ) {
320 2
			self::$cache->store ( $className, OrmUtils::getKeyValues ( $o ), $o );
321
		}
322 2
		self::$cache->optimize ();
323 2
		$offset = self::$modelsDatabase [$className] ?? 'default';
324 2
		$db = self::$db [$offset];
325 2
		$db->close ();
326 2
		unset ( self::$db [$offset] );
327 2
	}
328
329 2
	public static function setCache(AbstractDAOCache $cache) {
330 2
		self::$cache = $cache;
331 2
	}
332
333
	/**
334
	 *
335
	 * @return \Ubiquity\cache\dao\AbstractDAOCache
336
	 */
337 31
	public static function getCache() {
338 31
		return static::$cache;
339
	}
340
}
341