Completed
Push — master ( 3ee6aa...f7422c )
by Jean-Christophe
02:00
created

DAOUpdatesTrait::removeByKey_()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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