Completed
Push — master ( 61f3b2...32110c )
by Jean-Christophe
02:56
created

DAOUpdatesTrait::update()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 22
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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