Passed
Push — master ( ed813f...432706 )
by Jean-Christophe
02:43
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 0
Metric Value
cc 2
eloc 6
nc 2
nop 8
dl 0
loc 7
ccs 3
cts 6
cp 0.5
crap 2.5
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 1
	public static function getManyToOne($instance, $member, $included = false, $useCache = NULL) {
46 1
		$fieldAnnot = OrmUtils::getMemberJoinColumns ( $instance, $member );
47 1
		if ($fieldAnnot !== null) {
48 1
			$annotationArray = $fieldAnnot [1];
49 1
			$member = $annotationArray ["member"];
50 1
			$value = Reflexion::getMemberValue ( $instance, $member );
51 1
			$key = OrmUtils::getFirstKey ( $annotationArray ["className"] );
52 1
			$kv = array ($key => $value );
53 1
			$obj = self::getOne ( $annotationArray ["className"], $kv, $included, null, $useCache );
54 1
			if ($obj !== null) {
55 1
				Logger::info ( "DAO", "Loading the member " . $member . " for the object " . \get_class ( $instance ), "getManyToOne" );
56 1
				$accesseur = "set" . ucfirst ( $member );
57 1
				if (method_exists ( $instance, $accesseur )) {
58 1
					$instance->$accesseur ( $obj );
59 1
					$instance->_rest [$member] = $obj->_rest;
60 1
					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 1
	public static function getOneToMany($instance, $member, $included = true, $useCache = NULL, $annot = null) {
79 1
		$ret = array ();
80 1
		$class = get_class ( $instance );
81 1
		if (! isset ( $annot ))
82 1
			$annot = OrmUtils::getAnnotationInfoMember ( $class, "#oneToMany", $member );
83 1
		if ($annot !== false) {
84 1
			$fkAnnot = OrmUtils::getAnnotationInfoMember ( $annot ["className"], "#joinColumn", $annot ["mappedBy"] );
85 1
			if ($fkAnnot !== false) {
86 1
				$fkv = OrmUtils::getFirstKeyValue ( $instance );
87 1
				$ret = self::_getAll ( $annot ["className"], ConditionParser::simple ( $fkAnnot ["name"] . "= ?", $fkv ), $included, $useCache );
88 1
				if ($modifier = self::getAccessor ( $member, $instance, 'getOneToMany' )) {
89 1
					self::setToMember ( $member, $instance, $ret, $modifier );
90
				}
91
			}
92
		}
93 1
		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 1
	public static function getManyToMany($instance, $member, $included = false, $array = null, $useCache = NULL) {
110 1
		$ret = [ ];
111 1
		$class = get_class ( $instance );
112 1
		$parser = new ManyToManyParser ( $instance, $member );
113 1
		if ($parser->init ()) {
114 1
			if (is_null ( $array )) {
115 1
				$accessor = "get" . ucfirst ( $parser->getMyPk () );
116 1
				$condition = " INNER JOIN `" . $parser->getJoinTable () . "` on `" . $parser->getJoinTable () . "`.`" . $parser->getFkField () . "`=`" . $parser->getTargetEntityTable () . "`.`" . $parser->getPk () . "` WHERE `" . $parser->getJoinTable () . "`.`" . $parser->getMyFkField () . "`= ?";
117 1
				$ret = self::_getAll ( $parser->getTargetEntityClass (), ConditionParser::simple ( $condition, $instance->$accessor () ), $included, $useCache );
118
			} else {
119
				$ret = self::getManyToManyFromArray ( $instance, $array, $class, $parser );
120
			}
121 1
			if ($modifier = self::getAccessor ( $member, $instance, 'getManyToMany' )) {
122 1
				self::setToMember ( $member, $instance, $ret, $modifier );
123
			}
124
		}
125 1
		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 3
	public static function getAll($className, $condition = '', $included = true, $parameters = null, $useCache = NULL) {
159 3
		return self::_getAll ( $className, new ConditionParser ( $condition, null, $parameters ), $included, $useCache );
160
	}
161
162 1
	public static function paginate($className, $page = 1, $rowsPerPage = 20, $condition = null, $included = true) {
163 1
		if (! isset ( $condition )) {
164 1
			$condition = "1=1";
165
		}
166 1
		return self::getAll ( $className, $condition . " LIMIT " . $rowsPerPage . " OFFSET " . (($page - 1) * $rowsPerPage), $included );
167
	}
168
169 1
	public static function getRownum($className, $ids) {
170 1
		$tableName = OrmUtils::getTableName ( $className );
171 1
		self::parseKey ( $ids, $className );
172 1
		$condition = SqlUtils::getCondition ( $ids, $className );
173 1
		$keyFields = OrmUtils::getKeyFields ( $className );
174 1
		if (is_array ( $keyFields )) {
175 1
			$keys = implode ( ",", $keyFields );
176
		} else {
177
			$keys = "1";
178
		}
179 1
		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 1
	public static function count($className, $condition = '', $parameters = null) {
194 1
		$tableName = OrmUtils::getTableName ( $className );
195 1
		if ($condition != '')
196
			$condition = " WHERE " . $condition;
197 1
		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 4
	public static function getOne($className, $keyValues, $included = true, $parameters = null, $useCache = NULL) {
216 4
		$conditionParser = new ConditionParser ();
217 4
		if (! isset ( $parameters )) {
218 4
			$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 4
		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 10
	public static function connect($dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [], $cache = false) {
241 10
		self::$db = new Database ( $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache );
242
		try {
243 10
			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 10
	}
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 1
	public static function startDatabase(&$config) {
257 1
		$db = $config ['database'] ?? [ ];
258 1
		if ($db ['dbName'] !== '') {
259 1
			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 1
	}
262
263
	/**
264
	 * Returns true if the connection to the database is established
265
	 *
266
	 * @return boolean
267
	 */
268 2
	public static function isConnected() {
269 2
		return self::$db !== null && (self::$db instanceof Database) && self::$db->isConnected ();
270
	}
271
}
272