Passed
Push — master ( b968d7...aeea38 )
by Jean-Christophe
07:22
created

DAO   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Test Coverage

Coverage 80.61%

Importance

Changes 0
Metric Value
wmc 38
eloc 90
dl 0
loc 234
ccs 79
cts 98
cp 0.8061
rs 9.36
c 0
b 0
f 0

13 Methods

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