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