Test Failed
Push — master ( 094fe2...07472d )
by Jean-Christophe
08:13
created

DAO::count()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.1481

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 5
ccs 2
cts 3
cp 0.6667
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2.1481
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
	public static function getManyToOne($instance, $member, $included = false, $useCache = NULL) {
45
		$classname = self::getClass_ ( $instance );
46
		if (is_array ( $instance )) {
47 4
			$instance = self::getOne ( $classname, $instance [1], false, null, $useCache );
48 4
		}
49 4
		$fieldAnnot = OrmUtils::getMemberJoinColumns ( $classname, $member );
50 1
		if ($fieldAnnot !== null) {
51
			$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 4
				}
64 4
				return $obj;
65 4
			}
66
		}
67 4
	}
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
	public static function getOneToMany($instance, $member, $included = true, $useCache = NULL, $annot = null) {
79
		$ret = array ();
80
		$class = self::getClass_ ( $instance );
81
		if (! isset ( $annot )) {
82
			$annot = OrmUtils::getAnnotationInfoMember ( $class, "#oneToMany", $member );
83
		}
84
		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
					self::setToMember ( $member, $instance, $ret, $modifier );
91 7
				}
92 7
			}
93 7
		}
94 7
		return $ret;
95 7
	}
96 7
97 6
	/**
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 7
	 * @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
	public static function getManyToMany($instance, $member, $included = false, $array = null, $useCache = NULL) {
108
		$ret = [ ];
109
		$class = self::getClass_ ( $instance );
110
		$parser = new ManyToManyParser ( $class, $member );
111
		if ($parser->init ()) {
112
			if (is_null ( $array )) {
113
				$pk = self::getFirstKeyValue_ ( $instance );
114
				$condition = " INNER JOIN `" . $parser->getJoinTable () . "` on `" . $parser->getJoinTable () . "`.`" . $parser->getFkField () . "`=`" . $parser->getTargetEntityTable () . "`.`" . $parser->getPk () . "` WHERE `" . $parser->getJoinTable () . "`.`" . $parser->getMyFkField () . "`= ?";
115
				$ret = self::_getAll ( $parser->getTargetEntityClass (), ConditionParser::simple ( $condition, $pk ), $included, $useCache );
116
			} else {
117
				$ret = self::getManyToManyFromArray ( $instance, $array, $class, $parser );
118 4
			}
119 4
			if (is_object ( $instance ) && $modifier = self::getAccessor ( $member, $instance, 'getManyToMany' )) {
120 4
				self::setToMember ( $member, $instance, $ret, $modifier );
121 4
			}
122 4
		}
123 4
		return $ret;
124 4
	}
125 4
126 4
	/**
127
	 *
128
	 * @param object $instance
129
	 * @param array $array
130 4
	 * @param boolean $useCache
131 3
	 */
132
	public static function affectsManyToManys($instance, $array = NULL, $useCache = NULL) {
133
		$metaDatas = OrmUtils::getModelMetadata ( \get_class ( $instance ) );
134 4
		$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
	public static function getAll($className, $condition = '', $included = true, $parameters = null, $useCache = NULL) {
153
		return self::_getAll ( $className, new ConditionParser ( $condition, null, $parameters ), $included, $useCache );
154
	}
155
156
	public static function paginate($className, $page = 1, $rowsPerPage = 20, $condition = null, $included = true) {
157
		if (! isset ( $condition )) {
158
			$condition = "1=1";
159
		}
160
		return self::getAll ( $className, $condition . " LIMIT " . $rowsPerPage . " OFFSET " . (($page - 1) * $rowsPerPage), $included );
161
	}
162
163
	public static function getRownum($className, $ids) {
164
		$tableName = OrmUtils::getTableName ( $className );
165
		self::parseKey ( $ids, $className );
166
		$condition = SqlUtils::getCondition ( $ids, $className );
167 19
		$keyFields = OrmUtils::getKeyFields ( $className );
168 19
		if (is_array ( $keyFields )) {
169
			$keys = implode ( ",", $keyFields );
170
		} else {
171 3
			$keys = "1";
172 3
		}
173 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 );
174
	}
175 3
176
	/**
177
	 * Returns the number of objects of $className from the database respecting the condition possibly passed as parameter
178 3
	 *
179 3
	 * @param string $className complete classname of the model to load
180 3
	 * @param string $condition Part following the WHERE of an SQL statement
181 3
	 * @param array|null $parameters The query parameters
182 3
	 * @return int|false count of objects
183 3
	 */
184 3
	public static function count($className, $condition = '', $parameters = null) {
185
		$tableName = OrmUtils::getTableName ( $className );
186
		if ($condition != '')
187
			$condition = " WHERE " . $condition;
188 3
		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
	public static function getOne($className, $keyValues, $included = true, $parameters = null, $useCache = NULL) {
202 10
		$conditionParser = new ConditionParser ();
203 10
		if (! isset ( $parameters )) {
204 10
			$conditionParser->addKeyValues ( $keyValues, $className );
205 7
		} elseif (! is_array ( $keyValues )) {
206 10
			$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
		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 23
	 * @param boolean $cache
225 23
	 */
226 23
	public static function connect($dbType, $dbName, $serverName = '127.0.0.1', $port = '3306', $user = 'root', $password = '', $options = [], $cache = false) {
227 23
		self::$db = new Database ( $dbType, $dbName, $serverName, $port, $user, $password, $options, $cache );
228
		try {
229
			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 23
	}
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
	public static function startDatabase(&$config) {
242
		$db = $config ['database'] ?? [ ];
243
		if ($db ['dbName'] !== '') {
244
			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
	}
247
248
	/**
249 62
	 * Returns true if the connection to the database is established
250 62
	 *
251
	 * @return boolean
252 62
	 */
253
	public static function isConnected() {
254
		return self::$db !== null && (self::$db instanceof Database) && self::$db->isConnected ();
255
	}
256
257 62
	public static function setTransformerOp($op) {
258
		self::$transformerOp = $op;
259
	}
260
}
261