Test Failed
Push — master ( bca30b...29fe32 )
by Jean-Christophe
22:16
created

DAO::exists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

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