Passed
Push — master ( a7b436...a615fa )
by Jean-Christophe
02:41
created

DAO   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 248
Duplicated Lines 0 %

Test Coverage

Coverage 63.92%

Importance

Changes 0
Metric Value
wmc 33
eloc 88
dl 0
loc 248
ccs 62
cts 97
cp 0.6392
rs 9.76
c 0
b 0
f 0

12 Methods

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