Passed
Push — master ( 7ebb22...937a2c )
by Jean-Christophe
05:49
created

DAO::getRownum()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 2
dl 0
loc 11
ccs 8
cts 9
cp 0.8889
crap 2.0054
rs 9.9666
c 0
b 0
f 0
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
40
	 *        	The instance object or an array with [classname,id]
41
	 * @param string $member
42
	 *        	The member to load
43
	 * @param boolean|array $included
44
	 *        	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, $useCache);
0 ignored issues
show
Bug introduced by
It seems like $useCache can also be of type boolean; however, parameter $parameters of Ubiquity\orm\DAO::getOne() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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