Completed
Pull Request — 4.2 (#130)
by Jean-Baptiste
04:47
created
src/Mouf/Database/TDBM/TDBMService.php 1 patch
Indentation   +1405 added lines, -1405 removed lines patch added patch discarded remove patch
@@ -47,236 +47,236 @@  discard block
 block discarded – undo
47 47
  */
48 48
 class TDBMService
49 49
 {
50
-    const MODE_CURSOR = 1;
51
-    const MODE_ARRAY = 2;
52
-
53
-    /**
54
-     * The database connection.
55
-     *
56
-     * @var Connection
57
-     */
58
-    private $connection;
59
-
60
-    /**
61
-     * @var SchemaAnalyzer
62
-     */
63
-    private $schemaAnalyzer;
64
-
65
-    /**
66
-     * @var MagicQuery
67
-     */
68
-    private $magicQuery;
69
-
70
-    /**
71
-     * @var TDBMSchemaAnalyzer
72
-     */
73
-    private $tdbmSchemaAnalyzer;
74
-
75
-    /**
76
-     * @var string
77
-     */
78
-    private $cachePrefix;
79
-
80
-    /**
81
-     * Cache of table of primary keys.
82
-     * Primary keys are stored by tables, as an array of column.
83
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
84
-     *
85
-     * @var string[]
86
-     */
87
-    private $primaryKeysColumns;
88
-
89
-    /**
90
-     * Service storing objects in memory.
91
-     * Access is done by table name and then by primary key.
92
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
93
-     *
94
-     * @var StandardObjectStorage|WeakrefObjectStorage
95
-     */
96
-    private $objectStorage;
97
-
98
-    /**
99
-     * The fetch mode of the result sets returned by `getObjects`.
100
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
101
-     *
102
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
103
-     * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
104
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
105
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
106
-     * You can access the array by key, or using foreach, several times.
107
-     *
108
-     * @var int
109
-     */
110
-    private $mode = self::MODE_ARRAY;
111
-
112
-    /**
113
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
114
-     *
115
-     * @var \SplObjectStorage of DbRow objects
116
-     */
117
-    private $toSaveObjects;
118
-
119
-    /**
120
-     * A cache service to be used.
121
-     *
122
-     * @var Cache|null
123
-     */
124
-    private $cache;
125
-
126
-    /**
127
-     * Map associating a table name to a fully qualified Bean class name.
128
-     *
129
-     * @var array
130
-     */
131
-    private $tableToBeanMap = [];
132
-
133
-    /**
134
-     * @var \ReflectionClass[]
135
-     */
136
-    private $reflectionClassCache = array();
137
-
138
-    /**
139
-     * @var LoggerInterface
140
-     */
141
-    private $rootLogger;
142
-
143
-    /**
144
-     * @var LevelFilter|NullLogger
145
-     */
146
-    private $logger;
147
-
148
-    /**
149
-     * @var OrderByAnalyzer
150
-     */
151
-    private $orderByAnalyzer;
152
-
153
-    /**
154
-     * @param Connection     $connection     The DBAL DB connection to use
155
-     * @param Cache|null     $cache          A cache service to be used
156
-     * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
157
-     *                                       Will be automatically created if not passed
158
-     */
159
-    public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
160
-    {
161
-        if (extension_loaded('weakref')) {
162
-            $this->objectStorage = new WeakrefObjectStorage();
163
-        } else {
164
-            $this->objectStorage = new StandardObjectStorage();
165
-        }
166
-        $this->connection = $connection;
167
-        if ($cache !== null) {
168
-            $this->cache = $cache;
169
-        } else {
170
-            $this->cache = new VoidCache();
171
-        }
172
-        if ($schemaAnalyzer) {
173
-            $this->schemaAnalyzer = $schemaAnalyzer;
174
-        } else {
175
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
176
-        }
177
-
178
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
179
-
180
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
181
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
182
-
183
-        $this->toSaveObjects = new \SplObjectStorage();
184
-        if ($logger === null) {
185
-            $this->logger = new NullLogger();
186
-            $this->rootLogger = new NullLogger();
187
-        } else {
188
-            $this->rootLogger = $logger;
189
-            $this->setLogLevel(LogLevel::WARNING);
190
-        }
191
-        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
192
-    }
193
-
194
-    /**
195
-     * Returns the object used to connect to the database.
196
-     *
197
-     * @return Connection
198
-     */
199
-    public function getConnection()
200
-    {
201
-        return $this->connection;
202
-    }
203
-
204
-    /**
205
-     * Creates a unique cache key for the current connection.
206
-     *
207
-     * @return string
208
-     */
209
-    private function getConnectionUniqueId()
210
-    {
211
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
212
-    }
213
-
214
-    /**
215
-     * Sets the default fetch mode of the result sets returned by `findObjects`.
216
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
217
-     *
218
-     * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
219
-     * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
220
-     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
221
-     *
222
-     * @param int $mode
223
-     *
224
-     * @return $this
225
-     *
226
-     * @throws TDBMException
227
-     */
228
-    public function setFetchMode($mode)
229
-    {
230
-        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
231
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
232
-        }
233
-        $this->mode = $mode;
234
-
235
-        return $this;
236
-    }
237
-
238
-    /**
239
-     * Returns a TDBMObject associated from table "$table_name".
240
-     * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
241
-     * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
242
-     *
243
-     * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
244
-     * 			$user = $tdbmService->getObject('users',1);
245
-     * 			echo $user->name;
246
-     * will return the name of the user whose user_id is one.
247
-     *
248
-     * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
249
-     * For instance:
250
-     * 			$group = $tdbmService->getObject('groups',array(1,2));
251
-     *
252
-     * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
253
-     * will be the same.
254
-     *
255
-     * For instance:
256
-     * 			$user1 = $tdbmService->getObject('users',1);
257
-     * 			$user2 = $tdbmService->getObject('users',1);
258
-     * 			$user1->name = 'John Doe';
259
-     * 			echo $user2->name;
260
-     * will return 'John Doe'.
261
-     *
262
-     * You can use filters instead of passing the primary key. For instance:
263
-     * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
264
-     * This will return the user whose login is 'jdoe'.
265
-     * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
266
-     *
267
-     * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
268
-     * For instance:
269
-     *  	$user = $tdbmService->getObject('users',1,'User');
270
-     * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
271
-     * Please be sure not to override any method or any property unless you perfectly know what you are doing!
272
-     *
273
-     * @param string $table_name   The name of the table we retrieve an object from
274
-     * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
275
-     * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
276
-     * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
277
-     *
278
-     * @return TDBMObject
279
-     */
50
+	const MODE_CURSOR = 1;
51
+	const MODE_ARRAY = 2;
52
+
53
+	/**
54
+	 * The database connection.
55
+	 *
56
+	 * @var Connection
57
+	 */
58
+	private $connection;
59
+
60
+	/**
61
+	 * @var SchemaAnalyzer
62
+	 */
63
+	private $schemaAnalyzer;
64
+
65
+	/**
66
+	 * @var MagicQuery
67
+	 */
68
+	private $magicQuery;
69
+
70
+	/**
71
+	 * @var TDBMSchemaAnalyzer
72
+	 */
73
+	private $tdbmSchemaAnalyzer;
74
+
75
+	/**
76
+	 * @var string
77
+	 */
78
+	private $cachePrefix;
79
+
80
+	/**
81
+	 * Cache of table of primary keys.
82
+	 * Primary keys are stored by tables, as an array of column.
83
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
84
+	 *
85
+	 * @var string[]
86
+	 */
87
+	private $primaryKeysColumns;
88
+
89
+	/**
90
+	 * Service storing objects in memory.
91
+	 * Access is done by table name and then by primary key.
92
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
93
+	 *
94
+	 * @var StandardObjectStorage|WeakrefObjectStorage
95
+	 */
96
+	private $objectStorage;
97
+
98
+	/**
99
+	 * The fetch mode of the result sets returned by `getObjects`.
100
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
101
+	 *
102
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
103
+	 * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
104
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
105
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
106
+	 * You can access the array by key, or using foreach, several times.
107
+	 *
108
+	 * @var int
109
+	 */
110
+	private $mode = self::MODE_ARRAY;
111
+
112
+	/**
113
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
114
+	 *
115
+	 * @var \SplObjectStorage of DbRow objects
116
+	 */
117
+	private $toSaveObjects;
118
+
119
+	/**
120
+	 * A cache service to be used.
121
+	 *
122
+	 * @var Cache|null
123
+	 */
124
+	private $cache;
125
+
126
+	/**
127
+	 * Map associating a table name to a fully qualified Bean class name.
128
+	 *
129
+	 * @var array
130
+	 */
131
+	private $tableToBeanMap = [];
132
+
133
+	/**
134
+	 * @var \ReflectionClass[]
135
+	 */
136
+	private $reflectionClassCache = array();
137
+
138
+	/**
139
+	 * @var LoggerInterface
140
+	 */
141
+	private $rootLogger;
142
+
143
+	/**
144
+	 * @var LevelFilter|NullLogger
145
+	 */
146
+	private $logger;
147
+
148
+	/**
149
+	 * @var OrderByAnalyzer
150
+	 */
151
+	private $orderByAnalyzer;
152
+
153
+	/**
154
+	 * @param Connection     $connection     The DBAL DB connection to use
155
+	 * @param Cache|null     $cache          A cache service to be used
156
+	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
157
+	 *                                       Will be automatically created if not passed
158
+	 */
159
+	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
160
+	{
161
+		if (extension_loaded('weakref')) {
162
+			$this->objectStorage = new WeakrefObjectStorage();
163
+		} else {
164
+			$this->objectStorage = new StandardObjectStorage();
165
+		}
166
+		$this->connection = $connection;
167
+		if ($cache !== null) {
168
+			$this->cache = $cache;
169
+		} else {
170
+			$this->cache = new VoidCache();
171
+		}
172
+		if ($schemaAnalyzer) {
173
+			$this->schemaAnalyzer = $schemaAnalyzer;
174
+		} else {
175
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
176
+		}
177
+
178
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
179
+
180
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
181
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
182
+
183
+		$this->toSaveObjects = new \SplObjectStorage();
184
+		if ($logger === null) {
185
+			$this->logger = new NullLogger();
186
+			$this->rootLogger = new NullLogger();
187
+		} else {
188
+			$this->rootLogger = $logger;
189
+			$this->setLogLevel(LogLevel::WARNING);
190
+		}
191
+		$this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
192
+	}
193
+
194
+	/**
195
+	 * Returns the object used to connect to the database.
196
+	 *
197
+	 * @return Connection
198
+	 */
199
+	public function getConnection()
200
+	{
201
+		return $this->connection;
202
+	}
203
+
204
+	/**
205
+	 * Creates a unique cache key for the current connection.
206
+	 *
207
+	 * @return string
208
+	 */
209
+	private function getConnectionUniqueId()
210
+	{
211
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
212
+	}
213
+
214
+	/**
215
+	 * Sets the default fetch mode of the result sets returned by `findObjects`.
216
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
217
+	 *
218
+	 * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
219
+	 * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
220
+	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
221
+	 *
222
+	 * @param int $mode
223
+	 *
224
+	 * @return $this
225
+	 *
226
+	 * @throws TDBMException
227
+	 */
228
+	public function setFetchMode($mode)
229
+	{
230
+		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
231
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
232
+		}
233
+		$this->mode = $mode;
234
+
235
+		return $this;
236
+	}
237
+
238
+	/**
239
+	 * Returns a TDBMObject associated from table "$table_name".
240
+	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
241
+	 * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
242
+	 *
243
+	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
244
+	 * 			$user = $tdbmService->getObject('users',1);
245
+	 * 			echo $user->name;
246
+	 * will return the name of the user whose user_id is one.
247
+	 *
248
+	 * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
249
+	 * For instance:
250
+	 * 			$group = $tdbmService->getObject('groups',array(1,2));
251
+	 *
252
+	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
253
+	 * will be the same.
254
+	 *
255
+	 * For instance:
256
+	 * 			$user1 = $tdbmService->getObject('users',1);
257
+	 * 			$user2 = $tdbmService->getObject('users',1);
258
+	 * 			$user1->name = 'John Doe';
259
+	 * 			echo $user2->name;
260
+	 * will return 'John Doe'.
261
+	 *
262
+	 * You can use filters instead of passing the primary key. For instance:
263
+	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
264
+	 * This will return the user whose login is 'jdoe'.
265
+	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
266
+	 *
267
+	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
268
+	 * For instance:
269
+	 *  	$user = $tdbmService->getObject('users',1,'User');
270
+	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
271
+	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
272
+	 *
273
+	 * @param string $table_name   The name of the table we retrieve an object from
274
+	 * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
275
+	 * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
276
+	 * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
277
+	 *
278
+	 * @return TDBMObject
279
+	 */
280 280
 /*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
281 281
 
282 282
         if (is_array($filters) || $filters instanceof FilterInterface) {
@@ -362,199 +362,199 @@  discard block
 block discarded – undo
362 362
         return $obj;
363 363
     }*/
364 364
 
365
-    /**
366
-     * Removes the given object from database.
367
-     * This cannot be called on an object that is not attached to this TDBMService
368
-     * (will throw a TDBMInvalidOperationException).
369
-     *
370
-     * @param AbstractTDBMObject $object the object to delete
371
-     *
372
-     * @throws TDBMException
373
-     * @throws TDBMInvalidOperationException
374
-     */
375
-    public function delete(AbstractTDBMObject $object)
376
-    {
377
-        switch ($object->_getStatus()) {
378
-            case TDBMObjectStateEnum::STATE_DELETED:
379
-                // Nothing to do, object already deleted.
380
-                return;
381
-            case TDBMObjectStateEnum::STATE_DETACHED:
382
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
-            case TDBMObjectStateEnum::STATE_NEW:
384
-                $this->deleteManyToManyRelationships($object);
385
-                foreach ($object->_getDbRows() as $dbRow) {
386
-                    $this->removeFromToSaveObjectList($dbRow);
387
-                }
388
-                break;
389
-            case TDBMObjectStateEnum::STATE_DIRTY:
390
-                foreach ($object->_getDbRows() as $dbRow) {
391
-                    $this->removeFromToSaveObjectList($dbRow);
392
-                }
393
-                // And continue deleting...
394
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
395
-            case TDBMObjectStateEnum::STATE_LOADED:
396
-                $this->deleteManyToManyRelationships($object);
397
-                // Let's delete db rows, in reverse order.
398
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
399
-                    $tableName = $dbRow->_getDbTableName();
400
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
401
-                    $this->connection->delete($tableName, $primaryKeys);
402
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
403
-                }
404
-                break;
405
-            // @codeCoverageIgnoreStart
406
-            default:
407
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
408
-            // @codeCoverageIgnoreEnd
409
-        }
410
-
411
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
412
-    }
413
-
414
-    /**
415
-     * Removes all many to many relationships for this object.
416
-     *
417
-     * @param AbstractTDBMObject $object
418
-     */
419
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
420
-    {
421
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
422
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
423
-            foreach ($pivotTables as $pivotTable) {
424
-                $remoteBeans = $object->_getRelationships($pivotTable);
425
-                foreach ($remoteBeans as $remoteBean) {
426
-                    $object->_removeRelationship($pivotTable, $remoteBean);
427
-                }
428
-            }
429
-        }
430
-        $this->persistManyToManyRelationships($object);
431
-    }
432
-
433
-    /**
434
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
435
-     * by parameter before all.
436
-     *
437
-     * Notice: if the object has a multiple primary key, the function will not work.
438
-     *
439
-     * @param AbstractTDBMObject $objToDelete
440
-     */
441
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
442
-    {
443
-        $this->deleteAllConstraintWithThisObject($objToDelete);
444
-        $this->delete($objToDelete);
445
-    }
446
-
447
-    /**
448
-     * This function is used only in TDBMService (private function)
449
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
450
-     *
451
-     * @param AbstractTDBMObject $obj
452
-     */
453
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
454
-    {
455
-        $dbRows = $obj->_getDbRows();
456
-        foreach ($dbRows as $dbRow) {
457
-            $tableName = $dbRow->_getDbTableName();
458
-            $pks = array_values($dbRow->_getPrimaryKeys());
459
-            if (!empty($pks)) {
460
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
461
-
462
-                foreach ($incomingFks as $incomingFk) {
463
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
464
-
465
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
466
-
467
-                    foreach ($results as $bean) {
468
-                        $this->deleteCascade($bean);
469
-                    }
470
-                }
471
-            }
472
-        }
473
-    }
474
-
475
-    /**
476
-     * This function performs a save() of all the objects that have been modified.
477
-     */
478
-    public function completeSave()
479
-    {
480
-        foreach ($this->toSaveObjects as $dbRow) {
481
-            $this->save($dbRow->getTDBMObject());
482
-        }
483
-    }
484
-
485
-    /**
486
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
487
-     * and gives back a proper Filter object.
488
-     *
489
-     * @param mixed $filter_bag
490
-     * @param int   $counter
491
-     *
492
-     * @return array First item: filter string, second item: parameters
493
-     *
494
-     * @throws TDBMException
495
-     */
496
-    public function buildFilterFromFilterBag($filter_bag, $counter = 1)
497
-    {
498
-        if ($filter_bag === null) {
499
-            return ['', []];
500
-        } elseif (is_string($filter_bag)) {
501
-            return [$filter_bag, []];
502
-        } elseif (is_array($filter_bag)) {
503
-            $sqlParts = [];
504
-            $parameters = [];
505
-            foreach ($filter_bag as $column => $value) {
506
-                if (is_int($column)) {
507
-                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
508
-                    $sqlParts[] = $subSqlPart;
509
-                    $parameters += $subParameters;
510
-                } else {
511
-                    $paramName = 'tdbmparam'.$counter;
512
-                    if (is_array($value)) {
513
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
514
-                    } else {
515
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
516
-                    }
517
-                    $parameters[$paramName] = $value;
518
-                    ++$counter;
519
-                }
520
-            }
521
-
522
-            return [implode(' AND ', $sqlParts), $parameters];
523
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
524
-            $sqlParts = [];
525
-            $parameters = [];
526
-            $dbRows = $filter_bag->_getDbRows();
527
-            $dbRow = reset($dbRows);
528
-            $primaryKeys = $dbRow->_getPrimaryKeys();
529
-
530
-            foreach ($primaryKeys as $column => $value) {
531
-                $paramName = 'tdbmparam'.$counter;
532
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
533
-                $parameters[$paramName] = $value;
534
-                ++$counter;
535
-            }
536
-
537
-            return [implode(' AND ', $sqlParts), $parameters];
538
-        } elseif ($filter_bag instanceof \Iterator) {
539
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
540
-        } else {
541
-            throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
542
-        }
543
-    }
544
-
545
-    /**
546
-     * @param string $table
547
-     *
548
-     * @return string[]
549
-     */
550
-    public function getPrimaryKeyColumns($table)
551
-    {
552
-        if (!isset($this->primaryKeysColumns[$table])) {
553
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
554
-
555
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
556
-
557
-            /*$arr = array();
365
+	/**
366
+	 * Removes the given object from database.
367
+	 * This cannot be called on an object that is not attached to this TDBMService
368
+	 * (will throw a TDBMInvalidOperationException).
369
+	 *
370
+	 * @param AbstractTDBMObject $object the object to delete
371
+	 *
372
+	 * @throws TDBMException
373
+	 * @throws TDBMInvalidOperationException
374
+	 */
375
+	public function delete(AbstractTDBMObject $object)
376
+	{
377
+		switch ($object->_getStatus()) {
378
+			case TDBMObjectStateEnum::STATE_DELETED:
379
+				// Nothing to do, object already deleted.
380
+				return;
381
+			case TDBMObjectStateEnum::STATE_DETACHED:
382
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
+			case TDBMObjectStateEnum::STATE_NEW:
384
+				$this->deleteManyToManyRelationships($object);
385
+				foreach ($object->_getDbRows() as $dbRow) {
386
+					$this->removeFromToSaveObjectList($dbRow);
387
+				}
388
+				break;
389
+			case TDBMObjectStateEnum::STATE_DIRTY:
390
+				foreach ($object->_getDbRows() as $dbRow) {
391
+					$this->removeFromToSaveObjectList($dbRow);
392
+				}
393
+				// And continue deleting...
394
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
395
+			case TDBMObjectStateEnum::STATE_LOADED:
396
+				$this->deleteManyToManyRelationships($object);
397
+				// Let's delete db rows, in reverse order.
398
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
399
+					$tableName = $dbRow->_getDbTableName();
400
+					$primaryKeys = $dbRow->_getPrimaryKeys();
401
+					$this->connection->delete($tableName, $primaryKeys);
402
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
403
+				}
404
+				break;
405
+			// @codeCoverageIgnoreStart
406
+			default:
407
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
408
+			// @codeCoverageIgnoreEnd
409
+		}
410
+
411
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
412
+	}
413
+
414
+	/**
415
+	 * Removes all many to many relationships for this object.
416
+	 *
417
+	 * @param AbstractTDBMObject $object
418
+	 */
419
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
420
+	{
421
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
422
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
423
+			foreach ($pivotTables as $pivotTable) {
424
+				$remoteBeans = $object->_getRelationships($pivotTable);
425
+				foreach ($remoteBeans as $remoteBean) {
426
+					$object->_removeRelationship($pivotTable, $remoteBean);
427
+				}
428
+			}
429
+		}
430
+		$this->persistManyToManyRelationships($object);
431
+	}
432
+
433
+	/**
434
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
435
+	 * by parameter before all.
436
+	 *
437
+	 * Notice: if the object has a multiple primary key, the function will not work.
438
+	 *
439
+	 * @param AbstractTDBMObject $objToDelete
440
+	 */
441
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
442
+	{
443
+		$this->deleteAllConstraintWithThisObject($objToDelete);
444
+		$this->delete($objToDelete);
445
+	}
446
+
447
+	/**
448
+	 * This function is used only in TDBMService (private function)
449
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
450
+	 *
451
+	 * @param AbstractTDBMObject $obj
452
+	 */
453
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
454
+	{
455
+		$dbRows = $obj->_getDbRows();
456
+		foreach ($dbRows as $dbRow) {
457
+			$tableName = $dbRow->_getDbTableName();
458
+			$pks = array_values($dbRow->_getPrimaryKeys());
459
+			if (!empty($pks)) {
460
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
461
+
462
+				foreach ($incomingFks as $incomingFk) {
463
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
464
+
465
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
466
+
467
+					foreach ($results as $bean) {
468
+						$this->deleteCascade($bean);
469
+					}
470
+				}
471
+			}
472
+		}
473
+	}
474
+
475
+	/**
476
+	 * This function performs a save() of all the objects that have been modified.
477
+	 */
478
+	public function completeSave()
479
+	{
480
+		foreach ($this->toSaveObjects as $dbRow) {
481
+			$this->save($dbRow->getTDBMObject());
482
+		}
483
+	}
484
+
485
+	/**
486
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
487
+	 * and gives back a proper Filter object.
488
+	 *
489
+	 * @param mixed $filter_bag
490
+	 * @param int   $counter
491
+	 *
492
+	 * @return array First item: filter string, second item: parameters
493
+	 *
494
+	 * @throws TDBMException
495
+	 */
496
+	public function buildFilterFromFilterBag($filter_bag, $counter = 1)
497
+	{
498
+		if ($filter_bag === null) {
499
+			return ['', []];
500
+		} elseif (is_string($filter_bag)) {
501
+			return [$filter_bag, []];
502
+		} elseif (is_array($filter_bag)) {
503
+			$sqlParts = [];
504
+			$parameters = [];
505
+			foreach ($filter_bag as $column => $value) {
506
+				if (is_int($column)) {
507
+					list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
508
+					$sqlParts[] = $subSqlPart;
509
+					$parameters += $subParameters;
510
+				} else {
511
+					$paramName = 'tdbmparam'.$counter;
512
+					if (is_array($value)) {
513
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
514
+					} else {
515
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
516
+					}
517
+					$parameters[$paramName] = $value;
518
+					++$counter;
519
+				}
520
+			}
521
+
522
+			return [implode(' AND ', $sqlParts), $parameters];
523
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
524
+			$sqlParts = [];
525
+			$parameters = [];
526
+			$dbRows = $filter_bag->_getDbRows();
527
+			$dbRow = reset($dbRows);
528
+			$primaryKeys = $dbRow->_getPrimaryKeys();
529
+
530
+			foreach ($primaryKeys as $column => $value) {
531
+				$paramName = 'tdbmparam'.$counter;
532
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
533
+				$parameters[$paramName] = $value;
534
+				++$counter;
535
+			}
536
+
537
+			return [implode(' AND ', $sqlParts), $parameters];
538
+		} elseif ($filter_bag instanceof \Iterator) {
539
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
540
+		} else {
541
+			throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
542
+		}
543
+	}
544
+
545
+	/**
546
+	 * @param string $table
547
+	 *
548
+	 * @return string[]
549
+	 */
550
+	public function getPrimaryKeyColumns($table)
551
+	{
552
+		if (!isset($this->primaryKeysColumns[$table])) {
553
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
554
+
555
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
556
+
557
+			/*$arr = array();
558 558
             foreach ($this->connection->getPrimaryKey($table) as $col) {
559 559
                 $arr[] = $col->name;
560 560
             }
@@ -575,166 +575,166 @@  discard block
 block discarded – undo
575 575
                     throw new TDBMException($str);
576 576
                 }
577 577
             }*/
578
-        }
579
-
580
-        return $this->primaryKeysColumns[$table];
581
-    }
582
-
583
-    /**
584
-     * This is an internal function, you should not use it in your application.
585
-     * This is used internally by TDBM to add an object to the object cache.
586
-     *
587
-     * @param DbRow $dbRow
588
-     */
589
-    public function _addToCache(DbRow $dbRow)
590
-    {
591
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
592
-        $hash = $this->getObjectHash($primaryKey);
593
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
594
-    }
595
-
596
-    /**
597
-     * This is an internal function, you should not use it in your application.
598
-     * This is used internally by TDBM to remove the object from the list of objects that have been
599
-     * created/updated but not saved yet.
600
-     *
601
-     * @param DbRow $myObject
602
-     */
603
-    private function removeFromToSaveObjectList(DbRow $myObject)
604
-    {
605
-        unset($this->toSaveObjects[$myObject]);
606
-    }
607
-
608
-    /**
609
-     * This is an internal function, you should not use it in your application.
610
-     * This is used internally by TDBM to add an object to the list of objects that have been
611
-     * created/updated but not saved yet.
612
-     *
613
-     * @param AbstractTDBMObject $myObject
614
-     */
615
-    public function _addToToSaveObjectList(DbRow $myObject)
616
-    {
617
-        $this->toSaveObjects[$myObject] = true;
618
-    }
619
-
620
-    /**
621
-     * Generates all the daos and beans.
622
-     *
623
-     * @param string $daoFactoryClassName The classe name of the DAO factory
624
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
625
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
626
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
627
-     * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
628
-     *
629
-     * @return \string[] the list of tables
630
-     */
631
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
632
-    {
633
-        // Purge cache before generating anything.
634
-        $this->cache->deleteAll();
635
-
636
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
-        if (null !== $composerFile) {
638
-            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
-        }
640
-
641
-        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
-    }
643
-
644
-    /**
645
-     * @param array<string, string> $tableToBeanMap
646
-     */
647
-    public function setTableToBeanMap(array $tableToBeanMap)
648
-    {
649
-        $this->tableToBeanMap = $tableToBeanMap;
650
-    }
651
-
652
-    /**
653
-     * Returns the fully qualified class name of the bean associated with table $tableName.
654
-     *
655
-     *
656
-     * @param string $tableName
657
-     *
658
-     * @return string
659
-     */
660
-    public function getBeanClassName(string $tableName) : string
661
-    {
662
-        if (isset($this->tableToBeanMap[$tableName])) {
663
-            return $this->tableToBeanMap[$tableName];
664
-        } else {
665
-            throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
666
-        }
667
-    }
668
-
669
-    /**
670
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
671
-     *
672
-     * @param AbstractTDBMObject $object
673
-     *
674
-     * @throws TDBMException
675
-     */
676
-    public function save(AbstractTDBMObject $object)
677
-    {
678
-        $status = $object->_getStatus();
679
-
680
-        if ($status === null) {
681
-            throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
682
-        }
683
-
684
-        // Let's attach this object if it is in detached state.
685
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
686
-            $object->_attach($this);
687
-            $status = $object->_getStatus();
688
-        }
689
-
690
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
691
-            $dbRows = $object->_getDbRows();
692
-
693
-            $unindexedPrimaryKeys = array();
694
-
695
-            foreach ($dbRows as $dbRow) {
696
-                if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
697
-                    throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
698
-                }
699
-                $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
700
-                $tableName = $dbRow->_getDbTableName();
701
-
702
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
703
-                $tableDescriptor = $schema->getTable($tableName);
704
-
705
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
706
-
707
-                $references = $dbRow->_getReferences();
708
-
709
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
710
-                foreach ($references as $fkName => $reference) {
711
-                    if ($reference !== null) {
712
-                        $refStatus = $reference->_getStatus();
713
-                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
714
-                            try {
715
-                                $this->save($reference);
716
-                            } catch (TDBMCyclicReferenceException $e) {
717
-                                throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
718
-                            }
719
-                        }
720
-                    }
721
-                }
722
-
723
-                if (empty($unindexedPrimaryKeys)) {
724
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
725
-                } else {
726
-                    // First insert, the children must have the same primary key as the parent.
727
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
728
-                    $dbRow->_setPrimaryKeys($primaryKeys);
729
-                }
730
-
731
-                $dbRowData = $dbRow->_getDbRow();
732
-
733
-                // Let's see if the columns for primary key have been set before inserting.
734
-                // We assume that if one of the value of the PK has been set, the PK is set.
735
-                $isPkSet = !empty($primaryKeys);
736
-
737
-                /*if (!$isPkSet) {
578
+		}
579
+
580
+		return $this->primaryKeysColumns[$table];
581
+	}
582
+
583
+	/**
584
+	 * This is an internal function, you should not use it in your application.
585
+	 * This is used internally by TDBM to add an object to the object cache.
586
+	 *
587
+	 * @param DbRow $dbRow
588
+	 */
589
+	public function _addToCache(DbRow $dbRow)
590
+	{
591
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
592
+		$hash = $this->getObjectHash($primaryKey);
593
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
594
+	}
595
+
596
+	/**
597
+	 * This is an internal function, you should not use it in your application.
598
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
599
+	 * created/updated but not saved yet.
600
+	 *
601
+	 * @param DbRow $myObject
602
+	 */
603
+	private function removeFromToSaveObjectList(DbRow $myObject)
604
+	{
605
+		unset($this->toSaveObjects[$myObject]);
606
+	}
607
+
608
+	/**
609
+	 * This is an internal function, you should not use it in your application.
610
+	 * This is used internally by TDBM to add an object to the list of objects that have been
611
+	 * created/updated but not saved yet.
612
+	 *
613
+	 * @param AbstractTDBMObject $myObject
614
+	 */
615
+	public function _addToToSaveObjectList(DbRow $myObject)
616
+	{
617
+		$this->toSaveObjects[$myObject] = true;
618
+	}
619
+
620
+	/**
621
+	 * Generates all the daos and beans.
622
+	 *
623
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
624
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
625
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
626
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
627
+	 * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
628
+	 *
629
+	 * @return \string[] the list of tables
630
+	 */
631
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
632
+	{
633
+		// Purge cache before generating anything.
634
+		$this->cache->deleteAll();
635
+
636
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
+		if (null !== $composerFile) {
638
+			$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
+		}
640
+
641
+		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
+	}
643
+
644
+	/**
645
+	 * @param array<string, string> $tableToBeanMap
646
+	 */
647
+	public function setTableToBeanMap(array $tableToBeanMap)
648
+	{
649
+		$this->tableToBeanMap = $tableToBeanMap;
650
+	}
651
+
652
+	/**
653
+	 * Returns the fully qualified class name of the bean associated with table $tableName.
654
+	 *
655
+	 *
656
+	 * @param string $tableName
657
+	 *
658
+	 * @return string
659
+	 */
660
+	public function getBeanClassName(string $tableName) : string
661
+	{
662
+		if (isset($this->tableToBeanMap[$tableName])) {
663
+			return $this->tableToBeanMap[$tableName];
664
+		} else {
665
+			throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
666
+		}
667
+	}
668
+
669
+	/**
670
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
671
+	 *
672
+	 * @param AbstractTDBMObject $object
673
+	 *
674
+	 * @throws TDBMException
675
+	 */
676
+	public function save(AbstractTDBMObject $object)
677
+	{
678
+		$status = $object->_getStatus();
679
+
680
+		if ($status === null) {
681
+			throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
682
+		}
683
+
684
+		// Let's attach this object if it is in detached state.
685
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
686
+			$object->_attach($this);
687
+			$status = $object->_getStatus();
688
+		}
689
+
690
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
691
+			$dbRows = $object->_getDbRows();
692
+
693
+			$unindexedPrimaryKeys = array();
694
+
695
+			foreach ($dbRows as $dbRow) {
696
+				if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
697
+					throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
698
+				}
699
+				$dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
700
+				$tableName = $dbRow->_getDbTableName();
701
+
702
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
703
+				$tableDescriptor = $schema->getTable($tableName);
704
+
705
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
706
+
707
+				$references = $dbRow->_getReferences();
708
+
709
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
710
+				foreach ($references as $fkName => $reference) {
711
+					if ($reference !== null) {
712
+						$refStatus = $reference->_getStatus();
713
+						if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
714
+							try {
715
+								$this->save($reference);
716
+							} catch (TDBMCyclicReferenceException $e) {
717
+								throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
718
+							}
719
+						}
720
+					}
721
+				}
722
+
723
+				if (empty($unindexedPrimaryKeys)) {
724
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
725
+				} else {
726
+					// First insert, the children must have the same primary key as the parent.
727
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
728
+					$dbRow->_setPrimaryKeys($primaryKeys);
729
+				}
730
+
731
+				$dbRowData = $dbRow->_getDbRow();
732
+
733
+				// Let's see if the columns for primary key have been set before inserting.
734
+				// We assume that if one of the value of the PK has been set, the PK is set.
735
+				$isPkSet = !empty($primaryKeys);
736
+
737
+				/*if (!$isPkSet) {
738 738
                     // if there is no autoincrement and no pk set, let's go in error.
739 739
                     $isAutoIncrement = true;
740 740
 
@@ -752,27 +752,27 @@  discard block
 block discarded – undo
752 752
 
753 753
                 }*/
754 754
 
755
-                $types = [];
756
-                $escapedDbRowData = [];
755
+				$types = [];
756
+				$escapedDbRowData = [];
757 757
 
758
-                foreach ($dbRowData as $columnName => $value) {
759
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
760
-                    $types[] = $columnDescriptor->getType();
761
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
762
-                }
758
+				foreach ($dbRowData as $columnName => $value) {
759
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
760
+					$types[] = $columnDescriptor->getType();
761
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
762
+				}
763 763
 
764
-                $this->connection->insert($tableName, $escapedDbRowData, $types);
764
+				$this->connection->insert($tableName, $escapedDbRowData, $types);
765 765
 
766
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
767
-                    $id = $this->connection->lastInsertId();
768
-                    $primaryKeys[$primaryKeyColumns[0]] = $id;
769
-                }
766
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
767
+					$id = $this->connection->lastInsertId();
768
+					$primaryKeys[$primaryKeyColumns[0]] = $id;
769
+				}
770 770
 
771
-                // TODO: change this to some private magic accessor in future
772
-                $dbRow->_setPrimaryKeys($primaryKeys);
773
-                $unindexedPrimaryKeys = array_values($primaryKeys);
771
+				// TODO: change this to some private magic accessor in future
772
+				$dbRow->_setPrimaryKeys($primaryKeys);
773
+				$unindexedPrimaryKeys = array_values($primaryKeys);
774 774
 
775
-                /*
775
+				/*
776 776
                  * When attached, on "save", we check if the column updated is part of a primary key
777 777
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
778 778
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
                  *
783 783
                  */
784 784
 
785
-                /*try {
785
+				/*try {
786 786
                     $this->db_connection->exec($sql);
787 787
                 } catch (TDBMException $e) {
788 788
                     $this->db_onerror = true;
@@ -801,405 +801,405 @@  discard block
 block discarded – undo
801 801
                     }
802 802
                 }*/
803 803
 
804
-                // Let's remove this object from the $new_objects static table.
805
-                $this->removeFromToSaveObjectList($dbRow);
806
-
807
-                // TODO: change this behaviour to something more sensible performance-wise
808
-                // Maybe a setting to trigger this globally?
809
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
810
-                //$this->db_modified_state = false;
811
-                //$dbRow = array();
812
-
813
-                // Let's add this object to the list of objects in cache.
814
-                $this->_addToCache($dbRow);
815
-            }
816
-
817
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
818
-        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
819
-            $dbRows = $object->_getDbRows();
820
-
821
-            foreach ($dbRows as $dbRow) {
822
-                $references = $dbRow->_getReferences();
823
-
824
-                // Let's save all references in NEW state (we need their primary key)
825
-                foreach ($references as $fkName => $reference) {
826
-                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
827
-                        $this->save($reference);
828
-                    }
829
-                }
830
-
831
-                // Let's first get the primary keys
832
-                $tableName = $dbRow->_getDbTableName();
833
-                $dbRowData = $dbRow->_getDbRow();
834
-
835
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
836
-                $tableDescriptor = $schema->getTable($tableName);
837
-
838
-                $primaryKeys = $dbRow->_getPrimaryKeys();
839
-
840
-                $types = [];
841
-                $escapedDbRowData = [];
842
-                $escapedPrimaryKeys = [];
843
-
844
-                foreach ($dbRowData as $columnName => $value) {
845
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
846
-                    $types[] = $columnDescriptor->getType();
847
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
848
-                }
849
-                foreach ($primaryKeys as $columnName => $value) {
850
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
851
-                    $types[] = $columnDescriptor->getType();
852
-                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
853
-                }
854
-
855
-                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
856
-
857
-                // Let's check if the primary key has been updated...
858
-                $needsUpdatePk = false;
859
-                foreach ($primaryKeys as $column => $value) {
860
-                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
861
-                        $needsUpdatePk = true;
862
-                        break;
863
-                    }
864
-                }
865
-                if ($needsUpdatePk) {
866
-                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
867
-                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
868
-                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
869
-                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
870
-                }
871
-
872
-                // Let's remove this object from the list of objects to save.
873
-                $this->removeFromToSaveObjectList($dbRow);
874
-            }
875
-
876
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
877
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
878
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
879
-        }
880
-
881
-        // Finally, let's save all the many to many relationships to this bean.
882
-        $this->persistManyToManyRelationships($object);
883
-    }
884
-
885
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
886
-    {
887
-        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
888
-            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
889
-            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
890
-
891
-            $toRemoveFromStorage = [];
892
-
893
-            foreach ($storage as $remoteBean) {
894
-                /* @var $remoteBean AbstractTDBMObject */
895
-                $statusArr = $storage[$remoteBean];
896
-                $status = $statusArr['status'];
897
-                $reverse = $statusArr['reverse'];
898
-                if ($reverse) {
899
-                    continue;
900
-                }
901
-
902
-                if ($status === 'new') {
903
-                    $remoteBeanStatus = $remoteBean->_getStatus();
904
-                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
905
-                        // Let's save remote bean if needed.
906
-                        $this->save($remoteBean);
907
-                    }
908
-
909
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
910
-
911
-                    $types = [];
912
-                    $escapedFilters = [];
913
-
914
-                    foreach ($filters as $columnName => $value) {
915
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
916
-                        $types[] = $columnDescriptor->getType();
917
-                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
918
-                    }
919
-
920
-                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
921
-
922
-                    // Finally, let's mark relationships as saved.
923
-                    $statusArr['status'] = 'loaded';
924
-                    $storage[$remoteBean] = $statusArr;
925
-                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
926
-                    $remoteStatusArr = $remoteStorage[$object];
927
-                    $remoteStatusArr['status'] = 'loaded';
928
-                    $remoteStorage[$object] = $remoteStatusArr;
929
-                } elseif ($status === 'delete') {
930
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
931
-
932
-                    $types = [];
933
-
934
-                    foreach ($filters as $columnName => $value) {
935
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
936
-                        $types[] = $columnDescriptor->getType();
937
-                    }
938
-
939
-                    $this->connection->delete($pivotTableName, $filters, $types);
940
-
941
-                    // Finally, let's remove relationships completely from bean.
942
-                    $toRemoveFromStorage[] = $remoteBean;
943
-
944
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
945
-                }
946
-            }
947
-
948
-            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
949
-            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
950
-            foreach ($toRemoveFromStorage as $remoteBean) {
951
-                $storage->detach($remoteBean);
952
-            }
953
-        }
954
-    }
955
-
956
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
957
-    {
958
-        $localBeanPk = $this->getPrimaryKeyValues($localBean);
959
-        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
960
-        $localColumns = $localFk->getLocalColumns();
961
-        $remoteColumns = $remoteFk->getLocalColumns();
962
-
963
-        $localFilters = array_combine($localColumns, $localBeanPk);
964
-        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
965
-
966
-        return array_merge($localFilters, $remoteFilters);
967
-    }
968
-
969
-    /**
970
-     * Returns the "values" of the primary key.
971
-     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
972
-     *
973
-     * @param AbstractTDBMObject $bean
974
-     *
975
-     * @return array numerically indexed array of values
976
-     */
977
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
978
-    {
979
-        $dbRows = $bean->_getDbRows();
980
-        $dbRow = reset($dbRows);
981
-
982
-        return array_values($dbRow->_getPrimaryKeys());
983
-    }
984
-
985
-    /**
986
-     * Returns a unique hash used to store the object based on its primary key.
987
-     * If the array contains only one value, then the value is returned.
988
-     * Otherwise, a hash representing the array is returned.
989
-     *
990
-     * @param array $primaryKeys An array of columns => values forming the primary key
991
-     *
992
-     * @return string
993
-     */
994
-    public function getObjectHash(array $primaryKeys)
995
-    {
996
-        if (count($primaryKeys) === 1) {
997
-            return reset($primaryKeys);
998
-        } else {
999
-            ksort($primaryKeys);
1000
-
1001
-            return md5(json_encode($primaryKeys));
1002
-        }
1003
-    }
1004
-
1005
-    /**
1006
-     * Returns an array of primary keys from the object.
1007
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
1008
-     * $primaryKeys variable of the object.
1009
-     *
1010
-     * @param DbRow $dbRow
1011
-     *
1012
-     * @return array Returns an array of column => value
1013
-     */
1014
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1015
-    {
1016
-        $table = $dbRow->_getDbTableName();
1017
-        $dbRowData = $dbRow->_getDbRow();
1018
-
1019
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1020
-    }
1021
-
1022
-    /**
1023
-     * Returns an array of primary keys for the given row.
1024
-     * The primary keys are extracted from the object columns.
1025
-     *
1026
-     * @param $table
1027
-     * @param array $columns
1028
-     *
1029
-     * @return array
1030
-     */
1031
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
1032
-    {
1033
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1034
-        $values = array();
1035
-        foreach ($primaryKeyColumns as $column) {
1036
-            if (isset($columns[$column])) {
1037
-                $values[$column] = $columns[$column];
1038
-            }
1039
-        }
1040
-
1041
-        return $values;
1042
-    }
1043
-
1044
-    /**
1045
-     * Attaches $object to this TDBMService.
1046
-     * The $object must be in DETACHED state and will pass in NEW state.
1047
-     *
1048
-     * @param AbstractTDBMObject $object
1049
-     *
1050
-     * @throws TDBMInvalidOperationException
1051
-     */
1052
-    public function attach(AbstractTDBMObject $object)
1053
-    {
1054
-        $object->_attach($this);
1055
-    }
1056
-
1057
-    /**
1058
-     * Returns an associative array (column => value) for the primary keys from the table name and an
1059
-     * indexed array of primary key values.
1060
-     *
1061
-     * @param string $tableName
1062
-     * @param array  $indexedPrimaryKeys
1063
-     */
1064
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1065
-    {
1066
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1067
-
1068
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1069
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
804
+				// Let's remove this object from the $new_objects static table.
805
+				$this->removeFromToSaveObjectList($dbRow);
806
+
807
+				// TODO: change this behaviour to something more sensible performance-wise
808
+				// Maybe a setting to trigger this globally?
809
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
810
+				//$this->db_modified_state = false;
811
+				//$dbRow = array();
812
+
813
+				// Let's add this object to the list of objects in cache.
814
+				$this->_addToCache($dbRow);
815
+			}
816
+
817
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
818
+		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
819
+			$dbRows = $object->_getDbRows();
820
+
821
+			foreach ($dbRows as $dbRow) {
822
+				$references = $dbRow->_getReferences();
823
+
824
+				// Let's save all references in NEW state (we need their primary key)
825
+				foreach ($references as $fkName => $reference) {
826
+					if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
827
+						$this->save($reference);
828
+					}
829
+				}
830
+
831
+				// Let's first get the primary keys
832
+				$tableName = $dbRow->_getDbTableName();
833
+				$dbRowData = $dbRow->_getDbRow();
834
+
835
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
836
+				$tableDescriptor = $schema->getTable($tableName);
837
+
838
+				$primaryKeys = $dbRow->_getPrimaryKeys();
839
+
840
+				$types = [];
841
+				$escapedDbRowData = [];
842
+				$escapedPrimaryKeys = [];
843
+
844
+				foreach ($dbRowData as $columnName => $value) {
845
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
846
+					$types[] = $columnDescriptor->getType();
847
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
848
+				}
849
+				foreach ($primaryKeys as $columnName => $value) {
850
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
851
+					$types[] = $columnDescriptor->getType();
852
+					$escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
853
+				}
854
+
855
+				$this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
856
+
857
+				// Let's check if the primary key has been updated...
858
+				$needsUpdatePk = false;
859
+				foreach ($primaryKeys as $column => $value) {
860
+					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
861
+						$needsUpdatePk = true;
862
+						break;
863
+					}
864
+				}
865
+				if ($needsUpdatePk) {
866
+					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
867
+					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
868
+					$dbRow->_setPrimaryKeys($newPrimaryKeys);
869
+					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
870
+				}
871
+
872
+				// Let's remove this object from the list of objects to save.
873
+				$this->removeFromToSaveObjectList($dbRow);
874
+			}
875
+
876
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
877
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
878
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
879
+		}
880
+
881
+		// Finally, let's save all the many to many relationships to this bean.
882
+		$this->persistManyToManyRelationships($object);
883
+	}
884
+
885
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
886
+	{
887
+		foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
888
+			$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
889
+			list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
890
+
891
+			$toRemoveFromStorage = [];
892
+
893
+			foreach ($storage as $remoteBean) {
894
+				/* @var $remoteBean AbstractTDBMObject */
895
+				$statusArr = $storage[$remoteBean];
896
+				$status = $statusArr['status'];
897
+				$reverse = $statusArr['reverse'];
898
+				if ($reverse) {
899
+					continue;
900
+				}
901
+
902
+				if ($status === 'new') {
903
+					$remoteBeanStatus = $remoteBean->_getStatus();
904
+					if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
905
+						// Let's save remote bean if needed.
906
+						$this->save($remoteBean);
907
+					}
908
+
909
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
910
+
911
+					$types = [];
912
+					$escapedFilters = [];
913
+
914
+					foreach ($filters as $columnName => $value) {
915
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
916
+						$types[] = $columnDescriptor->getType();
917
+						$escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
918
+					}
919
+
920
+					$this->connection->insert($pivotTableName, $escapedFilters, $types);
921
+
922
+					// Finally, let's mark relationships as saved.
923
+					$statusArr['status'] = 'loaded';
924
+					$storage[$remoteBean] = $statusArr;
925
+					$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
926
+					$remoteStatusArr = $remoteStorage[$object];
927
+					$remoteStatusArr['status'] = 'loaded';
928
+					$remoteStorage[$object] = $remoteStatusArr;
929
+				} elseif ($status === 'delete') {
930
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
931
+
932
+					$types = [];
933
+
934
+					foreach ($filters as $columnName => $value) {
935
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
936
+						$types[] = $columnDescriptor->getType();
937
+					}
938
+
939
+					$this->connection->delete($pivotTableName, $filters, $types);
940
+
941
+					// Finally, let's remove relationships completely from bean.
942
+					$toRemoveFromStorage[] = $remoteBean;
943
+
944
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
945
+				}
946
+			}
947
+
948
+			// Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
949
+			// Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
950
+			foreach ($toRemoveFromStorage as $remoteBean) {
951
+				$storage->detach($remoteBean);
952
+			}
953
+		}
954
+	}
955
+
956
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
957
+	{
958
+		$localBeanPk = $this->getPrimaryKeyValues($localBean);
959
+		$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
960
+		$localColumns = $localFk->getLocalColumns();
961
+		$remoteColumns = $remoteFk->getLocalColumns();
962
+
963
+		$localFilters = array_combine($localColumns, $localBeanPk);
964
+		$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
965
+
966
+		return array_merge($localFilters, $remoteFilters);
967
+	}
968
+
969
+	/**
970
+	 * Returns the "values" of the primary key.
971
+	 * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
972
+	 *
973
+	 * @param AbstractTDBMObject $bean
974
+	 *
975
+	 * @return array numerically indexed array of values
976
+	 */
977
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
978
+	{
979
+		$dbRows = $bean->_getDbRows();
980
+		$dbRow = reset($dbRows);
981
+
982
+		return array_values($dbRow->_getPrimaryKeys());
983
+	}
984
+
985
+	/**
986
+	 * Returns a unique hash used to store the object based on its primary key.
987
+	 * If the array contains only one value, then the value is returned.
988
+	 * Otherwise, a hash representing the array is returned.
989
+	 *
990
+	 * @param array $primaryKeys An array of columns => values forming the primary key
991
+	 *
992
+	 * @return string
993
+	 */
994
+	public function getObjectHash(array $primaryKeys)
995
+	{
996
+		if (count($primaryKeys) === 1) {
997
+			return reset($primaryKeys);
998
+		} else {
999
+			ksort($primaryKeys);
1000
+
1001
+			return md5(json_encode($primaryKeys));
1002
+		}
1003
+	}
1004
+
1005
+	/**
1006
+	 * Returns an array of primary keys from the object.
1007
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
1008
+	 * $primaryKeys variable of the object.
1009
+	 *
1010
+	 * @param DbRow $dbRow
1011
+	 *
1012
+	 * @return array Returns an array of column => value
1013
+	 */
1014
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1015
+	{
1016
+		$table = $dbRow->_getDbTableName();
1017
+		$dbRowData = $dbRow->_getDbRow();
1018
+
1019
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1020
+	}
1021
+
1022
+	/**
1023
+	 * Returns an array of primary keys for the given row.
1024
+	 * The primary keys are extracted from the object columns.
1025
+	 *
1026
+	 * @param $table
1027
+	 * @param array $columns
1028
+	 *
1029
+	 * @return array
1030
+	 */
1031
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
1032
+	{
1033
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1034
+		$values = array();
1035
+		foreach ($primaryKeyColumns as $column) {
1036
+			if (isset($columns[$column])) {
1037
+				$values[$column] = $columns[$column];
1038
+			}
1039
+		}
1040
+
1041
+		return $values;
1042
+	}
1043
+
1044
+	/**
1045
+	 * Attaches $object to this TDBMService.
1046
+	 * The $object must be in DETACHED state and will pass in NEW state.
1047
+	 *
1048
+	 * @param AbstractTDBMObject $object
1049
+	 *
1050
+	 * @throws TDBMInvalidOperationException
1051
+	 */
1052
+	public function attach(AbstractTDBMObject $object)
1053
+	{
1054
+		$object->_attach($this);
1055
+	}
1056
+
1057
+	/**
1058
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
1059
+	 * indexed array of primary key values.
1060
+	 *
1061
+	 * @param string $tableName
1062
+	 * @param array  $indexedPrimaryKeys
1063
+	 */
1064
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1065
+	{
1066
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1067
+
1068
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1069
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1070 1070
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1071
-        }
1072
-
1073
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1074
-    }
1075
-
1076
-    /**
1077
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1078
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1079
-     *
1080
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1081
-     * we must be able to find all other tables.
1082
-     *
1083
-     * @param string[] $tables
1084
-     *
1085
-     * @return string[]
1086
-     */
1087
-    public function _getLinkBetweenInheritedTables(array $tables)
1088
-    {
1089
-        sort($tables);
1090
-
1091
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1092
-            function () use ($tables) {
1093
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1094
-            });
1095
-    }
1096
-
1097
-    /**
1098
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1099
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1100
-     *
1101
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1102
-     * we must be able to find all other tables.
1103
-     *
1104
-     * @param string[] $tables
1105
-     *
1106
-     * @return string[]
1107
-     */
1108
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1109
-    {
1110
-        $schemaAnalyzer = $this->schemaAnalyzer;
1111
-
1112
-        foreach ($tables as $currentTable) {
1113
-            $allParents = [$currentTable];
1114
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1115
-                $currentTable = $currentFk->getForeignTableName();
1116
-                $allParents[] = $currentTable;
1117
-            }
1118
-
1119
-            // Now, does the $allParents contain all the tables we want?
1120
-            $notFoundTables = array_diff($tables, $allParents);
1121
-            if (empty($notFoundTables)) {
1122
-                // We have a winner!
1123
-                return $allParents;
1124
-            }
1125
-        }
1126
-
1127
-        throw TDBMInheritanceException::create($tables);
1128
-    }
1129
-
1130
-    /**
1131
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1132
-     *
1133
-     * @param string $table
1134
-     *
1135
-     * @return string[]
1136
-     */
1137
-    public function _getRelatedTablesByInheritance($table)
1138
-    {
1139
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1140
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1141
-        });
1142
-    }
1143
-
1144
-    /**
1145
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1146
-     *
1147
-     * @param string $table
1148
-     *
1149
-     * @return string[]
1150
-     */
1151
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1152
-    {
1153
-        $schemaAnalyzer = $this->schemaAnalyzer;
1154
-
1155
-        // Let's scan the parent tables
1156
-        $currentTable = $table;
1157
-
1158
-        $parentTables = [];
1159
-
1160
-        // Get parent relationship
1161
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1162
-            $currentTable = $currentFk->getForeignTableName();
1163
-            $parentTables[] = $currentTable;
1164
-        }
1165
-
1166
-        // Let's recurse in children
1167
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1168
-
1169
-        return array_merge(array_reverse($parentTables), $childrenTables);
1170
-    }
1171
-
1172
-    /**
1173
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1174
-     *
1175
-     * @param string $table
1176
-     *
1177
-     * @return string[]
1178
-     */
1179
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1180
-    {
1181
-        $tables = [$table];
1182
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1183
-
1184
-        foreach ($keys as $key) {
1185
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1186
-        }
1187
-
1188
-        return $tables;
1189
-    }
1190
-
1191
-    /**
1192
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1193
-     * The returned value does contain only one table. For instance:.
1194
-     *
1195
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1196
-     *
1197
-     * @param ForeignKeyConstraint $fk
1198
-     * @param bool                 $leftTableIsLocal
1199
-     *
1200
-     * @return string
1201
-     */
1202
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1071
+		}
1072
+
1073
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1074
+	}
1075
+
1076
+	/**
1077
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1078
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1079
+	 *
1080
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1081
+	 * we must be able to find all other tables.
1082
+	 *
1083
+	 * @param string[] $tables
1084
+	 *
1085
+	 * @return string[]
1086
+	 */
1087
+	public function _getLinkBetweenInheritedTables(array $tables)
1088
+	{
1089
+		sort($tables);
1090
+
1091
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1092
+			function () use ($tables) {
1093
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1094
+			});
1095
+	}
1096
+
1097
+	/**
1098
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1099
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1100
+	 *
1101
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1102
+	 * we must be able to find all other tables.
1103
+	 *
1104
+	 * @param string[] $tables
1105
+	 *
1106
+	 * @return string[]
1107
+	 */
1108
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1109
+	{
1110
+		$schemaAnalyzer = $this->schemaAnalyzer;
1111
+
1112
+		foreach ($tables as $currentTable) {
1113
+			$allParents = [$currentTable];
1114
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1115
+				$currentTable = $currentFk->getForeignTableName();
1116
+				$allParents[] = $currentTable;
1117
+			}
1118
+
1119
+			// Now, does the $allParents contain all the tables we want?
1120
+			$notFoundTables = array_diff($tables, $allParents);
1121
+			if (empty($notFoundTables)) {
1122
+				// We have a winner!
1123
+				return $allParents;
1124
+			}
1125
+		}
1126
+
1127
+		throw TDBMInheritanceException::create($tables);
1128
+	}
1129
+
1130
+	/**
1131
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1132
+	 *
1133
+	 * @param string $table
1134
+	 *
1135
+	 * @return string[]
1136
+	 */
1137
+	public function _getRelatedTablesByInheritance($table)
1138
+	{
1139
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1140
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1141
+		});
1142
+	}
1143
+
1144
+	/**
1145
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1146
+	 *
1147
+	 * @param string $table
1148
+	 *
1149
+	 * @return string[]
1150
+	 */
1151
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1152
+	{
1153
+		$schemaAnalyzer = $this->schemaAnalyzer;
1154
+
1155
+		// Let's scan the parent tables
1156
+		$currentTable = $table;
1157
+
1158
+		$parentTables = [];
1159
+
1160
+		// Get parent relationship
1161
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1162
+			$currentTable = $currentFk->getForeignTableName();
1163
+			$parentTables[] = $currentTable;
1164
+		}
1165
+
1166
+		// Let's recurse in children
1167
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1168
+
1169
+		return array_merge(array_reverse($parentTables), $childrenTables);
1170
+	}
1171
+
1172
+	/**
1173
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1174
+	 *
1175
+	 * @param string $table
1176
+	 *
1177
+	 * @return string[]
1178
+	 */
1179
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1180
+	{
1181
+		$tables = [$table];
1182
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1183
+
1184
+		foreach ($keys as $key) {
1185
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1186
+		}
1187
+
1188
+		return $tables;
1189
+	}
1190
+
1191
+	/**
1192
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1193
+	 * The returned value does contain only one table. For instance:.
1194
+	 *
1195
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1196
+	 *
1197
+	 * @param ForeignKeyConstraint $fk
1198
+	 * @param bool                 $leftTableIsLocal
1199
+	 *
1200
+	 * @return string
1201
+	 */
1202
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1203 1203
         $onClauses = [];
1204 1204
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1205 1205
         $foreignColumns = $fk->getForeignColumns();
@@ -1225,411 +1225,411 @@  discard block
 block discarded – undo
1225 1225
         }
1226 1226
     }*/
1227 1227
 
1228
-    /**
1229
-     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1230
-     *
1231
-     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1232
-     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1233
-     *
1234
-     * The findObjects method takes in parameter:
1235
-     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1236
-     * 			`$mainTable` parameter should be the name of an existing table in database.
1237
-     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1238
-     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1239
-     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1240
-     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1241
-     *          Instead, please consider passing parameters (see documentation for more details).
1242
-     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1243
-     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1244
-     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1245
-     *
1246
-     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1247
-     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1248
-     *
1249
-     * Finally, if filter_bag is null, the whole table is returned.
1250
-     *
1251
-     * @param string                       $mainTable             The name of the table queried
1252
-     * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1253
-     * @param array                        $parameters
1254
-     * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1255
-     * @param array                        $additionalTablesFetch
1256
-     * @param int                          $mode
1257
-     * @param string                       $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1258
-     *
1259
-     * @return ResultIterator An object representing an array of results
1260
-     *
1261
-     * @throws TDBMException
1262
-     */
1263
-    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1264
-    {
1265
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1266
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1267
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1268
-        }
1269
-
1270
-        $mode = $mode ?: $this->mode;
1271
-
1272
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1273
-
1274
-        $parameters = array_merge($parameters, $additionalParameters);
1275
-
1276
-        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1277
-
1278
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1279
-    }
1280
-
1281
-    /**
1282
-     * @param string                       $mainTable   The name of the table queried
1283
-     * @param string                       $from        The from sql statement
1284
-     * @param string|array|null            $filter      The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1285
-     * @param array                        $parameters
1286
-     * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1287
-     * @param int                          $mode
1288
-     * @param string                       $className   Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1289
-     *
1290
-     * @return ResultIterator An object representing an array of results
1291
-     *
1292
-     * @throws TDBMException
1293
-     */
1294
-    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1295
-    {
1296
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1297
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1298
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1299
-        }
1300
-
1301
-        $mode = $mode ?: $this->mode;
1302
-
1303
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1304
-
1305
-        $parameters = array_merge($parameters, $additionalParameters);
1306
-
1307
-        $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1308
-
1309
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1310
-    }
1311
-
1312
-    /**
1313
-     * @param $table
1314
-     * @param array  $primaryKeys
1315
-     * @param array  $additionalTablesFetch
1316
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1317
-     * @param string $className
1318
-     *
1319
-     * @return AbstractTDBMObject
1320
-     *
1321
-     * @throws TDBMException
1322
-     */
1323
-    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1324
-    {
1325
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1326
-        $hash = $this->getObjectHash($primaryKeys);
1327
-
1328
-        if ($this->objectStorage->has($table, $hash)) {
1329
-            $dbRow = $this->objectStorage->get($table, $hash);
1330
-            $bean = $dbRow->getTDBMObject();
1331
-            if ($className !== null && !is_a($bean, $className)) {
1332
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1333
-            }
1334
-
1335
-            return $bean;
1336
-        }
1337
-
1338
-        // Are we performing lazy fetching?
1339
-        if ($lazy === true) {
1340
-            // Can we perform lazy fetching?
1341
-            $tables = $this->_getRelatedTablesByInheritance($table);
1342
-            // Only allowed if no inheritance.
1343
-            if (count($tables) === 1) {
1344
-                if ($className === null) {
1345
-                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1346
-                }
1347
-
1348
-                // Let's construct the bean
1349
-                if (!isset($this->reflectionClassCache[$className])) {
1350
-                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1351
-                }
1352
-                // Let's bypass the constructor when creating the bean!
1353
-                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1354
-                /* @var $bean AbstractTDBMObject */
1355
-                $bean->_constructLazy($table, $primaryKeys, $this);
1356
-
1357
-                return $bean;
1358
-            }
1359
-        }
1360
-
1361
-        // Did not find the object in cache? Let's query it!
1362
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1363
-    }
1364
-
1365
-    /**
1366
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1367
-     *
1368
-     * @param string            $mainTable             The name of the table queried
1369
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1370
-     * @param array             $parameters
1371
-     * @param array             $additionalTablesFetch
1372
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1373
-     *
1374
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1375
-     *
1376
-     * @throws TDBMException
1377
-     */
1378
-    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1379
-    {
1380
-        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1381
-        $page = $objects->take(0, 2);
1382
-        $count = $page->count();
1383
-        if ($count > 1) {
1384
-            throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1385
-        } elseif ($count === 0) {
1386
-            return;
1387
-        }
1388
-
1389
-        return $page[0];
1390
-    }
1391
-
1392
-    /**
1393
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1394
-     *
1395
-     * @param string            $mainTable  The name of the table queried
1396
-     * @param string            $from       The from sql statement
1397
-     * @param string|array|null $filter     The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1398
-     * @param array             $parameters
1399
-     * @param string            $className  Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1400
-     *
1401
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1402
-     *
1403
-     * @throws TDBMException
1404
-     */
1405
-    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1406
-    {
1407
-        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1408
-        $page = $objects->take(0, 2);
1409
-        $count = $page->count();
1410
-        if ($count > 1) {
1411
-            throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1412
-        } elseif ($count === 0) {
1413
-            return;
1414
-        }
1415
-
1416
-        return $page[0];
1417
-    }
1418
-
1419
-    /**
1420
-     * Returns a unique bean according to the filters passed in parameter.
1421
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1422
-     *
1423
-     * @param string            $mainTable             The name of the table queried
1424
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1425
-     * @param array             $parameters
1426
-     * @param array             $additionalTablesFetch
1427
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1428
-     *
1429
-     * @return AbstractTDBMObject The object we want
1430
-     *
1431
-     * @throws TDBMException
1432
-     */
1433
-    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1434
-    {
1435
-        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1436
-        if ($bean === null) {
1437
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1438
-        }
1439
-
1440
-        return $bean;
1441
-    }
1442
-
1443
-    /**
1444
-     * @param array $beanData An array of data: array<table, array<column, value>>
1445
-     *
1446
-     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1447
-     *
1448
-     * @throws TDBMInheritanceException
1449
-     */
1450
-    public function _getClassNameFromBeanData(array $beanData)
1451
-    {
1452
-        if (count($beanData) === 1) {
1453
-            $tableName = array_keys($beanData)[0];
1454
-            $allTables = [$tableName];
1455
-        } else {
1456
-            $tables = [];
1457
-            foreach ($beanData as $table => $row) {
1458
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1459
-                $pkSet = false;
1460
-                foreach ($primaryKeyColumns as $columnName) {
1461
-                    if ($row[$columnName] !== null) {
1462
-                        $pkSet = true;
1463
-                        break;
1464
-                    }
1465
-                }
1466
-                if ($pkSet) {
1467
-                    $tables[] = $table;
1468
-                }
1469
-            }
1470
-
1471
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1472
-            try {
1473
-                $allTables = $this->_getLinkBetweenInheritedTables($tables);
1474
-            } catch (TDBMInheritanceException $e) {
1475
-                throw TDBMInheritanceException::extendException($e, $this, $beanData);
1476
-            }
1477
-            $tableName = $allTables[0];
1478
-        }
1479
-
1480
-        // Only one table in this bean. Life is sweat, let's look at its type:
1481
-        if (isset($this->tableToBeanMap[$tableName])) {
1482
-            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1483
-        } else {
1484
-            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1485
-        }
1486
-    }
1487
-
1488
-    /**
1489
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1490
-     *
1491
-     * @param string   $key
1492
-     * @param callable $closure
1493
-     *
1494
-     * @return mixed
1495
-     */
1496
-    private function fromCache(string $key, callable $closure)
1497
-    {
1498
-        $item = $this->cache->fetch($key);
1499
-        if ($item === false) {
1500
-            $item = $closure();
1501
-            $this->cache->save($key, $item);
1502
-        }
1503
-
1504
-        return $item;
1505
-    }
1506
-
1507
-    /**
1508
-     * Returns the foreign key object.
1509
-     *
1510
-     * @param string $table
1511
-     * @param string $fkName
1512
-     *
1513
-     * @return ForeignKeyConstraint
1514
-     */
1515
-    public function _getForeignKeyByName(string $table, string $fkName)
1516
-    {
1517
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1518
-    }
1519
-
1520
-    /**
1521
-     * @param $pivotTableName
1522
-     * @param AbstractTDBMObject $bean
1523
-     *
1524
-     * @return AbstractTDBMObject[]
1525
-     */
1526
-    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1527
-    {
1528
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1529
-        /* @var $localFk ForeignKeyConstraint */
1530
-        /* @var $remoteFk ForeignKeyConstraint */
1531
-        $remoteTable = $remoteFk->getForeignTableName();
1532
-
1533
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1534
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1535
-            return $pivotTableName.'.'.$name;
1536
-        }, $localFk->getLocalColumns());
1537
-
1538
-        $filter = array_combine($columnNames, $primaryKeys);
1539
-
1540
-        return $this->findObjects($remoteTable, $filter);
1541
-    }
1542
-
1543
-    /**
1544
-     * @param $pivotTableName
1545
-     * @param AbstractTDBMObject $bean The LOCAL bean
1546
-     *
1547
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1548
-     *
1549
-     * @throws TDBMException
1550
-     */
1551
-    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1552
-    {
1553
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1554
-        $table1 = $fks[0]->getForeignTableName();
1555
-        $table2 = $fks[1]->getForeignTableName();
1556
-
1557
-        $beanTables = array_map(function (DbRow $dbRow) {
1558
-            return $dbRow->_getDbTableName();
1559
-        }, $bean->_getDbRows());
1560
-
1561
-        if (in_array($table1, $beanTables)) {
1562
-            return [$fks[0], $fks[1]];
1563
-        } elseif (in_array($table2, $beanTables)) {
1564
-            return [$fks[1], $fks[0]];
1565
-        } else {
1566
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1567
-        }
1568
-    }
1569
-
1570
-    /**
1571
-     * Returns a list of pivot tables linked to $bean.
1572
-     *
1573
-     * @param AbstractTDBMObject $bean
1574
-     *
1575
-     * @return string[]
1576
-     */
1577
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1578
-    {
1579
-        $junctionTables = [];
1580
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1581
-        foreach ($bean->_getDbRows() as $dbRow) {
1582
-            foreach ($allJunctionTables as $table) {
1583
-                // There are exactly 2 FKs since this is a pivot table.
1584
-                $fks = array_values($table->getForeignKeys());
1585
-
1586
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1587
-                    $junctionTables[] = $table->getName();
1588
-                }
1589
-            }
1590
-        }
1591
-
1592
-        return $junctionTables;
1593
-    }
1594
-
1595
-    /**
1596
-     * Array of types for tables.
1597
-     * Key: table name
1598
-     * Value: array of types indexed by column.
1599
-     *
1600
-     * @var array[]
1601
-     */
1602
-    private $typesForTable = [];
1603
-
1604
-    /**
1605
-     * @internal
1606
-     *
1607
-     * @param string $tableName
1608
-     *
1609
-     * @return Type[]
1610
-     */
1611
-    public function _getColumnTypesForTable(string $tableName)
1612
-    {
1613
-        if (!isset($typesForTable[$tableName])) {
1614
-            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1615
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1616
-                return $column->getType();
1617
-            }, $columns);
1618
-        }
1619
-
1620
-        return $typesForTable[$tableName];
1621
-    }
1622
-
1623
-    /**
1624
-     * Sets the minimum log level.
1625
-     * $level must be one of Psr\Log\LogLevel::xxx.
1626
-     *
1627
-     * Defaults to LogLevel::WARNING
1628
-     *
1629
-     * @param string $level
1630
-     */
1631
-    public function setLogLevel(string $level)
1632
-    {
1633
-        $this->logger = new LevelFilter($this->rootLogger, $level);
1634
-    }
1228
+	/**
1229
+	 * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1230
+	 *
1231
+	 * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1232
+	 * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1233
+	 *
1234
+	 * The findObjects method takes in parameter:
1235
+	 * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1236
+	 * 			`$mainTable` parameter should be the name of an existing table in database.
1237
+	 *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1238
+	 *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1239
+	 *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1240
+	 *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1241
+	 *          Instead, please consider passing parameters (see documentation for more details).
1242
+	 *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1243
+	 *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1244
+	 *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1245
+	 *
1246
+	 * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1247
+	 * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1248
+	 *
1249
+	 * Finally, if filter_bag is null, the whole table is returned.
1250
+	 *
1251
+	 * @param string                       $mainTable             The name of the table queried
1252
+	 * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1253
+	 * @param array                        $parameters
1254
+	 * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1255
+	 * @param array                        $additionalTablesFetch
1256
+	 * @param int                          $mode
1257
+	 * @param string                       $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1258
+	 *
1259
+	 * @return ResultIterator An object representing an array of results
1260
+	 *
1261
+	 * @throws TDBMException
1262
+	 */
1263
+	public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1264
+	{
1265
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1266
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1267
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1268
+		}
1269
+
1270
+		$mode = $mode ?: $this->mode;
1271
+
1272
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1273
+
1274
+		$parameters = array_merge($parameters, $additionalParameters);
1275
+
1276
+		$queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1277
+
1278
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1279
+	}
1280
+
1281
+	/**
1282
+	 * @param string                       $mainTable   The name of the table queried
1283
+	 * @param string                       $from        The from sql statement
1284
+	 * @param string|array|null            $filter      The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1285
+	 * @param array                        $parameters
1286
+	 * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1287
+	 * @param int                          $mode
1288
+	 * @param string                       $className   Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1289
+	 *
1290
+	 * @return ResultIterator An object representing an array of results
1291
+	 *
1292
+	 * @throws TDBMException
1293
+	 */
1294
+	public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1295
+	{
1296
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1297
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1298
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1299
+		}
1300
+
1301
+		$mode = $mode ?: $this->mode;
1302
+
1303
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1304
+
1305
+		$parameters = array_merge($parameters, $additionalParameters);
1306
+
1307
+		$queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1308
+
1309
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1310
+	}
1311
+
1312
+	/**
1313
+	 * @param $table
1314
+	 * @param array  $primaryKeys
1315
+	 * @param array  $additionalTablesFetch
1316
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1317
+	 * @param string $className
1318
+	 *
1319
+	 * @return AbstractTDBMObject
1320
+	 *
1321
+	 * @throws TDBMException
1322
+	 */
1323
+	public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1324
+	{
1325
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1326
+		$hash = $this->getObjectHash($primaryKeys);
1327
+
1328
+		if ($this->objectStorage->has($table, $hash)) {
1329
+			$dbRow = $this->objectStorage->get($table, $hash);
1330
+			$bean = $dbRow->getTDBMObject();
1331
+			if ($className !== null && !is_a($bean, $className)) {
1332
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1333
+			}
1334
+
1335
+			return $bean;
1336
+		}
1337
+
1338
+		// Are we performing lazy fetching?
1339
+		if ($lazy === true) {
1340
+			// Can we perform lazy fetching?
1341
+			$tables = $this->_getRelatedTablesByInheritance($table);
1342
+			// Only allowed if no inheritance.
1343
+			if (count($tables) === 1) {
1344
+				if ($className === null) {
1345
+					$className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1346
+				}
1347
+
1348
+				// Let's construct the bean
1349
+				if (!isset($this->reflectionClassCache[$className])) {
1350
+					$this->reflectionClassCache[$className] = new \ReflectionClass($className);
1351
+				}
1352
+				// Let's bypass the constructor when creating the bean!
1353
+				$bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1354
+				/* @var $bean AbstractTDBMObject */
1355
+				$bean->_constructLazy($table, $primaryKeys, $this);
1356
+
1357
+				return $bean;
1358
+			}
1359
+		}
1360
+
1361
+		// Did not find the object in cache? Let's query it!
1362
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1363
+	}
1364
+
1365
+	/**
1366
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1367
+	 *
1368
+	 * @param string            $mainTable             The name of the table queried
1369
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1370
+	 * @param array             $parameters
1371
+	 * @param array             $additionalTablesFetch
1372
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1373
+	 *
1374
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1375
+	 *
1376
+	 * @throws TDBMException
1377
+	 */
1378
+	public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1379
+	{
1380
+		$objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1381
+		$page = $objects->take(0, 2);
1382
+		$count = $page->count();
1383
+		if ($count > 1) {
1384
+			throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1385
+		} elseif ($count === 0) {
1386
+			return;
1387
+		}
1388
+
1389
+		return $page[0];
1390
+	}
1391
+
1392
+	/**
1393
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1394
+	 *
1395
+	 * @param string            $mainTable  The name of the table queried
1396
+	 * @param string            $from       The from sql statement
1397
+	 * @param string|array|null $filter     The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1398
+	 * @param array             $parameters
1399
+	 * @param string            $className  Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1400
+	 *
1401
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1402
+	 *
1403
+	 * @throws TDBMException
1404
+	 */
1405
+	public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1406
+	{
1407
+		$objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1408
+		$page = $objects->take(0, 2);
1409
+		$count = $page->count();
1410
+		if ($count > 1) {
1411
+			throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1412
+		} elseif ($count === 0) {
1413
+			return;
1414
+		}
1415
+
1416
+		return $page[0];
1417
+	}
1418
+
1419
+	/**
1420
+	 * Returns a unique bean according to the filters passed in parameter.
1421
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1422
+	 *
1423
+	 * @param string            $mainTable             The name of the table queried
1424
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1425
+	 * @param array             $parameters
1426
+	 * @param array             $additionalTablesFetch
1427
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1428
+	 *
1429
+	 * @return AbstractTDBMObject The object we want
1430
+	 *
1431
+	 * @throws TDBMException
1432
+	 */
1433
+	public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1434
+	{
1435
+		$bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1436
+		if ($bean === null) {
1437
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1438
+		}
1439
+
1440
+		return $bean;
1441
+	}
1442
+
1443
+	/**
1444
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1445
+	 *
1446
+	 * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1447
+	 *
1448
+	 * @throws TDBMInheritanceException
1449
+	 */
1450
+	public function _getClassNameFromBeanData(array $beanData)
1451
+	{
1452
+		if (count($beanData) === 1) {
1453
+			$tableName = array_keys($beanData)[0];
1454
+			$allTables = [$tableName];
1455
+		} else {
1456
+			$tables = [];
1457
+			foreach ($beanData as $table => $row) {
1458
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1459
+				$pkSet = false;
1460
+				foreach ($primaryKeyColumns as $columnName) {
1461
+					if ($row[$columnName] !== null) {
1462
+						$pkSet = true;
1463
+						break;
1464
+					}
1465
+				}
1466
+				if ($pkSet) {
1467
+					$tables[] = $table;
1468
+				}
1469
+			}
1470
+
1471
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1472
+			try {
1473
+				$allTables = $this->_getLinkBetweenInheritedTables($tables);
1474
+			} catch (TDBMInheritanceException $e) {
1475
+				throw TDBMInheritanceException::extendException($e, $this, $beanData);
1476
+			}
1477
+			$tableName = $allTables[0];
1478
+		}
1479
+
1480
+		// Only one table in this bean. Life is sweat, let's look at its type:
1481
+		if (isset($this->tableToBeanMap[$tableName])) {
1482
+			return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1483
+		} else {
1484
+			return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1485
+		}
1486
+	}
1487
+
1488
+	/**
1489
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1490
+	 *
1491
+	 * @param string   $key
1492
+	 * @param callable $closure
1493
+	 *
1494
+	 * @return mixed
1495
+	 */
1496
+	private function fromCache(string $key, callable $closure)
1497
+	{
1498
+		$item = $this->cache->fetch($key);
1499
+		if ($item === false) {
1500
+			$item = $closure();
1501
+			$this->cache->save($key, $item);
1502
+		}
1503
+
1504
+		return $item;
1505
+	}
1506
+
1507
+	/**
1508
+	 * Returns the foreign key object.
1509
+	 *
1510
+	 * @param string $table
1511
+	 * @param string $fkName
1512
+	 *
1513
+	 * @return ForeignKeyConstraint
1514
+	 */
1515
+	public function _getForeignKeyByName(string $table, string $fkName)
1516
+	{
1517
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1518
+	}
1519
+
1520
+	/**
1521
+	 * @param $pivotTableName
1522
+	 * @param AbstractTDBMObject $bean
1523
+	 *
1524
+	 * @return AbstractTDBMObject[]
1525
+	 */
1526
+	public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1527
+	{
1528
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1529
+		/* @var $localFk ForeignKeyConstraint */
1530
+		/* @var $remoteFk ForeignKeyConstraint */
1531
+		$remoteTable = $remoteFk->getForeignTableName();
1532
+
1533
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1534
+		$columnNames = array_map(function ($name) use ($pivotTableName) {
1535
+			return $pivotTableName.'.'.$name;
1536
+		}, $localFk->getLocalColumns());
1537
+
1538
+		$filter = array_combine($columnNames, $primaryKeys);
1539
+
1540
+		return $this->findObjects($remoteTable, $filter);
1541
+	}
1542
+
1543
+	/**
1544
+	 * @param $pivotTableName
1545
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1546
+	 *
1547
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1548
+	 *
1549
+	 * @throws TDBMException
1550
+	 */
1551
+	private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1552
+	{
1553
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1554
+		$table1 = $fks[0]->getForeignTableName();
1555
+		$table2 = $fks[1]->getForeignTableName();
1556
+
1557
+		$beanTables = array_map(function (DbRow $dbRow) {
1558
+			return $dbRow->_getDbTableName();
1559
+		}, $bean->_getDbRows());
1560
+
1561
+		if (in_array($table1, $beanTables)) {
1562
+			return [$fks[0], $fks[1]];
1563
+		} elseif (in_array($table2, $beanTables)) {
1564
+			return [$fks[1], $fks[0]];
1565
+		} else {
1566
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1567
+		}
1568
+	}
1569
+
1570
+	/**
1571
+	 * Returns a list of pivot tables linked to $bean.
1572
+	 *
1573
+	 * @param AbstractTDBMObject $bean
1574
+	 *
1575
+	 * @return string[]
1576
+	 */
1577
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1578
+	{
1579
+		$junctionTables = [];
1580
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1581
+		foreach ($bean->_getDbRows() as $dbRow) {
1582
+			foreach ($allJunctionTables as $table) {
1583
+				// There are exactly 2 FKs since this is a pivot table.
1584
+				$fks = array_values($table->getForeignKeys());
1585
+
1586
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1587
+					$junctionTables[] = $table->getName();
1588
+				}
1589
+			}
1590
+		}
1591
+
1592
+		return $junctionTables;
1593
+	}
1594
+
1595
+	/**
1596
+	 * Array of types for tables.
1597
+	 * Key: table name
1598
+	 * Value: array of types indexed by column.
1599
+	 *
1600
+	 * @var array[]
1601
+	 */
1602
+	private $typesForTable = [];
1603
+
1604
+	/**
1605
+	 * @internal
1606
+	 *
1607
+	 * @param string $tableName
1608
+	 *
1609
+	 * @return Type[]
1610
+	 */
1611
+	public function _getColumnTypesForTable(string $tableName)
1612
+	{
1613
+		if (!isset($typesForTable[$tableName])) {
1614
+			$columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1615
+			$typesForTable[$tableName] = array_map(function (Column $column) {
1616
+				return $column->getType();
1617
+			}, $columns);
1618
+		}
1619
+
1620
+		return $typesForTable[$tableName];
1621
+	}
1622
+
1623
+	/**
1624
+	 * Sets the minimum log level.
1625
+	 * $level must be one of Psr\Log\LogLevel::xxx.
1626
+	 *
1627
+	 * Defaults to LogLevel::WARNING
1628
+	 *
1629
+	 * @param string $level
1630
+	 */
1631
+	public function setLogLevel(string $level)
1632
+	{
1633
+		$this->logger = new LevelFilter($this->rootLogger, $level);
1634
+	}
1635 1635
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMInheritanceException.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -7,23 +7,23 @@
 block discarded – undo
7 7
  */
8 8
 class TDBMInheritanceException extends TDBMException
9 9
 {
10
-    public static function create(array $tables) : TDBMInheritanceException
11
-    {
12
-        return new self(sprintf('The tables (%s) cannot be linked by an inheritance relationship. Does your data set contains multiple children for one parent row? (multiple inheritance is not supported by TDBM)', implode(', ', $tables)));
13
-    }
10
+	public static function create(array $tables) : TDBMInheritanceException
11
+	{
12
+		return new self(sprintf('The tables (%s) cannot be linked by an inheritance relationship. Does your data set contains multiple children for one parent row? (multiple inheritance is not supported by TDBM)', implode(', ', $tables)));
13
+	}
14 14
 
15
-    public static function extendException(TDBMInheritanceException $e, TDBMService $tdbmService, array $beanData) : TDBMInheritanceException
16
-    {
17
-        $pks = [];
18
-        foreach ($beanData as $table => $row) {
19
-            $primaryKeyColumns = $tdbmService->getPrimaryKeyColumns($table);
20
-            foreach ($primaryKeyColumns as $columnName) {
21
-                if ($row[$columnName] !== null) {
22
-                    $pks[] = $table.'.'.$columnName.' => '.var_export($row[$columnName], true);
23
-                }
24
-            }
25
-        }
15
+	public static function extendException(TDBMInheritanceException $e, TDBMService $tdbmService, array $beanData) : TDBMInheritanceException
16
+	{
17
+		$pks = [];
18
+		foreach ($beanData as $table => $row) {
19
+			$primaryKeyColumns = $tdbmService->getPrimaryKeyColumns($table);
20
+			foreach ($primaryKeyColumns as $columnName) {
21
+				if ($row[$columnName] !== null) {
22
+					$pks[] = $table.'.'.$columnName.' => '.var_export($row[$columnName], true);
23
+				}
24
+			}
25
+		}
26 26
 
27
-        throw new self($e->getMessage().' (row in error: '.implode(', ', $pks).')', 0, $e);
28
-    }
27
+		throw new self($e->getMessage().' (row in error: '.implode(', ', $pks).')', 0, $e);
28
+	}
29 29
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMCyclicReferenceException.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -4,13 +4,13 @@
 block discarded – undo
4 4
 
5 5
 class TDBMCyclicReferenceException extends TDBMException
6 6
 {
7
-    public static function createCyclicReference(string $tableName, AbstractTDBMObject $object) : TDBMCyclicReferenceException
8
-    {
9
-        return new self(sprintf("You are trying a grape of objects that reference each other. Unable to save object '%s' in table '%s'. It is already in the process of being saved.", get_class($object), $tableName));
10
-    }
7
+	public static function createCyclicReference(string $tableName, AbstractTDBMObject $object) : TDBMCyclicReferenceException
8
+	{
9
+		return new self(sprintf("You are trying a grape of objects that reference each other. Unable to save object '%s' in table '%s'. It is already in the process of being saved.", get_class($object), $tableName));
10
+	}
11 11
 
12
-    public static function extendCyclicReference(TDBMCyclicReferenceException $e, string $tableName, AbstractTDBMObject $object, string $fkName) : TDBMCyclicReferenceException
13
-    {
14
-        return new self($e->getMessage().sprintf(" This object is referenced by an object of type '%s' (table '%s') via foreign key '%s'", get_class($object), $tableName, $fkName), $e->getCode(), $e);
15
-    }
12
+	public static function extendCyclicReference(TDBMCyclicReferenceException $e, string $tableName, AbstractTDBMObject $object, string $fkName) : TDBMCyclicReferenceException
13
+	{
14
+		return new self($e->getMessage().sprintf(" This object is referenced by an object of type '%s' (table '%s') via foreign key '%s'", get_class($object), $tableName, $fkName), $e->getCode(), $e);
15
+	}
16 16
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMMissingReferenceException.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@
 block discarded – undo
4 4
 
5 5
 class TDBMMissingReferenceException extends TDBMException
6 6
 {
7
-    public static function referenceDeleted(string $tableName, AbstractTDBMObject $reference) : TDBMMissingReferenceException
8
-    {
9
-        return new self(sprintf("Unable to save object in table '%s'. Your object references an object of type '%s' that is deleted.", $tableName, get_class($reference)));
10
-    }
7
+	public static function referenceDeleted(string $tableName, AbstractTDBMObject $reference) : TDBMMissingReferenceException
8
+	{
9
+		return new self(sprintf("Unable to save object in table '%s'. Your object references an object of type '%s' that is deleted.", $tableName, get_class($reference)));
10
+	}
11 11
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/DbRow.php 1 patch
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -27,170 +27,170 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class DbRow
29 29
 {
30
-    /**
31
-     * The service this object is bound to.
32
-     *
33
-     * @var TDBMService
34
-     */
35
-    protected $tdbmService;
36
-
37
-    /**
38
-     * The object containing this db row.
39
-     *
40
-     * @var AbstractTDBMObject
41
-     */
42
-    private $object;
43
-
44
-    /**
45
-     * The name of the table the object if issued from.
46
-     *
47
-     * @var string
48
-     */
49
-    private $dbTableName;
50
-
51
-    /**
52
-     * The array of columns returned from database.
53
-     *
54
-     * @var array
55
-     */
56
-    private $dbRow = array();
57
-
58
-    /**
59
-     * @var AbstractTDBMObject[]
60
-     */
61
-    private $references = array();
62
-
63
-    /**
64
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
-     *
69
-     * @var string
70
-     */
71
-    private $status;
72
-
73
-    /**
74
-     * The values of the primary key.
75
-     * This is set when the object is in "loaded" state.
76
-     *
77
-     * @var array An array of column => value
78
-     */
79
-    private $primaryKeys;
80
-
81
-    /**
82
-     * You should never call the constructor directly. Instead, you should use the
83
-     * TDBMService class that will create TDBMObjects for you.
84
-     *
85
-     * Used with id!=false when we want to retrieve an existing object
86
-     * and id==false if we want a new object
87
-     *
88
-     * @param AbstractTDBMObject $object      The object containing this db row
89
-     * @param string             $table_name
90
-     * @param array              $primaryKeys
91
-     * @param TDBMService        $tdbmService
92
-     *
93
-     * @throws TDBMException
94
-     * @throws TDBMInvalidOperationException
95
-     */
96
-    public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
-    {
98
-        $this->object = $object;
99
-        $this->dbTableName = $table_name;
100
-
101
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
-
103
-        if ($tdbmService === null) {
104
-            if (!empty($primaryKeys)) {
105
-                throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
-            }
107
-        } else {
108
-            $this->tdbmService = $tdbmService;
109
-
110
-            if (!empty($primaryKeys)) {
111
-                $this->_setPrimaryKeys($primaryKeys);
112
-                if (!empty($dbRow)) {
113
-                    $this->dbRow = $dbRow;
114
-                    $this->status = TDBMObjectStateEnum::STATE_LOADED;
115
-                } else {
116
-                    $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
-                }
118
-                $tdbmService->_addToCache($this);
119
-            } else {
120
-                $this->status = TDBMObjectStateEnum::STATE_NEW;
121
-                $this->tdbmService->_addToToSaveObjectList($this);
122
-            }
123
-        }
124
-    }
125
-
126
-    public function _attach(TDBMService $tdbmService)
127
-    {
128
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
-        }
131
-        $this->tdbmService = $tdbmService;
132
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
133
-        $this->tdbmService->_addToToSaveObjectList($this);
134
-    }
135
-
136
-    /**
137
-     * Sets the state of the TDBM Object
138
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
-     *
143
-     * @param string $state
144
-     */
145
-    public function _setStatus($state)
146
-    {
147
-        $this->status = $state;
148
-    }
149
-
150
-    /**
151
-     * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
-     * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
-     *
154
-     * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
-     * cannot be found).
156
-     */
157
-    public function _dbLoadIfNotLoaded()
158
-    {
159
-        if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
-            $connection = $this->tdbmService->getConnection();
161
-
162
-            /// buildFilterFromFilterBag($filter_bag)
163
-            list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
-
165
-            $sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
-            $result = $connection->executeQuery($sql, $parameters);
167
-
168
-            if ($result->rowCount() === 0) {
169
-                throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
-            }
171
-
172
-            $row = $result->fetch(\PDO::FETCH_ASSOC);
173
-
174
-            $this->dbRow = [];
175
-            $types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
-
177
-            foreach ($row as $key => $value) {
178
-                $this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
-            }
180
-
181
-            $result->closeCursor();
182
-
183
-            $this->status = TDBMObjectStateEnum::STATE_LOADED;
184
-        }
185
-    }
186
-
187
-    public function get($var)
188
-    {
189
-        $this->_dbLoadIfNotLoaded();
190
-
191
-        // Let's first check if the key exist.
192
-        if (!isset($this->dbRow[$var])) {
193
-            /*
30
+	/**
31
+	 * The service this object is bound to.
32
+	 *
33
+	 * @var TDBMService
34
+	 */
35
+	protected $tdbmService;
36
+
37
+	/**
38
+	 * The object containing this db row.
39
+	 *
40
+	 * @var AbstractTDBMObject
41
+	 */
42
+	private $object;
43
+
44
+	/**
45
+	 * The name of the table the object if issued from.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	private $dbTableName;
50
+
51
+	/**
52
+	 * The array of columns returned from database.
53
+	 *
54
+	 * @var array
55
+	 */
56
+	private $dbRow = array();
57
+
58
+	/**
59
+	 * @var AbstractTDBMObject[]
60
+	 */
61
+	private $references = array();
62
+
63
+	/**
64
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
+	 *
69
+	 * @var string
70
+	 */
71
+	private $status;
72
+
73
+	/**
74
+	 * The values of the primary key.
75
+	 * This is set when the object is in "loaded" state.
76
+	 *
77
+	 * @var array An array of column => value
78
+	 */
79
+	private $primaryKeys;
80
+
81
+	/**
82
+	 * You should never call the constructor directly. Instead, you should use the
83
+	 * TDBMService class that will create TDBMObjects for you.
84
+	 *
85
+	 * Used with id!=false when we want to retrieve an existing object
86
+	 * and id==false if we want a new object
87
+	 *
88
+	 * @param AbstractTDBMObject $object      The object containing this db row
89
+	 * @param string             $table_name
90
+	 * @param array              $primaryKeys
91
+	 * @param TDBMService        $tdbmService
92
+	 *
93
+	 * @throws TDBMException
94
+	 * @throws TDBMInvalidOperationException
95
+	 */
96
+	public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
+	{
98
+		$this->object = $object;
99
+		$this->dbTableName = $table_name;
100
+
101
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
+
103
+		if ($tdbmService === null) {
104
+			if (!empty($primaryKeys)) {
105
+				throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
+			}
107
+		} else {
108
+			$this->tdbmService = $tdbmService;
109
+
110
+			if (!empty($primaryKeys)) {
111
+				$this->_setPrimaryKeys($primaryKeys);
112
+				if (!empty($dbRow)) {
113
+					$this->dbRow = $dbRow;
114
+					$this->status = TDBMObjectStateEnum::STATE_LOADED;
115
+				} else {
116
+					$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
+				}
118
+				$tdbmService->_addToCache($this);
119
+			} else {
120
+				$this->status = TDBMObjectStateEnum::STATE_NEW;
121
+				$this->tdbmService->_addToToSaveObjectList($this);
122
+			}
123
+		}
124
+	}
125
+
126
+	public function _attach(TDBMService $tdbmService)
127
+	{
128
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
+		}
131
+		$this->tdbmService = $tdbmService;
132
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
133
+		$this->tdbmService->_addToToSaveObjectList($this);
134
+	}
135
+
136
+	/**
137
+	 * Sets the state of the TDBM Object
138
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
+	 *
143
+	 * @param string $state
144
+	 */
145
+	public function _setStatus($state)
146
+	{
147
+		$this->status = $state;
148
+	}
149
+
150
+	/**
151
+	 * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
+	 * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
+	 *
154
+	 * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
+	 * cannot be found).
156
+	 */
157
+	public function _dbLoadIfNotLoaded()
158
+	{
159
+		if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
+			$connection = $this->tdbmService->getConnection();
161
+
162
+			/// buildFilterFromFilterBag($filter_bag)
163
+			list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
+
165
+			$sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
+			$result = $connection->executeQuery($sql, $parameters);
167
+
168
+			if ($result->rowCount() === 0) {
169
+				throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
+			}
171
+
172
+			$row = $result->fetch(\PDO::FETCH_ASSOC);
173
+
174
+			$this->dbRow = [];
175
+			$types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
+
177
+			foreach ($row as $key => $value) {
178
+				$this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
+			}
180
+
181
+			$result->closeCursor();
182
+
183
+			$this->status = TDBMObjectStateEnum::STATE_LOADED;
184
+		}
185
+	}
186
+
187
+	public function get($var)
188
+	{
189
+		$this->_dbLoadIfNotLoaded();
190
+
191
+		// Let's first check if the key exist.
192
+		if (!isset($this->dbRow[$var])) {
193
+			/*
194 194
             // Unable to find column.... this is an error if the object has been retrieved from database.
195 195
             // If it's a new object, well, that may not be an error after all!
196 196
             // Let's check if the column does exist in the table
@@ -210,39 +210,39 @@  discard block
 block discarded – undo
210 210
             $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
211 211
 
212 212
             throw new TDBMException($str);*/
213
-            return;
214
-        }
215
-
216
-        $value = $this->dbRow[$var];
217
-        if ($value instanceof \DateTime) {
218
-            if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
-                return \DateTimeImmutable::createFromMutable($value);
220
-            } else {
221
-                return new \DateTimeImmutable($value->format('c'));
222
-            }
223
-        }
224
-
225
-        return $this->dbRow[$var];
226
-    }
227
-
228
-    /**
229
-     * Returns true if a column is set, false otherwise.
230
-     *
231
-     * @param string $var
232
-     *
233
-     * @return bool
234
-     */
235
-    /*public function has($var) {
213
+			return;
214
+		}
215
+
216
+		$value = $this->dbRow[$var];
217
+		if ($value instanceof \DateTime) {
218
+			if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
+				return \DateTimeImmutable::createFromMutable($value);
220
+			} else {
221
+				return new \DateTimeImmutable($value->format('c'));
222
+			}
223
+		}
224
+
225
+		return $this->dbRow[$var];
226
+	}
227
+
228
+	/**
229
+	 * Returns true if a column is set, false otherwise.
230
+	 *
231
+	 * @param string $var
232
+	 *
233
+	 * @return bool
234
+	 */
235
+	/*public function has($var) {
236 236
         $this->_dbLoadIfNotLoaded();
237 237
 
238 238
         return isset($this->dbRow[$var]);
239 239
     }*/
240 240
 
241
-    public function set($var, $value)
242
-    {
243
-        $this->_dbLoadIfNotLoaded();
241
+	public function set($var, $value)
242
+	{
243
+		$this->_dbLoadIfNotLoaded();
244 244
 
245
-        /*
245
+		/*
246 246
         // Ok, let's start by checking the column type
247 247
         $type = $this->db_connection->getColumnType($this->dbTableName, $var);
248 248
 
@@ -252,198 +252,198 @@  discard block
 block discarded – undo
252 252
         }
253 253
         */
254 254
 
255
-        /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
255
+		/*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
256 256
             throw new TDBMException("Error! Changing primary key value is forbidden.");*/
257
-        $this->dbRow[$var] = $value;
258
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
-            $this->tdbmService->_addToToSaveObjectList($this);
261
-        }
262
-    }
263
-
264
-    /**
265
-     * @param string             $foreignKeyName
266
-     * @param AbstractTDBMObject $bean
267
-     */
268
-    public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
-    {
270
-        $this->references[$foreignKeyName] = $bean;
271
-
272
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
-            $this->tdbmService->_addToToSaveObjectList($this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    public function getRef($foreignKeyName)
284
-    {
285
-        if (array_key_exists($foreignKeyName, $this->references)) {
286
-            return $this->references[$foreignKeyName];
287
-        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
288
-            // If the object is new and has no property, then it has to be empty.
289
-            return;
290
-        } else {
291
-            $this->_dbLoadIfNotLoaded();
292
-
293
-            // Let's match the name of the columns to the primary key values
294
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
-
296
-            $values = [];
297
-            foreach ($fk->getLocalColumns() as $column) {
298
-                if (!isset($this->dbRow[$column])) {
299
-                    return;
300
-                }
301
-                $values[] = $this->dbRow[$column];
302
-            }
303
-
304
-            $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
-
306
-            return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
-        }
308
-    }
309
-
310
-    /**
311
-     * Returns the name of the table this object comes from.
312
-     *
313
-     * @return string
314
-     */
315
-    public function _getDbTableName()
316
-    {
317
-        return $this->dbTableName;
318
-    }
319
-
320
-    /**
321
-     * Method used internally by TDBM. You should not use it directly.
322
-     * This method returns the status of the TDBMObject.
323
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
-     *
328
-     * @return string
329
-     */
330
-    public function _getStatus()
331
-    {
332
-        return $this->status;
333
-    }
334
-
335
-    /**
336
-     * Override the native php clone function for TDBMObjects.
337
-     */
338
-    public function __clone()
339
-    {
340
-        // Let's load the row (before we lose the ID!)
341
-        $this->_dbLoadIfNotLoaded();
342
-
343
-        //Let's set the status to detached
344
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
-
346
-        $this->primaryKeys = [];
347
-
348
-        //Now unset the PK from the row
349
-        if ($this->tdbmService) {
350
-            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
-            foreach ($pk_array as $pk) {
352
-                $this->dbRow[$pk] = null;
353
-            }
354
-        }
355
-    }
356
-
357
-    /**
358
-     * Returns raw database row.
359
-     *
360
-     * @return array
361
-     *
362
-     * @throws TDBMMissingReferenceException
363
-     */
364
-    public function _getDbRow()
365
-    {
366
-        // Let's merge $dbRow and $references
367
-        $dbRow = $this->dbRow;
368
-
369
-        foreach ($this->references as $foreignKeyName => $reference) {
370
-            // Let's match the name of the columns to the primary key values
371
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
372
-            $localColumns = $fk->getLocalColumns();
373
-
374
-            if ($reference !== null) {
375
-                $refDbRows = $reference->_getDbRows();
376
-                $firstRefDbRow = reset($refDbRows);
377
-                if ($firstRefDbRow->_getStatus() == TDBMObjectStateEnum::STATE_DELETED) {
378
-                    throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
379
-                }
380
-                $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
381
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
382
-                    $dbRow[$localColumns[$i]] = $pkValues[$i];
383
-                }
384
-            } else {
385
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
386
-                    $dbRow[$localColumns[$i]] = null;
387
-                }
388
-            }
389
-        }
390
-
391
-        return $dbRow;
392
-    }
393
-
394
-    /**
395
-     * Returns references array.
396
-     *
397
-     * @return AbstractTDBMObject[]
398
-     */
399
-    public function _getReferences()
400
-    {
401
-        return $this->references;
402
-    }
403
-
404
-    /**
405
-     * Returns the values of the primary key.
406
-     * This is set when the object is in "loaded" state.
407
-     *
408
-     * @return array
409
-     */
410
-    public function _getPrimaryKeys()
411
-    {
412
-        return $this->primaryKeys;
413
-    }
414
-
415
-    /**
416
-     * Sets the values of the primary key.
417
-     * This is set when the object is in "loaded" state.
418
-     *
419
-     * @param array $primaryKeys
420
-     */
421
-    public function _setPrimaryKeys(array $primaryKeys)
422
-    {
423
-        $this->primaryKeys = $primaryKeys;
424
-        foreach ($this->primaryKeys as $column => $value) {
425
-            $this->dbRow[$column] = $value;
426
-        }
427
-    }
428
-
429
-    /**
430
-     * Returns the TDBMObject this bean is associated to.
431
-     *
432
-     * @return AbstractTDBMObject
433
-     */
434
-    public function getTDBMObject()
435
-    {
436
-        return $this->object;
437
-    }
438
-
439
-    /**
440
-     * Sets the TDBMObject this bean is associated to.
441
-     * Only used when cloning.
442
-     *
443
-     * @param AbstractTDBMObject $object
444
-     */
445
-    public function setTDBMObject(AbstractTDBMObject $object)
446
-    {
447
-        $this->object = $object;
448
-    }
257
+		$this->dbRow[$var] = $value;
258
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
+			$this->tdbmService->_addToToSaveObjectList($this);
261
+		}
262
+	}
263
+
264
+	/**
265
+	 * @param string             $foreignKeyName
266
+	 * @param AbstractTDBMObject $bean
267
+	 */
268
+	public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
+	{
270
+		$this->references[$foreignKeyName] = $bean;
271
+
272
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
+			$this->tdbmService->_addToToSaveObjectList($this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	public function getRef($foreignKeyName)
284
+	{
285
+		if (array_key_exists($foreignKeyName, $this->references)) {
286
+			return $this->references[$foreignKeyName];
287
+		} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
288
+			// If the object is new and has no property, then it has to be empty.
289
+			return;
290
+		} else {
291
+			$this->_dbLoadIfNotLoaded();
292
+
293
+			// Let's match the name of the columns to the primary key values
294
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
+
296
+			$values = [];
297
+			foreach ($fk->getLocalColumns() as $column) {
298
+				if (!isset($this->dbRow[$column])) {
299
+					return;
300
+				}
301
+				$values[] = $this->dbRow[$column];
302
+			}
303
+
304
+			$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
+
306
+			return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
+		}
308
+	}
309
+
310
+	/**
311
+	 * Returns the name of the table this object comes from.
312
+	 *
313
+	 * @return string
314
+	 */
315
+	public function _getDbTableName()
316
+	{
317
+		return $this->dbTableName;
318
+	}
319
+
320
+	/**
321
+	 * Method used internally by TDBM. You should not use it directly.
322
+	 * This method returns the status of the TDBMObject.
323
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
+	 *
328
+	 * @return string
329
+	 */
330
+	public function _getStatus()
331
+	{
332
+		return $this->status;
333
+	}
334
+
335
+	/**
336
+	 * Override the native php clone function for TDBMObjects.
337
+	 */
338
+	public function __clone()
339
+	{
340
+		// Let's load the row (before we lose the ID!)
341
+		$this->_dbLoadIfNotLoaded();
342
+
343
+		//Let's set the status to detached
344
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
+
346
+		$this->primaryKeys = [];
347
+
348
+		//Now unset the PK from the row
349
+		if ($this->tdbmService) {
350
+			$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
+			foreach ($pk_array as $pk) {
352
+				$this->dbRow[$pk] = null;
353
+			}
354
+		}
355
+	}
356
+
357
+	/**
358
+	 * Returns raw database row.
359
+	 *
360
+	 * @return array
361
+	 *
362
+	 * @throws TDBMMissingReferenceException
363
+	 */
364
+	public function _getDbRow()
365
+	{
366
+		// Let's merge $dbRow and $references
367
+		$dbRow = $this->dbRow;
368
+
369
+		foreach ($this->references as $foreignKeyName => $reference) {
370
+			// Let's match the name of the columns to the primary key values
371
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
372
+			$localColumns = $fk->getLocalColumns();
373
+
374
+			if ($reference !== null) {
375
+				$refDbRows = $reference->_getDbRows();
376
+				$firstRefDbRow = reset($refDbRows);
377
+				if ($firstRefDbRow->_getStatus() == TDBMObjectStateEnum::STATE_DELETED) {
378
+					throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
379
+				}
380
+				$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
381
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
382
+					$dbRow[$localColumns[$i]] = $pkValues[$i];
383
+				}
384
+			} else {
385
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
386
+					$dbRow[$localColumns[$i]] = null;
387
+				}
388
+			}
389
+		}
390
+
391
+		return $dbRow;
392
+	}
393
+
394
+	/**
395
+	 * Returns references array.
396
+	 *
397
+	 * @return AbstractTDBMObject[]
398
+	 */
399
+	public function _getReferences()
400
+	{
401
+		return $this->references;
402
+	}
403
+
404
+	/**
405
+	 * Returns the values of the primary key.
406
+	 * This is set when the object is in "loaded" state.
407
+	 *
408
+	 * @return array
409
+	 */
410
+	public function _getPrimaryKeys()
411
+	{
412
+		return $this->primaryKeys;
413
+	}
414
+
415
+	/**
416
+	 * Sets the values of the primary key.
417
+	 * This is set when the object is in "loaded" state.
418
+	 *
419
+	 * @param array $primaryKeys
420
+	 */
421
+	public function _setPrimaryKeys(array $primaryKeys)
422
+	{
423
+		$this->primaryKeys = $primaryKeys;
424
+		foreach ($this->primaryKeys as $column => $value) {
425
+			$this->dbRow[$column] = $value;
426
+		}
427
+	}
428
+
429
+	/**
430
+	 * Returns the TDBMObject this bean is associated to.
431
+	 *
432
+	 * @return AbstractTDBMObject
433
+	 */
434
+	public function getTDBMObject()
435
+	{
436
+		return $this->object;
437
+	}
438
+
439
+	/**
440
+	 * Sets the TDBMObject this bean is associated to.
441
+	 * Only used when cloning.
442
+	 *
443
+	 * @param AbstractTDBMObject $object
444
+	 */
445
+	public function setTDBMObject(AbstractTDBMObject $object)
446
+	{
447
+		$this->object = $object;
448
+	}
449 449
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMObjectStateEnum.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -27,11 +27,11 @@
 block discarded – undo
27 27
  */
28 28
 final class TDBMObjectStateEnum
29 29
 {
30
-    const STATE_DETACHED = 'detached';
31
-    const STATE_NEW = 'new';
32
-    const STATE_SAVING = 'saving';
33
-    const STATE_NOT_LOADED = 'not loaded';
34
-    const STATE_LOADED = 'loaded';
35
-    const STATE_DIRTY = 'dirty';
36
-    const STATE_DELETED = 'deleted';
30
+	const STATE_DETACHED = 'detached';
31
+	const STATE_NEW = 'new';
32
+	const STATE_SAVING = 'saving';
33
+	const STATE_NOT_LOADED = 'not loaded';
34
+	const STATE_LOADED = 'loaded';
35
+	const STATE_DIRTY = 'dirty';
36
+	const STATE_DELETED = 'deleted';
37 37
 }
Please login to merge, or discard this patch.