Test Failed
Pull Request — 4.2 (#140)
by David
09:06
created
src/Mouf/Database/TDBM/TDBMService.php 2 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -21,11 +21,9 @@
 block discarded – undo
21 21
 namespace Mouf\Database\TDBM;
22 22
 
23 23
 use Doctrine\Common\Cache\Cache;
24
-use Doctrine\Common\Cache\VoidCache;
25 24
 use Doctrine\DBAL\Connection;
26 25
 use Doctrine\DBAL\Schema\Column;
27 26
 use Doctrine\DBAL\Schema\ForeignKeyConstraint;
28
-use Doctrine\DBAL\Schema\Schema;
29 27
 use Doctrine\DBAL\Schema\Table;
30 28
 use Doctrine\DBAL\Types\Type;
31 29
 use Mouf\Database\MagicQuery;
Please login to merge, or discard this patch.
Indentation   +1364 added lines, -1364 removed lines patch added patch discarded remove patch
@@ -48,384 +48,384 @@  discard block
 block discarded – undo
48 48
  */
49 49
 class TDBMService
50 50
 {
51
-    const MODE_CURSOR = 1;
52
-    const MODE_ARRAY = 2;
53
-
54
-    /**
55
-     * The database connection.
56
-     *
57
-     * @var Connection
58
-     */
59
-    private $connection;
60
-
61
-    /**
62
-     * @var SchemaAnalyzer
63
-     */
64
-    private $schemaAnalyzer;
65
-
66
-    /**
67
-     * @var MagicQuery
68
-     */
69
-    private $magicQuery;
70
-
71
-    /**
72
-     * @var TDBMSchemaAnalyzer
73
-     */
74
-    private $tdbmSchemaAnalyzer;
75
-
76
-    /**
77
-     * @var string
78
-     */
79
-    private $cachePrefix;
80
-
81
-    /**
82
-     * Cache of table of primary keys.
83
-     * Primary keys are stored by tables, as an array of column.
84
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
85
-     *
86
-     * @var string[]
87
-     */
88
-    private $primaryKeysColumns;
89
-
90
-    /**
91
-     * Service storing objects in memory.
92
-     * Access is done by table name and then by primary key.
93
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
94
-     *
95
-     * @var StandardObjectStorage|WeakrefObjectStorage
96
-     */
97
-    private $objectStorage;
98
-
99
-    /**
100
-     * The fetch mode of the result sets returned by `getObjects`.
101
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
102
-     *
103
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
104
-     * 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,
105
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
106
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
107
-     * You can access the array by key, or using foreach, several times.
108
-     *
109
-     * @var int
110
-     */
111
-    private $mode = self::MODE_ARRAY;
112
-
113
-    /**
114
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
115
-     *
116
-     * @var \SplObjectStorage of DbRow objects
117
-     */
118
-    private $toSaveObjects;
119
-
120
-    /**
121
-     * A cache service to be used.
122
-     *
123
-     * @var Cache|null
124
-     */
125
-    private $cache;
126
-
127
-    /**
128
-     * Map associating a table name to a fully qualified Bean class name.
129
-     *
130
-     * @var array
131
-     */
132
-    private $tableToBeanMap = [];
133
-
134
-    /**
135
-     * @var \ReflectionClass[]
136
-     */
137
-    private $reflectionClassCache = array();
138
-
139
-    /**
140
-     * @var LoggerInterface
141
-     */
142
-    private $rootLogger;
143
-
144
-    /**
145
-     * @var LevelFilter|NullLogger
146
-     */
147
-    private $logger;
148
-
149
-    /**
150
-     * @var OrderByAnalyzer
151
-     */
152
-    private $orderByAnalyzer;
153
-
154
-    /**
155
-     * @var string
156
-     */
157
-    private $beanNamespace;
158
-
159
-    /**
160
-     * @var NamingStrategyInterface
161
-     */
162
-    private $namingStrategy;
163
-    /**
164
-     * @var ConfigurationInterface
165
-     */
166
-    private $configuration;
167
-
168
-    /**
169
-     * @param ConfigurationInterface $configuration The configuration object
170
-     */
171
-    public function __construct(ConfigurationInterface $configuration)
172
-    {
173
-        if (extension_loaded('weakref')) {
174
-            $this->objectStorage = new WeakrefObjectStorage();
175
-        } else {
176
-            $this->objectStorage = new StandardObjectStorage();
177
-        }
178
-        $this->connection = $configuration->getConnection();
179
-        $this->cache = $configuration->getCache();
180
-        $this->schemaAnalyzer = $configuration->getSchemaAnalyzer();
181
-
182
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
183
-
184
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->connection, $this->cache, $this->schemaAnalyzer);
185
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
186
-
187
-        $this->toSaveObjects = new \SplObjectStorage();
188
-        $logger = $configuration->getLogger();
189
-        if ($logger === null) {
190
-            $this->logger = new NullLogger();
191
-            $this->rootLogger = new NullLogger();
192
-        } else {
193
-            $this->rootLogger = $logger;
194
-            $this->setLogLevel(LogLevel::WARNING);
195
-        }
196
-        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
197
-        $this->beanNamespace = $configuration->getBeanNamespace();
198
-        $this->namingStrategy = $configuration->getNamingStrategy();
199
-        $this->configuration = $configuration;
200
-    }
201
-
202
-    /**
203
-     * Returns the object used to connect to the database.
204
-     *
205
-     * @return Connection
206
-     */
207
-    public function getConnection(): Connection
208
-    {
209
-        return $this->connection;
210
-    }
211
-
212
-    /**
213
-     * Sets the default fetch mode of the result sets returned by `findObjects`.
214
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
215
-     *
216
-     * 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).
217
-     * 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
218
-     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
219
-     *
220
-     * @param int $mode
221
-     *
222
-     * @return $this
223
-     *
224
-     * @throws TDBMException
225
-     */
226
-    public function setFetchMode($mode)
227
-    {
228
-        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
229
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
230
-        }
231
-        $this->mode = $mode;
232
-
233
-        return $this;
234
-    }
235
-
236
-    /**
237
-     * Removes the given object from database.
238
-     * This cannot be called on an object that is not attached to this TDBMService
239
-     * (will throw a TDBMInvalidOperationException).
240
-     *
241
-     * @param AbstractTDBMObject $object the object to delete
242
-     *
243
-     * @throws TDBMException
244
-     * @throws TDBMInvalidOperationException
245
-     */
246
-    public function delete(AbstractTDBMObject $object)
247
-    {
248
-        switch ($object->_getStatus()) {
249
-            case TDBMObjectStateEnum::STATE_DELETED:
250
-                // Nothing to do, object already deleted.
251
-                return;
252
-            case TDBMObjectStateEnum::STATE_DETACHED:
253
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
254
-            case TDBMObjectStateEnum::STATE_NEW:
255
-                $this->deleteManyToManyRelationships($object);
256
-                foreach ($object->_getDbRows() as $dbRow) {
257
-                    $this->removeFromToSaveObjectList($dbRow);
258
-                }
259
-                break;
260
-            case TDBMObjectStateEnum::STATE_DIRTY:
261
-                foreach ($object->_getDbRows() as $dbRow) {
262
-                    $this->removeFromToSaveObjectList($dbRow);
263
-                }
264
-                // And continue deleting...
265
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
266
-            case TDBMObjectStateEnum::STATE_LOADED:
267
-                $this->deleteManyToManyRelationships($object);
268
-                // Let's delete db rows, in reverse order.
269
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
270
-                    $tableName = $dbRow->_getDbTableName();
271
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
272
-                    $this->connection->delete($tableName, $primaryKeys);
273
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
274
-                }
275
-                break;
276
-            // @codeCoverageIgnoreStart
277
-            default:
278
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
279
-            // @codeCoverageIgnoreEnd
280
-        }
281
-
282
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
283
-    }
284
-
285
-    /**
286
-     * Removes all many to many relationships for this object.
287
-     *
288
-     * @param AbstractTDBMObject $object
289
-     */
290
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
291
-    {
292
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
293
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
294
-            foreach ($pivotTables as $pivotTable) {
295
-                $remoteBeans = $object->_getRelationships($pivotTable);
296
-                foreach ($remoteBeans as $remoteBean) {
297
-                    $object->_removeRelationship($pivotTable, $remoteBean);
298
-                }
299
-            }
300
-        }
301
-        $this->persistManyToManyRelationships($object);
302
-    }
303
-
304
-    /**
305
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
306
-     * by parameter before all.
307
-     *
308
-     * Notice: if the object has a multiple primary key, the function will not work.
309
-     *
310
-     * @param AbstractTDBMObject $objToDelete
311
-     */
312
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
313
-    {
314
-        $this->deleteAllConstraintWithThisObject($objToDelete);
315
-        $this->delete($objToDelete);
316
-    }
317
-
318
-    /**
319
-     * This function is used only in TDBMService (private function)
320
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
321
-     *
322
-     * @param AbstractTDBMObject $obj
323
-     */
324
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
325
-    {
326
-        $dbRows = $obj->_getDbRows();
327
-        foreach ($dbRows as $dbRow) {
328
-            $tableName = $dbRow->_getDbTableName();
329
-            $pks = array_values($dbRow->_getPrimaryKeys());
330
-            if (!empty($pks)) {
331
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
332
-
333
-                foreach ($incomingFks as $incomingFk) {
334
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
335
-
336
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
337
-
338
-                    foreach ($results as $bean) {
339
-                        $this->deleteCascade($bean);
340
-                    }
341
-                }
342
-            }
343
-        }
344
-    }
345
-
346
-    /**
347
-     * This function performs a save() of all the objects that have been modified.
348
-     */
349
-    public function completeSave()
350
-    {
351
-        foreach ($this->toSaveObjects as $dbRow) {
352
-            $this->save($dbRow->getTDBMObject());
353
-        }
354
-    }
355
-
356
-    /**
357
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
358
-     * and gives back a proper Filter object.
359
-     *
360
-     * @param mixed $filter_bag
361
-     * @param int   $counter
362
-     *
363
-     * @return array First item: filter string, second item: parameters
364
-     *
365
-     * @throws TDBMException
366
-     */
367
-    public function buildFilterFromFilterBag($filter_bag, $counter = 1)
368
-    {
369
-        if ($filter_bag === null) {
370
-            return ['', []];
371
-        } elseif (is_string($filter_bag)) {
372
-            return [$filter_bag, []];
373
-        } elseif (is_array($filter_bag)) {
374
-            $sqlParts = [];
375
-            $parameters = [];
376
-            foreach ($filter_bag as $column => $value) {
377
-                if (is_int($column)) {
378
-                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
379
-                    $sqlParts[] = $subSqlPart;
380
-                    $parameters += $subParameters;
381
-                } else {
382
-                    $paramName = 'tdbmparam'.$counter;
383
-                    if (is_array($value)) {
384
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
385
-                    } else {
386
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
387
-                    }
388
-                    $parameters[$paramName] = $value;
389
-                    ++$counter;
390
-                }
391
-            }
392
-
393
-            return [implode(' AND ', $sqlParts), $parameters];
394
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
395
-            $sqlParts = [];
396
-            $parameters = [];
397
-            $dbRows = $filter_bag->_getDbRows();
398
-            $dbRow = reset($dbRows);
399
-            $primaryKeys = $dbRow->_getPrimaryKeys();
400
-
401
-            foreach ($primaryKeys as $column => $value) {
402
-                $paramName = 'tdbmparam'.$counter;
403
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
404
-                $parameters[$paramName] = $value;
405
-                ++$counter;
406
-            }
407
-
408
-            return [implode(' AND ', $sqlParts), $parameters];
409
-        } elseif ($filter_bag instanceof \Iterator) {
410
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
411
-        } else {
412
-            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.');
413
-        }
414
-    }
415
-
416
-    /**
417
-     * @param string $table
418
-     *
419
-     * @return string[]
420
-     */
421
-    public function getPrimaryKeyColumns($table)
422
-    {
423
-        if (!isset($this->primaryKeysColumns[$table])) {
424
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
425
-
426
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
427
-
428
-            /*$arr = array();
51
+	const MODE_CURSOR = 1;
52
+	const MODE_ARRAY = 2;
53
+
54
+	/**
55
+	 * The database connection.
56
+	 *
57
+	 * @var Connection
58
+	 */
59
+	private $connection;
60
+
61
+	/**
62
+	 * @var SchemaAnalyzer
63
+	 */
64
+	private $schemaAnalyzer;
65
+
66
+	/**
67
+	 * @var MagicQuery
68
+	 */
69
+	private $magicQuery;
70
+
71
+	/**
72
+	 * @var TDBMSchemaAnalyzer
73
+	 */
74
+	private $tdbmSchemaAnalyzer;
75
+
76
+	/**
77
+	 * @var string
78
+	 */
79
+	private $cachePrefix;
80
+
81
+	/**
82
+	 * Cache of table of primary keys.
83
+	 * Primary keys are stored by tables, as an array of column.
84
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
85
+	 *
86
+	 * @var string[]
87
+	 */
88
+	private $primaryKeysColumns;
89
+
90
+	/**
91
+	 * Service storing objects in memory.
92
+	 * Access is done by table name and then by primary key.
93
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
94
+	 *
95
+	 * @var StandardObjectStorage|WeakrefObjectStorage
96
+	 */
97
+	private $objectStorage;
98
+
99
+	/**
100
+	 * The fetch mode of the result sets returned by `getObjects`.
101
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
102
+	 *
103
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
104
+	 * 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,
105
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
106
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
107
+	 * You can access the array by key, or using foreach, several times.
108
+	 *
109
+	 * @var int
110
+	 */
111
+	private $mode = self::MODE_ARRAY;
112
+
113
+	/**
114
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
115
+	 *
116
+	 * @var \SplObjectStorage of DbRow objects
117
+	 */
118
+	private $toSaveObjects;
119
+
120
+	/**
121
+	 * A cache service to be used.
122
+	 *
123
+	 * @var Cache|null
124
+	 */
125
+	private $cache;
126
+
127
+	/**
128
+	 * Map associating a table name to a fully qualified Bean class name.
129
+	 *
130
+	 * @var array
131
+	 */
132
+	private $tableToBeanMap = [];
133
+
134
+	/**
135
+	 * @var \ReflectionClass[]
136
+	 */
137
+	private $reflectionClassCache = array();
138
+
139
+	/**
140
+	 * @var LoggerInterface
141
+	 */
142
+	private $rootLogger;
143
+
144
+	/**
145
+	 * @var LevelFilter|NullLogger
146
+	 */
147
+	private $logger;
148
+
149
+	/**
150
+	 * @var OrderByAnalyzer
151
+	 */
152
+	private $orderByAnalyzer;
153
+
154
+	/**
155
+	 * @var string
156
+	 */
157
+	private $beanNamespace;
158
+
159
+	/**
160
+	 * @var NamingStrategyInterface
161
+	 */
162
+	private $namingStrategy;
163
+	/**
164
+	 * @var ConfigurationInterface
165
+	 */
166
+	private $configuration;
167
+
168
+	/**
169
+	 * @param ConfigurationInterface $configuration The configuration object
170
+	 */
171
+	public function __construct(ConfigurationInterface $configuration)
172
+	{
173
+		if (extension_loaded('weakref')) {
174
+			$this->objectStorage = new WeakrefObjectStorage();
175
+		} else {
176
+			$this->objectStorage = new StandardObjectStorage();
177
+		}
178
+		$this->connection = $configuration->getConnection();
179
+		$this->cache = $configuration->getCache();
180
+		$this->schemaAnalyzer = $configuration->getSchemaAnalyzer();
181
+
182
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
183
+
184
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->connection, $this->cache, $this->schemaAnalyzer);
185
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
186
+
187
+		$this->toSaveObjects = new \SplObjectStorage();
188
+		$logger = $configuration->getLogger();
189
+		if ($logger === null) {
190
+			$this->logger = new NullLogger();
191
+			$this->rootLogger = new NullLogger();
192
+		} else {
193
+			$this->rootLogger = $logger;
194
+			$this->setLogLevel(LogLevel::WARNING);
195
+		}
196
+		$this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
197
+		$this->beanNamespace = $configuration->getBeanNamespace();
198
+		$this->namingStrategy = $configuration->getNamingStrategy();
199
+		$this->configuration = $configuration;
200
+	}
201
+
202
+	/**
203
+	 * Returns the object used to connect to the database.
204
+	 *
205
+	 * @return Connection
206
+	 */
207
+	public function getConnection(): Connection
208
+	{
209
+		return $this->connection;
210
+	}
211
+
212
+	/**
213
+	 * Sets the default fetch mode of the result sets returned by `findObjects`.
214
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
215
+	 *
216
+	 * 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).
217
+	 * 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
218
+	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
219
+	 *
220
+	 * @param int $mode
221
+	 *
222
+	 * @return $this
223
+	 *
224
+	 * @throws TDBMException
225
+	 */
226
+	public function setFetchMode($mode)
227
+	{
228
+		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
229
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
230
+		}
231
+		$this->mode = $mode;
232
+
233
+		return $this;
234
+	}
235
+
236
+	/**
237
+	 * Removes the given object from database.
238
+	 * This cannot be called on an object that is not attached to this TDBMService
239
+	 * (will throw a TDBMInvalidOperationException).
240
+	 *
241
+	 * @param AbstractTDBMObject $object the object to delete
242
+	 *
243
+	 * @throws TDBMException
244
+	 * @throws TDBMInvalidOperationException
245
+	 */
246
+	public function delete(AbstractTDBMObject $object)
247
+	{
248
+		switch ($object->_getStatus()) {
249
+			case TDBMObjectStateEnum::STATE_DELETED:
250
+				// Nothing to do, object already deleted.
251
+				return;
252
+			case TDBMObjectStateEnum::STATE_DETACHED:
253
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
254
+			case TDBMObjectStateEnum::STATE_NEW:
255
+				$this->deleteManyToManyRelationships($object);
256
+				foreach ($object->_getDbRows() as $dbRow) {
257
+					$this->removeFromToSaveObjectList($dbRow);
258
+				}
259
+				break;
260
+			case TDBMObjectStateEnum::STATE_DIRTY:
261
+				foreach ($object->_getDbRows() as $dbRow) {
262
+					$this->removeFromToSaveObjectList($dbRow);
263
+				}
264
+				// And continue deleting...
265
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
266
+			case TDBMObjectStateEnum::STATE_LOADED:
267
+				$this->deleteManyToManyRelationships($object);
268
+				// Let's delete db rows, in reverse order.
269
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
270
+					$tableName = $dbRow->_getDbTableName();
271
+					$primaryKeys = $dbRow->_getPrimaryKeys();
272
+					$this->connection->delete($tableName, $primaryKeys);
273
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
274
+				}
275
+				break;
276
+			// @codeCoverageIgnoreStart
277
+			default:
278
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
279
+			// @codeCoverageIgnoreEnd
280
+		}
281
+
282
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
283
+	}
284
+
285
+	/**
286
+	 * Removes all many to many relationships for this object.
287
+	 *
288
+	 * @param AbstractTDBMObject $object
289
+	 */
290
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
291
+	{
292
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
293
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
294
+			foreach ($pivotTables as $pivotTable) {
295
+				$remoteBeans = $object->_getRelationships($pivotTable);
296
+				foreach ($remoteBeans as $remoteBean) {
297
+					$object->_removeRelationship($pivotTable, $remoteBean);
298
+				}
299
+			}
300
+		}
301
+		$this->persistManyToManyRelationships($object);
302
+	}
303
+
304
+	/**
305
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
306
+	 * by parameter before all.
307
+	 *
308
+	 * Notice: if the object has a multiple primary key, the function will not work.
309
+	 *
310
+	 * @param AbstractTDBMObject $objToDelete
311
+	 */
312
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
313
+	{
314
+		$this->deleteAllConstraintWithThisObject($objToDelete);
315
+		$this->delete($objToDelete);
316
+	}
317
+
318
+	/**
319
+	 * This function is used only in TDBMService (private function)
320
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
321
+	 *
322
+	 * @param AbstractTDBMObject $obj
323
+	 */
324
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
325
+	{
326
+		$dbRows = $obj->_getDbRows();
327
+		foreach ($dbRows as $dbRow) {
328
+			$tableName = $dbRow->_getDbTableName();
329
+			$pks = array_values($dbRow->_getPrimaryKeys());
330
+			if (!empty($pks)) {
331
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
332
+
333
+				foreach ($incomingFks as $incomingFk) {
334
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
335
+
336
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
337
+
338
+					foreach ($results as $bean) {
339
+						$this->deleteCascade($bean);
340
+					}
341
+				}
342
+			}
343
+		}
344
+	}
345
+
346
+	/**
347
+	 * This function performs a save() of all the objects that have been modified.
348
+	 */
349
+	public function completeSave()
350
+	{
351
+		foreach ($this->toSaveObjects as $dbRow) {
352
+			$this->save($dbRow->getTDBMObject());
353
+		}
354
+	}
355
+
356
+	/**
357
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
358
+	 * and gives back a proper Filter object.
359
+	 *
360
+	 * @param mixed $filter_bag
361
+	 * @param int   $counter
362
+	 *
363
+	 * @return array First item: filter string, second item: parameters
364
+	 *
365
+	 * @throws TDBMException
366
+	 */
367
+	public function buildFilterFromFilterBag($filter_bag, $counter = 1)
368
+	{
369
+		if ($filter_bag === null) {
370
+			return ['', []];
371
+		} elseif (is_string($filter_bag)) {
372
+			return [$filter_bag, []];
373
+		} elseif (is_array($filter_bag)) {
374
+			$sqlParts = [];
375
+			$parameters = [];
376
+			foreach ($filter_bag as $column => $value) {
377
+				if (is_int($column)) {
378
+					list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
379
+					$sqlParts[] = $subSqlPart;
380
+					$parameters += $subParameters;
381
+				} else {
382
+					$paramName = 'tdbmparam'.$counter;
383
+					if (is_array($value)) {
384
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
385
+					} else {
386
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
387
+					}
388
+					$parameters[$paramName] = $value;
389
+					++$counter;
390
+				}
391
+			}
392
+
393
+			return [implode(' AND ', $sqlParts), $parameters];
394
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
395
+			$sqlParts = [];
396
+			$parameters = [];
397
+			$dbRows = $filter_bag->_getDbRows();
398
+			$dbRow = reset($dbRows);
399
+			$primaryKeys = $dbRow->_getPrimaryKeys();
400
+
401
+			foreach ($primaryKeys as $column => $value) {
402
+				$paramName = 'tdbmparam'.$counter;
403
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
404
+				$parameters[$paramName] = $value;
405
+				++$counter;
406
+			}
407
+
408
+			return [implode(' AND ', $sqlParts), $parameters];
409
+		} elseif ($filter_bag instanceof \Iterator) {
410
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
411
+		} else {
412
+			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.');
413
+		}
414
+	}
415
+
416
+	/**
417
+	 * @param string $table
418
+	 *
419
+	 * @return string[]
420
+	 */
421
+	public function getPrimaryKeyColumns($table)
422
+	{
423
+		if (!isset($this->primaryKeysColumns[$table])) {
424
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
425
+
426
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
427
+
428
+			/*$arr = array();
429 429
             foreach ($this->connection->getPrimaryKey($table) as $col) {
430 430
                 $arr[] = $col->name;
431 431
             }
@@ -446,161 +446,161 @@  discard block
 block discarded – undo
446 446
                     throw new TDBMException($str);
447 447
                 }
448 448
             }*/
449
-        }
450
-
451
-        return $this->primaryKeysColumns[$table];
452
-    }
453
-
454
-    /**
455
-     * This is an internal function, you should not use it in your application.
456
-     * This is used internally by TDBM to add an object to the object cache.
457
-     *
458
-     * @param DbRow $dbRow
459
-     */
460
-    public function _addToCache(DbRow $dbRow)
461
-    {
462
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
463
-        $hash = $this->getObjectHash($primaryKey);
464
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
465
-    }
466
-
467
-    /**
468
-     * This is an internal function, you should not use it in your application.
469
-     * This is used internally by TDBM to remove the object from the list of objects that have been
470
-     * created/updated but not saved yet.
471
-     *
472
-     * @param DbRow $myObject
473
-     */
474
-    private function removeFromToSaveObjectList(DbRow $myObject)
475
-    {
476
-        unset($this->toSaveObjects[$myObject]);
477
-    }
478
-
479
-    /**
480
-     * This is an internal function, you should not use it in your application.
481
-     * This is used internally by TDBM to add an object to the list of objects that have been
482
-     * created/updated but not saved yet.
483
-     *
484
-     * @param DbRow $myObject
485
-     */
486
-    public function _addToToSaveObjectList(DbRow $myObject)
487
-    {
488
-        $this->toSaveObjects[$myObject] = true;
489
-    }
490
-
491
-    /**
492
-     * Generates all the daos and beans.
493
-     *
494
-     * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
495
-     *
496
-     * @return \string[] the list of tables (key) and bean name (value)
497
-     */
498
-    public function generateAllDaosAndBeans($composerFile = null)
499
-    {
500
-        // Purge cache before generating anything.
501
-        $this->cache->deleteAll();
502
-
503
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->configuration, $this->tdbmSchemaAnalyzer);
504
-        if (null !== $composerFile) {
505
-            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
506
-        }
507
-
508
-        $tdbmDaoGenerator->generateAllDaosAndBeans();
509
-    }
510
-
511
-    /**
512
-     * Returns the fully qualified class name of the bean associated with table $tableName.
513
-     *
514
-     *
515
-     * @param string $tableName
516
-     *
517
-     * @return string
518
-     */
519
-    public function getBeanClassName(string $tableName) : string
520
-    {
521
-        if (isset($this->tableToBeanMap[$tableName])) {
522
-            return $this->tableToBeanMap[$tableName];
523
-        } else {
524
-            $className = $this->beanNamespace.'\\'.$this->namingStrategy->getBeanClassName($tableName);
525
-
526
-            if (!class_exists($className)) {
527
-                throw new TDBMInvalidArgumentException(sprintf('Could not find class "%s". Does table "%s" exist? If yes, consider regenerating the DAOs and beans.', $className, $tableName));
528
-            }
529
-
530
-            $this->tableToBeanMap[$tableName] = $className;
531
-            return $className;
532
-        }
533
-    }
534
-
535
-    /**
536
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
537
-     *
538
-     * @param AbstractTDBMObject $object
539
-     *
540
-     * @throws TDBMException
541
-     */
542
-    public function save(AbstractTDBMObject $object)
543
-    {
544
-        $status = $object->_getStatus();
545
-
546
-        if ($status === null) {
547
-            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)));
548
-        }
549
-
550
-        // Let's attach this object if it is in detached state.
551
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
552
-            $object->_attach($this);
553
-            $status = $object->_getStatus();
554
-        }
555
-
556
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
557
-            $dbRows = $object->_getDbRows();
558
-
559
-            $unindexedPrimaryKeys = array();
560
-
561
-            foreach ($dbRows as $dbRow) {
562
-                if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
563
-                    throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
564
-                }
565
-                $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
566
-                $tableName = $dbRow->_getDbTableName();
567
-
568
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
569
-                $tableDescriptor = $schema->getTable($tableName);
570
-
571
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
572
-
573
-                $references = $dbRow->_getReferences();
574
-
575
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
576
-                foreach ($references as $fkName => $reference) {
577
-                    if ($reference !== null) {
578
-                        $refStatus = $reference->_getStatus();
579
-                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
580
-                            try {
581
-                                $this->save($reference);
582
-                            } catch (TDBMCyclicReferenceException $e) {
583
-                                throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
584
-                            }
585
-                        }
586
-                    }
587
-                }
588
-
589
-                if (empty($unindexedPrimaryKeys)) {
590
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
591
-                } else {
592
-                    // First insert, the children must have the same primary key as the parent.
593
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
594
-                    $dbRow->_setPrimaryKeys($primaryKeys);
595
-                }
596
-
597
-                $dbRowData = $dbRow->_getDbRow();
598
-
599
-                // Let's see if the columns for primary key have been set before inserting.
600
-                // We assume that if one of the value of the PK has been set, the PK is set.
601
-                $isPkSet = !empty($primaryKeys);
602
-
603
-                /*if (!$isPkSet) {
449
+		}
450
+
451
+		return $this->primaryKeysColumns[$table];
452
+	}
453
+
454
+	/**
455
+	 * This is an internal function, you should not use it in your application.
456
+	 * This is used internally by TDBM to add an object to the object cache.
457
+	 *
458
+	 * @param DbRow $dbRow
459
+	 */
460
+	public function _addToCache(DbRow $dbRow)
461
+	{
462
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
463
+		$hash = $this->getObjectHash($primaryKey);
464
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
465
+	}
466
+
467
+	/**
468
+	 * This is an internal function, you should not use it in your application.
469
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
470
+	 * created/updated but not saved yet.
471
+	 *
472
+	 * @param DbRow $myObject
473
+	 */
474
+	private function removeFromToSaveObjectList(DbRow $myObject)
475
+	{
476
+		unset($this->toSaveObjects[$myObject]);
477
+	}
478
+
479
+	/**
480
+	 * This is an internal function, you should not use it in your application.
481
+	 * This is used internally by TDBM to add an object to the list of objects that have been
482
+	 * created/updated but not saved yet.
483
+	 *
484
+	 * @param DbRow $myObject
485
+	 */
486
+	public function _addToToSaveObjectList(DbRow $myObject)
487
+	{
488
+		$this->toSaveObjects[$myObject] = true;
489
+	}
490
+
491
+	/**
492
+	 * Generates all the daos and beans.
493
+	 *
494
+	 * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
495
+	 *
496
+	 * @return \string[] the list of tables (key) and bean name (value)
497
+	 */
498
+	public function generateAllDaosAndBeans($composerFile = null)
499
+	{
500
+		// Purge cache before generating anything.
501
+		$this->cache->deleteAll();
502
+
503
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->configuration, $this->tdbmSchemaAnalyzer);
504
+		if (null !== $composerFile) {
505
+			$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
506
+		}
507
+
508
+		$tdbmDaoGenerator->generateAllDaosAndBeans();
509
+	}
510
+
511
+	/**
512
+	 * Returns the fully qualified class name of the bean associated with table $tableName.
513
+	 *
514
+	 *
515
+	 * @param string $tableName
516
+	 *
517
+	 * @return string
518
+	 */
519
+	public function getBeanClassName(string $tableName) : string
520
+	{
521
+		if (isset($this->tableToBeanMap[$tableName])) {
522
+			return $this->tableToBeanMap[$tableName];
523
+		} else {
524
+			$className = $this->beanNamespace.'\\'.$this->namingStrategy->getBeanClassName($tableName);
525
+
526
+			if (!class_exists($className)) {
527
+				throw new TDBMInvalidArgumentException(sprintf('Could not find class "%s". Does table "%s" exist? If yes, consider regenerating the DAOs and beans.', $className, $tableName));
528
+			}
529
+
530
+			$this->tableToBeanMap[$tableName] = $className;
531
+			return $className;
532
+		}
533
+	}
534
+
535
+	/**
536
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
537
+	 *
538
+	 * @param AbstractTDBMObject $object
539
+	 *
540
+	 * @throws TDBMException
541
+	 */
542
+	public function save(AbstractTDBMObject $object)
543
+	{
544
+		$status = $object->_getStatus();
545
+
546
+		if ($status === null) {
547
+			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)));
548
+		}
549
+
550
+		// Let's attach this object if it is in detached state.
551
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
552
+			$object->_attach($this);
553
+			$status = $object->_getStatus();
554
+		}
555
+
556
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
557
+			$dbRows = $object->_getDbRows();
558
+
559
+			$unindexedPrimaryKeys = array();
560
+
561
+			foreach ($dbRows as $dbRow) {
562
+				if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
563
+					throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
564
+				}
565
+				$dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
566
+				$tableName = $dbRow->_getDbTableName();
567
+
568
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
569
+				$tableDescriptor = $schema->getTable($tableName);
570
+
571
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
572
+
573
+				$references = $dbRow->_getReferences();
574
+
575
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
576
+				foreach ($references as $fkName => $reference) {
577
+					if ($reference !== null) {
578
+						$refStatus = $reference->_getStatus();
579
+						if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
580
+							try {
581
+								$this->save($reference);
582
+							} catch (TDBMCyclicReferenceException $e) {
583
+								throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
584
+							}
585
+						}
586
+					}
587
+				}
588
+
589
+				if (empty($unindexedPrimaryKeys)) {
590
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
591
+				} else {
592
+					// First insert, the children must have the same primary key as the parent.
593
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
594
+					$dbRow->_setPrimaryKeys($primaryKeys);
595
+				}
596
+
597
+				$dbRowData = $dbRow->_getDbRow();
598
+
599
+				// Let's see if the columns for primary key have been set before inserting.
600
+				// We assume that if one of the value of the PK has been set, the PK is set.
601
+				$isPkSet = !empty($primaryKeys);
602
+
603
+				/*if (!$isPkSet) {
604 604
                     // if there is no autoincrement and no pk set, let's go in error.
605 605
                     $isAutoIncrement = true;
606 606
 
@@ -618,30 +618,30 @@  discard block
 block discarded – undo
618 618
 
619 619
                 }*/
620 620
 
621
-                $types = [];
622
-                $escapedDbRowData = [];
621
+				$types = [];
622
+				$escapedDbRowData = [];
623 623
 
624
-                foreach ($dbRowData as $columnName => $value) {
625
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
626
-                    $types[] = $columnDescriptor->getType();
627
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
628
-                }
624
+				foreach ($dbRowData as $columnName => $value) {
625
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
626
+					$types[] = $columnDescriptor->getType();
627
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
628
+				}
629 629
 
630
-                $this->connection->insert($tableName, $escapedDbRowData, $types);
630
+				$this->connection->insert($tableName, $escapedDbRowData, $types);
631 631
 
632
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
633
-                    $id = $this->connection->lastInsertId();
634
-                    $pkColumn = $primaryKeyColumns[0];
635
-                    // lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
636
-                    $id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
637
-                    $primaryKeys[$pkColumn] = $id;
638
-                }
632
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
633
+					$id = $this->connection->lastInsertId();
634
+					$pkColumn = $primaryKeyColumns[0];
635
+					// lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
636
+					$id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
637
+					$primaryKeys[$pkColumn] = $id;
638
+				}
639 639
 
640
-                // TODO: change this to some private magic accessor in future
641
-                $dbRow->_setPrimaryKeys($primaryKeys);
642
-                $unindexedPrimaryKeys = array_values($primaryKeys);
640
+				// TODO: change this to some private magic accessor in future
641
+				$dbRow->_setPrimaryKeys($primaryKeys);
642
+				$unindexedPrimaryKeys = array_values($primaryKeys);
643 643
 
644
-                /*
644
+				/*
645 645
                  * When attached, on "save", we check if the column updated is part of a primary key
646 646
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
647 647
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
                  *
652 652
                  */
653 653
 
654
-                /*try {
654
+				/*try {
655 655
                     $this->db_connection->exec($sql);
656 656
                 } catch (TDBMException $e) {
657 657
                     $this->db_onerror = true;
@@ -670,405 +670,405 @@  discard block
 block discarded – undo
670 670
                     }
671 671
                 }*/
672 672
 
673
-                // Let's remove this object from the $new_objects static table.
674
-                $this->removeFromToSaveObjectList($dbRow);
675
-
676
-                // TODO: change this behaviour to something more sensible performance-wise
677
-                // Maybe a setting to trigger this globally?
678
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
679
-                //$this->db_modified_state = false;
680
-                //$dbRow = array();
681
-
682
-                // Let's add this object to the list of objects in cache.
683
-                $this->_addToCache($dbRow);
684
-            }
685
-
686
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
687
-        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
688
-            $dbRows = $object->_getDbRows();
689
-
690
-            foreach ($dbRows as $dbRow) {
691
-                $references = $dbRow->_getReferences();
692
-
693
-                // Let's save all references in NEW state (we need their primary key)
694
-                foreach ($references as $fkName => $reference) {
695
-                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
696
-                        $this->save($reference);
697
-                    }
698
-                }
699
-
700
-                // Let's first get the primary keys
701
-                $tableName = $dbRow->_getDbTableName();
702
-                $dbRowData = $dbRow->_getDbRow();
703
-
704
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
705
-                $tableDescriptor = $schema->getTable($tableName);
706
-
707
-                $primaryKeys = $dbRow->_getPrimaryKeys();
708
-
709
-                $types = [];
710
-                $escapedDbRowData = [];
711
-                $escapedPrimaryKeys = [];
712
-
713
-                foreach ($dbRowData as $columnName => $value) {
714
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
715
-                    $types[] = $columnDescriptor->getType();
716
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
717
-                }
718
-                foreach ($primaryKeys as $columnName => $value) {
719
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
720
-                    $types[] = $columnDescriptor->getType();
721
-                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
722
-                }
723
-
724
-                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
725
-
726
-                // Let's check if the primary key has been updated...
727
-                $needsUpdatePk = false;
728
-                foreach ($primaryKeys as $column => $value) {
729
-                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
730
-                        $needsUpdatePk = true;
731
-                        break;
732
-                    }
733
-                }
734
-                if ($needsUpdatePk) {
735
-                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
736
-                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
737
-                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
738
-                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
739
-                }
740
-
741
-                // Let's remove this object from the list of objects to save.
742
-                $this->removeFromToSaveObjectList($dbRow);
743
-            }
744
-
745
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
746
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
747
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
748
-        }
749
-
750
-        // Finally, let's save all the many to many relationships to this bean.
751
-        $this->persistManyToManyRelationships($object);
752
-    }
753
-
754
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
755
-    {
756
-        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
757
-            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
758
-            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
759
-
760
-            $toRemoveFromStorage = [];
761
-
762
-            foreach ($storage as $remoteBean) {
763
-                /* @var $remoteBean AbstractTDBMObject */
764
-                $statusArr = $storage[$remoteBean];
765
-                $status = $statusArr['status'];
766
-                $reverse = $statusArr['reverse'];
767
-                if ($reverse) {
768
-                    continue;
769
-                }
770
-
771
-                if ($status === 'new') {
772
-                    $remoteBeanStatus = $remoteBean->_getStatus();
773
-                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
774
-                        // Let's save remote bean if needed.
775
-                        $this->save($remoteBean);
776
-                    }
777
-
778
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
779
-
780
-                    $types = [];
781
-                    $escapedFilters = [];
782
-
783
-                    foreach ($filters as $columnName => $value) {
784
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
785
-                        $types[] = $columnDescriptor->getType();
786
-                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
787
-                    }
788
-
789
-                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
790
-
791
-                    // Finally, let's mark relationships as saved.
792
-                    $statusArr['status'] = 'loaded';
793
-                    $storage[$remoteBean] = $statusArr;
794
-                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
795
-                    $remoteStatusArr = $remoteStorage[$object];
796
-                    $remoteStatusArr['status'] = 'loaded';
797
-                    $remoteStorage[$object] = $remoteStatusArr;
798
-                } elseif ($status === 'delete') {
799
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
800
-
801
-                    $types = [];
802
-
803
-                    foreach ($filters as $columnName => $value) {
804
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
805
-                        $types[] = $columnDescriptor->getType();
806
-                    }
807
-
808
-                    $this->connection->delete($pivotTableName, $filters, $types);
809
-
810
-                    // Finally, let's remove relationships completely from bean.
811
-                    $toRemoveFromStorage[] = $remoteBean;
812
-
813
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
814
-                }
815
-            }
816
-
817
-            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
818
-            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
819
-            foreach ($toRemoveFromStorage as $remoteBean) {
820
-                $storage->detach($remoteBean);
821
-            }
822
-        }
823
-    }
824
-
825
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
826
-    {
827
-        $localBeanPk = $this->getPrimaryKeyValues($localBean);
828
-        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
829
-        $localColumns = $localFk->getLocalColumns();
830
-        $remoteColumns = $remoteFk->getLocalColumns();
831
-
832
-        $localFilters = array_combine($localColumns, $localBeanPk);
833
-        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
834
-
835
-        return array_merge($localFilters, $remoteFilters);
836
-    }
837
-
838
-    /**
839
-     * Returns the "values" of the primary key.
840
-     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
841
-     *
842
-     * @param AbstractTDBMObject $bean
843
-     *
844
-     * @return array numerically indexed array of values
845
-     */
846
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
847
-    {
848
-        $dbRows = $bean->_getDbRows();
849
-        $dbRow = reset($dbRows);
850
-
851
-        return array_values($dbRow->_getPrimaryKeys());
852
-    }
853
-
854
-    /**
855
-     * Returns a unique hash used to store the object based on its primary key.
856
-     * If the array contains only one value, then the value is returned.
857
-     * Otherwise, a hash representing the array is returned.
858
-     *
859
-     * @param array $primaryKeys An array of columns => values forming the primary key
860
-     *
861
-     * @return string
862
-     */
863
-    public function getObjectHash(array $primaryKeys)
864
-    {
865
-        if (count($primaryKeys) === 1) {
866
-            return reset($primaryKeys);
867
-        } else {
868
-            ksort($primaryKeys);
869
-
870
-            return md5(json_encode($primaryKeys));
871
-        }
872
-    }
873
-
874
-    /**
875
-     * Returns an array of primary keys from the object.
876
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
877
-     * $primaryKeys variable of the object.
878
-     *
879
-     * @param DbRow $dbRow
880
-     *
881
-     * @return array Returns an array of column => value
882
-     */
883
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
884
-    {
885
-        $table = $dbRow->_getDbTableName();
886
-        $dbRowData = $dbRow->_getDbRow();
887
-
888
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
889
-    }
890
-
891
-    /**
892
-     * Returns an array of primary keys for the given row.
893
-     * The primary keys are extracted from the object columns.
894
-     *
895
-     * @param $table
896
-     * @param array $columns
897
-     *
898
-     * @return array
899
-     */
900
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
901
-    {
902
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
903
-        $values = array();
904
-        foreach ($primaryKeyColumns as $column) {
905
-            if (isset($columns[$column])) {
906
-                $values[$column] = $columns[$column];
907
-            }
908
-        }
909
-
910
-        return $values;
911
-    }
912
-
913
-    /**
914
-     * Attaches $object to this TDBMService.
915
-     * The $object must be in DETACHED state and will pass in NEW state.
916
-     *
917
-     * @param AbstractTDBMObject $object
918
-     *
919
-     * @throws TDBMInvalidOperationException
920
-     */
921
-    public function attach(AbstractTDBMObject $object)
922
-    {
923
-        $object->_attach($this);
924
-    }
925
-
926
-    /**
927
-     * Returns an associative array (column => value) for the primary keys from the table name and an
928
-     * indexed array of primary key values.
929
-     *
930
-     * @param string $tableName
931
-     * @param array  $indexedPrimaryKeys
932
-     */
933
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
934
-    {
935
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
936
-
937
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
938
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
673
+				// Let's remove this object from the $new_objects static table.
674
+				$this->removeFromToSaveObjectList($dbRow);
675
+
676
+				// TODO: change this behaviour to something more sensible performance-wise
677
+				// Maybe a setting to trigger this globally?
678
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
679
+				//$this->db_modified_state = false;
680
+				//$dbRow = array();
681
+
682
+				// Let's add this object to the list of objects in cache.
683
+				$this->_addToCache($dbRow);
684
+			}
685
+
686
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
687
+		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
688
+			$dbRows = $object->_getDbRows();
689
+
690
+			foreach ($dbRows as $dbRow) {
691
+				$references = $dbRow->_getReferences();
692
+
693
+				// Let's save all references in NEW state (we need their primary key)
694
+				foreach ($references as $fkName => $reference) {
695
+					if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
696
+						$this->save($reference);
697
+					}
698
+				}
699
+
700
+				// Let's first get the primary keys
701
+				$tableName = $dbRow->_getDbTableName();
702
+				$dbRowData = $dbRow->_getDbRow();
703
+
704
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
705
+				$tableDescriptor = $schema->getTable($tableName);
706
+
707
+				$primaryKeys = $dbRow->_getPrimaryKeys();
708
+
709
+				$types = [];
710
+				$escapedDbRowData = [];
711
+				$escapedPrimaryKeys = [];
712
+
713
+				foreach ($dbRowData as $columnName => $value) {
714
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
715
+					$types[] = $columnDescriptor->getType();
716
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
717
+				}
718
+				foreach ($primaryKeys as $columnName => $value) {
719
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
720
+					$types[] = $columnDescriptor->getType();
721
+					$escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
722
+				}
723
+
724
+				$this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
725
+
726
+				// Let's check if the primary key has been updated...
727
+				$needsUpdatePk = false;
728
+				foreach ($primaryKeys as $column => $value) {
729
+					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
730
+						$needsUpdatePk = true;
731
+						break;
732
+					}
733
+				}
734
+				if ($needsUpdatePk) {
735
+					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
736
+					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
737
+					$dbRow->_setPrimaryKeys($newPrimaryKeys);
738
+					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
739
+				}
740
+
741
+				// Let's remove this object from the list of objects to save.
742
+				$this->removeFromToSaveObjectList($dbRow);
743
+			}
744
+
745
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
746
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
747
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
748
+		}
749
+
750
+		// Finally, let's save all the many to many relationships to this bean.
751
+		$this->persistManyToManyRelationships($object);
752
+	}
753
+
754
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
755
+	{
756
+		foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
757
+			$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
758
+			list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
759
+
760
+			$toRemoveFromStorage = [];
761
+
762
+			foreach ($storage as $remoteBean) {
763
+				/* @var $remoteBean AbstractTDBMObject */
764
+				$statusArr = $storage[$remoteBean];
765
+				$status = $statusArr['status'];
766
+				$reverse = $statusArr['reverse'];
767
+				if ($reverse) {
768
+					continue;
769
+				}
770
+
771
+				if ($status === 'new') {
772
+					$remoteBeanStatus = $remoteBean->_getStatus();
773
+					if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
774
+						// Let's save remote bean if needed.
775
+						$this->save($remoteBean);
776
+					}
777
+
778
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
779
+
780
+					$types = [];
781
+					$escapedFilters = [];
782
+
783
+					foreach ($filters as $columnName => $value) {
784
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
785
+						$types[] = $columnDescriptor->getType();
786
+						$escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
787
+					}
788
+
789
+					$this->connection->insert($pivotTableName, $escapedFilters, $types);
790
+
791
+					// Finally, let's mark relationships as saved.
792
+					$statusArr['status'] = 'loaded';
793
+					$storage[$remoteBean] = $statusArr;
794
+					$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
795
+					$remoteStatusArr = $remoteStorage[$object];
796
+					$remoteStatusArr['status'] = 'loaded';
797
+					$remoteStorage[$object] = $remoteStatusArr;
798
+				} elseif ($status === 'delete') {
799
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
800
+
801
+					$types = [];
802
+
803
+					foreach ($filters as $columnName => $value) {
804
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
805
+						$types[] = $columnDescriptor->getType();
806
+					}
807
+
808
+					$this->connection->delete($pivotTableName, $filters, $types);
809
+
810
+					// Finally, let's remove relationships completely from bean.
811
+					$toRemoveFromStorage[] = $remoteBean;
812
+
813
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
814
+				}
815
+			}
816
+
817
+			// Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
818
+			// Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
819
+			foreach ($toRemoveFromStorage as $remoteBean) {
820
+				$storage->detach($remoteBean);
821
+			}
822
+		}
823
+	}
824
+
825
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
826
+	{
827
+		$localBeanPk = $this->getPrimaryKeyValues($localBean);
828
+		$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
829
+		$localColumns = $localFk->getLocalColumns();
830
+		$remoteColumns = $remoteFk->getLocalColumns();
831
+
832
+		$localFilters = array_combine($localColumns, $localBeanPk);
833
+		$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
834
+
835
+		return array_merge($localFilters, $remoteFilters);
836
+	}
837
+
838
+	/**
839
+	 * Returns the "values" of the primary key.
840
+	 * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
841
+	 *
842
+	 * @param AbstractTDBMObject $bean
843
+	 *
844
+	 * @return array numerically indexed array of values
845
+	 */
846
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
847
+	{
848
+		$dbRows = $bean->_getDbRows();
849
+		$dbRow = reset($dbRows);
850
+
851
+		return array_values($dbRow->_getPrimaryKeys());
852
+	}
853
+
854
+	/**
855
+	 * Returns a unique hash used to store the object based on its primary key.
856
+	 * If the array contains only one value, then the value is returned.
857
+	 * Otherwise, a hash representing the array is returned.
858
+	 *
859
+	 * @param array $primaryKeys An array of columns => values forming the primary key
860
+	 *
861
+	 * @return string
862
+	 */
863
+	public function getObjectHash(array $primaryKeys)
864
+	{
865
+		if (count($primaryKeys) === 1) {
866
+			return reset($primaryKeys);
867
+		} else {
868
+			ksort($primaryKeys);
869
+
870
+			return md5(json_encode($primaryKeys));
871
+		}
872
+	}
873
+
874
+	/**
875
+	 * Returns an array of primary keys from the object.
876
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
877
+	 * $primaryKeys variable of the object.
878
+	 *
879
+	 * @param DbRow $dbRow
880
+	 *
881
+	 * @return array Returns an array of column => value
882
+	 */
883
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
884
+	{
885
+		$table = $dbRow->_getDbTableName();
886
+		$dbRowData = $dbRow->_getDbRow();
887
+
888
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
889
+	}
890
+
891
+	/**
892
+	 * Returns an array of primary keys for the given row.
893
+	 * The primary keys are extracted from the object columns.
894
+	 *
895
+	 * @param $table
896
+	 * @param array $columns
897
+	 *
898
+	 * @return array
899
+	 */
900
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
901
+	{
902
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
903
+		$values = array();
904
+		foreach ($primaryKeyColumns as $column) {
905
+			if (isset($columns[$column])) {
906
+				$values[$column] = $columns[$column];
907
+			}
908
+		}
909
+
910
+		return $values;
911
+	}
912
+
913
+	/**
914
+	 * Attaches $object to this TDBMService.
915
+	 * The $object must be in DETACHED state and will pass in NEW state.
916
+	 *
917
+	 * @param AbstractTDBMObject $object
918
+	 *
919
+	 * @throws TDBMInvalidOperationException
920
+	 */
921
+	public function attach(AbstractTDBMObject $object)
922
+	{
923
+		$object->_attach($this);
924
+	}
925
+
926
+	/**
927
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
928
+	 * indexed array of primary key values.
929
+	 *
930
+	 * @param string $tableName
931
+	 * @param array  $indexedPrimaryKeys
932
+	 */
933
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
934
+	{
935
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
936
+
937
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
938
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
939 939
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
940
-        }
941
-
942
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
943
-    }
944
-
945
-    /**
946
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
947
-     * Tables must be in a single line of inheritance. The method will find missing tables.
948
-     *
949
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
950
-     * we must be able to find all other tables.
951
-     *
952
-     * @param string[] $tables
953
-     *
954
-     * @return string[]
955
-     */
956
-    public function _getLinkBetweenInheritedTables(array $tables)
957
-    {
958
-        sort($tables);
959
-
960
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
961
-            function () use ($tables) {
962
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
963
-            });
964
-    }
965
-
966
-    /**
967
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
968
-     * Tables must be in a single line of inheritance. The method will find missing tables.
969
-     *
970
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
971
-     * we must be able to find all other tables.
972
-     *
973
-     * @param string[] $tables
974
-     *
975
-     * @return string[]
976
-     */
977
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
978
-    {
979
-        $schemaAnalyzer = $this->schemaAnalyzer;
980
-
981
-        foreach ($tables as $currentTable) {
982
-            $allParents = [$currentTable];
983
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
984
-                $currentTable = $currentFk->getForeignTableName();
985
-                $allParents[] = $currentTable;
986
-            }
987
-
988
-            // Now, does the $allParents contain all the tables we want?
989
-            $notFoundTables = array_diff($tables, $allParents);
990
-            if (empty($notFoundTables)) {
991
-                // We have a winner!
992
-                return $allParents;
993
-            }
994
-        }
995
-
996
-        throw TDBMInheritanceException::create($tables);
997
-    }
998
-
999
-    /**
1000
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1001
-     *
1002
-     * @param string $table
1003
-     *
1004
-     * @return string[]
1005
-     */
1006
-    public function _getRelatedTablesByInheritance($table)
1007
-    {
1008
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1009
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1010
-        });
1011
-    }
1012
-
1013
-    /**
1014
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1015
-     *
1016
-     * @param string $table
1017
-     *
1018
-     * @return string[]
1019
-     */
1020
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1021
-    {
1022
-        $schemaAnalyzer = $this->schemaAnalyzer;
1023
-
1024
-        // Let's scan the parent tables
1025
-        $currentTable = $table;
1026
-
1027
-        $parentTables = [];
1028
-
1029
-        // Get parent relationship
1030
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1031
-            $currentTable = $currentFk->getForeignTableName();
1032
-            $parentTables[] = $currentTable;
1033
-        }
1034
-
1035
-        // Let's recurse in children
1036
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1037
-
1038
-        return array_merge(array_reverse($parentTables), $childrenTables);
1039
-    }
1040
-
1041
-    /**
1042
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1043
-     *
1044
-     * @param string $table
1045
-     *
1046
-     * @return string[]
1047
-     */
1048
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1049
-    {
1050
-        $tables = [$table];
1051
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1052
-
1053
-        foreach ($keys as $key) {
1054
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1055
-        }
1056
-
1057
-        return $tables;
1058
-    }
1059
-
1060
-    /**
1061
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1062
-     * The returned value does contain only one table. For instance:.
1063
-     *
1064
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1065
-     *
1066
-     * @param ForeignKeyConstraint $fk
1067
-     * @param bool                 $leftTableIsLocal
1068
-     *
1069
-     * @return string
1070
-     */
1071
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
940
+		}
941
+
942
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
943
+	}
944
+
945
+	/**
946
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
947
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
948
+	 *
949
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
950
+	 * we must be able to find all other tables.
951
+	 *
952
+	 * @param string[] $tables
953
+	 *
954
+	 * @return string[]
955
+	 */
956
+	public function _getLinkBetweenInheritedTables(array $tables)
957
+	{
958
+		sort($tables);
959
+
960
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
961
+			function () use ($tables) {
962
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
963
+			});
964
+	}
965
+
966
+	/**
967
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
968
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
969
+	 *
970
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
971
+	 * we must be able to find all other tables.
972
+	 *
973
+	 * @param string[] $tables
974
+	 *
975
+	 * @return string[]
976
+	 */
977
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
978
+	{
979
+		$schemaAnalyzer = $this->schemaAnalyzer;
980
+
981
+		foreach ($tables as $currentTable) {
982
+			$allParents = [$currentTable];
983
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
984
+				$currentTable = $currentFk->getForeignTableName();
985
+				$allParents[] = $currentTable;
986
+			}
987
+
988
+			// Now, does the $allParents contain all the tables we want?
989
+			$notFoundTables = array_diff($tables, $allParents);
990
+			if (empty($notFoundTables)) {
991
+				// We have a winner!
992
+				return $allParents;
993
+			}
994
+		}
995
+
996
+		throw TDBMInheritanceException::create($tables);
997
+	}
998
+
999
+	/**
1000
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1001
+	 *
1002
+	 * @param string $table
1003
+	 *
1004
+	 * @return string[]
1005
+	 */
1006
+	public function _getRelatedTablesByInheritance($table)
1007
+	{
1008
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1009
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1010
+		});
1011
+	}
1012
+
1013
+	/**
1014
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1015
+	 *
1016
+	 * @param string $table
1017
+	 *
1018
+	 * @return string[]
1019
+	 */
1020
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1021
+	{
1022
+		$schemaAnalyzer = $this->schemaAnalyzer;
1023
+
1024
+		// Let's scan the parent tables
1025
+		$currentTable = $table;
1026
+
1027
+		$parentTables = [];
1028
+
1029
+		// Get parent relationship
1030
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1031
+			$currentTable = $currentFk->getForeignTableName();
1032
+			$parentTables[] = $currentTable;
1033
+		}
1034
+
1035
+		// Let's recurse in children
1036
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1037
+
1038
+		return array_merge(array_reverse($parentTables), $childrenTables);
1039
+	}
1040
+
1041
+	/**
1042
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1043
+	 *
1044
+	 * @param string $table
1045
+	 *
1046
+	 * @return string[]
1047
+	 */
1048
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1049
+	{
1050
+		$tables = [$table];
1051
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1052
+
1053
+		foreach ($keys as $key) {
1054
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1055
+		}
1056
+
1057
+		return $tables;
1058
+	}
1059
+
1060
+	/**
1061
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1062
+	 * The returned value does contain only one table. For instance:.
1063
+	 *
1064
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1065
+	 *
1066
+	 * @param ForeignKeyConstraint $fk
1067
+	 * @param bool                 $leftTableIsLocal
1068
+	 *
1069
+	 * @return string
1070
+	 */
1071
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1072 1072
         $onClauses = [];
1073 1073
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1074 1074
         $foreignColumns = $fk->getForeignColumns();
@@ -1094,417 +1094,417 @@  discard block
 block discarded – undo
1094 1094
         }
1095 1095
     }*/
1096 1096
 
1097
-    /**
1098
-     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1099
-     *
1100
-     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1101
-     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1102
-     *
1103
-     * The findObjects method takes in parameter:
1104
-     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1105
-     * 			`$mainTable` parameter should be the name of an existing table in database.
1106
-     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1107
-     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1108
-     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1109
-     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1110
-     *          Instead, please consider passing parameters (see documentation for more details).
1111
-     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1112
-     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1113
-     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1114
-     *
1115
-     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1116
-     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1117
-     *
1118
-     * Finally, if filter_bag is null, the whole table is returned.
1119
-     *
1120
-     * @param string                       $mainTable             The name of the table queried
1121
-     * @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)
1122
-     * @param array                        $parameters
1123
-     * @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)
1124
-     * @param array                        $additionalTablesFetch
1125
-     * @param int                          $mode
1126
-     * @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
1127
-     *
1128
-     * @return ResultIterator An object representing an array of results
1129
-     *
1130
-     * @throws TDBMException
1131
-     */
1132
-    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1133
-    {
1134
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1135
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1136
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1137
-        }
1138
-
1139
-        $mode = $mode ?: $this->mode;
1140
-
1141
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1142
-
1143
-        $parameters = array_merge($parameters, $additionalParameters);
1144
-
1145
-        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1146
-
1147
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1148
-    }
1149
-
1150
-    /**
1151
-     * @param string                       $mainTable   The name of the table queried
1152
-     * @param string                       $from        The from sql statement
1153
-     * @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)
1154
-     * @param array                        $parameters
1155
-     * @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)
1156
-     * @param int                          $mode
1157
-     * @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
1158
-     *
1159
-     * @return ResultIterator An object representing an array of results
1160
-     *
1161
-     * @throws TDBMException
1162
-     */
1163
-    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1164
-    {
1165
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1166
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1167
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1168
-        }
1169
-
1170
-        $mode = $mode ?: $this->mode;
1171
-
1172
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1173
-
1174
-        $parameters = array_merge($parameters, $additionalParameters);
1175
-
1176
-        $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1177
-
1178
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1179
-    }
1180
-
1181
-    /**
1182
-     * @param $table
1183
-     * @param array  $primaryKeys
1184
-     * @param array  $additionalTablesFetch
1185
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1186
-     * @param string $className
1187
-     *
1188
-     * @return AbstractTDBMObject
1189
-     *
1190
-     * @throws TDBMException
1191
-     */
1192
-    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1193
-    {
1194
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1195
-        $hash = $this->getObjectHash($primaryKeys);
1196
-
1197
-        if ($this->objectStorage->has($table, $hash)) {
1198
-            $dbRow = $this->objectStorage->get($table, $hash);
1199
-            $bean = $dbRow->getTDBMObject();
1200
-            if ($className !== null && !is_a($bean, $className)) {
1201
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1202
-            }
1203
-
1204
-            return $bean;
1205
-        }
1206
-
1207
-        // Are we performing lazy fetching?
1208
-        if ($lazy === true) {
1209
-            // Can we perform lazy fetching?
1210
-            $tables = $this->_getRelatedTablesByInheritance($table);
1211
-            // Only allowed if no inheritance.
1212
-            if (count($tables) === 1) {
1213
-                if ($className === null) {
1214
-                    try {
1215
-                        $className = $this->getBeanClassName($table);
1216
-                    } catch (TDBMInvalidArgumentException $e) {
1217
-                        $className = TDBMObject::class;
1218
-                    }
1219
-                }
1220
-
1221
-                // Let's construct the bean
1222
-                if (!isset($this->reflectionClassCache[$className])) {
1223
-                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1224
-                }
1225
-                // Let's bypass the constructor when creating the bean!
1226
-                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1227
-                /* @var $bean AbstractTDBMObject */
1228
-                $bean->_constructLazy($table, $primaryKeys, $this);
1229
-
1230
-                return $bean;
1231
-            }
1232
-        }
1233
-
1234
-        // Did not find the object in cache? Let's query it!
1235
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1236
-    }
1237
-
1238
-    /**
1239
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1240
-     *
1241
-     * @param string            $mainTable             The name of the table queried
1242
-     * @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)
1243
-     * @param array             $parameters
1244
-     * @param array             $additionalTablesFetch
1245
-     * @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
1246
-     *
1247
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1248
-     *
1249
-     * @throws TDBMException
1250
-     */
1251
-    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1252
-    {
1253
-        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1254
-        $page = $objects->take(0, 2);
1255
-        $count = $page->count();
1256
-        if ($count > 1) {
1257
-            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.");
1258
-        } elseif ($count === 0) {
1259
-            return;
1260
-        }
1261
-
1262
-        return $page[0];
1263
-    }
1264
-
1265
-    /**
1266
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1267
-     *
1268
-     * @param string            $mainTable  The name of the table queried
1269
-     * @param string            $from       The from sql statement
1270
-     * @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)
1271
-     * @param array             $parameters
1272
-     * @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
1273
-     *
1274
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1275
-     *
1276
-     * @throws TDBMException
1277
-     */
1278
-    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1279
-    {
1280
-        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1281
-        $page = $objects->take(0, 2);
1282
-        $count = $page->count();
1283
-        if ($count > 1) {
1284
-            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.");
1285
-        } elseif ($count === 0) {
1286
-            return;
1287
-        }
1288
-
1289
-        return $page[0];
1290
-    }
1291
-
1292
-    /**
1293
-     * Returns a unique bean according to the filters passed in parameter.
1294
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1295
-     *
1296
-     * @param string            $mainTable             The name of the table queried
1297
-     * @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)
1298
-     * @param array             $parameters
1299
-     * @param array             $additionalTablesFetch
1300
-     * @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
1301
-     *
1302
-     * @return AbstractTDBMObject The object we want
1303
-     *
1304
-     * @throws TDBMException
1305
-     */
1306
-    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1307
-    {
1308
-        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1309
-        if ($bean === null) {
1310
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1311
-        }
1312
-
1313
-        return $bean;
1314
-    }
1315
-
1316
-    /**
1317
-     * @param array $beanData An array of data: array<table, array<column, value>>
1318
-     *
1319
-     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1320
-     *
1321
-     * @throws TDBMInheritanceException
1322
-     */
1323
-    public function _getClassNameFromBeanData(array $beanData)
1324
-    {
1325
-        if (count($beanData) === 1) {
1326
-            $tableName = array_keys($beanData)[0];
1327
-            $allTables = [$tableName];
1328
-        } else {
1329
-            $tables = [];
1330
-            foreach ($beanData as $table => $row) {
1331
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1332
-                $pkSet = false;
1333
-                foreach ($primaryKeyColumns as $columnName) {
1334
-                    if ($row[$columnName] !== null) {
1335
-                        $pkSet = true;
1336
-                        break;
1337
-                    }
1338
-                }
1339
-                if ($pkSet) {
1340
-                    $tables[] = $table;
1341
-                }
1342
-            }
1343
-
1344
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1345
-            try {
1346
-                $allTables = $this->_getLinkBetweenInheritedTables($tables);
1347
-            } catch (TDBMInheritanceException $e) {
1348
-                throw TDBMInheritanceException::extendException($e, $this, $beanData);
1349
-            }
1350
-            $tableName = $allTables[0];
1351
-        }
1352
-
1353
-        // Only one table in this bean. Life is sweat, let's look at its type:
1354
-        try {
1355
-            $className = $this->getBeanClassName($tableName);
1356
-        } catch (TDBMInvalidArgumentException $e) {
1357
-            $className = 'Mouf\\Database\\TDBM\\TDBMObject';
1358
-        }
1359
-
1360
-        return [$className, $tableName, $allTables];
1361
-    }
1362
-
1363
-    /**
1364
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1365
-     *
1366
-     * @param string   $key
1367
-     * @param callable $closure
1368
-     *
1369
-     * @return mixed
1370
-     */
1371
-    private function fromCache(string $key, callable $closure)
1372
-    {
1373
-        $item = $this->cache->fetch($key);
1374
-        if ($item === false) {
1375
-            $item = $closure();
1376
-            $this->cache->save($key, $item);
1377
-        }
1378
-
1379
-        return $item;
1380
-    }
1381
-
1382
-    /**
1383
-     * Returns the foreign key object.
1384
-     *
1385
-     * @param string $table
1386
-     * @param string $fkName
1387
-     *
1388
-     * @return ForeignKeyConstraint
1389
-     */
1390
-    public function _getForeignKeyByName(string $table, string $fkName)
1391
-    {
1392
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1393
-    }
1394
-
1395
-    /**
1396
-     * @param $pivotTableName
1397
-     * @param AbstractTDBMObject $bean
1398
-     *
1399
-     * @return AbstractTDBMObject[]
1400
-     */
1401
-    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1402
-    {
1403
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1404
-        /* @var $localFk ForeignKeyConstraint */
1405
-        /* @var $remoteFk ForeignKeyConstraint */
1406
-        $remoteTable = $remoteFk->getForeignTableName();
1407
-
1408
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1409
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1410
-            return $pivotTableName.'.'.$name;
1411
-        }, $localFk->getLocalColumns());
1412
-
1413
-        $filter = array_combine($columnNames, $primaryKeys);
1414
-
1415
-        return $this->findObjects($remoteTable, $filter);
1416
-    }
1417
-
1418
-    /**
1419
-     * @param $pivotTableName
1420
-     * @param AbstractTDBMObject $bean The LOCAL bean
1421
-     *
1422
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1423
-     *
1424
-     * @throws TDBMException
1425
-     */
1426
-    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1427
-    {
1428
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1429
-        $table1 = $fks[0]->getForeignTableName();
1430
-        $table2 = $fks[1]->getForeignTableName();
1431
-
1432
-        $beanTables = array_map(function (DbRow $dbRow) {
1433
-            return $dbRow->_getDbTableName();
1434
-        }, $bean->_getDbRows());
1435
-
1436
-        if (in_array($table1, $beanTables)) {
1437
-            return [$fks[0], $fks[1]];
1438
-        } elseif (in_array($table2, $beanTables)) {
1439
-            return [$fks[1], $fks[0]];
1440
-        } else {
1441
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1442
-        }
1443
-    }
1444
-
1445
-    /**
1446
-     * Returns a list of pivot tables linked to $bean.
1447
-     *
1448
-     * @param AbstractTDBMObject $bean
1449
-     *
1450
-     * @return string[]
1451
-     */
1452
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1453
-    {
1454
-        $junctionTables = [];
1455
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1456
-        foreach ($bean->_getDbRows() as $dbRow) {
1457
-            foreach ($allJunctionTables as $table) {
1458
-                // There are exactly 2 FKs since this is a pivot table.
1459
-                $fks = array_values($table->getForeignKeys());
1460
-
1461
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1462
-                    $junctionTables[] = $table->getName();
1463
-                }
1464
-            }
1465
-        }
1466
-
1467
-        return $junctionTables;
1468
-    }
1469
-
1470
-    /**
1471
-     * Array of types for tables.
1472
-     * Key: table name
1473
-     * Value: array of types indexed by column.
1474
-     *
1475
-     * @var array[]
1476
-     */
1477
-    private $typesForTable = [];
1478
-
1479
-    /**
1480
-     * @internal
1481
-     *
1482
-     * @param string $tableName
1483
-     *
1484
-     * @return Type[]
1485
-     */
1486
-    public function _getColumnTypesForTable(string $tableName)
1487
-    {
1488
-        if (!isset($typesForTable[$tableName])) {
1489
-            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1490
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1491
-                return $column->getType();
1492
-            }, $columns);
1493
-        }
1494
-
1495
-        return $typesForTable[$tableName];
1496
-    }
1497
-
1498
-    /**
1499
-     * Sets the minimum log level.
1500
-     * $level must be one of Psr\Log\LogLevel::xxx.
1501
-     *
1502
-     * Defaults to LogLevel::WARNING
1503
-     *
1504
-     * @param string $level
1505
-     */
1506
-    public function setLogLevel(string $level)
1507
-    {
1508
-        $this->logger = new LevelFilter($this->rootLogger, $level);
1509
-    }
1097
+	/**
1098
+	 * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1099
+	 *
1100
+	 * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1101
+	 * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1102
+	 *
1103
+	 * The findObjects method takes in parameter:
1104
+	 * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1105
+	 * 			`$mainTable` parameter should be the name of an existing table in database.
1106
+	 *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1107
+	 *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1108
+	 *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1109
+	 *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1110
+	 *          Instead, please consider passing parameters (see documentation for more details).
1111
+	 *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1112
+	 *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1113
+	 *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1114
+	 *
1115
+	 * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1116
+	 * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1117
+	 *
1118
+	 * Finally, if filter_bag is null, the whole table is returned.
1119
+	 *
1120
+	 * @param string                       $mainTable             The name of the table queried
1121
+	 * @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)
1122
+	 * @param array                        $parameters
1123
+	 * @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)
1124
+	 * @param array                        $additionalTablesFetch
1125
+	 * @param int                          $mode
1126
+	 * @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
1127
+	 *
1128
+	 * @return ResultIterator An object representing an array of results
1129
+	 *
1130
+	 * @throws TDBMException
1131
+	 */
1132
+	public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1133
+	{
1134
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1135
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1136
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1137
+		}
1138
+
1139
+		$mode = $mode ?: $this->mode;
1140
+
1141
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1142
+
1143
+		$parameters = array_merge($parameters, $additionalParameters);
1144
+
1145
+		$queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1146
+
1147
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1148
+	}
1149
+
1150
+	/**
1151
+	 * @param string                       $mainTable   The name of the table queried
1152
+	 * @param string                       $from        The from sql statement
1153
+	 * @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)
1154
+	 * @param array                        $parameters
1155
+	 * @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)
1156
+	 * @param int                          $mode
1157
+	 * @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
1158
+	 *
1159
+	 * @return ResultIterator An object representing an array of results
1160
+	 *
1161
+	 * @throws TDBMException
1162
+	 */
1163
+	public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1164
+	{
1165
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1166
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1167
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1168
+		}
1169
+
1170
+		$mode = $mode ?: $this->mode;
1171
+
1172
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1173
+
1174
+		$parameters = array_merge($parameters, $additionalParameters);
1175
+
1176
+		$queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1177
+
1178
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1179
+	}
1180
+
1181
+	/**
1182
+	 * @param $table
1183
+	 * @param array  $primaryKeys
1184
+	 * @param array  $additionalTablesFetch
1185
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1186
+	 * @param string $className
1187
+	 *
1188
+	 * @return AbstractTDBMObject
1189
+	 *
1190
+	 * @throws TDBMException
1191
+	 */
1192
+	public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1193
+	{
1194
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1195
+		$hash = $this->getObjectHash($primaryKeys);
1196
+
1197
+		if ($this->objectStorage->has($table, $hash)) {
1198
+			$dbRow = $this->objectStorage->get($table, $hash);
1199
+			$bean = $dbRow->getTDBMObject();
1200
+			if ($className !== null && !is_a($bean, $className)) {
1201
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1202
+			}
1203
+
1204
+			return $bean;
1205
+		}
1206
+
1207
+		// Are we performing lazy fetching?
1208
+		if ($lazy === true) {
1209
+			// Can we perform lazy fetching?
1210
+			$tables = $this->_getRelatedTablesByInheritance($table);
1211
+			// Only allowed if no inheritance.
1212
+			if (count($tables) === 1) {
1213
+				if ($className === null) {
1214
+					try {
1215
+						$className = $this->getBeanClassName($table);
1216
+					} catch (TDBMInvalidArgumentException $e) {
1217
+						$className = TDBMObject::class;
1218
+					}
1219
+				}
1220
+
1221
+				// Let's construct the bean
1222
+				if (!isset($this->reflectionClassCache[$className])) {
1223
+					$this->reflectionClassCache[$className] = new \ReflectionClass($className);
1224
+				}
1225
+				// Let's bypass the constructor when creating the bean!
1226
+				$bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1227
+				/* @var $bean AbstractTDBMObject */
1228
+				$bean->_constructLazy($table, $primaryKeys, $this);
1229
+
1230
+				return $bean;
1231
+			}
1232
+		}
1233
+
1234
+		// Did not find the object in cache? Let's query it!
1235
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1236
+	}
1237
+
1238
+	/**
1239
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1240
+	 *
1241
+	 * @param string            $mainTable             The name of the table queried
1242
+	 * @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)
1243
+	 * @param array             $parameters
1244
+	 * @param array             $additionalTablesFetch
1245
+	 * @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
1246
+	 *
1247
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1248
+	 *
1249
+	 * @throws TDBMException
1250
+	 */
1251
+	public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1252
+	{
1253
+		$objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1254
+		$page = $objects->take(0, 2);
1255
+		$count = $page->count();
1256
+		if ($count > 1) {
1257
+			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.");
1258
+		} elseif ($count === 0) {
1259
+			return;
1260
+		}
1261
+
1262
+		return $page[0];
1263
+	}
1264
+
1265
+	/**
1266
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1267
+	 *
1268
+	 * @param string            $mainTable  The name of the table queried
1269
+	 * @param string            $from       The from sql statement
1270
+	 * @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)
1271
+	 * @param array             $parameters
1272
+	 * @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
1273
+	 *
1274
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1275
+	 *
1276
+	 * @throws TDBMException
1277
+	 */
1278
+	public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1279
+	{
1280
+		$objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1281
+		$page = $objects->take(0, 2);
1282
+		$count = $page->count();
1283
+		if ($count > 1) {
1284
+			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.");
1285
+		} elseif ($count === 0) {
1286
+			return;
1287
+		}
1288
+
1289
+		return $page[0];
1290
+	}
1291
+
1292
+	/**
1293
+	 * Returns a unique bean according to the filters passed in parameter.
1294
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1295
+	 *
1296
+	 * @param string            $mainTable             The name of the table queried
1297
+	 * @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)
1298
+	 * @param array             $parameters
1299
+	 * @param array             $additionalTablesFetch
1300
+	 * @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
1301
+	 *
1302
+	 * @return AbstractTDBMObject The object we want
1303
+	 *
1304
+	 * @throws TDBMException
1305
+	 */
1306
+	public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1307
+	{
1308
+		$bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1309
+		if ($bean === null) {
1310
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1311
+		}
1312
+
1313
+		return $bean;
1314
+	}
1315
+
1316
+	/**
1317
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1318
+	 *
1319
+	 * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1320
+	 *
1321
+	 * @throws TDBMInheritanceException
1322
+	 */
1323
+	public function _getClassNameFromBeanData(array $beanData)
1324
+	{
1325
+		if (count($beanData) === 1) {
1326
+			$tableName = array_keys($beanData)[0];
1327
+			$allTables = [$tableName];
1328
+		} else {
1329
+			$tables = [];
1330
+			foreach ($beanData as $table => $row) {
1331
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1332
+				$pkSet = false;
1333
+				foreach ($primaryKeyColumns as $columnName) {
1334
+					if ($row[$columnName] !== null) {
1335
+						$pkSet = true;
1336
+						break;
1337
+					}
1338
+				}
1339
+				if ($pkSet) {
1340
+					$tables[] = $table;
1341
+				}
1342
+			}
1343
+
1344
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1345
+			try {
1346
+				$allTables = $this->_getLinkBetweenInheritedTables($tables);
1347
+			} catch (TDBMInheritanceException $e) {
1348
+				throw TDBMInheritanceException::extendException($e, $this, $beanData);
1349
+			}
1350
+			$tableName = $allTables[0];
1351
+		}
1352
+
1353
+		// Only one table in this bean. Life is sweat, let's look at its type:
1354
+		try {
1355
+			$className = $this->getBeanClassName($tableName);
1356
+		} catch (TDBMInvalidArgumentException $e) {
1357
+			$className = 'Mouf\\Database\\TDBM\\TDBMObject';
1358
+		}
1359
+
1360
+		return [$className, $tableName, $allTables];
1361
+	}
1362
+
1363
+	/**
1364
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1365
+	 *
1366
+	 * @param string   $key
1367
+	 * @param callable $closure
1368
+	 *
1369
+	 * @return mixed
1370
+	 */
1371
+	private function fromCache(string $key, callable $closure)
1372
+	{
1373
+		$item = $this->cache->fetch($key);
1374
+		if ($item === false) {
1375
+			$item = $closure();
1376
+			$this->cache->save($key, $item);
1377
+		}
1378
+
1379
+		return $item;
1380
+	}
1381
+
1382
+	/**
1383
+	 * Returns the foreign key object.
1384
+	 *
1385
+	 * @param string $table
1386
+	 * @param string $fkName
1387
+	 *
1388
+	 * @return ForeignKeyConstraint
1389
+	 */
1390
+	public function _getForeignKeyByName(string $table, string $fkName)
1391
+	{
1392
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1393
+	}
1394
+
1395
+	/**
1396
+	 * @param $pivotTableName
1397
+	 * @param AbstractTDBMObject $bean
1398
+	 *
1399
+	 * @return AbstractTDBMObject[]
1400
+	 */
1401
+	public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1402
+	{
1403
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1404
+		/* @var $localFk ForeignKeyConstraint */
1405
+		/* @var $remoteFk ForeignKeyConstraint */
1406
+		$remoteTable = $remoteFk->getForeignTableName();
1407
+
1408
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1409
+		$columnNames = array_map(function ($name) use ($pivotTableName) {
1410
+			return $pivotTableName.'.'.$name;
1411
+		}, $localFk->getLocalColumns());
1412
+
1413
+		$filter = array_combine($columnNames, $primaryKeys);
1414
+
1415
+		return $this->findObjects($remoteTable, $filter);
1416
+	}
1417
+
1418
+	/**
1419
+	 * @param $pivotTableName
1420
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1421
+	 *
1422
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1423
+	 *
1424
+	 * @throws TDBMException
1425
+	 */
1426
+	private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1427
+	{
1428
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1429
+		$table1 = $fks[0]->getForeignTableName();
1430
+		$table2 = $fks[1]->getForeignTableName();
1431
+
1432
+		$beanTables = array_map(function (DbRow $dbRow) {
1433
+			return $dbRow->_getDbTableName();
1434
+		}, $bean->_getDbRows());
1435
+
1436
+		if (in_array($table1, $beanTables)) {
1437
+			return [$fks[0], $fks[1]];
1438
+		} elseif (in_array($table2, $beanTables)) {
1439
+			return [$fks[1], $fks[0]];
1440
+		} else {
1441
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1442
+		}
1443
+	}
1444
+
1445
+	/**
1446
+	 * Returns a list of pivot tables linked to $bean.
1447
+	 *
1448
+	 * @param AbstractTDBMObject $bean
1449
+	 *
1450
+	 * @return string[]
1451
+	 */
1452
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1453
+	{
1454
+		$junctionTables = [];
1455
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1456
+		foreach ($bean->_getDbRows() as $dbRow) {
1457
+			foreach ($allJunctionTables as $table) {
1458
+				// There are exactly 2 FKs since this is a pivot table.
1459
+				$fks = array_values($table->getForeignKeys());
1460
+
1461
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1462
+					$junctionTables[] = $table->getName();
1463
+				}
1464
+			}
1465
+		}
1466
+
1467
+		return $junctionTables;
1468
+	}
1469
+
1470
+	/**
1471
+	 * Array of types for tables.
1472
+	 * Key: table name
1473
+	 * Value: array of types indexed by column.
1474
+	 *
1475
+	 * @var array[]
1476
+	 */
1477
+	private $typesForTable = [];
1478
+
1479
+	/**
1480
+	 * @internal
1481
+	 *
1482
+	 * @param string $tableName
1483
+	 *
1484
+	 * @return Type[]
1485
+	 */
1486
+	public function _getColumnTypesForTable(string $tableName)
1487
+	{
1488
+		if (!isset($typesForTable[$tableName])) {
1489
+			$columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1490
+			$typesForTable[$tableName] = array_map(function (Column $column) {
1491
+				return $column->getType();
1492
+			}, $columns);
1493
+		}
1494
+
1495
+		return $typesForTable[$tableName];
1496
+	}
1497
+
1498
+	/**
1499
+	 * Sets the minimum log level.
1500
+	 * $level must be one of Psr\Log\LogLevel::xxx.
1501
+	 *
1502
+	 * Defaults to LogLevel::WARNING
1503
+	 *
1504
+	 * @param string $level
1505
+	 */
1506
+	public function setLogLevel(string $level)
1507
+	{
1508
+		$this->logger = new LevelFilter($this->rootLogger, $level);
1509
+	}
1510 1510
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -616,7 +616,7 @@
 block discarded – undo
616 616
      * Tries to put string to the singular form (if it is plural).
617 617
      * We assume the table names are in english.
618 618
      *
619
-     * @param $str string
619
+     * @param string $str string
620 620
      *
621 621
      * @return string
622 622
      */
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -89,11 +89,11 @@  discard block
 block discarded – undo
89 89
 
90 90
         // Remove all beans and daos from junction tables
91 91
         $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
92
-        $junctionTableNames = array_map(function (Table $table) {
92
+        $junctionTableNames = array_map(function(Table $table) {
93 93
             return $table->getName();
94 94
         }, $junctionTables);
95 95
 
96
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
96
+        $tableList = array_filter($tableList, function(Table $table) use ($junctionTableNames) {
97 97
             return !in_array($table->getName(), $junctionTableNames);
98 98
         });
99 99
 
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
         $usedBeans[] = $beanClassName;
252 252
         // Let's suppress duplicates in used beans (if any)
253 253
         $usedBeans = array_flip(array_flip($usedBeans));
254
-        $useStatements = array_map(function ($usedBean) {
254
+        $useStatements = array_map(function($usedBean) {
255 255
             return "use $usedBean;\n";
256 256
         }, $usedBeans);
257 257
 
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
                 $pos = strpos($str, ' ');
607 607
             }
608 608
             $before = substr($str, 0, $pos);
609
-            $after = substr($str, $pos + 1);
609
+            $after = substr($str, $pos+1);
610 610
             $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
611 611
         }
612 612
 
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
         $map = [
683 683
             Type::TARRAY => 'array',
684 684
             Type::SIMPLE_ARRAY => 'array',
685
-            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
685
+            'json' => 'array', // 'json' is supported from Doctrine DBAL 2.6 only.
686 686
             Type::JSON_ARRAY => 'array',
687 687
             Type::BIGINT => 'string',
688 688
             Type::BOOLEAN => 'bool',
Please login to merge, or discard this patch.
Indentation   +376 added lines, -376 removed lines patch added patch discarded remove patch
@@ -16,143 +16,143 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class TDBMDaoGenerator
18 18
 {
19
-    /**
20
-     * @var Schema
21
-     */
22
-    private $schema;
23
-
24
-    /**
25
-     * The root directory of the project.
26
-     *
27
-     * @var string
28
-     */
29
-    private $rootPath;
30
-
31
-    /**
32
-     * Name of composer file.
33
-     *
34
-     * @var string
35
-     */
36
-    private $composerFile;
37
-
38
-    /**
39
-     * @var TDBMSchemaAnalyzer
40
-     */
41
-    private $tdbmSchemaAnalyzer;
42
-
43
-    /**
44
-     * @var EventDispatcherInterface
45
-     */
46
-    private $eventDispatcher;
47
-
48
-    /**
49
-     * @var NamingStrategyInterface
50
-     */
51
-    private $namingStrategy;
52
-    /**
53
-     * @var ConfigurationInterface
54
-     */
55
-    private $configuration;
56
-
57
-    /**
58
-     * Constructor.
59
-     *
60
-     * @param ConfigurationInterface $configuration
61
-     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
62
-     */
63
-    public function __construct(ConfigurationInterface $configuration, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
64
-    {
65
-        $this->configuration = $configuration;
66
-        $this->schema = $tdbmSchemaAnalyzer->getSchema();
67
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
68
-        $this->rootPath = __DIR__.'/../../../../../../../../';
69
-        $this->namingStrategy = $configuration->getNamingStrategy();
70
-        $this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
71
-    }
72
-
73
-    /**
74
-     * Generates all the daos and beans.
75
-     *
76
-     * @throws TDBMException
77
-     */
78
-    public function generateAllDaosAndBeans(): void
79
-    {
80
-        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
81
-
82
-        $tableList = $this->schema->getTables();
83
-
84
-        // Remove all beans and daos from junction tables
85
-        $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
86
-        $junctionTableNames = array_map(function (Table $table) {
87
-            return $table->getName();
88
-        }, $junctionTables);
89
-
90
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
91
-            return !in_array($table->getName(), $junctionTableNames);
92
-        });
93
-
94
-        $beanDescriptors = [];
95
-
96
-        foreach ($tableList as $table) {
97
-            $beanDescriptors[] = $this->generateDaoAndBean($table);
98
-        }
99
-
100
-
101
-        $this->generateFactory($tableList);
102
-
103
-        // Let's call the list of listeners
104
-        $this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
105
-    }
106
-
107
-    /**
108
-     * Generates in one method call the daos and the beans for one table.
109
-     *
110
-     * @param Table $table
111
-     *
112
-     * @return BeanDescriptor
113
-     * @throws TDBMException
114
-     */
115
-    private function generateDaoAndBean(Table $table) : BeanDescriptor
116
-    {
117
-        // TODO: $storeInUtc is NOT USED.
118
-        $tableName = $table->getName();
119
-        $daoName = $this->namingStrategy->getDaoClassName($tableName);
120
-        $beanName = $this->namingStrategy->getBeanClassName($tableName);
121
-        $baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
122
-        $baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
123
-
124
-        $beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
125
-        $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table);
126
-        $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table);
127
-        return $beanDescriptor;
128
-    }
129
-
130
-    /**
131
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
132
-     *
133
-     * @param BeanDescriptor  $beanDescriptor
134
-     * @param string          $className       The name of the class
135
-     * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
136
-     * @param Table           $table           The table
137
-     *
138
-     * @throws TDBMException
139
-     */
140
-    public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table)
141
-    {
142
-        $beannamespace = $this->configuration->getBeanNamespace();
143
-        $str = $beanDescriptor->generatePhpCode($beannamespace);
144
-
145
-        $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\Generated\\'.$baseClassName)->getPathname();
146
-
147
-        $this->ensureDirectoryExist($possibleBaseFileName);
148
-        file_put_contents($possibleBaseFileName, $str);
149
-        @chmod($possibleBaseFileName, 0664);
150
-
151
-        $possibleFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\'.$className)->getPathname();
152
-
153
-        if (!file_exists($possibleFileName)) {
154
-            $tableName = $table->getName();
155
-            $str = "<?php
19
+	/**
20
+	 * @var Schema
21
+	 */
22
+	private $schema;
23
+
24
+	/**
25
+	 * The root directory of the project.
26
+	 *
27
+	 * @var string
28
+	 */
29
+	private $rootPath;
30
+
31
+	/**
32
+	 * Name of composer file.
33
+	 *
34
+	 * @var string
35
+	 */
36
+	private $composerFile;
37
+
38
+	/**
39
+	 * @var TDBMSchemaAnalyzer
40
+	 */
41
+	private $tdbmSchemaAnalyzer;
42
+
43
+	/**
44
+	 * @var EventDispatcherInterface
45
+	 */
46
+	private $eventDispatcher;
47
+
48
+	/**
49
+	 * @var NamingStrategyInterface
50
+	 */
51
+	private $namingStrategy;
52
+	/**
53
+	 * @var ConfigurationInterface
54
+	 */
55
+	private $configuration;
56
+
57
+	/**
58
+	 * Constructor.
59
+	 *
60
+	 * @param ConfigurationInterface $configuration
61
+	 * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
62
+	 */
63
+	public function __construct(ConfigurationInterface $configuration, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
64
+	{
65
+		$this->configuration = $configuration;
66
+		$this->schema = $tdbmSchemaAnalyzer->getSchema();
67
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
68
+		$this->rootPath = __DIR__.'/../../../../../../../../';
69
+		$this->namingStrategy = $configuration->getNamingStrategy();
70
+		$this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
71
+	}
72
+
73
+	/**
74
+	 * Generates all the daos and beans.
75
+	 *
76
+	 * @throws TDBMException
77
+	 */
78
+	public function generateAllDaosAndBeans(): void
79
+	{
80
+		// TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
81
+
82
+		$tableList = $this->schema->getTables();
83
+
84
+		// Remove all beans and daos from junction tables
85
+		$junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
86
+		$junctionTableNames = array_map(function (Table $table) {
87
+			return $table->getName();
88
+		}, $junctionTables);
89
+
90
+		$tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
91
+			return !in_array($table->getName(), $junctionTableNames);
92
+		});
93
+
94
+		$beanDescriptors = [];
95
+
96
+		foreach ($tableList as $table) {
97
+			$beanDescriptors[] = $this->generateDaoAndBean($table);
98
+		}
99
+
100
+
101
+		$this->generateFactory($tableList);
102
+
103
+		// Let's call the list of listeners
104
+		$this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
105
+	}
106
+
107
+	/**
108
+	 * Generates in one method call the daos and the beans for one table.
109
+	 *
110
+	 * @param Table $table
111
+	 *
112
+	 * @return BeanDescriptor
113
+	 * @throws TDBMException
114
+	 */
115
+	private function generateDaoAndBean(Table $table) : BeanDescriptor
116
+	{
117
+		// TODO: $storeInUtc is NOT USED.
118
+		$tableName = $table->getName();
119
+		$daoName = $this->namingStrategy->getDaoClassName($tableName);
120
+		$beanName = $this->namingStrategy->getBeanClassName($tableName);
121
+		$baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
122
+		$baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
123
+
124
+		$beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
125
+		$this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table);
126
+		$this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table);
127
+		return $beanDescriptor;
128
+	}
129
+
130
+	/**
131
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
132
+	 *
133
+	 * @param BeanDescriptor  $beanDescriptor
134
+	 * @param string          $className       The name of the class
135
+	 * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
136
+	 * @param Table           $table           The table
137
+	 *
138
+	 * @throws TDBMException
139
+	 */
140
+	public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table)
141
+	{
142
+		$beannamespace = $this->configuration->getBeanNamespace();
143
+		$str = $beanDescriptor->generatePhpCode($beannamespace);
144
+
145
+		$possibleBaseFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\Generated\\'.$baseClassName)->getPathname();
146
+
147
+		$this->ensureDirectoryExist($possibleBaseFileName);
148
+		file_put_contents($possibleBaseFileName, $str);
149
+		@chmod($possibleBaseFileName, 0664);
150
+
151
+		$possibleFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\'.$className)->getPathname();
152
+
153
+		if (!file_exists($possibleFileName)) {
154
+			$tableName = $table->getName();
155
+			$str = "<?php
156 156
 /*
157 157
  * This file has been automatically generated by TDBM.
158 158
  * You can edit this file as it will not be overwritten.
@@ -169,75 +169,75 @@  discard block
 block discarded – undo
169 169
 {
170 170
 }
171 171
 ";
172
-            $this->ensureDirectoryExist($possibleFileName);
173
-            file_put_contents($possibleFileName, $str);
174
-            @chmod($possibleFileName, 0664);
175
-        }
176
-    }
177
-
178
-    /**
179
-     * Tries to find a @defaultSort annotation in one of the columns.
180
-     *
181
-     * @param Table $table
182
-     *
183
-     * @return array First item: column name, Second item: column order (asc/desc)
184
-     */
185
-    private function getDefaultSortColumnFromAnnotation(Table $table)
186
-    {
187
-        $defaultSort = null;
188
-        $defaultSortDirection = null;
189
-        foreach ($table->getColumns() as $column) {
190
-            $comments = $column->getComment();
191
-            $matches = [];
192
-            if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
193
-                $defaultSort = $column->getName();
194
-                if (count($matches) === 3) {
195
-                    $defaultSortDirection = $matches[2];
196
-                } else {
197
-                    $defaultSortDirection = 'ASC';
198
-                }
199
-            }
200
-        }
201
-
202
-        return [$defaultSort, $defaultSortDirection];
203
-    }
204
-
205
-    /**
206
-     * Writes the PHP bean DAO with simple functions to create/get/save objects.
207
-     *
208
-     * @param BeanDescriptor  $beanDescriptor
209
-     * @param string          $className       The name of the class
210
-     * @param string          $baseClassName
211
-     * @param string          $beanClassName
212
-     * @param Table           $table
213
-     *
214
-     * @throws TDBMException
215
-     */
216
-    private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table)
217
-    {
218
-        $daonamespace = $this->configuration->getDaoNamespace();
219
-        $beannamespace = $this->configuration->getBeanNamespace();
220
-        $tableName = $table->getName();
221
-        $primaryKeyColumns = $table->getPrimaryKeyColumns();
222
-
223
-        list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
224
-
225
-        // FIXME: lowercase tables with _ in the name should work!
226
-        $tableCamel = self::toSingular(self::toCamelCase($tableName));
227
-
228
-        $beanClassWithoutNameSpace = $beanClassName;
229
-        $beanClassName = $beannamespace.'\\'.$beanClassName;
230
-
231
-        list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
232
-
233
-        $usedBeans[] = $beanClassName;
234
-        // Let's suppress duplicates in used beans (if any)
235
-        $usedBeans = array_flip(array_flip($usedBeans));
236
-        $useStatements = array_map(function ($usedBean) {
237
-            return "use $usedBean;\n";
238
-        }, $usedBeans);
239
-
240
-        $str = "<?php
172
+			$this->ensureDirectoryExist($possibleFileName);
173
+			file_put_contents($possibleFileName, $str);
174
+			@chmod($possibleFileName, 0664);
175
+		}
176
+	}
177
+
178
+	/**
179
+	 * Tries to find a @defaultSort annotation in one of the columns.
180
+	 *
181
+	 * @param Table $table
182
+	 *
183
+	 * @return array First item: column name, Second item: column order (asc/desc)
184
+	 */
185
+	private function getDefaultSortColumnFromAnnotation(Table $table)
186
+	{
187
+		$defaultSort = null;
188
+		$defaultSortDirection = null;
189
+		foreach ($table->getColumns() as $column) {
190
+			$comments = $column->getComment();
191
+			$matches = [];
192
+			if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
193
+				$defaultSort = $column->getName();
194
+				if (count($matches) === 3) {
195
+					$defaultSortDirection = $matches[2];
196
+				} else {
197
+					$defaultSortDirection = 'ASC';
198
+				}
199
+			}
200
+		}
201
+
202
+		return [$defaultSort, $defaultSortDirection];
203
+	}
204
+
205
+	/**
206
+	 * Writes the PHP bean DAO with simple functions to create/get/save objects.
207
+	 *
208
+	 * @param BeanDescriptor  $beanDescriptor
209
+	 * @param string          $className       The name of the class
210
+	 * @param string          $baseClassName
211
+	 * @param string          $beanClassName
212
+	 * @param Table           $table
213
+	 *
214
+	 * @throws TDBMException
215
+	 */
216
+	private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table)
217
+	{
218
+		$daonamespace = $this->configuration->getDaoNamespace();
219
+		$beannamespace = $this->configuration->getBeanNamespace();
220
+		$tableName = $table->getName();
221
+		$primaryKeyColumns = $table->getPrimaryKeyColumns();
222
+
223
+		list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
224
+
225
+		// FIXME: lowercase tables with _ in the name should work!
226
+		$tableCamel = self::toSingular(self::toCamelCase($tableName));
227
+
228
+		$beanClassWithoutNameSpace = $beanClassName;
229
+		$beanClassName = $beannamespace.'\\'.$beanClassName;
230
+
231
+		list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
232
+
233
+		$usedBeans[] = $beanClassName;
234
+		// Let's suppress duplicates in used beans (if any)
235
+		$usedBeans = array_flip(array_flip($usedBeans));
236
+		$useStatements = array_map(function ($usedBean) {
237
+			return "use $usedBean;\n";
238
+		}, $usedBeans);
239
+
240
+		$str = "<?php
241 241
 
242 242
 /*
243 243
  * This file has been automatically generated by TDBM.
@@ -313,10 +313,10 @@  discard block
 block discarded – undo
313 313
     }
314 314
     ";
315 315
 
316
-        if (count($primaryKeyColumns) === 1) {
317
-            $primaryKeyColumn = $primaryKeyColumns[0];
318
-            $primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
319
-            $str .= "
316
+		if (count($primaryKeyColumns) === 1) {
317
+			$primaryKeyColumn = $primaryKeyColumns[0];
318
+			$primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
319
+			$str .= "
320 320
     /**
321 321
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
322 322
      * If the primary key does not exist, an exception is thrown.
@@ -331,8 +331,8 @@  discard block
 block discarded – undo
331 331
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
332 332
     }
333 333
     ";
334
-        }
335
-        $str .= "
334
+		}
335
+		$str .= "
336 336
     /**
337 337
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
338 338
      *
@@ -432,21 +432,21 @@  discard block
 block discarded – undo
432 432
     }
433 433
 ";
434 434
 
435
-        $str .= $findByDaoCode;
436
-        $str .= '}
435
+		$str .= $findByDaoCode;
436
+		$str .= '}
437 437
 ';
438 438
 
439
-        $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\Generated\\'.$baseClassName)->getPathname();
439
+		$possibleBaseFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\Generated\\'.$baseClassName)->getPathname();
440 440
 
441
-        $this->ensureDirectoryExist($possibleBaseFileName);
442
-        file_put_contents($possibleBaseFileName, $str);
443
-        @chmod($possibleBaseFileName, 0664);
441
+		$this->ensureDirectoryExist($possibleBaseFileName);
442
+		file_put_contents($possibleBaseFileName, $str);
443
+		@chmod($possibleBaseFileName, 0664);
444 444
 
445
-        $possibleFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\'.$className)->getPathname();
445
+		$possibleFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\'.$className)->getPathname();
446 446
 
447
-        // Now, let's generate the "editable" class
448
-        if (!file_exists($possibleFileName)) {
449
-            $str = "<?php
447
+		// Now, let's generate the "editable" class
448
+		if (!file_exists($possibleFileName)) {
449
+			$str = "<?php
450 450
 
451 451
 /*
452 452
  * This file has been automatically generated by TDBM.
@@ -464,26 +464,26 @@  discard block
 block discarded – undo
464 464
 {
465 465
 }
466 466
 ";
467
-            $this->ensureDirectoryExist($possibleFileName);
468
-            file_put_contents($possibleFileName, $str);
469
-            @chmod($possibleFileName, 0664);
470
-        }
471
-    }
472
-
473
-    /**
474
-     * Generates the factory bean.
475
-     *
476
-     * @param Table[] $tableList
477
-     * @throws TDBMException
478
-     */
479
-    private function generateFactory(array $tableList) : void
480
-    {
481
-        $daoNamespace = $this->configuration->getDaoNamespace();
482
-        $daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
483
-
484
-        // For each table, let's write a property.
485
-
486
-        $str = "<?php
467
+			$this->ensureDirectoryExist($possibleFileName);
468
+			file_put_contents($possibleFileName, $str);
469
+			@chmod($possibleFileName, 0664);
470
+		}
471
+	}
472
+
473
+	/**
474
+	 * Generates the factory bean.
475
+	 *
476
+	 * @param Table[] $tableList
477
+	 * @throws TDBMException
478
+	 */
479
+	private function generateFactory(array $tableList) : void
480
+	{
481
+		$daoNamespace = $this->configuration->getDaoNamespace();
482
+		$daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
483
+
484
+		// For each table, let's write a property.
485
+
486
+		$str = "<?php
487 487
 
488 488
 /*
489 489
  * This file has been automatically generated by TDBM.
@@ -493,13 +493,13 @@  discard block
 block discarded – undo
493 493
 namespace {$daoNamespace}\\Generated;
494 494
 
495 495
 ";
496
-        foreach ($tableList as $table) {
497
-            $tableName = $table->getName();
498
-            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
499
-            $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
500
-        }
496
+		foreach ($tableList as $table) {
497
+			$tableName = $table->getName();
498
+			$daoClassName = $this->namingStrategy->getDaoClassName($tableName);
499
+			$str .= "use {$daoNamespace}\\".$daoClassName.";\n";
500
+		}
501 501
 
502
-        $str .= "
502
+		$str .= "
503 503
 /**
504 504
  * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
505 505
  *
@@ -508,12 +508,12 @@  discard block
 block discarded – undo
508 508
 {
509 509
 ";
510 510
 
511
-        foreach ($tableList as $table) {
512
-            $tableName = $table->getName();
513
-            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
514
-            $daoInstanceName = self::toVariableName($daoClassName);
511
+		foreach ($tableList as $table) {
512
+			$tableName = $table->getName();
513
+			$daoClassName = $this->namingStrategy->getDaoClassName($tableName);
514
+			$daoInstanceName = self::toVariableName($daoClassName);
515 515
 
516
-            $str .= '    /**
516
+			$str .= '    /**
517 517
      * @var '.$daoClassName.'
518 518
      */
519 519
     private $'.$daoInstanceName.';
@@ -537,136 +537,136 @@  discard block
 block discarded – undo
537 537
     {
538 538
         $this->'.$daoInstanceName.' = $'.$daoInstanceName.';
539 539
     }';
540
-        }
540
+		}
541 541
 
542
-        $str .= '
542
+		$str .= '
543 543
 }
544 544
 ';
545 545
 
546
-        $possibleFileName = $this->configuration->getPathFinder()->getPath($daoNamespace.'\\Generated\\'.$daoFactoryClassName)->getPathname();
547
-
548
-        $this->ensureDirectoryExist($possibleFileName);
549
-        file_put_contents($possibleFileName, $str);
550
-        @chmod($possibleFileName, 0664);
551
-    }
552
-
553
-    /**
554
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
555
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
556
-     *
557
-     * @param $str string
558
-     *
559
-     * @return string
560
-     */
561
-    public static function toCamelCase($str)
562
-    {
563
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
564
-        while (true) {
565
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
566
-                break;
567
-            }
568
-
569
-            $pos = strpos($str, '_');
570
-            if ($pos === false) {
571
-                $pos = strpos($str, ' ');
572
-            }
573
-            $before = substr($str, 0, $pos);
574
-            $after = substr($str, $pos + 1);
575
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
576
-        }
577
-
578
-        return $str;
579
-    }
580
-
581
-    /**
582
-     * Tries to put string to the singular form (if it is plural).
583
-     * We assume the table names are in english.
584
-     *
585
-     * @param $str string
586
-     *
587
-     * @return string
588
-     */
589
-    public static function toSingular($str)
590
-    {
591
-        return Inflector::singularize($str);
592
-    }
593
-
594
-    /**
595
-     * Put the first letter of the string in lower case.
596
-     * Very useful to transform a class name into a variable name.
597
-     *
598
-     * @param $str string
599
-     *
600
-     * @return string
601
-     */
602
-    public static function toVariableName($str)
603
-    {
604
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
605
-    }
606
-
607
-    /**
608
-     * Ensures the file passed in parameter can be written in its directory.
609
-     *
610
-     * @param string $fileName
611
-     *
612
-     * @throws TDBMException
613
-     */
614
-    private function ensureDirectoryExist($fileName)
615
-    {
616
-        $dirName = dirname($fileName);
617
-        if (!file_exists($dirName)) {
618
-            $old = umask(0);
619
-            $result = mkdir($dirName, 0775, true);
620
-            umask($old);
621
-            if ($result === false) {
622
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
623
-            }
624
-        }
625
-    }
626
-
627
-    /**
628
-     * Absolute path to composer json file.
629
-     *
630
-     * @param string $composerFile
631
-     */
632
-    /*public function setComposerFile($composerFile)
546
+		$possibleFileName = $this->configuration->getPathFinder()->getPath($daoNamespace.'\\Generated\\'.$daoFactoryClassName)->getPathname();
547
+
548
+		$this->ensureDirectoryExist($possibleFileName);
549
+		file_put_contents($possibleFileName, $str);
550
+		@chmod($possibleFileName, 0664);
551
+	}
552
+
553
+	/**
554
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
555
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
556
+	 *
557
+	 * @param $str string
558
+	 *
559
+	 * @return string
560
+	 */
561
+	public static function toCamelCase($str)
562
+	{
563
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
564
+		while (true) {
565
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
566
+				break;
567
+			}
568
+
569
+			$pos = strpos($str, '_');
570
+			if ($pos === false) {
571
+				$pos = strpos($str, ' ');
572
+			}
573
+			$before = substr($str, 0, $pos);
574
+			$after = substr($str, $pos + 1);
575
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
576
+		}
577
+
578
+		return $str;
579
+	}
580
+
581
+	/**
582
+	 * Tries to put string to the singular form (if it is plural).
583
+	 * We assume the table names are in english.
584
+	 *
585
+	 * @param $str string
586
+	 *
587
+	 * @return string
588
+	 */
589
+	public static function toSingular($str)
590
+	{
591
+		return Inflector::singularize($str);
592
+	}
593
+
594
+	/**
595
+	 * Put the first letter of the string in lower case.
596
+	 * Very useful to transform a class name into a variable name.
597
+	 *
598
+	 * @param $str string
599
+	 *
600
+	 * @return string
601
+	 */
602
+	public static function toVariableName($str)
603
+	{
604
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
605
+	}
606
+
607
+	/**
608
+	 * Ensures the file passed in parameter can be written in its directory.
609
+	 *
610
+	 * @param string $fileName
611
+	 *
612
+	 * @throws TDBMException
613
+	 */
614
+	private function ensureDirectoryExist($fileName)
615
+	{
616
+		$dirName = dirname($fileName);
617
+		if (!file_exists($dirName)) {
618
+			$old = umask(0);
619
+			$result = mkdir($dirName, 0775, true);
620
+			umask($old);
621
+			if ($result === false) {
622
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
623
+			}
624
+		}
625
+	}
626
+
627
+	/**
628
+	 * Absolute path to composer json file.
629
+	 *
630
+	 * @param string $composerFile
631
+	 */
632
+	/*public function setComposerFile($composerFile)
633 633
     {
634 634
         $this->rootPath = dirname($composerFile).'/';
635 635
         $this->composerFile = basename($composerFile);
636 636
     }*/
637 637
 
638
-    /**
639
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
640
-     *
641
-     * @param Type $type The DBAL type
642
-     *
643
-     * @return string The PHP type
644
-     */
645
-    public static function dbalTypeToPhpType(Type $type)
646
-    {
647
-        $map = [
648
-            Type::TARRAY => 'array',
649
-            Type::SIMPLE_ARRAY => 'array',
650
-            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
651
-            Type::JSON_ARRAY => 'array',
652
-            Type::BIGINT => 'string',
653
-            Type::BOOLEAN => 'bool',
654
-            Type::DATETIME => '\DateTimeInterface',
655
-            Type::DATETIMETZ => '\DateTimeInterface',
656
-            Type::DATE => '\DateTimeInterface',
657
-            Type::TIME => '\DateTimeInterface',
658
-            Type::DECIMAL => 'float',
659
-            Type::INTEGER => 'int',
660
-            Type::OBJECT => 'string',
661
-            Type::SMALLINT => 'int',
662
-            Type::STRING => 'string',
663
-            Type::TEXT => 'string',
664
-            Type::BINARY => 'string',
665
-            Type::BLOB => 'string',
666
-            Type::FLOAT => 'float',
667
-            Type::GUID => 'string',
668
-        ];
669
-
670
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
671
-    }
638
+	/**
639
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
640
+	 *
641
+	 * @param Type $type The DBAL type
642
+	 *
643
+	 * @return string The PHP type
644
+	 */
645
+	public static function dbalTypeToPhpType(Type $type)
646
+	{
647
+		$map = [
648
+			Type::TARRAY => 'array',
649
+			Type::SIMPLE_ARRAY => 'array',
650
+			'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
651
+			Type::JSON_ARRAY => 'array',
652
+			Type::BIGINT => 'string',
653
+			Type::BOOLEAN => 'bool',
654
+			Type::DATETIME => '\DateTimeInterface',
655
+			Type::DATETIMETZ => '\DateTimeInterface',
656
+			Type::DATE => '\DateTimeInterface',
657
+			Type::TIME => '\DateTimeInterface',
658
+			Type::DECIMAL => 'float',
659
+			Type::INTEGER => 'int',
660
+			Type::OBJECT => 'string',
661
+			Type::SMALLINT => 'int',
662
+			Type::STRING => 'string',
663
+			Type::TEXT => 'string',
664
+			Type::BINARY => 'string',
665
+			Type::BLOB => 'string',
666
+			Type::FLOAT => 'float',
667
+			Type::GUID => 'string',
668
+		];
669
+
670
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
671
+	}
672 672
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/ScalarBeanPropertyDescriptor.php 1 patch
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -11,136 +11,136 @@  discard block
 block discarded – undo
11 11
  */
12 12
 class ScalarBeanPropertyDescriptor extends AbstractBeanPropertyDescriptor
13 13
 {
14
-    /**
15
-     * @var Column
16
-     */
17
-    private $column;
18
-    /**
19
-     * @var NamingStrategyInterface
20
-     */
21
-    private $namingStrategy;
22
-
23
-    /**
24
-     * ScalarBeanPropertyDescriptor constructor.
25
-     * @param Table $table
26
-     * @param Column $column
27
-     * @param NamingStrategyInterface $namingStrategy
28
-     */
29
-    public function __construct(Table $table, Column $column, NamingStrategyInterface $namingStrategy)
30
-    {
31
-        parent::__construct($table);
32
-        $this->table = $table;
33
-        $this->column = $column;
34
-        $this->namingStrategy = $namingStrategy;
35
-    }
36
-
37
-    /**
38
-     * Returns the foreign-key the column is part of, if any. null otherwise.
39
-     *
40
-     * @return ForeignKeyConstraint|null
41
-     */
42
-    public function getForeignKey()
43
-    {
44
-        return false;
45
-    }
46
-
47
-    /**
48
-     * Returns the param annotation for this property (useful for constructor).
49
-     *
50
-     * @return string
51
-     */
52
-    public function getParamAnnotation()
53
-    {
54
-        $className = $this->getClassName();
55
-        $paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
56
-
57
-        $str = '     * @param %s %s';
58
-
59
-        return sprintf($str, $paramType, $this->getVariableName());
60
-    }
61
-
62
-    public function getUpperCamelCaseName()
63
-    {
64
-        return TDBMDaoGenerator::toCamelCase($this->column->getName());
65
-    }
66
-
67
-    /**
68
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
69
-     *
70
-     * @return null|string
71
-     */
72
-    public function getClassName()
73
-    {
74
-        return;
75
-    }
76
-
77
-    /**
78
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
79
-     *
80
-     * @return bool
81
-     */
82
-    public function isCompulsory()
83
-    {
84
-        return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
85
-    }
86
-
87
-    /**
88
-     * Returns true if the property has a default value.
89
-     *
90
-     * @return bool
91
-     */
92
-    public function hasDefault()
93
-    {
94
-        return $this->column->getDefault() !== null;
95
-    }
96
-
97
-    /**
98
-     * Returns the code that assigns a value to its default value.
99
-     *
100
-     * @return string
101
-     */
102
-    public function assignToDefaultCode()
103
-    {
104
-        $str = '        $this->%s(%s);';
105
-
106
-        $default = $this->column->getDefault();
107
-
108
-        if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
109
-            $defaultCode = 'new \DateTimeImmutable()';
110
-        } else {
111
-            $defaultCode = var_export($this->column->getDefault(), true);
112
-        }
113
-
114
-        return sprintf($str, $this->getSetterName(), $defaultCode);
115
-    }
116
-
117
-    /**
118
-     * Returns true if the property is the primary key.
119
-     *
120
-     * @return bool
121
-     */
122
-    public function isPrimaryKey()
123
-    {
124
-        return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
125
-    }
126
-
127
-    /**
128
-     * Returns the PHP code for getters and setters.
129
-     *
130
-     * @return string
131
-     */
132
-    public function getGetterSetterCode()
133
-    {
134
-        $type = $this->column->getType();
135
-        $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
136
-
137
-        $columnGetterName = $this->getGetterName();
138
-        $columnSetterName = $this->getSetterName();
139
-
140
-        // A column type can be forced if it is not nullable and not auto-incrementable (for auto-increment columns, we can get "null" as long as the bean is not saved).
141
-        $isNullable = !$this->column->getNotnull() || $this->column->getAutoincrement();
142
-
143
-        $getterAndSetterCode = '    /**
14
+	/**
15
+	 * @var Column
16
+	 */
17
+	private $column;
18
+	/**
19
+	 * @var NamingStrategyInterface
20
+	 */
21
+	private $namingStrategy;
22
+
23
+	/**
24
+	 * ScalarBeanPropertyDescriptor constructor.
25
+	 * @param Table $table
26
+	 * @param Column $column
27
+	 * @param NamingStrategyInterface $namingStrategy
28
+	 */
29
+	public function __construct(Table $table, Column $column, NamingStrategyInterface $namingStrategy)
30
+	{
31
+		parent::__construct($table);
32
+		$this->table = $table;
33
+		$this->column = $column;
34
+		$this->namingStrategy = $namingStrategy;
35
+	}
36
+
37
+	/**
38
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
39
+	 *
40
+	 * @return ForeignKeyConstraint|null
41
+	 */
42
+	public function getForeignKey()
43
+	{
44
+		return false;
45
+	}
46
+
47
+	/**
48
+	 * Returns the param annotation for this property (useful for constructor).
49
+	 *
50
+	 * @return string
51
+	 */
52
+	public function getParamAnnotation()
53
+	{
54
+		$className = $this->getClassName();
55
+		$paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
56
+
57
+		$str = '     * @param %s %s';
58
+
59
+		return sprintf($str, $paramType, $this->getVariableName());
60
+	}
61
+
62
+	public function getUpperCamelCaseName()
63
+	{
64
+		return TDBMDaoGenerator::toCamelCase($this->column->getName());
65
+	}
66
+
67
+	/**
68
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
69
+	 *
70
+	 * @return null|string
71
+	 */
72
+	public function getClassName()
73
+	{
74
+		return;
75
+	}
76
+
77
+	/**
78
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
79
+	 *
80
+	 * @return bool
81
+	 */
82
+	public function isCompulsory()
83
+	{
84
+		return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
85
+	}
86
+
87
+	/**
88
+	 * Returns true if the property has a default value.
89
+	 *
90
+	 * @return bool
91
+	 */
92
+	public function hasDefault()
93
+	{
94
+		return $this->column->getDefault() !== null;
95
+	}
96
+
97
+	/**
98
+	 * Returns the code that assigns a value to its default value.
99
+	 *
100
+	 * @return string
101
+	 */
102
+	public function assignToDefaultCode()
103
+	{
104
+		$str = '        $this->%s(%s);';
105
+
106
+		$default = $this->column->getDefault();
107
+
108
+		if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
109
+			$defaultCode = 'new \DateTimeImmutable()';
110
+		} else {
111
+			$defaultCode = var_export($this->column->getDefault(), true);
112
+		}
113
+
114
+		return sprintf($str, $this->getSetterName(), $defaultCode);
115
+	}
116
+
117
+	/**
118
+	 * Returns true if the property is the primary key.
119
+	 *
120
+	 * @return bool
121
+	 */
122
+	public function isPrimaryKey()
123
+	{
124
+		return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
125
+	}
126
+
127
+	/**
128
+	 * Returns the PHP code for getters and setters.
129
+	 *
130
+	 * @return string
131
+	 */
132
+	public function getGetterSetterCode()
133
+	{
134
+		$type = $this->column->getType();
135
+		$normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
136
+
137
+		$columnGetterName = $this->getGetterName();
138
+		$columnSetterName = $this->getSetterName();
139
+
140
+		// A column type can be forced if it is not nullable and not auto-incrementable (for auto-increment columns, we can get "null" as long as the bean is not saved).
141
+		$isNullable = !$this->column->getNotnull() || $this->column->getAutoincrement();
142
+
143
+		$getterAndSetterCode = '    /**
144 144
      * The getter for the "%s" column.
145 145
      *
146 146
      * @return %s
@@ -162,54 +162,54 @@  discard block
 block discarded – undo
162 162
 
163 163
 ';
164 164
 
165
-        return sprintf($getterAndSetterCode,
166
-            // Getter
167
-            $this->column->getName(),
168
-            $normalizedType.($isNullable ? '|null' : ''),
169
-            $columnGetterName,
170
-            ($isNullable ? '?' : ''),
171
-            $normalizedType,
172
-            var_export($this->column->getName(), true),
173
-            var_export($this->table->getName(), true),
174
-            // Setter
175
-            $this->column->getName(),
176
-            $normalizedType,
177
-            $this->column->getName(),
178
-            $columnSetterName,
179
-            $this->column->getNotnull() ? '' : '?',
180
-            $normalizedType,
181
-                //$castTo,
182
-            $this->column->getName(),
183
-            var_export($this->column->getName(), true),
184
-            $this->column->getName(),
185
-            var_export($this->table->getName(), true)
186
-        );
187
-    }
188
-
189
-    /**
190
-     * Returns the part of code useful when doing json serialization.
191
-     *
192
-     * @return string
193
-     */
194
-    public function getJsonSerializeCode()
195
-    {
196
-        $type = $this->column->getType();
197
-        $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
198
-
199
-        if ($normalizedType == '\\DateTimeInterface') {
200
-            return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null) ? null : $this->'.$this->getGetterName()."()->format('c');\n";
201
-        } else {
202
-            return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
203
-        }
204
-    }
205
-
206
-    /**
207
-     * Returns the column name.
208
-     *
209
-     * @return string
210
-     */
211
-    public function getColumnName()
212
-    {
213
-        return $this->column->getName();
214
-    }
165
+		return sprintf($getterAndSetterCode,
166
+			// Getter
167
+			$this->column->getName(),
168
+			$normalizedType.($isNullable ? '|null' : ''),
169
+			$columnGetterName,
170
+			($isNullable ? '?' : ''),
171
+			$normalizedType,
172
+			var_export($this->column->getName(), true),
173
+			var_export($this->table->getName(), true),
174
+			// Setter
175
+			$this->column->getName(),
176
+			$normalizedType,
177
+			$this->column->getName(),
178
+			$columnSetterName,
179
+			$this->column->getNotnull() ? '' : '?',
180
+			$normalizedType,
181
+				//$castTo,
182
+			$this->column->getName(),
183
+			var_export($this->column->getName(), true),
184
+			$this->column->getName(),
185
+			var_export($this->table->getName(), true)
186
+		);
187
+	}
188
+
189
+	/**
190
+	 * Returns the part of code useful when doing json serialization.
191
+	 *
192
+	 * @return string
193
+	 */
194
+	public function getJsonSerializeCode()
195
+	{
196
+		$type = $this->column->getType();
197
+		$normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
198
+
199
+		if ($normalizedType == '\\DateTimeInterface') {
200
+			return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null) ? null : $this->'.$this->getGetterName()."()->format('c');\n";
201
+		} else {
202
+			return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
203
+		}
204
+	}
205
+
206
+	/**
207
+	 * Returns the column name.
208
+	 *
209
+	 * @return string
210
+	 */
211
+	public function getColumnName()
212
+	{
213
+		return $this->column->getName();
214
+	}
215 215
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/PivotTableMethodsDescriptor.php 1 patch
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -7,105 +7,105 @@  discard block
 block discarded – undo
7 7
 
8 8
 class PivotTableMethodsDescriptor implements MethodDescriptorInterface
9 9
 {
10
-    /**
11
-     * @var Table
12
-     */
13
-    private $pivotTable;
14
-
15
-    private $useAlternateName = false;
16
-
17
-    /**
18
-     * @var ForeignKeyConstraint
19
-     */
20
-    private $localFk;
21
-
22
-    /**
23
-     * @var ForeignKeyConstraint
24
-     */
25
-    private $remoteFk;
26
-    /**
27
-     * @var NamingStrategyInterface
28
-     */
29
-    private $namingStrategy;
30
-
31
-    /**
32
-     * @param Table $pivotTable The pivot table
33
-     * @param ForeignKeyConstraint $localFk
34
-     * @param ForeignKeyConstraint $remoteFk
35
-     * @param NamingStrategyInterface $namingStrategy
36
-     */
37
-    public function __construct(Table $pivotTable, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk, NamingStrategyInterface $namingStrategy)
38
-    {
39
-        $this->pivotTable = $pivotTable;
40
-        $this->localFk = $localFk;
41
-        $this->remoteFk = $remoteFk;
42
-        $this->namingStrategy = $namingStrategy;
43
-    }
44
-
45
-    /**
46
-     * Requests the use of an alternative name for this method.
47
-     */
48
-    public function useAlternativeName()
49
-    {
50
-        $this->useAlternateName = true;
51
-    }
52
-
53
-    /**
54
-     * Returns the name of the method to be generated.
55
-     *
56
-     * @return string
57
-     */
58
-    public function getName() : string
59
-    {
60
-        if (!$this->useAlternateName) {
61
-            return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName());
62
-        } else {
63
-            return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
64
-        }
65
-    }
66
-
67
-    /**
68
-     * Returns the plural name.
69
-     *
70
-     * @return string
71
-     */
72
-    private function getPluralName() : string
73
-    {
74
-        if (!$this->useAlternateName) {
75
-            return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName());
76
-        } else {
77
-            return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
78
-        }
79
-    }
80
-
81
-    /**
82
-     * Returns the singular name.
83
-     *
84
-     * @return string
85
-     */
86
-    private function getSingularName() : string
87
-    {
88
-        if (!$this->useAlternateName) {
89
-            return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName()));
90
-        } else {
91
-            return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
92
-        }
93
-    }
94
-
95
-    /**
96
-     * Returns the code of the method.
97
-     *
98
-     * @return string
99
-     */
100
-    public function getCode() : string
101
-    {
102
-        $singularName = $this->getSingularName();
103
-        $pluralName = $this->getPluralName();
104
-        $remoteBeanName = $this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName());
105
-        $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
106
-        $pluralVariableName = $variableName.'s';
107
-
108
-        $str = '    /**
10
+	/**
11
+	 * @var Table
12
+	 */
13
+	private $pivotTable;
14
+
15
+	private $useAlternateName = false;
16
+
17
+	/**
18
+	 * @var ForeignKeyConstraint
19
+	 */
20
+	private $localFk;
21
+
22
+	/**
23
+	 * @var ForeignKeyConstraint
24
+	 */
25
+	private $remoteFk;
26
+	/**
27
+	 * @var NamingStrategyInterface
28
+	 */
29
+	private $namingStrategy;
30
+
31
+	/**
32
+	 * @param Table $pivotTable The pivot table
33
+	 * @param ForeignKeyConstraint $localFk
34
+	 * @param ForeignKeyConstraint $remoteFk
35
+	 * @param NamingStrategyInterface $namingStrategy
36
+	 */
37
+	public function __construct(Table $pivotTable, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk, NamingStrategyInterface $namingStrategy)
38
+	{
39
+		$this->pivotTable = $pivotTable;
40
+		$this->localFk = $localFk;
41
+		$this->remoteFk = $remoteFk;
42
+		$this->namingStrategy = $namingStrategy;
43
+	}
44
+
45
+	/**
46
+	 * Requests the use of an alternative name for this method.
47
+	 */
48
+	public function useAlternativeName()
49
+	{
50
+		$this->useAlternateName = true;
51
+	}
52
+
53
+	/**
54
+	 * Returns the name of the method to be generated.
55
+	 *
56
+	 * @return string
57
+	 */
58
+	public function getName() : string
59
+	{
60
+		if (!$this->useAlternateName) {
61
+			return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName());
62
+		} else {
63
+			return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
64
+		}
65
+	}
66
+
67
+	/**
68
+	 * Returns the plural name.
69
+	 *
70
+	 * @return string
71
+	 */
72
+	private function getPluralName() : string
73
+	{
74
+		if (!$this->useAlternateName) {
75
+			return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName());
76
+		} else {
77
+			return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
78
+		}
79
+	}
80
+
81
+	/**
82
+	 * Returns the singular name.
83
+	 *
84
+	 * @return string
85
+	 */
86
+	private function getSingularName() : string
87
+	{
88
+		if (!$this->useAlternateName) {
89
+			return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName()));
90
+		} else {
91
+			return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
92
+		}
93
+	}
94
+
95
+	/**
96
+	 * Returns the code of the method.
97
+	 *
98
+	 * @return string
99
+	 */
100
+	public function getCode() : string
101
+	{
102
+		$singularName = $this->getSingularName();
103
+		$pluralName = $this->getPluralName();
104
+		$remoteBeanName = $this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName());
105
+		$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
106
+		$pluralVariableName = $variableName.'s';
107
+
108
+		$str = '    /**
109 109
      * Returns the list of %s associated to this bean via the %s pivot table.
110 110
      *
111 111
      * @return %s[]
@@ -116,9 +116,9 @@  discard block
 block discarded – undo
116 116
     }
117 117
 ';
118 118
 
119
-        $getterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralName, var_export($this->remoteFk->getLocalTableName(), true));
119
+		$getterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralName, var_export($this->remoteFk->getLocalTableName(), true));
120 120
 
121
-        $str = '    /**
121
+		$str = '    /**
122 122
      * Adds a relationship with %s associated to this bean via the %s pivot table.
123 123
      *
124 124
      * @param %s %s
@@ -129,9 +129,9 @@  discard block
 block discarded – undo
129 129
     }
130 130
 ';
131 131
 
132
-        $adderCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
132
+		$adderCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
133 133
 
134
-        $str = '    /**
134
+		$str = '    /**
135 135
      * Deletes the relationship with %s associated to this bean via the %s pivot table.
136 136
      *
137 137
      * @param %s %s
@@ -142,9 +142,9 @@  discard block
 block discarded – undo
142 142
     }
143 143
 ';
144 144
 
145
-        $removerCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
145
+		$removerCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
146 146
 
147
-        $str = '    /**
147
+		$str = '    /**
148 148
      * Returns whether this bean is associated with %s via the %s pivot table.
149 149
      *
150 150
      * @param %s %s
@@ -156,9 +156,9 @@  discard block
 block discarded – undo
156 156
     }
157 157
 ';
158 158
 
159
-        $hasCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
159
+		$hasCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
160 160
 
161
-        $str = '    /**
161
+		$str = '    /**
162 162
      * Sets all relationships with %s associated to this bean via the %s pivot table.
163 163
      * Exiting relationships will be removed and replaced by the provided relationships.
164 164
      *
@@ -170,38 +170,38 @@  discard block
 block discarded – undo
170 170
     }
171 171
 ';
172 172
 
173
-        $setterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($this->remoteFk->getLocalTableName(), true), $pluralVariableName);
174
-
175
-        $code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode;
176
-
177
-        return $code;
178
-    }
179
-
180
-    /**
181
-     * Returns an array of classes that needs a "use" for this method.
182
-     *
183
-     * @return string[]
184
-     */
185
-    public function getUsedClasses() : array
186
-    {
187
-        return [$this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName())];
188
-    }
189
-
190
-    /**
191
-     * Returns the code to past in jsonSerialize.
192
-     *
193
-     * @return string
194
-     */
195
-    public function getJsonSerializeCode() : string
196
-    {
197
-        $remoteBeanName = $this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName());
198
-        $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
199
-
200
-        return '        if (!$stopRecursion) {
173
+		$setterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($this->remoteFk->getLocalTableName(), true), $pluralVariableName);
174
+
175
+		$code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode;
176
+
177
+		return $code;
178
+	}
179
+
180
+	/**
181
+	 * Returns an array of classes that needs a "use" for this method.
182
+	 *
183
+	 * @return string[]
184
+	 */
185
+	public function getUsedClasses() : array
186
+	{
187
+		return [$this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName())];
188
+	}
189
+
190
+	/**
191
+	 * Returns the code to past in jsonSerialize.
192
+	 *
193
+	 * @return string
194
+	 */
195
+	public function getJsonSerializeCode() : string
196
+	{
197
+		$remoteBeanName = $this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName());
198
+		$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
199
+
200
+		return '        if (!$stopRecursion) {
201 201
             $array[\''.lcfirst($this->getPluralName()).'\'] = array_map(function ('.$remoteBeanName.' '.$variableName.') {
202 202
                 return '.$variableName.'->jsonSerialize(true);
203 203
             }, $this->'.$this->getName().'());
204 204
         }
205 205
 ';
206
-    }
206
+	}
207 207
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/GeneratorEventDispatcher.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -7,28 +7,28 @@
 block discarded – undo
7 7
 
8 8
 class GeneratorEventDispatcher implements GeneratorListenerInterface
9 9
 {
10
-    /**
11
-     * @var GeneratorListenerInterface[]
12
-     */
13
-    private $listeners;
10
+	/**
11
+	 * @var GeneratorListenerInterface[]
12
+	 */
13
+	private $listeners;
14 14
 
15
-    /**
16
-     * GeneratorEventDispatcher constructor.
17
-     * @param GeneratorListenerInterface[] $listeners
18
-     */
19
-    public function __construct(array $listeners)
20
-    {
21
-        $this->listeners = $listeners;
22
-    }
15
+	/**
16
+	 * GeneratorEventDispatcher constructor.
17
+	 * @param GeneratorListenerInterface[] $listeners
18
+	 */
19
+	public function __construct(array $listeners)
20
+	{
21
+		$this->listeners = $listeners;
22
+	}
23 23
 
24
-    /**
25
-     * @param ConfigurationInterface $configuration
26
-     * @param BeanDescriptorInterface[] $beanDescriptors
27
-     */
28
-    public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
29
-    {
30
-        foreach ($this->listeners as $listener) {
31
-            $listener->onGenerate($configuration, $beanDescriptors);
32
-        }
33
-    }
24
+	/**
25
+	 * @param ConfigurationInterface $configuration
26
+	 * @param BeanDescriptorInterface[] $beanDescriptors
27
+	 */
28
+	public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
29
+	{
30
+		foreach ($this->listeners as $listener) {
31
+			$listener->onGenerate($configuration, $beanDescriptors);
32
+		}
33
+	}
34 34
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/DirectForeignKeyMethodDescriptor.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -12,71 +12,71 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class DirectForeignKeyMethodDescriptor implements MethodDescriptorInterface
14 14
 {
15
-    /**
16
-     * @var ForeignKeyConstraint
17
-     */
18
-    private $fk;
19
-
20
-    private $useAlternateName = false;
21
-    /**
22
-     * @var Table
23
-     */
24
-    private $mainTable;
25
-    /**
26
-     * @var NamingStrategyInterface
27
-     */
28
-    private $namingStrategy;
29
-
30
-    /**
31
-     * @param ForeignKeyConstraint $fk The foreign key pointing to our bean
32
-     * @param Table $mainTable The main table that is pointed to
33
-     * @param NamingStrategyInterface $namingStrategy
34
-     */
35
-    public function __construct(ForeignKeyConstraint $fk, Table $mainTable, NamingStrategyInterface $namingStrategy)
36
-    {
37
-        $this->fk = $fk;
38
-        $this->mainTable = $mainTable;
39
-        $this->namingStrategy = $namingStrategy;
40
-    }
41
-
42
-    /**
43
-     * Returns the name of the method to be generated.
44
-     *
45
-     * @return string
46
-     */
47
-    public function getName() : string
48
-    {
49
-        if (!$this->useAlternateName) {
50
-            return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName());
51
-        } else {
52
-            $methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By';
53
-
54
-            $camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns());
55
-
56
-            $methodName .= implode('And', $camelizedColumns);
57
-
58
-            return $methodName;
59
-        }
60
-    }
61
-
62
-    /**
63
-     * Requests the use of an alternative name for this method.
64
-     */
65
-    public function useAlternativeName()
66
-    {
67
-        $this->useAlternateName = true;
68
-    }
69
-
70
-    /**
71
-     * Returns the code of the method.
72
-     *
73
-     * @return string
74
-     */
75
-    public function getCode() : string
76
-    {
77
-        $code = '';
78
-
79
-        $getterCode = '    /**
15
+	/**
16
+	 * @var ForeignKeyConstraint
17
+	 */
18
+	private $fk;
19
+
20
+	private $useAlternateName = false;
21
+	/**
22
+	 * @var Table
23
+	 */
24
+	private $mainTable;
25
+	/**
26
+	 * @var NamingStrategyInterface
27
+	 */
28
+	private $namingStrategy;
29
+
30
+	/**
31
+	 * @param ForeignKeyConstraint $fk The foreign key pointing to our bean
32
+	 * @param Table $mainTable The main table that is pointed to
33
+	 * @param NamingStrategyInterface $namingStrategy
34
+	 */
35
+	public function __construct(ForeignKeyConstraint $fk, Table $mainTable, NamingStrategyInterface $namingStrategy)
36
+	{
37
+		$this->fk = $fk;
38
+		$this->mainTable = $mainTable;
39
+		$this->namingStrategy = $namingStrategy;
40
+	}
41
+
42
+	/**
43
+	 * Returns the name of the method to be generated.
44
+	 *
45
+	 * @return string
46
+	 */
47
+	public function getName() : string
48
+	{
49
+		if (!$this->useAlternateName) {
50
+			return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName());
51
+		} else {
52
+			$methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By';
53
+
54
+			$camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns());
55
+
56
+			$methodName .= implode('And', $camelizedColumns);
57
+
58
+			return $methodName;
59
+		}
60
+	}
61
+
62
+	/**
63
+	 * Requests the use of an alternative name for this method.
64
+	 */
65
+	public function useAlternativeName()
66
+	{
67
+		$this->useAlternateName = true;
68
+	}
69
+
70
+	/**
71
+	 * Returns the code of the method.
72
+	 *
73
+	 * @return string
74
+	 */
75
+	public function getCode() : string
76
+	{
77
+		$code = '';
78
+
79
+		$getterCode = '    /**
80 80
      * Returns the list of %s pointing to this bean via the %s column.
81 81
      *
82 82
      * @return %s[]|AlterableResultIterator
@@ -88,55 +88,55 @@  discard block
 block discarded – undo
88 88
 
89 89
 ';
90 90
 
91
-        $beanClass = $this->namingStrategy->getBeanClassName($this->fk->getLocalTableName());
92
-        $code .= sprintf($getterCode,
93
-            $beanClass,
94
-            implode(', ', $this->fk->getColumns()),
95
-            $beanClass,
96
-            $this->getName(),
97
-            var_export($this->fk->getLocalTableName(), true),
98
-            var_export($this->fk->getName(), true),
99
-            var_export($this->fk->getLocalTableName(), true),
100
-            $this->getFilters($this->fk)
101
-        );
102
-
103
-        return $code;
104
-    }
105
-
106
-    private function getFilters(ForeignKeyConstraint $fk) : string
107
-    {
108
-        $counter = 0;
109
-        $parameters = [];
110
-
111
-        $pkColumns = $this->mainTable->getPrimaryKeyColumns();
112
-
113
-        foreach ($fk->getLocalColumns() as $columnName) {
114
-            $pkColumn = $pkColumns[$counter];
115
-            $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true));
116
-            ++$counter;
117
-        }
118
-        $parametersCode = '['.implode(', ', $parameters).']';
119
-
120
-        return $parametersCode;
121
-    }
122
-
123
-    /**
124
-     * Returns an array of classes that needs a "use" for this method.
125
-     *
126
-     * @return string[]
127
-     */
128
-    public function getUsedClasses() : array
129
-    {
130
-        return [$this->namingStrategy->getBeanClassName($this->fk->getForeignTableName())];
131
-    }
132
-
133
-    /**
134
-     * Returns the code to past in jsonSerialize.
135
-     *
136
-     * @return string
137
-     */
138
-    public function getJsonSerializeCode() : string
139
-    {
140
-        return '';
141
-    }
91
+		$beanClass = $this->namingStrategy->getBeanClassName($this->fk->getLocalTableName());
92
+		$code .= sprintf($getterCode,
93
+			$beanClass,
94
+			implode(', ', $this->fk->getColumns()),
95
+			$beanClass,
96
+			$this->getName(),
97
+			var_export($this->fk->getLocalTableName(), true),
98
+			var_export($this->fk->getName(), true),
99
+			var_export($this->fk->getLocalTableName(), true),
100
+			$this->getFilters($this->fk)
101
+		);
102
+
103
+		return $code;
104
+	}
105
+
106
+	private function getFilters(ForeignKeyConstraint $fk) : string
107
+	{
108
+		$counter = 0;
109
+		$parameters = [];
110
+
111
+		$pkColumns = $this->mainTable->getPrimaryKeyColumns();
112
+
113
+		foreach ($fk->getLocalColumns() as $columnName) {
114
+			$pkColumn = $pkColumns[$counter];
115
+			$parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true));
116
+			++$counter;
117
+		}
118
+		$parametersCode = '['.implode(', ', $parameters).']';
119
+
120
+		return $parametersCode;
121
+	}
122
+
123
+	/**
124
+	 * Returns an array of classes that needs a "use" for this method.
125
+	 *
126
+	 * @return string[]
127
+	 */
128
+	public function getUsedClasses() : array
129
+	{
130
+		return [$this->namingStrategy->getBeanClassName($this->fk->getForeignTableName())];
131
+	}
132
+
133
+	/**
134
+	 * Returns the code to past in jsonSerialize.
135
+	 *
136
+	 * @return string
137
+	 */
138
+	public function getJsonSerializeCode() : string
139
+	{
140
+		return '';
141
+	}
142 142
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/VoidListener.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -11,12 +11,12 @@
 block discarded – undo
11 11
 class VoidListener implements GeneratorListenerInterface
12 12
 {
13 13
 
14
-    /**
15
-     * @param ConfigurationInterface $configuration
16
-     * @param BeanDescriptorInterface[] $beanDescriptors
17
-     */
18
-    public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
19
-    {
20
-        // Let's do nothing.
21
-    }
14
+	/**
15
+	 * @param ConfigurationInterface $configuration
16
+	 * @param BeanDescriptorInterface[] $beanDescriptors
17
+	 */
18
+	public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
19
+	{
20
+		// Let's do nothing.
21
+	}
22 22
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/ObjectBeanPropertyDescriptor.php 2 patches
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -12,169 +12,169 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class ObjectBeanPropertyDescriptor extends AbstractBeanPropertyDescriptor
14 14
 {
15
-    /**
16
-     * @var ForeignKeyConstraint
17
-     */
18
-    private $foreignKey;
19
-
20
-    /**
21
-     * @var SchemaAnalyzer
22
-     */
23
-    private $schemaAnalyzer;
24
-    /**
25
-     * @var NamingStrategyInterface
26
-     */
27
-    private $namingStrategy;
28
-
29
-    /**
30
-     * ObjectBeanPropertyDescriptor constructor.
31
-     * @param Table $table
32
-     * @param ForeignKeyConstraint $foreignKey
33
-     * @param SchemaAnalyzer $schemaAnalyzer
34
-     * @param NamingStrategyInterface $namingStrategy
35
-     */
36
-    public function __construct(Table $table, ForeignKeyConstraint $foreignKey, SchemaAnalyzer $schemaAnalyzer, NamingStrategyInterface $namingStrategy)
37
-    {
38
-        parent::__construct($table);
39
-        $this->foreignKey = $foreignKey;
40
-        $this->schemaAnalyzer = $schemaAnalyzer;
41
-        $this->namingStrategy = $namingStrategy;
42
-    }
43
-
44
-    /**
45
-     * Returns the foreignkey the column is part of, if any. null otherwise.
46
-     *
47
-     * @return ForeignKeyConstraint|null
48
-     */
49
-    public function getForeignKey()
50
-    {
51
-        return $this->foreignKey;
52
-    }
53
-
54
-    /**
55
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
56
-     *
57
-     * @return null|string
58
-     */
59
-    public function getClassName()
60
-    {
61
-        return $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
62
-    }
63
-
64
-    /**
65
-     * Returns the param annotation for this property (useful for constructor).
66
-     *
67
-     * @return string
68
-     */
69
-    public function getParamAnnotation()
70
-    {
71
-        $str = '     * @param %s %s';
72
-
73
-        return sprintf($str, $this->getClassName(), $this->getVariableName());
74
-    }
75
-
76
-    public function getUpperCamelCaseName()
77
-    {
78
-        // First, are there many column or only one?
79
-        // If one column, we name the setter after it. Otherwise, we name the setter after the table name
80
-        if (count($this->foreignKey->getLocalColumns()) > 1) {
81
-            $name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
82
-            if ($this->alternativeName) {
83
-                $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
84
-
85
-                $name .= 'By'.implode('And', $camelizedColumns);
86
-            }
87
-        } else {
88
-            $column = $this->foreignKey->getLocalColumns()[0];
89
-            // Let's remove any _id or id_.
90
-            if (strpos(strtolower($column), 'id_') === 0) {
91
-                $column = substr($column, 3);
92
-            }
93
-            if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
94
-                $column = substr($column, 0, strlen($column) - 3);
95
-            }
96
-            $name = TDBMDaoGenerator::toCamelCase($column);
97
-            if ($this->alternativeName) {
98
-                $name .= 'Object';
99
-            }
100
-        }
101
-
102
-        return $name;
103
-    }
104
-
105
-    /**
106
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
107
-     *
108
-     * @return bool
109
-     */
110
-    public function isCompulsory()
111
-    {
112
-        // Are all columns nullable?
113
-        $localColumnNames = $this->foreignKey->getLocalColumns();
114
-
115
-        foreach ($localColumnNames as $name) {
116
-            $column = $this->table->getColumn($name);
117
-            if ($column->getNotnull()) {
118
-                return true;
119
-            }
120
-        }
121
-
122
-        return false;
123
-    }
124
-
125
-    /**
126
-     * Returns true if the property has a default value.
127
-     *
128
-     * @return bool
129
-     */
130
-    public function hasDefault()
131
-    {
132
-        return false;
133
-    }
134
-
135
-    /**
136
-     * Returns the code that assigns a value to its default value.
137
-     *
138
-     * @return string
139
-     *
140
-     * @throws \TDBMException
141
-     */
142
-    public function assignToDefaultCode()
143
-    {
144
-        throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
145
-    }
146
-
147
-    /**
148
-     * Returns true if the property is the primary key.
149
-     *
150
-     * @return bool
151
-     */
152
-    public function isPrimaryKey()
153
-    {
154
-        $fkColumns = $this->foreignKey->getLocalColumns();
155
-        sort($fkColumns);
156
-
157
-        $pkColumns = $this->table->getPrimaryKeyColumns();
158
-        sort($pkColumns);
159
-
160
-        return $fkColumns == $pkColumns;
161
-    }
162
-
163
-    /**
164
-     * Returns the PHP code for getters and setters.
165
-     *
166
-     * @return string
167
-     */
168
-    public function getGetterSetterCode()
169
-    {
170
-        $tableName = $this->table->getName();
171
-        $getterName = $this->getGetterName();
172
-        $setterName = $this->getSetterName();
173
-        $isNullable = !$this->isCompulsory();
174
-
175
-        $referencedBeanName = $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
176
-
177
-        $str = '    /**
15
+	/**
16
+	 * @var ForeignKeyConstraint
17
+	 */
18
+	private $foreignKey;
19
+
20
+	/**
21
+	 * @var SchemaAnalyzer
22
+	 */
23
+	private $schemaAnalyzer;
24
+	/**
25
+	 * @var NamingStrategyInterface
26
+	 */
27
+	private $namingStrategy;
28
+
29
+	/**
30
+	 * ObjectBeanPropertyDescriptor constructor.
31
+	 * @param Table $table
32
+	 * @param ForeignKeyConstraint $foreignKey
33
+	 * @param SchemaAnalyzer $schemaAnalyzer
34
+	 * @param NamingStrategyInterface $namingStrategy
35
+	 */
36
+	public function __construct(Table $table, ForeignKeyConstraint $foreignKey, SchemaAnalyzer $schemaAnalyzer, NamingStrategyInterface $namingStrategy)
37
+	{
38
+		parent::__construct($table);
39
+		$this->foreignKey = $foreignKey;
40
+		$this->schemaAnalyzer = $schemaAnalyzer;
41
+		$this->namingStrategy = $namingStrategy;
42
+	}
43
+
44
+	/**
45
+	 * Returns the foreignkey the column is part of, if any. null otherwise.
46
+	 *
47
+	 * @return ForeignKeyConstraint|null
48
+	 */
49
+	public function getForeignKey()
50
+	{
51
+		return $this->foreignKey;
52
+	}
53
+
54
+	/**
55
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
56
+	 *
57
+	 * @return null|string
58
+	 */
59
+	public function getClassName()
60
+	{
61
+		return $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
62
+	}
63
+
64
+	/**
65
+	 * Returns the param annotation for this property (useful for constructor).
66
+	 *
67
+	 * @return string
68
+	 */
69
+	public function getParamAnnotation()
70
+	{
71
+		$str = '     * @param %s %s';
72
+
73
+		return sprintf($str, $this->getClassName(), $this->getVariableName());
74
+	}
75
+
76
+	public function getUpperCamelCaseName()
77
+	{
78
+		// First, are there many column or only one?
79
+		// If one column, we name the setter after it. Otherwise, we name the setter after the table name
80
+		if (count($this->foreignKey->getLocalColumns()) > 1) {
81
+			$name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
82
+			if ($this->alternativeName) {
83
+				$camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
84
+
85
+				$name .= 'By'.implode('And', $camelizedColumns);
86
+			}
87
+		} else {
88
+			$column = $this->foreignKey->getLocalColumns()[0];
89
+			// Let's remove any _id or id_.
90
+			if (strpos(strtolower($column), 'id_') === 0) {
91
+				$column = substr($column, 3);
92
+			}
93
+			if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
94
+				$column = substr($column, 0, strlen($column) - 3);
95
+			}
96
+			$name = TDBMDaoGenerator::toCamelCase($column);
97
+			if ($this->alternativeName) {
98
+				$name .= 'Object';
99
+			}
100
+		}
101
+
102
+		return $name;
103
+	}
104
+
105
+	/**
106
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
107
+	 *
108
+	 * @return bool
109
+	 */
110
+	public function isCompulsory()
111
+	{
112
+		// Are all columns nullable?
113
+		$localColumnNames = $this->foreignKey->getLocalColumns();
114
+
115
+		foreach ($localColumnNames as $name) {
116
+			$column = $this->table->getColumn($name);
117
+			if ($column->getNotnull()) {
118
+				return true;
119
+			}
120
+		}
121
+
122
+		return false;
123
+	}
124
+
125
+	/**
126
+	 * Returns true if the property has a default value.
127
+	 *
128
+	 * @return bool
129
+	 */
130
+	public function hasDefault()
131
+	{
132
+		return false;
133
+	}
134
+
135
+	/**
136
+	 * Returns the code that assigns a value to its default value.
137
+	 *
138
+	 * @return string
139
+	 *
140
+	 * @throws \TDBMException
141
+	 */
142
+	public function assignToDefaultCode()
143
+	{
144
+		throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
145
+	}
146
+
147
+	/**
148
+	 * Returns true if the property is the primary key.
149
+	 *
150
+	 * @return bool
151
+	 */
152
+	public function isPrimaryKey()
153
+	{
154
+		$fkColumns = $this->foreignKey->getLocalColumns();
155
+		sort($fkColumns);
156
+
157
+		$pkColumns = $this->table->getPrimaryKeyColumns();
158
+		sort($pkColumns);
159
+
160
+		return $fkColumns == $pkColumns;
161
+	}
162
+
163
+	/**
164
+	 * Returns the PHP code for getters and setters.
165
+	 *
166
+	 * @return string
167
+	 */
168
+	public function getGetterSetterCode()
169
+	{
170
+		$tableName = $this->table->getName();
171
+		$getterName = $this->getGetterName();
172
+		$setterName = $this->getSetterName();
173
+		$isNullable = !$this->isCompulsory();
174
+
175
+		$referencedBeanName = $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
176
+
177
+		$str = '    /**
178 178
      * Returns the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
179 179
      *
180 180
      * @return '.$referencedBeanName.($isNullable?'|null':'').'
@@ -196,20 +196,20 @@  discard block
 block discarded – undo
196 196
 
197 197
 ';
198 198
 
199
-        return $str;
200
-    }
201
-
202
-    /**
203
-     * Returns the part of code useful when doing json serialization.
204
-     *
205
-     * @return string
206
-     */
207
-    public function getJsonSerializeCode()
208
-    {
209
-        return '        if (!$stopRecursion) {
199
+		return $str;
200
+	}
201
+
202
+	/**
203
+	 * Returns the part of code useful when doing json serialization.
204
+	 *
205
+	 * @return string
206
+	 */
207
+	public function getJsonSerializeCode()
208
+	{
209
+		return '        if (!$stopRecursion) {
210 210
             $object = $this->'.$this->getGetterName().'();
211 211
             $array['.var_export($this->getLowerCamelCaseName(), true).'] = $object ? $object->jsonSerialize(true) : null;
212 212
         }
213 213
 ';
214
-    }
214
+	}
215 215
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
     {
78 78
         // First, are there many column or only one?
79 79
         // If one column, we name the setter after it. Otherwise, we name the setter after the table name
80
-        if (count($this->foreignKey->getLocalColumns()) > 1) {
80
+        if (count($this->foreignKey->getLocalColumns())>1) {
81 81
             $name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
82 82
             if ($this->alternativeName) {
83 83
                 $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
@@ -90,8 +90,8 @@  discard block
 block discarded – undo
90 90
             if (strpos(strtolower($column), 'id_') === 0) {
91 91
                 $column = substr($column, 3);
92 92
             }
93
-            if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
94
-                $column = substr($column, 0, strlen($column) - 3);
93
+            if (strrpos(strtolower($column), '_id') === strlen($column)-3) {
94
+                $column = substr($column, 0, strlen($column)-3);
95 95
             }
96 96
             $name = TDBMDaoGenerator::toCamelCase($column);
97 97
             if ($this->alternativeName) {
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
         $str = '    /**
178 178
      * Returns the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
179 179
      *
180
-     * @return '.$referencedBeanName.($isNullable?'|null':'').'
180
+     * @return '.$referencedBeanName.($isNullable ? '|null' : '').'
181 181
      */
182
-    public function '.$getterName.'(): '.($isNullable?'?':'').$referencedBeanName.'
182
+    public function '.$getterName.'(): '.($isNullable ? '?' : '').$referencedBeanName.'
183 183
     {
184 184
         return $this->getRef('.var_export($this->foreignKey->getName(), true).', '.var_export($tableName, true).');
185 185
     }
@@ -187,9 +187,9 @@  discard block
 block discarded – undo
187 187
     /**
188 188
      * The setter for the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
189 189
      *
190
-     * @param '.$referencedBeanName.($isNullable?'|null':'').' $object
190
+     * @param '.$referencedBeanName.($isNullable ? '|null' : '').' $object
191 191
      */
192
-    public function '.$setterName.'('.($isNullable?'?':'').$referencedBeanName.' $object) : void
192
+    public function '.$setterName.'('.($isNullable ? '?' : '').$referencedBeanName.' $object) : void
193 193
     {
194 194
         $this->setRef('.var_export($this->foreignKey->getName(), true).', $object, '.var_export($tableName, true).');
195 195
     }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/BeanDescriptor.php 2 patches
Indentation   +625 added lines, -625 removed lines patch added patch discarded remove patch
@@ -16,241 +16,241 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class BeanDescriptor implements BeanDescriptorInterface
18 18
 {
19
-    /**
20
-     * @var Table
21
-     */
22
-    private $table;
23
-
24
-    /**
25
-     * @var SchemaAnalyzer
26
-     */
27
-    private $schemaAnalyzer;
28
-
29
-    /**
30
-     * @var Schema
31
-     */
32
-    private $schema;
33
-
34
-    /**
35
-     * @var AbstractBeanPropertyDescriptor[]
36
-     */
37
-    private $beanPropertyDescriptors = [];
38
-
39
-    /**
40
-     * @var TDBMSchemaAnalyzer
41
-     */
42
-    private $tdbmSchemaAnalyzer;
43
-
44
-    /**
45
-     * @var NamingStrategyInterface
46
-     */
47
-    private $namingStrategy;
48
-
49
-    /**
50
-     * @param Table $table
51
-     * @param SchemaAnalyzer $schemaAnalyzer
52
-     * @param Schema $schema
53
-     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
54
-     * @param NamingStrategyInterface $namingStrategy
55
-     */
56
-    public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer, NamingStrategyInterface $namingStrategy)
57
-    {
58
-        $this->table = $table;
59
-        $this->schemaAnalyzer = $schemaAnalyzer;
60
-        $this->schema = $schema;
61
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
62
-        $this->namingStrategy = $namingStrategy;
63
-        $this->initBeanPropertyDescriptors();
64
-    }
65
-
66
-    private function initBeanPropertyDescriptors()
67
-    {
68
-        $this->beanPropertyDescriptors = $this->getProperties($this->table);
69
-    }
70
-
71
-    /**
72
-     * Returns the foreign-key the column is part of, if any. null otherwise.
73
-     *
74
-     * @param Table  $table
75
-     * @param Column $column
76
-     *
77
-     * @return ForeignKeyConstraint|null
78
-     */
79
-    private function isPartOfForeignKey(Table $table, Column $column)
80
-    {
81
-        $localColumnName = $column->getName();
82
-        foreach ($table->getForeignKeys() as $foreignKey) {
83
-            foreach ($foreignKey->getColumns() as $columnName) {
84
-                if ($columnName === $localColumnName) {
85
-                    return $foreignKey;
86
-                }
87
-            }
88
-        }
89
-
90
-        return;
91
-    }
92
-
93
-    /**
94
-     * @return AbstractBeanPropertyDescriptor[]
95
-     */
96
-    public function getBeanPropertyDescriptors()
97
-    {
98
-        return $this->beanPropertyDescriptors;
99
-    }
100
-
101
-    /**
102
-     * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
103
-     *
104
-     * @return AbstractBeanPropertyDescriptor[]
105
-     */
106
-    public function getConstructorProperties()
107
-    {
108
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
109
-            return $property->isCompulsory();
110
-        });
111
-
112
-        return $constructorProperties;
113
-    }
114
-
115
-    /**
116
-     * Returns the list of columns that have default values for a given table.
117
-     *
118
-     * @return AbstractBeanPropertyDescriptor[]
119
-     */
120
-    public function getPropertiesWithDefault()
121
-    {
122
-        $properties = $this->getPropertiesForTable($this->table);
123
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
124
-            return $property->hasDefault();
125
-        });
126
-
127
-        return $defaultProperties;
128
-    }
129
-
130
-    /**
131
-     * Returns the list of properties exposed as getters and setters in this class.
132
-     *
133
-     * @return AbstractBeanPropertyDescriptor[]
134
-     */
135
-    public function getExposedProperties(): array
136
-    {
137
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
138
-            return $property->getTable()->getName() == $this->table->getName();
139
-        });
140
-
141
-        return $exposedProperties;
142
-    }
143
-
144
-    /**
145
-     * Returns the list of properties for this table (including parent tables).
146
-     *
147
-     * @param Table $table
148
-     *
149
-     * @return AbstractBeanPropertyDescriptor[]
150
-     */
151
-    private function getProperties(Table $table)
152
-    {
153
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
154
-        if ($parentRelationship) {
155
-            $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
156
-            $properties = $this->getProperties($parentTable);
157
-            // we merge properties by overriding property names.
158
-            $localProperties = $this->getPropertiesForTable($table);
159
-            foreach ($localProperties as $name => $property) {
160
-                // We do not override properties if this is a primary key!
161
-                if ($property->isPrimaryKey()) {
162
-                    continue;
163
-                }
164
-                $properties[$name] = $property;
165
-            }
166
-        } else {
167
-            $properties = $this->getPropertiesForTable($table);
168
-        }
169
-
170
-        return $properties;
171
-    }
172
-
173
-    /**
174
-     * Returns the list of properties for this table (ignoring parent tables).
175
-     *
176
-     * @param Table $table
177
-     *
178
-     * @return AbstractBeanPropertyDescriptor[]
179
-     */
180
-    private function getPropertiesForTable(Table $table)
181
-    {
182
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
183
-        if ($parentRelationship) {
184
-            $ignoreColumns = $parentRelationship->getLocalColumns();
185
-        } else {
186
-            $ignoreColumns = [];
187
-        }
188
-
189
-        $beanPropertyDescriptors = [];
190
-
191
-        foreach ($table->getColumns() as $column) {
192
-            if (array_search($column->getName(), $ignoreColumns) !== false) {
193
-                continue;
194
-            }
195
-
196
-            $fk = $this->isPartOfForeignKey($table, $column);
197
-            if ($fk !== null) {
198
-                // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
199
-                foreach ($beanPropertyDescriptors as $beanDescriptor) {
200
-                    if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
201
-                        continue 2;
202
-                    }
203
-                }
204
-                // Check that this property is not an inheritance relationship
205
-                $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
206
-                if ($parentRelationship === $fk) {
207
-                    continue;
208
-                }
209
-
210
-                $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer, $this->namingStrategy);
211
-            } else {
212
-                $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column, $this->namingStrategy);
213
-            }
214
-        }
215
-
216
-        // Now, let's get the name of all properties and let's check there is no duplicate.
217
-        /** @var $names AbstractBeanPropertyDescriptor[] */
218
-        $names = [];
219
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
220
-            $name = $beanDescriptor->getUpperCamelCaseName();
221
-            if (isset($names[$name])) {
222
-                $names[$name]->useAlternativeName();
223
-                $beanDescriptor->useAlternativeName();
224
-            } else {
225
-                $names[$name] = $beanDescriptor;
226
-            }
227
-        }
228
-
229
-        // Final check (throw exceptions if problem arises)
230
-        $names = [];
231
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
232
-            $name = $beanDescriptor->getUpperCamelCaseName();
233
-            if (isset($names[$name])) {
234
-                throw new TDBMException('Unsolvable name conflict while generating method name');
235
-            } else {
236
-                $names[$name] = $beanDescriptor;
237
-            }
238
-        }
239
-
240
-        // Last step, let's rebuild the list with a map:
241
-        $beanPropertyDescriptorsMap = [];
242
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
243
-            $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
244
-        }
245
-
246
-        return $beanPropertyDescriptorsMap;
247
-    }
248
-
249
-    private function generateBeanConstructor() : string
250
-    {
251
-        $constructorProperties = $this->getConstructorProperties();
252
-
253
-        $constructorCode = '    /**
19
+	/**
20
+	 * @var Table
21
+	 */
22
+	private $table;
23
+
24
+	/**
25
+	 * @var SchemaAnalyzer
26
+	 */
27
+	private $schemaAnalyzer;
28
+
29
+	/**
30
+	 * @var Schema
31
+	 */
32
+	private $schema;
33
+
34
+	/**
35
+	 * @var AbstractBeanPropertyDescriptor[]
36
+	 */
37
+	private $beanPropertyDescriptors = [];
38
+
39
+	/**
40
+	 * @var TDBMSchemaAnalyzer
41
+	 */
42
+	private $tdbmSchemaAnalyzer;
43
+
44
+	/**
45
+	 * @var NamingStrategyInterface
46
+	 */
47
+	private $namingStrategy;
48
+
49
+	/**
50
+	 * @param Table $table
51
+	 * @param SchemaAnalyzer $schemaAnalyzer
52
+	 * @param Schema $schema
53
+	 * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
54
+	 * @param NamingStrategyInterface $namingStrategy
55
+	 */
56
+	public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer, NamingStrategyInterface $namingStrategy)
57
+	{
58
+		$this->table = $table;
59
+		$this->schemaAnalyzer = $schemaAnalyzer;
60
+		$this->schema = $schema;
61
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
62
+		$this->namingStrategy = $namingStrategy;
63
+		$this->initBeanPropertyDescriptors();
64
+	}
65
+
66
+	private function initBeanPropertyDescriptors()
67
+	{
68
+		$this->beanPropertyDescriptors = $this->getProperties($this->table);
69
+	}
70
+
71
+	/**
72
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
73
+	 *
74
+	 * @param Table  $table
75
+	 * @param Column $column
76
+	 *
77
+	 * @return ForeignKeyConstraint|null
78
+	 */
79
+	private function isPartOfForeignKey(Table $table, Column $column)
80
+	{
81
+		$localColumnName = $column->getName();
82
+		foreach ($table->getForeignKeys() as $foreignKey) {
83
+			foreach ($foreignKey->getColumns() as $columnName) {
84
+				if ($columnName === $localColumnName) {
85
+					return $foreignKey;
86
+				}
87
+			}
88
+		}
89
+
90
+		return;
91
+	}
92
+
93
+	/**
94
+	 * @return AbstractBeanPropertyDescriptor[]
95
+	 */
96
+	public function getBeanPropertyDescriptors()
97
+	{
98
+		return $this->beanPropertyDescriptors;
99
+	}
100
+
101
+	/**
102
+	 * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
103
+	 *
104
+	 * @return AbstractBeanPropertyDescriptor[]
105
+	 */
106
+	public function getConstructorProperties()
107
+	{
108
+		$constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
109
+			return $property->isCompulsory();
110
+		});
111
+
112
+		return $constructorProperties;
113
+	}
114
+
115
+	/**
116
+	 * Returns the list of columns that have default values for a given table.
117
+	 *
118
+	 * @return AbstractBeanPropertyDescriptor[]
119
+	 */
120
+	public function getPropertiesWithDefault()
121
+	{
122
+		$properties = $this->getPropertiesForTable($this->table);
123
+		$defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
124
+			return $property->hasDefault();
125
+		});
126
+
127
+		return $defaultProperties;
128
+	}
129
+
130
+	/**
131
+	 * Returns the list of properties exposed as getters and setters in this class.
132
+	 *
133
+	 * @return AbstractBeanPropertyDescriptor[]
134
+	 */
135
+	public function getExposedProperties(): array
136
+	{
137
+		$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
138
+			return $property->getTable()->getName() == $this->table->getName();
139
+		});
140
+
141
+		return $exposedProperties;
142
+	}
143
+
144
+	/**
145
+	 * Returns the list of properties for this table (including parent tables).
146
+	 *
147
+	 * @param Table $table
148
+	 *
149
+	 * @return AbstractBeanPropertyDescriptor[]
150
+	 */
151
+	private function getProperties(Table $table)
152
+	{
153
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
154
+		if ($parentRelationship) {
155
+			$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
156
+			$properties = $this->getProperties($parentTable);
157
+			// we merge properties by overriding property names.
158
+			$localProperties = $this->getPropertiesForTable($table);
159
+			foreach ($localProperties as $name => $property) {
160
+				// We do not override properties if this is a primary key!
161
+				if ($property->isPrimaryKey()) {
162
+					continue;
163
+				}
164
+				$properties[$name] = $property;
165
+			}
166
+		} else {
167
+			$properties = $this->getPropertiesForTable($table);
168
+		}
169
+
170
+		return $properties;
171
+	}
172
+
173
+	/**
174
+	 * Returns the list of properties for this table (ignoring parent tables).
175
+	 *
176
+	 * @param Table $table
177
+	 *
178
+	 * @return AbstractBeanPropertyDescriptor[]
179
+	 */
180
+	private function getPropertiesForTable(Table $table)
181
+	{
182
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
183
+		if ($parentRelationship) {
184
+			$ignoreColumns = $parentRelationship->getLocalColumns();
185
+		} else {
186
+			$ignoreColumns = [];
187
+		}
188
+
189
+		$beanPropertyDescriptors = [];
190
+
191
+		foreach ($table->getColumns() as $column) {
192
+			if (array_search($column->getName(), $ignoreColumns) !== false) {
193
+				continue;
194
+			}
195
+
196
+			$fk = $this->isPartOfForeignKey($table, $column);
197
+			if ($fk !== null) {
198
+				// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
199
+				foreach ($beanPropertyDescriptors as $beanDescriptor) {
200
+					if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
201
+						continue 2;
202
+					}
203
+				}
204
+				// Check that this property is not an inheritance relationship
205
+				$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
206
+				if ($parentRelationship === $fk) {
207
+					continue;
208
+				}
209
+
210
+				$beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer, $this->namingStrategy);
211
+			} else {
212
+				$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column, $this->namingStrategy);
213
+			}
214
+		}
215
+
216
+		// Now, let's get the name of all properties and let's check there is no duplicate.
217
+		/** @var $names AbstractBeanPropertyDescriptor[] */
218
+		$names = [];
219
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
220
+			$name = $beanDescriptor->getUpperCamelCaseName();
221
+			if (isset($names[$name])) {
222
+				$names[$name]->useAlternativeName();
223
+				$beanDescriptor->useAlternativeName();
224
+			} else {
225
+				$names[$name] = $beanDescriptor;
226
+			}
227
+		}
228
+
229
+		// Final check (throw exceptions if problem arises)
230
+		$names = [];
231
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
232
+			$name = $beanDescriptor->getUpperCamelCaseName();
233
+			if (isset($names[$name])) {
234
+				throw new TDBMException('Unsolvable name conflict while generating method name');
235
+			} else {
236
+				$names[$name] = $beanDescriptor;
237
+			}
238
+		}
239
+
240
+		// Last step, let's rebuild the list with a map:
241
+		$beanPropertyDescriptorsMap = [];
242
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
243
+			$beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
244
+		}
245
+
246
+		return $beanPropertyDescriptorsMap;
247
+	}
248
+
249
+	private function generateBeanConstructor() : string
250
+	{
251
+		$constructorProperties = $this->getConstructorProperties();
252
+
253
+		$constructorCode = '    /**
254 254
      * The constructor takes all compulsory arguments.
255 255
      *
256 256
 %s
@@ -260,110 +260,110 @@  discard block
 block discarded – undo
260 260
 %s%s    }
261 261
     ';
262 262
 
263
-        $paramAnnotations = [];
264
-        $arguments = [];
265
-        $assigns = [];
266
-        $parentConstructorArguments = [];
267
-
268
-        foreach ($constructorProperties as $property) {
269
-            $className = $property->getClassName();
270
-            if ($className) {
271
-                $arguments[] = $className.' '.$property->getVariableName();
272
-            } else {
273
-                $arguments[] = $property->getVariableName();
274
-            }
275
-            $paramAnnotations[] = $property->getParamAnnotation();
276
-            if ($property->getTable()->getName() === $this->table->getName()) {
277
-                $assigns[] = $property->getConstructorAssignCode()."\n";
278
-            } else {
279
-                $parentConstructorArguments[] = $property->getVariableName();
280
-            }
281
-        }
282
-
283
-        $parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
284
-
285
-        foreach ($this->getPropertiesWithDefault() as $property) {
286
-            $assigns[] = $property->assignToDefaultCode()."\n";
287
-        }
288
-
289
-        return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode('', $assigns));
290
-    }
291
-
292
-    public function getDirectForeignKeysDescriptors(): array
293
-    {
294
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
295
-
296
-        $descriptors = [];
297
-
298
-        foreach ($fks as $fk) {
299
-            $descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table, $this->namingStrategy);
300
-        }
301
-
302
-        return $descriptors;
303
-    }
304
-
305
-    private function getPivotTableDescriptors(): array
306
-    {
307
-        $descs = [];
308
-        foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
309
-            // There are exactly 2 FKs since this is a pivot table.
310
-            $fks = array_values($table->getForeignKeys());
311
-
312
-            if ($fks[0]->getForeignTableName() === $this->table->getName()) {
313
-                list($localFk, $remoteFk) = $fks;
314
-            } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
315
-                list($remoteFk, $localFk) = $fks;
316
-            } else {
317
-                continue;
318
-            }
319
-
320
-            $descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk, $this->namingStrategy);
321
-        }
322
-
323
-        return $descs;
324
-    }
325
-
326
-    /**
327
-     * Returns the list of method descriptors (and applies the alternative name if needed).
328
-     *
329
-     * @return MethodDescriptorInterface[]
330
-     */
331
-    private function getMethodDescriptors(): array
332
-    {
333
-        $directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
334
-        $pivotTableDescriptors = $this->getPivotTableDescriptors();
335
-
336
-        $descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
337
-
338
-        // Descriptors by method names
339
-        $descriptorsByMethodName = [];
340
-
341
-        foreach ($descriptors as $descriptor) {
342
-            $descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
343
-        }
344
-
345
-        foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
346
-            if (count($descriptorsForMethodName) > 1) {
347
-                foreach ($descriptorsForMethodName as $descriptor) {
348
-                    $descriptor->useAlternativeName();
349
-                }
350
-            }
351
-        }
352
-
353
-        return $descriptors;
354
-    }
355
-
356
-    public function generateJsonSerialize(): string
357
-    {
358
-        $tableName = $this->table->getName();
359
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
360
-        if ($parentFk !== null) {
361
-            $initializer = '$array = parent::jsonSerialize($stopRecursion);';
362
-        } else {
363
-            $initializer = '$array = [];';
364
-        }
365
-
366
-        $str = '
263
+		$paramAnnotations = [];
264
+		$arguments = [];
265
+		$assigns = [];
266
+		$parentConstructorArguments = [];
267
+
268
+		foreach ($constructorProperties as $property) {
269
+			$className = $property->getClassName();
270
+			if ($className) {
271
+				$arguments[] = $className.' '.$property->getVariableName();
272
+			} else {
273
+				$arguments[] = $property->getVariableName();
274
+			}
275
+			$paramAnnotations[] = $property->getParamAnnotation();
276
+			if ($property->getTable()->getName() === $this->table->getName()) {
277
+				$assigns[] = $property->getConstructorAssignCode()."\n";
278
+			} else {
279
+				$parentConstructorArguments[] = $property->getVariableName();
280
+			}
281
+		}
282
+
283
+		$parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
284
+
285
+		foreach ($this->getPropertiesWithDefault() as $property) {
286
+			$assigns[] = $property->assignToDefaultCode()."\n";
287
+		}
288
+
289
+		return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode('', $assigns));
290
+	}
291
+
292
+	public function getDirectForeignKeysDescriptors(): array
293
+	{
294
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
295
+
296
+		$descriptors = [];
297
+
298
+		foreach ($fks as $fk) {
299
+			$descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table, $this->namingStrategy);
300
+		}
301
+
302
+		return $descriptors;
303
+	}
304
+
305
+	private function getPivotTableDescriptors(): array
306
+	{
307
+		$descs = [];
308
+		foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
309
+			// There are exactly 2 FKs since this is a pivot table.
310
+			$fks = array_values($table->getForeignKeys());
311
+
312
+			if ($fks[0]->getForeignTableName() === $this->table->getName()) {
313
+				list($localFk, $remoteFk) = $fks;
314
+			} elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
315
+				list($remoteFk, $localFk) = $fks;
316
+			} else {
317
+				continue;
318
+			}
319
+
320
+			$descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk, $this->namingStrategy);
321
+		}
322
+
323
+		return $descs;
324
+	}
325
+
326
+	/**
327
+	 * Returns the list of method descriptors (and applies the alternative name if needed).
328
+	 *
329
+	 * @return MethodDescriptorInterface[]
330
+	 */
331
+	private function getMethodDescriptors(): array
332
+	{
333
+		$directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
334
+		$pivotTableDescriptors = $this->getPivotTableDescriptors();
335
+
336
+		$descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
337
+
338
+		// Descriptors by method names
339
+		$descriptorsByMethodName = [];
340
+
341
+		foreach ($descriptors as $descriptor) {
342
+			$descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
343
+		}
344
+
345
+		foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
346
+			if (count($descriptorsForMethodName) > 1) {
347
+				foreach ($descriptorsForMethodName as $descriptor) {
348
+					$descriptor->useAlternativeName();
349
+				}
350
+			}
351
+		}
352
+
353
+		return $descriptors;
354
+	}
355
+
356
+	public function generateJsonSerialize(): string
357
+	{
358
+		$tableName = $this->table->getName();
359
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
360
+		if ($parentFk !== null) {
361
+			$initializer = '$array = parent::jsonSerialize($stopRecursion);';
362
+		} else {
363
+			$initializer = '$array = [];';
364
+		}
365
+
366
+		$str = '
367 367
     /**
368 368
      * Serializes the object for JSON encoding.
369 369
      *
@@ -379,77 +379,77 @@  discard block
 block discarded – undo
379 379
     }
380 380
 ';
381 381
 
382
-        $propertiesCode = '';
383
-        foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
384
-            $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
385
-        }
386
-
387
-        // Many2many relationships
388
-        $methodsCode = '';
389
-        foreach ($this->getMethodDescriptors() as $methodDescriptor) {
390
-            $methodsCode .= $methodDescriptor->getJsonSerializeCode();
391
-        }
392
-
393
-        return sprintf($str, $initializer, $propertiesCode, $methodsCode);
394
-    }
395
-
396
-    /**
397
-     * Returns as an array the class we need to extend from and the list of use statements.
398
-     *
399
-     * @param ForeignKeyConstraint|null $parentFk
400
-     * @return array
401
-     */
402
-    private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null): array
403
-    {
404
-        $classes = [];
405
-        if ($parentFk !== null) {
406
-            $extends = $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
407
-            $classes[] = $extends;
408
-        }
409
-
410
-        foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
411
-            $className = $beanPropertyDescriptor->getClassName();
412
-            if (null !== $className) {
413
-                $classes[] = $beanPropertyDescriptor->getClassName();
414
-            }
415
-        }
416
-
417
-        foreach ($this->getMethodDescriptors() as $descriptor) {
418
-            $classes = array_merge($classes, $descriptor->getUsedClasses());
419
-        }
420
-
421
-        $classes = array_unique($classes);
422
-
423
-        return $classes;
424
-    }
425
-
426
-    /**
427
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
428
-     *
429
-     * @param string $beannamespace The namespace of the bean
430
-     * @return string
431
-     */
432
-    public function generatePhpCode($beannamespace): string
433
-    {
434
-        $tableName = $this->table->getName();
435
-        $baseClassName = $this->namingStrategy->getBaseBeanClassName($tableName);
436
-        $className = $this->namingStrategy->getBeanClassName($tableName);
437
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
438
-
439
-        $classes = $this->generateExtendsAndUseStatements($parentFk);
440
-
441
-        $uses = array_map(function ($className) use ($beannamespace) {
442
-            return 'use '.$beannamespace.'\\'.$className.";\n";
443
-        }, $classes);
444
-        $use = implode('', $uses);
445
-
446
-        $extends = $this->getExtendedBeanClassName();
447
-        if ($extends === null) {
448
-            $extends = 'AbstractTDBMObject';
449
-            $use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
450
-        }
451
-
452
-        $str = "<?php
382
+		$propertiesCode = '';
383
+		foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
384
+			$propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
385
+		}
386
+
387
+		// Many2many relationships
388
+		$methodsCode = '';
389
+		foreach ($this->getMethodDescriptors() as $methodDescriptor) {
390
+			$methodsCode .= $methodDescriptor->getJsonSerializeCode();
391
+		}
392
+
393
+		return sprintf($str, $initializer, $propertiesCode, $methodsCode);
394
+	}
395
+
396
+	/**
397
+	 * Returns as an array the class we need to extend from and the list of use statements.
398
+	 *
399
+	 * @param ForeignKeyConstraint|null $parentFk
400
+	 * @return array
401
+	 */
402
+	private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null): array
403
+	{
404
+		$classes = [];
405
+		if ($parentFk !== null) {
406
+			$extends = $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
407
+			$classes[] = $extends;
408
+		}
409
+
410
+		foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
411
+			$className = $beanPropertyDescriptor->getClassName();
412
+			if (null !== $className) {
413
+				$classes[] = $beanPropertyDescriptor->getClassName();
414
+			}
415
+		}
416
+
417
+		foreach ($this->getMethodDescriptors() as $descriptor) {
418
+			$classes = array_merge($classes, $descriptor->getUsedClasses());
419
+		}
420
+
421
+		$classes = array_unique($classes);
422
+
423
+		return $classes;
424
+	}
425
+
426
+	/**
427
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
428
+	 *
429
+	 * @param string $beannamespace The namespace of the bean
430
+	 * @return string
431
+	 */
432
+	public function generatePhpCode($beannamespace): string
433
+	{
434
+		$tableName = $this->table->getName();
435
+		$baseClassName = $this->namingStrategy->getBaseBeanClassName($tableName);
436
+		$className = $this->namingStrategy->getBeanClassName($tableName);
437
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
438
+
439
+		$classes = $this->generateExtendsAndUseStatements($parentFk);
440
+
441
+		$uses = array_map(function ($className) use ($beannamespace) {
442
+			return 'use '.$beannamespace.'\\'.$className.";\n";
443
+		}, $classes);
444
+		$use = implode('', $uses);
445
+
446
+		$extends = $this->getExtendedBeanClassName();
447
+		if ($extends === null) {
448
+			$extends = 'AbstractTDBMObject';
449
+			$use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
450
+		}
451
+
452
+		$str = "<?php
453 453
 namespace {$beannamespace}\\Generated;
454 454
 
455 455
 use Mouf\\Database\\TDBM\\ResultIterator;
@@ -469,125 +469,125 @@  discard block
 block discarded – undo
469 469
 {
470 470
 ";
471 471
 
472
-        $str .= $this->generateBeanConstructor();
472
+		$str .= $this->generateBeanConstructor();
473 473
 
474
-        foreach ($this->getExposedProperties() as $property) {
475
-            $str .= $property->getGetterSetterCode();
476
-        }
474
+		foreach ($this->getExposedProperties() as $property) {
475
+			$str .= $property->getGetterSetterCode();
476
+		}
477 477
 
478
-        foreach ($this->getMethodDescriptors() as $methodDescriptor) {
479
-            $str .= $methodDescriptor->getCode();
480
-        }
481
-        $str .= $this->generateJsonSerialize();
478
+		foreach ($this->getMethodDescriptors() as $methodDescriptor) {
479
+			$str .= $methodDescriptor->getCode();
480
+		}
481
+		$str .= $this->generateJsonSerialize();
482 482
 
483
-        $str .= $this->generateGetUsedTablesCode();
483
+		$str .= $this->generateGetUsedTablesCode();
484 484
 
485
-        $str .= $this->generateOnDeleteCode();
485
+		$str .= $this->generateOnDeleteCode();
486 486
 
487
-        $str .= '}
487
+		$str .= '}
488 488
 ';
489 489
 
490
-        return $str;
491
-    }
492
-
493
-    /**
494
-     * @param string $beanNamespace
495
-     * @param string $beanClassName
496
-     *
497
-     * @return array first element: list of used beans, second item: PHP code as a string
498
-     */
499
-    public function generateFindByDaoCode($beanNamespace, $beanClassName)
500
-    {
501
-        $code = '';
502
-        $usedBeans = [];
503
-        foreach ($this->table->getIndexes() as $index) {
504
-            if (!$index->isPrimary()) {
505
-                list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
506
-                $code .= $codeForIndex;
507
-                $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
508
-            }
509
-        }
510
-
511
-        return [$usedBeans, $code];
512
-    }
513
-
514
-    /**
515
-     * @param Index  $index
516
-     * @param string $beanNamespace
517
-     * @param string $beanClassName
518
-     *
519
-     * @return array first element: list of used beans, second item: PHP code as a string
520
-     */
521
-    private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
522
-    {
523
-        $columns = $index->getColumns();
524
-        $usedBeans = [];
525
-
526
-        /*
490
+		return $str;
491
+	}
492
+
493
+	/**
494
+	 * @param string $beanNamespace
495
+	 * @param string $beanClassName
496
+	 *
497
+	 * @return array first element: list of used beans, second item: PHP code as a string
498
+	 */
499
+	public function generateFindByDaoCode($beanNamespace, $beanClassName)
500
+	{
501
+		$code = '';
502
+		$usedBeans = [];
503
+		foreach ($this->table->getIndexes() as $index) {
504
+			if (!$index->isPrimary()) {
505
+				list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
506
+				$code .= $codeForIndex;
507
+				$usedBeans = array_merge($usedBeans, $usedBeansForIndex);
508
+			}
509
+		}
510
+
511
+		return [$usedBeans, $code];
512
+	}
513
+
514
+	/**
515
+	 * @param Index  $index
516
+	 * @param string $beanNamespace
517
+	 * @param string $beanClassName
518
+	 *
519
+	 * @return array first element: list of used beans, second item: PHP code as a string
520
+	 */
521
+	private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
522
+	{
523
+		$columns = $index->getColumns();
524
+		$usedBeans = [];
525
+
526
+		/*
527 527
          * The list of elements building this index (expressed as columns or foreign keys)
528 528
          * @var AbstractBeanPropertyDescriptor[]
529 529
          */
530
-        $elements = [];
531
-
532
-        foreach ($columns as $column) {
533
-            $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
534
-            if ($fk !== null) {
535
-                if (!in_array($fk, $elements)) {
536
-                    $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer, $this->namingStrategy);
537
-                }
538
-            } else {
539
-                $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column), $this->namingStrategy);
540
-            }
541
-        }
542
-
543
-        // If the index is actually only a foreign key, let's bypass it entirely.
544
-        if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
545
-            return [[], ''];
546
-        }
547
-
548
-        $methodNameComponent = [];
549
-        $functionParameters = [];
550
-        $first = true;
551
-        foreach ($elements as $element) {
552
-            $methodNameComponent[] = $element->getUpperCamelCaseName();
553
-            $functionParameter = $element->getClassName();
554
-            if ($functionParameter) {
555
-                $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
556
-                $functionParameter .= ' ';
557
-            }
558
-            $functionParameter .= $element->getVariableName();
559
-            if ($first) {
560
-                $first = false;
561
-            } else {
562
-                $functionParameter .= ' = null';
563
-            }
564
-            $functionParameters[] = $functionParameter;
565
-        }
566
-
567
-        $functionParametersString = implode(', ', $functionParameters);
568
-
569
-        $count = 0;
570
-
571
-        $params = [];
572
-        $filterArrayCode = '';
573
-        $commentArguments = [];
574
-        foreach ($elements as $element) {
575
-            $params[] = $element->getParamAnnotation();
576
-            if ($element instanceof ScalarBeanPropertyDescriptor) {
577
-                $filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
578
-            } else {
579
-                ++$count;
580
-                $filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
581
-            }
582
-            $commentArguments[] = substr($element->getVariableName(), 1);
583
-        }
584
-        $paramsString = implode("\n", $params);
585
-
586
-        if ($index->isUnique()) {
587
-            $methodName = 'findOneBy'.implode('And', $methodNameComponent);
588
-            $returnType = "{$beanClassName}";
589
-
590
-            $code = "
530
+		$elements = [];
531
+
532
+		foreach ($columns as $column) {
533
+			$fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
534
+			if ($fk !== null) {
535
+				if (!in_array($fk, $elements)) {
536
+					$elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer, $this->namingStrategy);
537
+				}
538
+			} else {
539
+				$elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column), $this->namingStrategy);
540
+			}
541
+		}
542
+
543
+		// If the index is actually only a foreign key, let's bypass it entirely.
544
+		if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
545
+			return [[], ''];
546
+		}
547
+
548
+		$methodNameComponent = [];
549
+		$functionParameters = [];
550
+		$first = true;
551
+		foreach ($elements as $element) {
552
+			$methodNameComponent[] = $element->getUpperCamelCaseName();
553
+			$functionParameter = $element->getClassName();
554
+			if ($functionParameter) {
555
+				$usedBeans[] = $beanNamespace.'\\'.$functionParameter;
556
+				$functionParameter .= ' ';
557
+			}
558
+			$functionParameter .= $element->getVariableName();
559
+			if ($first) {
560
+				$first = false;
561
+			} else {
562
+				$functionParameter .= ' = null';
563
+			}
564
+			$functionParameters[] = $functionParameter;
565
+		}
566
+
567
+		$functionParametersString = implode(', ', $functionParameters);
568
+
569
+		$count = 0;
570
+
571
+		$params = [];
572
+		$filterArrayCode = '';
573
+		$commentArguments = [];
574
+		foreach ($elements as $element) {
575
+			$params[] = $element->getParamAnnotation();
576
+			if ($element instanceof ScalarBeanPropertyDescriptor) {
577
+				$filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
578
+			} else {
579
+				++$count;
580
+				$filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
581
+			}
582
+			$commentArguments[] = substr($element->getVariableName(), 1);
583
+		}
584
+		$paramsString = implode("\n", $params);
585
+
586
+		if ($index->isUnique()) {
587
+			$methodName = 'findOneBy'.implode('And', $methodNameComponent);
588
+			$returnType = "{$beanClassName}";
589
+
590
+			$code = "
591 591
     /**
592 592
      * Get a $beanClassName filtered by ".implode(', ', $commentArguments).".
593 593
      *
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
         return \$this->findOne(\$filter, [], \$additionalTablesFetch);
603 603
     }
604 604
 ";
605
-        } else {
606
-            $methodName = 'findBy'.implode('And', $methodNameComponent);
607
-            $returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
605
+		} else {
606
+			$methodName = 'findBy'.implode('And', $methodNameComponent);
607
+			$returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
608 608
 
609
-            $code = "
609
+			$code = "
610 610
     /**
611 611
      * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
612 612
      *
@@ -623,29 +623,29 @@  discard block
 block discarded – undo
623 623
         return \$this->find(\$filter, [], \$orderBy, \$additionalTablesFetch, \$mode);
624 624
     }
625 625
 ";
626
-        }
627
-
628
-        return [$usedBeans, $code];
629
-    }
630
-
631
-    /**
632
-     * Generates the code for the getUsedTable protected method.
633
-     *
634
-     * @return string
635
-     */
636
-    private function generateGetUsedTablesCode()
637
-    {
638
-        $hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
639
-        if ($hasParentRelationship) {
640
-            $code = sprintf('        $tables = parent::getUsedTables();
626
+		}
627
+
628
+		return [$usedBeans, $code];
629
+	}
630
+
631
+	/**
632
+	 * Generates the code for the getUsedTable protected method.
633
+	 *
634
+	 * @return string
635
+	 */
636
+	private function generateGetUsedTablesCode()
637
+	{
638
+		$hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
639
+		if ($hasParentRelationship) {
640
+			$code = sprintf('        $tables = parent::getUsedTables();
641 641
         $tables[] = %s;
642 642
 
643 643
         return $tables;', var_export($this->table->getName(), true));
644
-        } else {
645
-            $code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
646
-        }
644
+		} else {
645
+			$code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
646
+		}
647 647
 
648
-        return sprintf('
648
+		return sprintf('
649 649
     /**
650 650
      * Returns an array of used tables by this bean (from parent to child relationship).
651 651
      *
@@ -656,20 +656,20 @@  discard block
 block discarded – undo
656 656
 %s
657 657
     }
658 658
 ', $code);
659
-    }
660
-
661
-    private function generateOnDeleteCode()
662
-    {
663
-        $code = '';
664
-        $relationships = $this->getPropertiesForTable($this->table);
665
-        foreach ($relationships as $relationship) {
666
-            if ($relationship instanceof ObjectBeanPropertyDescriptor) {
667
-                $code .= sprintf('        $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
668
-            }
669
-        }
670
-
671
-        if ($code) {
672
-            return sprintf('
659
+	}
660
+
661
+	private function generateOnDeleteCode()
662
+	{
663
+		$code = '';
664
+		$relationships = $this->getPropertiesForTable($this->table);
665
+		foreach ($relationships as $relationship) {
666
+			if ($relationship instanceof ObjectBeanPropertyDescriptor) {
667
+				$code .= sprintf('        $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
668
+			}
669
+		}
670
+
671
+		if ($code) {
672
+			return sprintf('
673 673
     /**
674 674
      * Method called when the bean is removed from database.
675 675
      *
@@ -679,73 +679,73 @@  discard block
 block discarded – undo
679 679
         parent::onDelete();
680 680
 %s    }
681 681
 ', $code);
682
-        }
683
-
684
-        return '';
685
-    }
686
-
687
-    /**
688
-     * Returns the bean class name (without the namespace).
689
-     *
690
-     * @return string
691
-     */
692
-    public function getBeanClassName() : string
693
-    {
694
-        return $this->namingStrategy->getBeanClassName($this->table->getName());
695
-    }
696
-
697
-    /**
698
-     * Returns the base bean class name (without the namespace).
699
-     *
700
-     * @return string
701
-     */
702
-    public function getBaseBeanClassName() : string
703
-    {
704
-        return $this->namingStrategy->getBaseBeanClassName($this->table->getName());
705
-    }
706
-
707
-    /**
708
-     * Returns the DAO class name (without the namespace).
709
-     *
710
-     * @return string
711
-     */
712
-    public function getDaoClassName() : string
713
-    {
714
-        return $this->namingStrategy->getDaoClassName($this->table->getName());
715
-    }
716
-
717
-    /**
718
-     * Returns the base DAO class name (without the namespace).
719
-     *
720
-     * @return string
721
-     */
722
-    public function getBaseDaoClassName() : string
723
-    {
724
-        return $this->namingStrategy->getBaseDaoClassName($this->table->getName());
725
-    }
726
-
727
-    /**
728
-     * Returns the table used to build this bean.
729
-     *
730
-     * @return Table
731
-     */
732
-    public function getTable(): Table
733
-    {
734
-        return $this->table;
735
-    }
736
-
737
-    /**
738
-     * Returns the extended bean class name (without the namespace), or null if the bean is not extended.
739
-     *
740
-     * @return string
741
-     */
742
-    public function getExtendedBeanClassName(): ?string
743
-    {
744
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
745
-        if ($parentFk !== null) {
746
-            return $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
747
-        } else {
748
-            return null;
749
-        }
750
-    }
682
+		}
683
+
684
+		return '';
685
+	}
686
+
687
+	/**
688
+	 * Returns the bean class name (without the namespace).
689
+	 *
690
+	 * @return string
691
+	 */
692
+	public function getBeanClassName() : string
693
+	{
694
+		return $this->namingStrategy->getBeanClassName($this->table->getName());
695
+	}
696
+
697
+	/**
698
+	 * Returns the base bean class name (without the namespace).
699
+	 *
700
+	 * @return string
701
+	 */
702
+	public function getBaseBeanClassName() : string
703
+	{
704
+		return $this->namingStrategy->getBaseBeanClassName($this->table->getName());
705
+	}
706
+
707
+	/**
708
+	 * Returns the DAO class name (without the namespace).
709
+	 *
710
+	 * @return string
711
+	 */
712
+	public function getDaoClassName() : string
713
+	{
714
+		return $this->namingStrategy->getDaoClassName($this->table->getName());
715
+	}
716
+
717
+	/**
718
+	 * Returns the base DAO class name (without the namespace).
719
+	 *
720
+	 * @return string
721
+	 */
722
+	public function getBaseDaoClassName() : string
723
+	{
724
+		return $this->namingStrategy->getBaseDaoClassName($this->table->getName());
725
+	}
726
+
727
+	/**
728
+	 * Returns the table used to build this bean.
729
+	 *
730
+	 * @return Table
731
+	 */
732
+	public function getTable(): Table
733
+	{
734
+		return $this->table;
735
+	}
736
+
737
+	/**
738
+	 * Returns the extended bean class name (without the namespace), or null if the bean is not extended.
739
+	 *
740
+	 * @return string
741
+	 */
742
+	public function getExtendedBeanClassName(): ?string
743
+	{
744
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
745
+		if ($parentFk !== null) {
746
+			return $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
747
+		} else {
748
+			return null;
749
+		}
750
+	}
751 751
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
      */
106 106
     public function getConstructorProperties()
107 107
     {
108
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
108
+        $constructorProperties = array_filter($this->beanPropertyDescriptors, function(AbstractBeanPropertyDescriptor $property) {
109 109
             return $property->isCompulsory();
110 110
         });
111 111
 
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
     public function getPropertiesWithDefault()
121 121
     {
122 122
         $properties = $this->getPropertiesForTable($this->table);
123
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
123
+        $defaultProperties = array_filter($properties, function(AbstractBeanPropertyDescriptor $property) {
124 124
             return $property->hasDefault();
125 125
         });
126 126
 
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
      */
135 135
     public function getExposedProperties(): array
136 136
     {
137
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
137
+        $exposedProperties = array_filter($this->beanPropertyDescriptors, function(AbstractBeanPropertyDescriptor $property) {
138 138
             return $property->getTable()->getName() == $this->table->getName();
139 139
         });
140 140
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
         }
344 344
 
345 345
         foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
346
-            if (count($descriptorsForMethodName) > 1) {
346
+            if (count($descriptorsForMethodName)>1) {
347 347
                 foreach ($descriptorsForMethodName as $descriptor) {
348 348
                     $descriptor->useAlternativeName();
349 349
                 }
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 
439 439
         $classes = $this->generateExtendsAndUseStatements($parentFk);
440 440
 
441
-        $uses = array_map(function ($className) use ($beannamespace) {
441
+        $uses = array_map(function($className) use ($beannamespace) {
442 442
             return 'use '.$beannamespace.'\\'.$className.";\n";
443 443
         }, $classes);
444 444
         $use = implode('', $uses);
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
      *
740 740
      * @return string
741 741
      */
742
-    public function getExtendedBeanClassName(): ?string
742
+    public function getExtendedBeanClassName(): ? string
743 743
     {
744 744
         $parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
745 745
         if ($parentFk !== null) {
Please login to merge, or discard this patch.