Passed
Push — master ( be71ba...d26f6c )
by Jean-Christophe
03:55
created

DAO::isConnected()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

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