Passed
Push — master ( abe30a...78bb6e )
by Jean-Christophe
01:41
created

DAO   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 194
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 75
dl 0
loc 194
rs 10
c 0
b 0
f 0
wmc 28

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getManyToOne() 0 16 4
A getOneToMany() 0 14 4
A affectsManyToManys() 0 6 3
A getAll() 0 2 1
A paginate() 0 5 2
A isConnected() 0 2 3
A connect() 0 7 2
A getOne() 0 11 3
A count() 0 5 2
A getRownum() 0 6 1
A getManyToMany() 0 15 3
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
18
/**
19
 * Gateway class between database and object model
20
 * @author jc
21
 * @version 1.1.3
22
 * @package orm
23
 */
24
class DAO {
25
	use DAOCoreTrait,DAOUpdatesTrait,DAORelationsTrait,DAORelationsPrepareTrait,DAOUQueries;
26
	
27
	
28
	/**
29
	 * @var Database
30
	 */
31
	public static $db;
32
33
	/**
34
	 * Loads member associated with $instance by a ManyToOne relationship
35
	 * @param object $instance
36
	 * @param string $member
37
	 * @param boolean|array $included if true, loads associate members with associations, if array, example : ["client.*","commands"]
38
	 * @param boolean|null $useCache
39
	 */
40
	public static function getManyToOne($instance, $member, $included=false,$useCache=NULL) {
41
		$fieldAnnot=OrmUtils::getMemberJoinColumns($instance, $member);
42
		if($fieldAnnot!==null){
43
			$annotationArray=$fieldAnnot[1];
44
			$member=$annotationArray["member"];
45
			$value=Reflexion::getMemberValue($instance, $member);
46
			$key=OrmUtils::getFirstKey($annotationArray["className"]);
47
			$kv=array ($key => $value );
48
			$obj=self::getOne($annotationArray["className"], $kv, $included, null,$useCache);
49
			if ($obj !== null) {
50
				Logger::info("DAO", "Loading the member " . $member . " for the object " . \get_class($instance),"getManyToOne");
51
				$accesseur="set" . ucfirst($member);
52
				if (method_exists($instance, $accesseur)) {
53
					$instance->$accesseur($obj);
54
					$instance->_rest[$member]=$obj->_rest;
55
					return $obj;
56
				}
57
			}
58
		}
59
	}
60
61
	/**
62
	 * Assign / load the child records in the $member member of $instance.
63
	 * @param object $instance
64
	 * @param string $member Member on which a oneToMany annotation must be present
65
	 * @param boolean|array $included if true, loads associate members with associations, if array, example : ["client.*","commands"]
66
	 * @param boolean $useCache
67
	 * @param array $annot used internally
68
	 */
69
	public static function getOneToMany($instance, $member, $included=true,$useCache=NULL, $annot=null) {
70
		$ret=array ();
71
		$class=get_class($instance);
72
		if (!isset($annot))
73
			$annot=OrmUtils::getAnnotationInfoMember($class, "#oneToMany", $member);
74
			if ($annot !== false) {
75
				$fkAnnot=OrmUtils::getAnnotationInfoMember($annot["className"], "#joinColumn", $annot["mappedBy"]);
76
				if ($fkAnnot !== false) {
77
					$fkv=OrmUtils::getFirstKeyValue($instance);
78
					$ret=self::_getAll($annot["className"], ConditionParser::simple($fkAnnot["name"] . "= ?",$fkv), $included, $useCache);
79
					self::setToMember($member, $instance, $ret, $class, "getOneToMany");
80
				}
81
			}
82
			return $ret;
83
	}
84
85
	/**
86
	 * Assigns / loads the child records in the $member member of $instance.
87
	 * If $ array is null, the records are loaded from the database
88
	 * @param object $instance
89
	 * @param string $member Member on which a ManyToMany annotation must be present
90
	 * @param boolean|array $included if true, loads associate members with associations, if array, example : ["client.*","commands"]
91
	 * @param array $array optional parameter containing the list of possible child records
92
	 * @param boolean $useCache
93
	 */
94
	public static function getManyToMany($instance, $member,$included=false,$array=null,$useCache=NULL){
95
		$ret=[];
96
		$class=get_class($instance);
97
		$parser=new ManyToManyParser($instance, $member);
98
		if ($parser->init()) {
99
			if (is_null($array)) {
100
				$accessor="get" . ucfirst($parser->getMyPk());
101
				$condition=" INNER JOIN `" . $parser->getJoinTable() . "` on `".$parser->getJoinTable()."`.`".$parser->getFkField()."`=`".$parser->getTargetEntityTable()."`.`".$parser->getPk()."` WHERE `".$parser->getJoinTable()."`.`". $parser->getMyFkField() . "`= ?";
102
				$ret=self::_getAll($parser->getTargetEntityClass(),ConditionParser::simple($condition, $instance->$accessor()),$included,$useCache);
103
			}else{
104
				$ret=self::getManyToManyFromArray($instance, $array, $class, $parser);
105
			}
106
			self::setToMember($member, $instance, $ret, $class, "getManyToMany");
107
		}
108
		return $ret;
109
	}
110
111
	/**
112
	 * @param object $instance
113
	 * @param array $array
114
	 * @param boolean $useCache
115
	 */
116
	public static function affectsManyToManys($instance,$array=NULL,$useCache=NULL){
117
		$metaDatas=OrmUtils::getModelMetadata(\get_class($instance));
118
		$manyToManyFields=$metaDatas["#manyToMany"];
119
		if(\sizeof($manyToManyFields)>0){
120
			foreach ($manyToManyFields as $member){
121
				self::getManyToMany($instance, $member,false,$array,$useCache);
122
			}
123
		}
124
	}
125
126
	/**
127
	 * Returns an array of $className objects from the database
128
	 * @param string $className class name of the model to load
129
	 * @param string $condition Part following the WHERE of an SQL statement
130
	 * @param boolean|array $included if true, loads associate members with associations, if array, example : ["client.*","commands"]
131
	 * @param array|null $parameters
132
	 * @param boolean $useCache use the active cache if true
133
	 * @return array
134
	 */
135
	public static function getAll($className, $condition='', $included=true,$parameters=null,$useCache=NULL) {
136
		return self::_getAll($className, new ConditionParser($condition,null,$parameters),$included,$useCache);
137
	}
138
139
	public static function paginate($className,$page=1,$rowsPerPage=20,$condition=null,$included=true){
140
		if(!isset($condition)){
141
			$condition="1=1";
142
		}
143
		return self::getAll($className,$condition." LIMIT ".$rowsPerPage." OFFSET ".(($page-1)*$rowsPerPage),$included);
144
	}
145
	
146
	public static function getRownum($className,$ids){
147
		$tableName=OrmUtils::getTableName($className);
148
		self::parseKey($ids,$className);
149
		$condition=SqlUtils::getCondition($ids,$className);
150
		$keys=implode(",", OrmUtils::getKeyFields($className));
0 ignored issues
show
Bug introduced by
It seems like Ubiquity\orm\OrmUtils::getKeyFields($className) can also be of type false; however, parameter $pieces of implode() does only seem to accept array, 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

150
		$keys=implode(",", /** @scrutinizer ignore-type */ OrmUtils::getKeyFields($className));
Loading history...
151
		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);
152
	}
153
154
	/**
155
	 * Returns the number of objects of $className from the database respecting the condition possibly passed as parameter
156
	 * @param string $className complete classname of the model to load
157
	 * @param string $condition Part following the WHERE of an SQL statement
158
	 * @param array|null $parameters The query parameters
159
	 * @return int count of objects
160
	 */
161
	public static function count($className, $condition='',$parameters=null) {
162
		$tableName=OrmUtils::getTableName($className);
163
		if ($condition != '')
164
			$condition=" WHERE " . $condition;
165
		return self::$db->prepareAndFetchColumn("SELECT COUNT(*) FROM `" . $tableName ."`". $condition,$parameters);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::db->prepare...condition, $parameters) could also return false which is incompatible with the documented return type integer. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
166
	}
167
168
	/**
169
	 * Returns an instance of $className from the database, from $keyvalues values of the primary key
170
	 * @param String $className complete classname of the model to load
171
	 * @param Array|string $keyValues primary key values or condition
172
	 * @param boolean|array $included if true, charges associate members with association
173
	 * @param array|null $parameters the request parameters
174
	 * @param boolean|null $useCache use cache if true
175
	 * @return object the instance loaded or null if not found
176
	 */
177
	public static function getOne($className, $keyValues, $included=true,$parameters=null,$useCache=NULL) {
178
		$conditionParser=new ConditionParser();
179
		if(!isset($parameters)){
180
			$conditionParser->addKeyValues($keyValues,$className);
181
		}elseif(!is_array($keyValues)){
182
			$conditionParser->setCondition($keyValues);
183
			$conditionParser->setParams($parameters);
184
		}else{
185
			throw new DAOException("The \$keyValues parameter should not be an array if \$parameters is not null");
186
		}
187
		return self::_getOne($className, $conditionParser, $included, $useCache);
1 ignored issue
show
Bug introduced by
Are you sure the usage of self::_getOne($className..., $included, $useCache) targeting Ubiquity\orm\DAO::_getOne() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
188
	}
189
190
191
	/**
192
	 * Establishes the connection to the database using the past parameters
193
	 * @param string $dbType
194
	 * @param string $dbName
195
	 * @param string $serverName
196
	 * @param string $port
197
	 * @param string $user
198
	 * @param string $password
199
	 * @param array $options
200
	 * @param boolean $cache
201
	 */
202
	public static function connect($dbType,$dbName, $serverName="127.0.0.1", $port="3306", $user="root", $password="", $options=[],$cache=false) {
203
		self::$db=new Database($dbType,$dbName, $serverName, $port, $user, $password, $options,$cache);
204
		try {
205
			self::$db->connect();
206
		} catch (\Exception $e) {
207
			Logger::error("DAO", $e->getMessage());
208
			throw new DAOException($e->getMessage(),$e->getCode(),$e->getPrevious());
209
		}
210
	}
211
212
	/**
213
	 * Returns true if the connection to the database is established
214
	 * @return boolean
215
	 */
216
	public static function isConnected(){
217
		return self::$db!==null && (self::$db instanceof Database) && self::$db->isConnected();
218
	}
219
}
220