Passed
Push — master ( 6bed03...9b7ff5 )
by Jean-Christophe
24:45
created

DAO::getManyToMany()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.0073

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 15
c 1
b 1
f 0
dl 0
loc 19
ccs 14
cts 15
cp 0.9333
rs 9.4555
cc 5
nc 5
nop 5
crap 5.0073

1 Method

Rating   Name   Duplication   Size   Complexity  
A DAO::getById() 0 2 1
1
<?php
2
3
namespace Ubiquity\orm;
4
5
use Ubiquity\db\Database;
6
use Ubiquity\log\Logger;
7
use Ubiquity\orm\parser\ManyToManyParser;
8
use Ubiquity\db\SqlUtils;
9
use Ubiquity\orm\traits\DAOUpdatesTrait;
10
use Ubiquity\orm\traits\DAORelationsTrait;
11
use Ubiquity\orm\parser\ConditionParser;
12
use Ubiquity\orm\traits\DAOUQueries;
13
use Ubiquity\orm\traits\DAOCoreTrait;
14
use Ubiquity\orm\traits\DAORelationsPrepareTrait;
15
use Ubiquity\exceptions\DAOException;
16
use Ubiquity\orm\traits\DAORelationsAssignmentsTrait;
17
use Ubiquity\orm\parser\Reflexion;
18
use Ubiquity\orm\traits\DAOTransactionsTrait;
19
use Ubiquity\controllers\Startup;
20
use Ubiquity\cache\CacheManager;
21
use Ubiquity\orm\traits\DAOPooling;
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.1
29
 *
30
 */
31
class DAO {
32
	use DAOCoreTrait,DAOUpdatesTrait,DAORelationsTrait,DAORelationsPrepareTrait,DAORelationsAssignmentsTrait,
33
	DAOUQueries,DAOTransactionsTrait,DAOPooling;
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 69
	protected static function getDb($model) {
46 69
		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
		return self::_getAll ( self::getDb ( $className ), $className, new ConditionParser ( $condition, null, $parameters ), $included, $useCache );
61
	}
62
63 3
	public static function paginate($className, $page = 1, $rowsPerPage = 20, $condition = null, $included = true) {
64 3
		if (! isset ( $condition )) {
65 1
			$condition = "1=1";
66
		}
67 3
		return self::getAll ( $className, $condition . " LIMIT " . $rowsPerPage . " OFFSET " . (($page - 1) * $rowsPerPage), $included );
68
	}
69
70 3
	public static function getRownum($className, $ids) {
71 3
		$tableName = OrmUtils::getTableName ( $className );
72 3
		$db = self::getDb ( $className );
73 3
		$quote = $db->quote;
74 3
		self::parseKey ( $ids, $className, $quote );
75 3
		$condition = SqlUtils::getCondition ( $ids, $className );
76 3
		$keyFields = OrmUtils::getKeyFields ( $className );
77 3
		if (is_array ( $keyFields )) {
78 3
			$keys = implode ( ",", $keyFields );
79
		} else {
80
			$keys = "1";
81
		}
82
83 3
		return $db->queryColumn ( "SELECT num FROM (SELECT *, @rownum:=@rownum + 1 AS num FROM {$quote}{$tableName}{$quote}, (SELECT @rownum:=0) r ORDER BY {$keys}) d WHERE " . $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
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key or with a condition
106
	 *
107
	 * @param String $className complete classname of the model to load
108
	 * @param Array|string $condition condition or primary key values
109
	 * @param boolean|array $included if true, charges associate members with association
110
	 * @param array|null $parameters the request parameters
111
	 * @param boolean|null $useCache use cache if true
112
	 * @return object the instance loaded or null if not found
113
	 */
114 16
	public static function getOne($className, $condition, $included = true, $parameters = null, $useCache = NULL) {
115 16
		$conditionParser = new ConditionParser ();
116 16
		if (! isset ( $parameters )) {
117 16
			$conditionParser->addKeyValues ( $condition, $className );
118
		} elseif (! is_array ( $condition )) {
119
			$conditionParser->setCondition ( $condition );
120
			$conditionParser->setParams ( $parameters );
121
		} else {
122
			throw new DAOException ( "The \$keyValues parameter should not be an array if \$parameters is not null" );
123
		}
124 16
		return self::_getOne ( self::getDb ( $className ), $className, $conditionParser, $included, $useCache );
125
	}
126
127
	/**
128
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key
129
	 *
130
	 * @param String $className complete classname of the model to load
131
	 * @param Array|string $keyValues primary key values or condition
132
	 * @param boolean|array $included if true, charges associate members with association
133
	 * @param array|null $parameters the request parameters
134
	 * @param boolean|null $useCache use cache if true
135
	 * @return object the instance loaded or null if not found
136
	 */
137 24
	public static function getById($className, $keyValues, $included = true, $useCache = NULL) {
138 24
		return self::_getOne ( self::getDb ( $className ), $className, self::getConditionParser ( $className, $keyValues ), $included, $useCache );
139
	}
140
141 24
	protected static function getConditionParser($className, $keyValues) {
142 24
		if (! isset ( self::$conditionParsers [$className] )) {
143 13
			$conditionParser = new ConditionParser ();
144 13
			$conditionParser->addKeyValues ( $keyValues, $className );
145 13
			self::$conditionParsers [$className] = $conditionParser;
146
		} else {
147 13
			self::$conditionParsers [$className]->setKeyValues ( $keyValues );
148
		}
149 24
		return self::$conditionParsers [$className];
150
	}
151
152
	/**
153
	 * Establishes the connection to the database using the past parameters
154
	 *
155
	 * @param string $offset
156
	 * @param string $wrapper
157
	 * @param string $dbType
158
	 * @param string $dbName
159
	 * @param string $serverName
160
	 * @param string $port
161
	 * @param string $user
162
	 * @param string $password
163
	 * @param array $options
164
	 * @param boolean $cache
165
	 */
166 73
	public static function connect($offset, $wrapper, $dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [], $cache = false) {
167 73
		self::$db [$offset] = new Database ( $wrapper, $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache, self::$pool );
168
		try {
169 73
			self::$db [$offset]->connect ();
170
		} catch ( \Exception $e ) {
171
			Logger::error ( "DAO", $e->getMessage () );
172
			throw new DAOException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
173
		}
174 73
	}
175
176
	/**
177
	 * Establishes the connection to the database using the $config array
178
	 *
179
	 * @param array $config the config array (Startup::getConfig())
180
	 */
181 20
	public static function startDatabase(&$config, $offset = null) {
182 20
		$db = $offset ? ($config ['database'] [$offset] ?? ($config ['database'] ?? [ ])) : ($config ['database'] ['default'] ?? $config ['database']);
183 20
		if ($db ['dbName'] !== '') {
184 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);
185
		}
186 20
	}
187
188 119
	public static function getDbOffset(&$config, $offset = null) {
189 119
		return $offset ? ($config ['database'] [$offset] ?? ($config ['database'] ?? [ ])) : ($config ['database'] ['default'] ?? $config ['database']);
190
	}
191
192
	/**
193
	 * Returns true if the connection to the database is established
194
	 *
195
	 * @return boolean
196
	 */
197 5
	public static function isConnected($offset = 'default') {
198 5
		$db = self::$db [$offset] ?? false;
199 5
		return $db && ($db instanceof Database) && $db->isConnected ();
200
	}
201
202
	/**
203
	 * Sets the transformer operation
204
	 *
205
	 * @param string $op
206
	 */
207
	public static function setTransformerOp($op) {
208
		self::$transformerOp = $op;
209
	}
210
211
	/**
212
	 * Closes the active pdo connection to the database
213
	 */
214 27
	public static function closeDb($offset = 'default') {
215 27
		$db = self::$db [$offset] ?? false;
216 27
		if ($db !== false) {
217 27
			$db->close ();
218
		}
219 27
	}
220
221
	/**
222
	 * Defines the database connection to use for $model class
223
	 *
224
	 * @param string $model a model class
225
	 * @param string $database a database connection defined in config.php
226
	 */
227
	public static function setModelDatabase($model, $database = 'default') {
228
		self::$modelsDatabase [$model] = $database;
229
	}
230
231
	/**
232
	 * Defines the database connections to use for models classes
233
	 *
234
	 * @param array $modelsDatabase
235
	 */
236
	public static function setModelsDatabases($modelsDatabase) {
237
		self::$modelsDatabase = $modelsDatabase;
238
	}
239
240
	/**
241
	 * Returns the database instance defined at $offset key in config
242
	 *
243
	 * @param string $offset
244
	 * @return \Ubiquity\db\Database
245
	 */
246 70
	public static function getDatabase($offset = 'default') {
247 70
		if (! isset ( self::$db [$offset] )) {
248 18
			self::startDatabase ( Startup::$config, $offset );
249
		}
250 70
		SqlUtils::$quote = self::$db [$offset]->quote;
251 70
		return self::$db [$offset];
252
	}
253
254 5
	public static function getDatabases() {
255 5
		$config = Startup::getConfig ();
256 5
		if (isset ( $config ['database'] )) {
257 5
			if (isset ( $config ['database'] ['dbName'] )) {
258
				return [ 'default' ];
259
			} else {
260 5
				return \array_keys ( $config ['database'] );
261
			}
262
		}
263
		return [ ];
264
	}
265
266
	public static function updateDatabaseParams(array &$config, array $parameters, $offset = 'default') {
267
		if ($offset === 'default') {
268
			if (isset ( $config ['database'] [$offset] )) {
269
				foreach ( $parameters as $k => $param ) {
270
					$config ['database'] [$offset] [$k] = $param;
271
				}
272
			} else {
273
				foreach ( $parameters as $k => $param ) {
274
					$config ['database'] [$k] = $param;
275
				}
276
			}
277
		} else {
278
			if (isset ( $config ['database'] [$offset] )) {
279
				foreach ( $parameters as $k => $param ) {
280
					$config ['database'] [$offset] [$k] = $param;
281
				}
282
			}
283
		}
284
	}
285
286 38
	public static function start() {
287 38
		self::$modelsDatabase = CacheManager::getModelsDatabases ();
288 38
	}
289
}
290