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