Passed
Push — master ( 0be816...793982 )
by Jean-Christophe
02:53
created

DAO::connect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 8
dl 0
loc 7
ccs 0
cts 7
cp 0
crap 6
rs 10
c 0
b 0
f 0

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\orm\parser\ManyToManyParser;
8
use Ubiquity\db\SqlUtils;
9
use Ubiquity\orm\parser\Reflexion;
10
use Ubiquity\orm\traits\DAOUpdatesTrait;
11
use Ubiquity\orm\traits\DAORelationsTrait;
12
use Ubiquity\orm\parser\ConditionParser;
13
use Ubiquity\orm\traits\DAOUQueries;
14
use Ubiquity\orm\traits\DAOCoreTrait;
15
use Ubiquity\orm\traits\DAORelationsPrepareTrait;
16
use Ubiquity\exceptions\DAOException;
17
use Ubiquity\orm\traits\DAORelationsAssignmentsTrait;
18
19
/**
20
 * Gateway class between database and object model
21
 * This class is part of Ubiquity
22
 *
23
 * @author jcheron <[email protected]>
24
 * @version 1.1.5
25
 *
26
 */
27
class DAO {
28
	use DAOCoreTrait,DAOUpdatesTrait,DAORelationsTrait,DAORelationsPrepareTrait,DAORelationsAssignmentsTrait,DAOUQueries;
29
30
	/**
31
	 *
32
	 * @var Database
33
	 */
34
	public static $db;
35
36
	/**
37
	 * Loads member associated with $instance by a ManyToOne relationship
38
	 *
39
	 * @param object $instance
40
	 * @param string $member
41
	 * @param boolean|array $included
42
	 *        	if true, loads associate members with associations, if array, example : ["client.*","commands"]
43
	 * @param boolean|null $useCache
44
	 */
45
	public static function getManyToOne($instance, $member, $included = false, $useCache = NULL) {
46
		$fieldAnnot = OrmUtils::getMemberJoinColumns ( $instance, $member );
47
		if ($fieldAnnot !== null) {
48
			$annotationArray = $fieldAnnot [1];
49
			$member = $annotationArray ["member"];
50
			$value = Reflexion::getMemberValue ( $instance, $member );
51
			$key = OrmUtils::getFirstKey ( $annotationArray ["className"] );
52
			$kv = array ($key => $value );
53
			$obj = self::getOne ( $annotationArray ["className"], $kv, $included, null, $useCache );
54
			if ($obj !== null) {
55
				Logger::info ( "DAO", "Loading the member " . $member . " for the object " . \get_class ( $instance ), "getManyToOne" );
56
				$accesseur = "set" . ucfirst ( $member );
57
				if (method_exists ( $instance, $accesseur )) {
58
					$instance->$accesseur ( $obj );
59
					$instance->_rest [$member] = $obj->_rest;
60
					return $obj;
61
				}
62
			}
63
		}
64
	}
65
66
	/**
67
	 * Assign / load the child records in the $member member of $instance.
68
	 *
69
	 * @param object $instance
70
	 * @param string $member
71
	 *        	Member on which a oneToMany annotation must be present
72
	 * @param boolean|array $included
73
	 *        	if true, loads associate members with associations, if array, example : ["client.*","commands"]
74
	 * @param boolean $useCache
75
	 * @param array $annot
76
	 *        	used internally
77
	 */
78
	public static function getOneToMany($instance, $member, $included = true, $useCache = NULL, $annot = null) {
79
		$ret = array ();
80
		$class = get_class ( $instance );
81
		if (! isset ( $annot ))
82
			$annot = OrmUtils::getAnnotationInfoMember ( $class, "#oneToMany", $member );
83
		if ($annot !== false) {
84
			$fkAnnot = OrmUtils::getAnnotationInfoMember ( $annot ["className"], "#joinColumn", $annot ["mappedBy"] );
85
			if ($fkAnnot !== false) {
86
				$fkv = OrmUtils::getFirstKeyValue ( $instance );
87
				$ret = self::_getAll ( $annot ["className"], ConditionParser::simple ( $fkAnnot ["name"] . "= ?", $fkv ), $included, $useCache );
88
				if ($modifier = self::getAccessor ( $member, $instance, 'getOneToMany' )) {
89
					self::setToMember ( $member, $instance, $ret, $modifier );
90
				}
91
			}
92
		}
93
		return $ret;
94
	}
95
96
	/**
97
	 * Assigns / loads the child records in the $member member of $instance.
98
	 * If $array is null, the records are loaded from the database
99
	 *
100
	 * @param object $instance
101
	 * @param string $member
102
	 *        	Member on which a ManyToMany annotation must be present
103
	 * @param boolean|array $included
104
	 *        	if true, loads associate members with associations, if array, example : ["client.*","commands"]
105
	 * @param array $array
106
	 *        	optional parameter containing the list of possible child records
107
	 * @param boolean $useCache
108
	 */
109
	public static function getManyToMany($instance, $member, $included = false, $array = null, $useCache = NULL) {
110
		$ret = [ ];
111
		$class = get_class ( $instance );
112
		$parser = new ManyToManyParser ( $instance, $member );
113
		if ($parser->init ()) {
114
			if (is_null ( $array )) {
115
				$accessor = "get" . ucfirst ( $parser->getMyPk () );
116
				$condition = " INNER JOIN `" . $parser->getJoinTable () . "` on `" . $parser->getJoinTable () . "`.`" . $parser->getFkField () . "`=`" . $parser->getTargetEntityTable () . "`.`" . $parser->getPk () . "` WHERE `" . $parser->getJoinTable () . "`.`" . $parser->getMyFkField () . "`= ?";
117
				$ret = self::_getAll ( $parser->getTargetEntityClass (), ConditionParser::simple ( $condition, $instance->$accessor () ), $included, $useCache );
118
			} else {
119
				$ret = self::getManyToManyFromArray ( $instance, $array, $class, $parser );
120
			}
121
			if ($modifier = self::getAccessor ( $member, $instance, 'getManyToMany' )) {
122
				self::setToMember ( $member, $instance, $ret, $modifier );
123
			}
124
		}
125
		return $ret;
126
	}
127
128
	/**
129
	 *
130
	 * @param object $instance
131
	 * @param array $array
132
	 * @param boolean $useCache
133
	 */
134
	public static function affectsManyToManys($instance, $array = NULL, $useCache = NULL) {
135
		$metaDatas = OrmUtils::getModelMetadata ( \get_class ( $instance ) );
136
		$manyToManyFields = $metaDatas ["#manyToMany"];
137
		if (\sizeof ( $manyToManyFields ) > 0) {
138
			foreach ( $manyToManyFields as $member ) {
139
				self::getManyToMany ( $instance, $member, false, $array, $useCache );
140
			}
141
		}
142
	}
143
144
	/**
145
	 * Returns an array of $className objects from the database
146
	 *
147
	 * @param string $className
148
	 *        	class name of the model to load
149
	 * @param string $condition
150
	 *        	Part following the WHERE of an SQL statement
151
	 * @param boolean|array $included
152
	 *        	if true, loads associate members with associations, if array, example : ["client.*","commands"]
153
	 * @param array|null $parameters
154
	 * @param boolean $useCache
155
	 *        	use the active cache if true
156
	 * @return array
157
	 */
158
	public static function getAll($className, $condition = '', $included = true, $parameters = null, $useCache = NULL) {
159
		return self::_getAll ( $className, new ConditionParser ( $condition, null, $parameters ), $included, $useCache );
160
	}
161
162
	public static function paginate($className, $page = 1, $rowsPerPage = 20, $condition = null, $included = true) {
163
		if (! isset ( $condition )) {
164
			$condition = "1=1";
165
		}
166
		return self::getAll ( $className, $condition . " LIMIT " . $rowsPerPage . " OFFSET " . (($page - 1) * $rowsPerPage), $included );
167
	}
168
169
	public static function getRownum($className, $ids) {
170
		$tableName = OrmUtils::getTableName ( $className );
171
		self::parseKey ( $ids, $className );
172
		$condition = SqlUtils::getCondition ( $ids, $className );
173
		$keyFields = OrmUtils::getKeyFields ( $className );
174
		if (is_array ( $keyFields )) {
175
			$keys = implode ( ",", $keyFields );
176
		} else {
177
			$keys = "1";
178
		}
179
		return self::$db->queryColumn ( "SELECT num FROM (SELECT *, @rownum:=@rownum + 1 AS num FROM `{$tableName}`, (SELECT @rownum:=0) r ORDER BY {$keys}) d WHERE " . $condition );
180
	}
181
182
	/**
183
	 * Returns the number of objects of $className from the database respecting the condition possibly passed as parameter
184
	 *
185
	 * @param string $className
186
	 *        	complete classname of the model to load
187
	 * @param string $condition
188
	 *        	Part following the WHERE of an SQL statement
189
	 * @param array|null $parameters
190
	 *        	The query parameters
191
	 * @return int|false count of objects
192
	 */
193
	public static function count($className, $condition = '', $parameters = null) {
194
		$tableName = OrmUtils::getTableName ( $className );
195
		if ($condition != '')
196
			$condition = " WHERE " . $condition;
197
		return self::$db->prepareAndFetchColumn ( "SELECT COUNT(*) FROM `" . $tableName . "`" . $condition, $parameters );
198
	}
199
200
	/**
201
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key
202
	 *
203
	 * @param String $className
204
	 *        	complete classname of the model to load
205
	 * @param Array|string $keyValues
206
	 *        	primary key values or condition
207
	 * @param boolean|array $included
208
	 *        	if true, charges associate members with association
209
	 * @param array|null $parameters
210
	 *        	the request parameters
211
	 * @param boolean|null $useCache
212
	 *        	use cache if true
213
	 * @return object the instance loaded or null if not found
214
	 */
215
	public static function getOne($className, $keyValues, $included = true, $parameters = null, $useCache = NULL) {
216
		$conditionParser = new ConditionParser ();
217
		if (! isset ( $parameters )) {
218
			$conditionParser->addKeyValues ( $keyValues, $className );
219
		} elseif (! is_array ( $keyValues )) {
220
			$conditionParser->setCondition ( $keyValues );
221
			$conditionParser->setParams ( $parameters );
222
		} else {
223
			throw new DAOException ( "The \$keyValues parameter should not be an array if \$parameters is not null" );
224
		}
225
		return self::_getOne ( $className, $conditionParser, $included, $useCache );
226
	}
227
228
	/**
229
	 * Establishes the connection to the database using the past parameters
230
	 *
231
	 * @param string $dbType
232
	 * @param string $dbName
233
	 * @param string $serverName
234
	 * @param string $port
235
	 * @param string $user
236
	 * @param string $password
237
	 * @param array $options
238
	 * @param boolean $cache
239
	 */
240
	public static function connect($dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [], $cache = false) {
241
		self::$db = new Database ( $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache );
242
		try {
243
			self::$db->connect ();
244
		} catch ( \Exception $e ) {
245
			Logger::error ( "DAO", $e->getMessage () );
246
			throw new DAOException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
247
		}
248
	}
249
250
	/**
251
	 * Establishes the connection to the database using the $config array
252
	 *
253
	 * @param array $config
254
	 *        	the config array (Startup::getConfig())
255
	 */
256
	public static function startDatabase(&$config) {
257
		$db = $config ['database'] ?? [ ];
258
		if ($db ['dbName'] !== '') {
259
			self::connect ( $db ['type'], $db ['dbName'], $db ['serverName'] ?? '127.0.0.1', $db ['port'] ?? 3306, $db ['user'] ?? 'root', $db ['password'] ?? '', $db ['options'] ?? [ ], $db ['cache'] ?? false);
260
		}
261
	}
262
263
	/**
264
	 * Returns true if the connection to the database is established
265
	 *
266
	 * @return boolean
267
	 */
268
	public static function isConnected() {
269
		return self::$db !== null && (self::$db instanceof Database) && self::$db->isConnected ();
270
	}
271
}
272