Completed
Push — master ( 5cada7...a17991 )
by Jean-Christophe
05:01
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
		}
84 1
		if ($annot !== false) {
85 1
			$fkAnnot = OrmUtils::getAnnotationInfoMember ( $annot ["className"], "#joinColumn", $annot ["mappedBy"] );
86 1
			if ($fkAnnot !== false) {
87 1
				$fkv = OrmUtils::getFirstKeyValue ( $instance );
88 1
				$ret = self::_getAll ( $annot ["className"], ConditionParser::simple ( $fkAnnot ["name"] . "= ?", $fkv ), $included, $useCache );
89 1
				if ($modifier = self::getAccessor ( $member, $instance, 'getOneToMany' )) {
90 1
					self::setToMember ( $member, $instance, $ret, $modifier );
91
				}
92
			}
93
		}
94 1
		return $ret;
95
	}
96
97
	/**
98
	 * Assigns / loads the child records in the $member member of $instance.
99
	 * If $array is null, the records are loaded from the database
100
	 *
101
	 * @param object $instance
102
	 * @param string $member
103
	 *        	Member on which a ManyToMany annotation must be present
104
	 * @param boolean|array $included
105
	 *        	if true, loads associate members with associations, if array, example : ["client.*","commands"]
106
	 * @param array $array
107
	 *        	optional parameter containing the list of possible child records
108
	 * @param boolean $useCache
109
	 */
110 1
	public static function getManyToMany($instance, $member, $included = false, $array = null, $useCache = NULL) {
111 1
		$ret = [ ];
112 1
		$class = get_class ( $instance );
113 1
		$parser = new ManyToManyParser ( $instance, $member );
114 1
		if ($parser->init ()) {
115 1
			if (is_null ( $array )) {
116 1
				$accessor = "get" . ucfirst ( $parser->getMyPk () );
117 1
				$condition = " INNER JOIN `" . $parser->getJoinTable () . "` on `" . $parser->getJoinTable () . "`.`" . $parser->getFkField () . "`=`" . $parser->getTargetEntityTable () . "`.`" . $parser->getPk () . "` WHERE `" . $parser->getJoinTable () . "`.`" . $parser->getMyFkField () . "`= ?";
118 1
				$ret = self::_getAll ( $parser->getTargetEntityClass (), ConditionParser::simple ( $condition, $instance->$accessor () ), $included, $useCache );
119
			} else {
120
				$ret = self::getManyToManyFromArray ( $instance, $array, $class, $parser );
121
			}
122 1
			if ($modifier = self::getAccessor ( $member, $instance, 'getManyToMany' )) {
123 1
				self::setToMember ( $member, $instance, $ret, $modifier );
124
			}
125
		}
126 1
		return $ret;
127
	}
128
129
	/**
130
	 *
131
	 * @param object $instance
132
	 * @param array $array
133
	 * @param boolean $useCache
134
	 */
135
	public static function affectsManyToManys($instance, $array = NULL, $useCache = NULL) {
136
		$metaDatas = OrmUtils::getModelMetadata ( \get_class ( $instance ) );
137
		$manyToManyFields = $metaDatas ["#manyToMany"];
138
		if (\sizeof ( $manyToManyFields ) > 0) {
139
			foreach ( $manyToManyFields as $member ) {
140
				self::getManyToMany ( $instance, $member, false, $array, $useCache );
141
			}
142
		}
143
	}
144
145
	/**
146
	 * Returns an array of $className objects from the database
147
	 *
148
	 * @param string $className
149
	 *        	class name of the model to load
150
	 * @param string $condition
151
	 *        	Part following the WHERE of an SQL statement
152
	 * @param boolean|array $included
153
	 *        	if true, loads associate members with associations, if array, example : ["client.*","commands"]
154
	 * @param array|null $parameters
155
	 * @param boolean $useCache
156
	 *        	use the active cache if true
157
	 * @return array
158
	 */
159 5
	public static function getAll($className, $condition = '', $included = true, $parameters = null, $useCache = NULL) {
160 5
		return self::_getAll ( $className, new ConditionParser ( $condition, null, $parameters ), $included, $useCache );
161
	}
162
163 2
	public static function paginate($className, $page = 1, $rowsPerPage = 20, $condition = null, $included = true) {
164 2
		if (! isset ( $condition )) {
165 1
			$condition = "1=1";
166
		}
167 2
		return self::getAll ( $className, $condition . " LIMIT " . $rowsPerPage . " OFFSET " . (($page - 1) * $rowsPerPage), $included );
168
	}
169
170 1
	public static function getRownum($className, $ids) {
171 1
		$tableName = OrmUtils::getTableName ( $className );
172 1
		self::parseKey ( $ids, $className );
173 1
		$condition = SqlUtils::getCondition ( $ids, $className );
174 1
		$keyFields = OrmUtils::getKeyFields ( $className );
175 1
		if (is_array ( $keyFields )) {
176 1
			$keys = implode ( ",", $keyFields );
177
		} else {
178
			$keys = "1";
179
		}
180 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 );
181
	}
182
183
	/**
184
	 * Returns the number of objects of $className from the database respecting the condition possibly passed as parameter
185
	 *
186
	 * @param string $className
187
	 *        	complete classname of the model to load
188
	 * @param string $condition
189
	 *        	Part following the WHERE of an SQL statement
190
	 * @param array|null $parameters
191
	 *        	The query parameters
192
	 * @return int|false count of objects
193
	 */
194 3
	public static function count($className, $condition = '', $parameters = null) {
195 3
		$tableName = OrmUtils::getTableName ( $className );
196 3
		if ($condition != '')
197 1
			$condition = " WHERE " . $condition;
198 3
		return self::$db->prepareAndFetchColumn ( "SELECT COUNT(*) FROM `" . $tableName . "`" . $condition, $parameters );
199
	}
200
201
	/**
202
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key
203
	 *
204
	 * @param String $className
205
	 *        	complete classname of the model to load
206
	 * @param Array|string $keyValues
207
	 *        	primary key values or condition
208
	 * @param boolean|array $included
209
	 *        	if true, charges associate members with association
210
	 * @param array|null $parameters
211
	 *        	the request parameters
212
	 * @param boolean|null $useCache
213
	 *        	use cache if true
214
	 * @return object the instance loaded or null if not found
215
	 */
216 6
	public static function getOne($className, $keyValues, $included = true, $parameters = null, $useCache = NULL) {
217 6
		$conditionParser = new ConditionParser ();
218 6
		if (! isset ( $parameters )) {
219 6
			$conditionParser->addKeyValues ( $keyValues, $className );
220
		} elseif (! is_array ( $keyValues )) {
221
			$conditionParser->setCondition ( $keyValues );
222
			$conditionParser->setParams ( $parameters );
223
		} else {
224
			throw new DAOException ( "The \$keyValues parameter should not be an array if \$parameters is not null" );
225
		}
226 6
		return self::_getOne ( $className, $conditionParser, $included, $useCache );
227
	}
228
229
	/**
230
	 * Establishes the connection to the database using the past parameters
231
	 *
232
	 * @param string $dbType
233
	 * @param string $dbName
234
	 * @param string $serverName
235
	 * @param string $port
236
	 * @param string $user
237
	 * @param string $password
238
	 * @param array $options
239
	 * @param boolean $cache
240
	 */
241 22
	public static function connect($dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [], $cache = false) {
242 22
		self::$db = new Database ( $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache );
243
		try {
244 22
			self::$db->connect ();
245
		} catch ( \Exception $e ) {
246
			Logger::error ( "DAO", $e->getMessage () );
247
			throw new DAOException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
248
		}
249 22
	}
250
251
	/**
252
	 * Establishes the connection to the database using the $config array
253
	 *
254
	 * @param array $config
255
	 *        	the config array (Startup::getConfig())
256
	 */
257 1
	public static function startDatabase(&$config) {
258 1
		$db = $config ['database'] ?? [ ];
259 1
		if ($db ['dbName'] !== '') {
260 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);
261
		}
262 1
	}
263
264
	/**
265
	 * Returns true if the connection to the database is established
266
	 *
267
	 * @return boolean
268
	 */
269 4
	public static function isConnected() {
270 4
		return self::$db !== null && (self::$db instanceof Database) && self::$db->isConnected ();
271
	}
272
}
273