Passed
Push — master ( 82db47...968994 )
by Jean-Christophe
07:17
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\db\SqlUtils;
6
use Ubiquity\events\DAOEvents;
7
use Ubiquity\events\EventsManager;
8
use Ubiquity\log\Logger;
9
use Ubiquity\orm\OrmUtils;
10
use Ubiquity\orm\parser\ManyToManyParser;
11
use Ubiquity\orm\parser\Reflexion;
12
13
/**
14
 * Trait for DAO Updates (Create, Update, Delete)
15
 * Ubiquity\orm\traits$DAOUpdatesTrait
16
 * This class is part of Ubiquity
17
 *
18
 * @author jcheron <[email protected]>
19
 * @version 1.0.3
20
 * @property \Ubiquity\db\Database $db
21
 *
22
 */
23
trait DAOUpdatesTrait {
24
25
	/**
26
	 * Deletes the object $instance from the database
27
	 *
28
	 * @param object $instance instance à supprimer
29
	 */
30 4
	public static function remove($instance) {
31 4
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
32 4
		$keyAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
33 4
		return self::removeByKey_ ( $tableName, $keyAndValues );
34
	}
35
36
	/**
37
	 *
38
	 * @param string $tableName
39
	 * @param array $keyAndValues
40
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
41
	 */
42 4
	private static function removeByKey_($tableName, $keyAndValues) {
43 4
		$sql = "DELETE FROM " . $tableName . " WHERE " . SqlUtils::getWhere ( $keyAndValues );
44 4
		Logger::info ( "DAOUpdates", $sql, "delete" );
45 4
		$statement = self::$db->prepareStatement ( $sql );
46
		try {
47 4
			if ($statement->execute ( $keyAndValues )) {
48 3
				return $statement->rowCount ();
49
			}
50 1
		} catch ( \PDOException $e ) {
51 1
			Logger::warn ( "DAOUpdates", $e->getMessage (), "delete" );
52 1
			return;
53
		}
54
		return;
55
	}
56
57
	/**
58
	 *
59
	 * @param string $tableName
60
	 * @param string $where
61
	 * @return boolean|int the number of rows that were modified or deleted by the SQL statement you issued
62
	 */
63
	private static function remove_($tableName, $where) {
64
		$sql = "DELETE FROM `" . $tableName . "` " . SqlUtils::checkWhere ( $where );
65
		Logger::info ( "DAOUpdates", $sql, "delete" );
66
		$statement = self::$db->prepareStatement ( $sql );
67
		try {
68
			if ($statement->execute ()) {
69
				return $statement->rowCount ();
70
			}
71
		} catch ( \PDOException $e ) {
72
			Logger::warn ( "DAOUpdates", $e->getMessage (), "delete" );
73
			return false;
74
		}
75
	}
76
77
	/**
78
	 * Deletes all instances from $modelName matching the condition $where
79
	 *
80
	 * @param string $modelName
81
	 * @param string $where
82
	 * @return int|boolean
83
	 */
84
	public static function deleteAll($modelName, $where) {
85
		$tableName = OrmUtils::getTableName ( $modelName );
86
		return self::remove_ ( $tableName, $where );
87
	}
88
89
	/**
90
	 * Deletes all instances from $modelName corresponding to $ids
91
	 *
92
	 * @param string $modelName
93
	 * @param array|int $ids
94
	 * @return int|boolean
95
	 */
96
	public static function delete($modelName, $ids) {
97
		$tableName = OrmUtils::getTableName ( $modelName );
98
		$pk = OrmUtils::getFirstKey ( $modelName );
99
		if (! \is_array ( $ids )) {
100
			$ids = [ $ids ];
101
		}
102
		$where = SqlUtils::getMultiWhere ( $ids, $pk );
103
		return self::remove_ ( $tableName, $where );
104
	}
105
106
	/**
107
	 * Inserts a new instance $instance into the database
108
	 *
109
	 * @param object $instance the instance to insert
110
	 * @param boolean $insertMany if true, save instances related to $instance by a ManyToMany association
111
	 */
112 3
	public static function insert($instance, $insertMany = false) {
113 3
		EventsManager::trigger ( 'dao.before.insert', $instance );
114 3
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
115 3
		$keyAndValues = Reflexion::getPropertiesAndValues ( $instance );
116 3
		$keyAndValues = array_merge ( $keyAndValues, OrmUtils::getManyToOneMembersAndValues ( $instance ) );
117 3
		$sql = "INSERT INTO `" . $tableName . "`(" . SqlUtils::getInsertFields ( $keyAndValues ) . ") VALUES(" . SqlUtils::getInsertFieldsValues ( $keyAndValues ) . ")";
118 3
		if (Logger::isActive ()) {
119 3
			Logger::info ( "DAOUpdates", $sql, "insert" );
120 3
			Logger::info ( "DAOUpdates", json_encode ( $keyAndValues ), "Key and values" );
121
		}
122 3
		$statement = self::$db->prepareStatement ( $sql );
123
		try {
124 3
			$result = $statement->execute ( $keyAndValues );
125 3
			if ($result) {
126 3
				$pk = OrmUtils::getFirstKey ( get_class ( $instance ) );
127 3
				$accesseurId = "set" . ucfirst ( $pk );
128 3
				$lastId = self::$db->lastInserId ();
129 3
				if ($lastId != 0) {
130 3
					$instance->$accesseurId ( $lastId );
131 3
					$instance->_rest = $keyAndValues;
132 3
					$instance->_rest [$pk] = $lastId;
133
				}
134 3
				if ($insertMany) {
135 1
					self::insertOrUpdateAllManyToMany ( $instance );
136
				}
137
			}
138 3
			EventsManager::trigger ( DAOEvents::AFTER_INSERT, $instance, $result );
139 3
			return $result;
140 1
		} catch ( \PDOException $e ) {
141 1
			Logger::warn ( "DAOUpdates", $e->getMessage (), "insert" );
142
		}
143 1
		return false;
144
	}
145
146
	/**
147
	 * Met à jour les membres de $instance annotés par un ManyToMany
148
	 *
149
	 * @param object $instance
150
	 */
151 1
	public static function insertOrUpdateAllManyToMany($instance) {
152 1
		$members = OrmUtils::getAnnotationInfo ( get_class ( $instance ), "#manyToMany" );
153 1
		if ($members !== false) {
154
			$members = \array_keys ( $members );
155
			foreach ( $members as $member ) {
156
				self::insertOrUpdateManyToMany ( $instance, $member );
157
			}
158
		}
159 1
	}
160
161
	/**
162
	 * Updates the $member member of $instance annotated by a ManyToMany
163
	 *
164
	 * @param Object $instance
165
	 * @param String $member
166
	 */
167
	public static function insertOrUpdateManyToMany($instance, $member) {
168
		$parser = new ManyToManyParser ( $instance, $member );
169
		if ($parser->init ()) {
170
			$myField = $parser->getMyFkField ();
171
			$field = $parser->getFkField ();
172
			$sql = "INSERT INTO `" . $parser->getJoinTable () . "`(`" . $myField . "`,`" . $field . "`) VALUES (:" . $myField . ",:" . $field . ");";
173
			$memberAccessor = "get" . ucfirst ( $member );
174
			$memberValues = $instance->$memberAccessor ();
175
			$myKey = $parser->getMyPk ();
176
			$myAccessorId = "get" . ucfirst ( $myKey );
177
			$accessorId = "get" . ucfirst ( $parser->getPk () );
178
			$id = $instance->$myAccessorId ();
179
			if (! is_null ( $memberValues )) {
180
				self::$db->execute ( "DELETE FROM `" . $parser->getJoinTable () . "` WHERE `" . $myField . "`='" . $id . "'" );
181
				$statement = self::$db->prepareStatement ( $sql );
182
				foreach ( $memberValues as $targetInstance ) {
183
					$foreignId = $targetInstance->$accessorId ();
184
					$foreignInstances = self::getAll ( $parser->getTargetEntity (), "`" . $parser->getPk () . "`" . "='" . $foreignId . "'" );
185
					if (! OrmUtils::exists ( $targetInstance, $parser->getPk (), $foreignInstances )) {
186
						self::insert ( $targetInstance, false );
187
						$foreignId = $targetInstance->$accessorId ();
188
						Logger::info ( "DAOUpdates", "Insertion d'une instance de " . get_class ( $instance ), "InsertMany" );
189
					}
190
					self::$db->bindValueFromStatement ( $statement, $myField, $id );
1 ignored issue
show
Bug introduced by
It seems like $statement can also be of type boolean; however, parameter $statement of Ubiquity\db\Database::bindValueFromStatement() does only seem to accept PDOStatement, 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

190
					self::$db->bindValueFromStatement ( /** @scrutinizer ignore-type */ $statement, $myField, $id );
Loading history...
191
					self::$db->bindValueFromStatement ( $statement, $field, $foreignId );
192
					$statement->execute ();
193
					Logger::info ( "DAOUpdates", "Insertion des valeurs dans la table association '" . $parser->getJoinTable () . "'", "InsertMany" );
194
				}
195
			}
196
		}
197
	}
198
199
	/**
200
	 * Updates an existing $instance in the database.
201
	 * Be careful not to modify the primary key
202
	 *
203
	 * @param object $instance instance to modify
204
	 * @param boolean $updateMany Adds or updates ManyToMany members
205
	 */
206 3
	public static function update($instance, $updateMany = false) {
207 3
		EventsManager::trigger ( "dao.before.update", $instance );
208 3
		$tableName = OrmUtils::getTableName ( get_class ( $instance ) );
209 3
		$ColumnskeyAndValues = Reflexion::getPropertiesAndValues ( $instance );
210 3
		$ColumnskeyAndValues = array_merge ( $ColumnskeyAndValues, OrmUtils::getManyToOneMembersAndValues ( $instance ) );
211 3
		$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
212 3
		$sql = "UPDATE `" . $tableName . "` SET " . SqlUtils::getUpdateFieldsKeyAndValues ( $ColumnskeyAndValues ) . " WHERE " . SqlUtils::getWhere ( $keyFieldsAndValues );
213 3
		if (Logger::isActive ()) {
214 3
			Logger::info ( "DAOUpdates", $sql, "update" );
215 3
			Logger::info ( "DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
216
		}
217 3
		$statement = self::$db->prepareStatement ( $sql );
218
		try {
219 3
			$result = $statement->execute ( $ColumnskeyAndValues );
220 3
			if ($result && $updateMany)
221 1
				self::insertOrUpdateAllManyToMany ( $instance );
222 3
			EventsManager::trigger ( DAOEvents::AFTER_UPDATE, $instance, $result );
223 3
			$instance->_rest = array_merge ( $instance->_rest, $ColumnskeyAndValues );
224 3
			return $result;
225
		} catch ( \PDOException $e ) {
226
			Logger::warn ( "DAOUpdates", $e->getMessage (), "update" );
227
		}
228
		return false;
229
	}
230
231
	/**
232
	 *
233
	 * @param object $instance
234
	 * @param boolean $updateMany
235
	 * @return boolean|int
236
	 */
237
	public static function save($instance, $updateMany = false) {
238
		if (isset ( $instance->_rest )) {
239
			return self::update ( $instance, $updateMany );
240
		}
241
		return self::insert ( $instance, $updateMany );
242
	}
243
}
244