Passed
Push — master ( 213516...f477f5 )
by Jean-Christophe
04:14
created

DAOUpdatesTrait::deleteAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ubiquity\orm\traits;
4
5
use Ubiquity\orm\OrmUtils;
6
use Ubiquity\orm\parser\Reflexion;
7
use Ubiquity\db\SqlUtils;
8
use Ubiquity\log\Logger;
9
use Ubiquity\orm\parser\ManyToManyParser;
10
use Ubiquity\events\EventsManager;
11
12
/**
13
 * Trait for DAO Updates (Create, Update, Delete)
14
 *
15
 * @author jc
16
 * @static Database $db
17
 */
18
trait DAOUpdatesTrait{
19
20
	/**
21
	 * Deletes the object $instance from the database
22
	 *
23
	 * @param object $instance
24
	 *        	instance à supprimer
25
	 */
26
	public static function remove($instance) {
27
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
28
		$keyAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
29
		return self::removeByKey_ ( $tableName, $keyAndValues );
30
	}
31
32
	/**
33
	 *
34
	 * @param string $tableName
35
	 * @param array $keyAndValues
36
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
37
	 */
38
	private static function removeByKey_($tableName, $keyAndValues) {
39
		$sql = "DELETE FROM " . $tableName . " WHERE " . SqlUtils::getWhere ( $keyAndValues );
40
		Logger::info("DAOUpdates", $sql,"delete");
41
		$statement = self::$db->prepareStatement ( $sql );
42
		foreach ( $keyAndValues as $key => $value ) {
43
			self::$db->bindValueFromStatement ( $statement, $key, $value );
44
		}
45
		try{
46
			if( $statement->execute ()){
47
				return $statement->rowCount();
48
			}
49
		}catch(\PDOException $e){
50
			Logger::warn("DAOUpdates",  $e->getMessage() ,"delete");
51
			return;
52
		}
53
		return;
54
	}
55
56
	/**
57
	 *
58
	 * @param string $tableName
59
	 * @param string $where
60
	 * @return boolean|int the number of rows that were modified or deleted by the SQL statement you issued
61
	 */
62
	private static function remove_($tableName, $where) {
63
		$sql = "DELETE FROM `" . $tableName . "` " . SqlUtils::checkWhere ( $where );
64
		Logger::info ("DAOUpdates",  $sql ,"delete");
65
		$statement = self::$db->prepareStatement ( $sql );
66
		try{
67
			if($statement->execute ()){
68
				return $statement->rowCount();
69
			}
70
		}catch(\PDOException $e){
71
			Logger::warn("DAOUpdates",  $e->getMessage() ,"delete");
72
			return false;
73
		}
74
	}
75
	
76
	/**
77
	 * Deletes all instances from $modelName matching the condition $where
78
	 * @param string $modelName
79
	 * @param string $where
80
	 * @return int|boolean
81
	 */
82
	public static function deleteAll($modelName,$where){
83
		$tableName = OrmUtils::getTableName ( $modelName );
84
		return self::remove_($tableName, $where);
85
	}
86
87
	/**
88
	 * Deletes all instances from $modelName corresponding to $ids
89
	 * @param string $modelName
90
	 * @param array|int $ids
91
	 * @return int|boolean
92
	 */
93
	public static function delete($modelName, $ids) {
94
		$tableName = OrmUtils::getTableName ( $modelName );
95
		$pk = OrmUtils::getFirstKey ( $modelName );
96
		if (! \is_array ( $ids )) {
97
			$ids = [ $ids ];
98
		}
99
		$where = SqlUtils::getMultiWhere ( $ids, $pk );
100
		return self::remove_ ( $tableName, $where );
101
	}
102
103
	/**
104
	 * Inserts a new instance $instance into the database
105
	 *
106
	 * @param object $instance
107
	 *        	the instance to insert
108
	 * @param boolean $insertMany
109
	 *        	if true, save instances related to $instance by a ManyToMany association
110
	 */
111
	public static function insert($instance, $insertMany = false) {
112
		EventsManager::trigger('dao.before.insert', $instance);
113
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
114
		$keyAndValues = Reflexion::getPropertiesAndValues ( $instance );
115
		$keyAndValues = array_merge ( $keyAndValues, OrmUtils::getManyToOneMembersAndValues ( $instance ) );
116
		$sql = "INSERT INTO `" . $tableName . "`(" . SqlUtils::getInsertFields ( $keyAndValues ) . ") VALUES(" . SqlUtils::getInsertFieldsValues ( $keyAndValues ) . ")";
117
		Logger::info ( "DAOUpdates", $sql,"insert" );
118
		Logger::info ( "DAOUpdates", json_encode ( $keyAndValues ),"Key and values" );
119
		$statement = self::$db->prepareStatement ( $sql );
120
		foreach ( $keyAndValues as $key => $value ) {
121
			self::$db->bindValueFromStatement ( $statement, $key, $value );
122
		}
123
		try{
124
			$result = $statement->execute ();
125
			if ($result) {
126
				$accesseurId = "set" . ucfirst ( OrmUtils::getFirstKey ( get_class ( $instance ) ) );
127
				$lastId=self::$db->lastInserId ();
128
				if($lastId!=0){
129
					$instance->$accesseurId ( $lastId);
130
				}
131
				if ($insertMany) {
132
					self::insertOrUpdateAllManyToMany ( $instance );
133
				}
134
			}
135
			EventsManager::trigger('dao.after.insert', $instance,$result);
136
			return $result;
137
		}catch(\PDOException $e){
138
			Logger::warn("DAOUpdates",  $e->getMessage() ,"insert");
139
		}
140
		return false;
141
	}
142
143
	/**
144
	 * Met à jour les membres de $instance annotés par un ManyToMany
145
	 *
146
	 * @param object $instance
147
	 */
148
	public static function insertOrUpdateAllManyToMany($instance) {
149
		$members = OrmUtils::getAnnotationInfo ( get_class ( $instance ), "#manyToMany" );
150
		if ($members !== false) {
151
			$members = \array_keys ( $members );
152
			foreach ( $members as $member ) {
153
				self::insertOrUpdateManyToMany ( $instance, $member );
154
			}
155
		}
156
	}
157
158
	/**
159
	 * Updates the $member member of $instance annotated by a ManyToMany
160
	 *
161
	 * @param Object $instance
162
	 * @param String $member
163
	 */
164
	public static function insertOrUpdateManyToMany($instance, $member) {
165
		$parser = new ManyToManyParser ( $instance, $member );
166
		if ($parser->init ()) {
167
			$myField = $parser->getMyFkField ();
168
			$field = $parser->getFkField ();
169
			$sql = "INSERT INTO `" . $parser->getJoinTable () . "`(`" . $myField . "`,`" . $field . "`) VALUES (:" . $myField . ",:" . $field . ");";
170
			$memberAccessor = "get" . ucfirst ( $member );
171
			$memberValues = $instance->$memberAccessor ();
172
			$myKey = $parser->getMyPk ();
173
			$myAccessorId = "get" . ucfirst ( $myKey );
174
			$accessorId = "get" . ucfirst ( $parser->getPk () );
175
			$id = $instance->$myAccessorId ();
176
			if (! is_null ( $memberValues )) {
177
				self::$db->execute ( "DELETE FROM `" . $parser->getJoinTable () . "` WHERE `" . $myField . "`='" . $id . "'" );
178
				$statement = self::$db->prepareStatement ( $sql );
179
				foreach ( $memberValues as $targetInstance ) {
180
					$foreignId = $targetInstance->$accessorId ();
181
					$foreignInstances = self::getAll ( $parser->getTargetEntity (), "`" . $parser->getPk () . "`" . "='" . $foreignId . "'" );
182
					if (! OrmUtils::exists ( $targetInstance, $parser->getPk (), $foreignInstances )) {
183
						self::insert ( $targetInstance, false );
184
						$foreignId = $targetInstance->$accessorId ();
185
						Logger::info ( "DAOUpdates", "Insertion d'une instance de " . get_class ( $instance ),"InsertMany" );
186
					}
187
					self::$db->bindValueFromStatement ( $statement, $myField, $id );
188
					self::$db->bindValueFromStatement ( $statement, $field, $foreignId );
189
					$statement->execute ();
190
					Logger::info ( "DAOUpdates", "Insertion des valeurs dans la table association '" . $parser->getJoinTable () . "'","InsertMany" );
191
				}
192
			}
193
		}
194
	}
195
196
	/**
197
	 * Updates an existing $instance in the database.
198
	 * Be careful not to modify the primary key
199
	 *
200
	 * @param object $instance
201
	 *        	instance to modify
202
	 * @param boolean $updateMany
203
	 *        	Adds or updates ManyToMany members
204
	 */
205 1
	public static function update($instance, $updateMany = false) {
206 1
		EventsManager::trigger("dao.before.update", $instance);
207 1
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
208 1
		$ColumnskeyAndValues = Reflexion::getPropertiesAndValues ( $instance );
209 1
		$ColumnskeyAndValues = array_merge ( $ColumnskeyAndValues, OrmUtils::getManyToOneMembersAndValues ( $instance ) );
210 1
		$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
211 1
		$sql = "UPDATE `" . $tableName . "` SET " . SqlUtils::getUpdateFieldsKeyAndValues ( $ColumnskeyAndValues ) . " WHERE " . SqlUtils::getWhere ( $keyFieldsAndValues );
212 1
		Logger::info ( "DAOUpdates", $sql,"update" );
213 1
		Logger::info ("DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
214 1
		$statement = self::$db->prepareStatement ( $sql );
215 1
		foreach ( $ColumnskeyAndValues as $key => $value ) {
216 1
			self::$db->bindValueFromStatement ( $statement, $key, $value );
217
		}
218
		try{
219 1
			$result = $statement->execute ();
220 1
			if ($result && $updateMany)
221
				self::insertOrUpdateAllManyToMany ( $instance );
222 1
			EventsManager::trigger('dao.after.update', $instance,$result);
223 1
			return $result;
224
		}catch(\PDOException $e){
225
			Logger::warn("DAOUpdates",  $e->getMessage() ,"update");
226
		}
227
		return false;
228
	}
229
230
	/**
231
	 *
232
	 * @param object $instance
233
	 * @param boolean $updateMany
234
	 * @return boolean|int
235
	 */
236
	public static function save($instance, $updateMany = false) {
237
		if (isset ( $instance->_rest )) {
238
			return self::update ( $instance, $updateMany );
239
		}
240
		return self::insert ( $instance, $updateMany );
241
	}
242
}
243