Passed
Push — master ( bb544e...dd4df6 )
by Jean-Christophe
09:39
created

DAO::connect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 6
c 2
b 0
f 0
dl 0
loc 7
ccs 3
cts 6
cp 0.5
rs 10
cc 2
nc 2
nop 10
crap 2.5

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 76
	public static function getDb($model) {
52 76
		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 24
	public static function getAll($className, $condition = '', $included = true, $parameters = null, $useCache = NULL) {
66 24
		$db = self::getDb ( $className );
67 24
		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
	public static function exists($className, $condition = '', $parameters = null) {
116
		$tableName = OrmUtils::getTableName ( $className );
117
		if ($condition != '') {
118
			$condition = ' WHERE ' . $condition;
119
		}
120
		$db = self::getDb ( $className );
121
		$quote = $db->quote;
122
		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 17
	public static function getOne($className, $condition, $included = true, $parameters = null, $useCache = NULL) {
136 17
		$db = self::getDb ( $className );
137 17
		$conditionParser = new ConditionParser ();
138 17
		if (! isset ( $parameters )) {
139 17
			$conditionParser->addKeyValues ( $condition, $className );
140
		} elseif (! is_array ( $condition )) {
141
			$conditionParser->setCondition ( $condition );
142
			$conditionParser->setParams ( $parameters );
143
		} else {
144
			throw new DAOException ( "The \$condition parameter should not be an array if \$parameters is not null" );
145
		}
146 17
		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 26
	public static function getById($className, $keyValues, $included = true, $useCache = NULL) {
160 26
		return static::_getOne ( self::getDatabase ( self::$modelsDatabase [$className] ?? 'default'), $className, self::getConditionParser ( $className, $keyValues ), $included, $useCache );
161
	}
162
163 26
	protected static function getConditionParser($className, $keyValues): ConditionParser {
164 26
		if (! isset ( self::$conditionParsers [$className] )) {
165 14
			$conditionParser = new ConditionParser ();
166 14
			$conditionParser->addKeyValues ( $keyValues, $className );
167 14
			self::$conditionParsers [$className] = $conditionParser;
168
		} else {
169 14
			self::$conditionParsers [$className]->setKeyValues ( $keyValues );
170
		}
171 26
		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 76
	public static function connect($offset, $wrapper, $dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [ ], $cache = false) {
189 76
		self::$db [$offset] = new Database ( $wrapper, $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache, self::$pool );
190
		try {
191 76
			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 76
	}
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 20
	public static function startDatabase(&$config, $offset = null) {
204 20
		$db = $offset ? ($config ['database'] [$offset] ?? ($config ['database'] ?? [ ])) : ($config ['database'] ['default'] ?? $config ['database']);
205 20
		if ($db ['dbName'] !== '') {
206 20
			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 20
	}
209
210 122
	public static function getDbOffset(&$config, $offset = null) {
211 122
		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 30
	public static function closeDb($offset = 'default') {
237 30
		$db = self::$db [$offset] ?? false;
238 30
		if ($db !== false) {
239 30
			$db->close ();
240
		}
241 30
	}
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 1
	public static function setModelDatabase($model, $database = 'default') {
250 1
		self::$modelsDatabase [$model] = $database;
251 1
	}
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 78
	public static function getDatabase($offset = 'default') {
269 78
		if (! isset ( self::$db [$offset] )) {
270 18
			self::startDatabase ( Startup::$config, $offset );
271
		}
272 78
		SqlUtils::$quote = self::$db [$offset]->quote;
273 78
		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
	public static function warmupCache($className, $condition = '', $included = false, $parameters = [ ]) {
318
		$objects = self::getAll ( $className, $condition, $included, $parameters );
319
		foreach ( $objects as $o ) {
320
			self::$cache->store ( $className, OrmUtils::getKeyValues ( $o ), $o );
321
		}
322
		self::$cache->optimize ();
323
		$offset = self::$modelsDatabase [$className] ?? 'default';
324
		$db = self::$db [$offset];
325
		$db->close ();
326
		unset ( self::$db [$offset] );
327
	}
328
329
	public static function setCache(AbstractDAOCache $cache) {
330
		self::$cache = $cache;
331
	}
332
333
	/**
334
	 *
335
	 * @return \Ubiquity\cache\dao\AbstractDAOCache
336
	 */
337 28
	public static function getCache() {
338 28
		return static::$cache;
339
	}
340
}
341