Completed
Push — master ( 84bffa...c0d988 )
by Jean-Christophe
01:38
created

DAOUpdatesTrait::update()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2568
c 0
b 0
f 0
cc 5
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
				$lastId=self::$db->lastInserId ();
126
				if($lastId!=0){
127
					$instance->$accesseurId ( $lastId);
128
				}
129
				if ($insertMany) {
130
					self::insertOrUpdateAllManyToMany ( $instance );
131
				}
132
			}
133
			return $result;
134
		}catch(\PDOException $e){
135
			Logger::warn("DAOUpdates",  $e->getMessage() ,"insert");
136
		}
137
		return false;
138
	}
139
140
	/**
141
	 * Met à jour les membres de $instance annotés par un ManyToMany
142
	 *
143
	 * @param object $instance
144
	 */
145
	public static function insertOrUpdateAllManyToMany($instance) {
146
		$members = OrmUtils::getAnnotationInfo ( get_class ( $instance ), "#manyToMany" );
147
		if ($members !== false) {
148
			$members = \array_keys ( $members );
149
			foreach ( $members as $member ) {
150
				self::insertOrUpdateManyToMany ( $instance, $member );
151
			}
152
		}
153
	}
154
155
	/**
156
	 * Updates the $member member of $instance annotated by a ManyToMany
157
	 *
158
	 * @param Object $instance
159
	 * @param String $member
160
	 */
161
	public static function insertOrUpdateManyToMany($instance, $member) {
162
		$parser = new ManyToManyParser ( $instance, $member );
163
		if ($parser->init ()) {
164
			$myField = $parser->getMyFkField ();
165
			$field = $parser->getFkField ();
166
			$sql = "INSERT INTO `" . $parser->getJoinTable () . "`(`" . $myField . "`,`" . $field . "`) VALUES (:" . $myField . ",:" . $field . ");";
167
			$memberAccessor = "get" . ucfirst ( $member );
168
			$memberValues = $instance->$memberAccessor ();
169
			$myKey = $parser->getMyPk ();
170
			$myAccessorId = "get" . ucfirst ( $myKey );
171
			$accessorId = "get" . ucfirst ( $parser->getPk () );
172
			$id = $instance->$myAccessorId ();
173
			if (! is_null ( $memberValues )) {
174
				self::$db->execute ( "DELETE FROM `" . $parser->getJoinTable () . "` WHERE `" . $myField . "`='" . $id . "'" );
175
				$statement = self::$db->prepareStatement ( $sql );
176
				foreach ( $memberValues as $targetInstance ) {
177
					$foreignId = $targetInstance->$accessorId ();
178
					$foreignInstances = self::getAll ( $parser->getTargetEntity (), "`" . $parser->getPk () . "`" . "='" . $foreignId . "'" );
179
					if (! OrmUtils::exists ( $targetInstance, $parser->getPk (), $foreignInstances )) {
180
						self::insert ( $targetInstance, false );
181
						$foreignId = $targetInstance->$accessorId ();
182
						Logger::info ( "DAOUpdates", "Insertion d'une instance de " . get_class ( $instance ),"InsertMany" );
183
					}
184
					self::$db->bindValueFromStatement ( $statement, $myField, $id );
185
					self::$db->bindValueFromStatement ( $statement, $field, $foreignId );
186
					$statement->execute ();
187
					Logger::info ( "DAOUpdates", "Insertion des valeurs dans la table association '" . $parser->getJoinTable () . "'","InsertMany" );
188
				}
189
			}
190
		}
191
	}
192
193
	/**
194
	 * Updates an existing $instance in the database.
195
	 * Be careful not to modify the primary key
196
	 *
197
	 * @param object $instance
198
	 *        	instance to modify
199
	 * @param boolean $updateMany
200
	 *        	Adds or updates ManyToMany members
201
	 */
202
	public static function update($instance, $updateMany = false) {
203
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
204
		$ColumnskeyAndValues = Reflexion::getPropertiesAndValues ( $instance );
205
		$ColumnskeyAndValues = array_merge ( $ColumnskeyAndValues, OrmUtils::getManyToOneMembersAndValues ( $instance ) );
206
		$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
207
		$sql = "UPDATE `" . $tableName . "` SET " . SqlUtils::getUpdateFieldsKeyAndValues ( $ColumnskeyAndValues ) . " WHERE " . SqlUtils::getWhere ( $keyFieldsAndValues );
208
		Logger::info ( "DAOUpdates", $sql,"update" );
209
		Logger::info ("DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
210
		$statement = self::$db->prepareStatement ( $sql );
211
		foreach ( $ColumnskeyAndValues as $key => $value ) {
212
			self::$db->bindValueFromStatement ( $statement, $key, $value );
213
		}
214
		try{
215
			$result = $statement->execute ();
216
			if ($result && $updateMany)
217
				self::insertOrUpdateAllManyToMany ( $instance );
218
			return $result;
219
		}catch(\PDOException $e){
220
			Logger::warn("DAOUpdates",  $e->getMessage() ,"update");
221
		}
222
		return false;
223
	}
224
225
	/**
226
	 *
227
	 * @param object $instance
228
	 * @param boolean $updateMany
229
	 * @return int
230
	 */
231
	public static function save($instance, $updateMany = false) {
232
		if (isset ( $instance->_rest )) {
233
			return self::update ( $instance, $updateMany );
234
		}
235
		return self::insert ( $instance, $updateMany );
236
	}
237
}
238