Completed
Push — 4.1 ( 0565a2...a83f91 )
by David
57s
created
src/Mouf/Database/TDBM/AbstractTDBMObject.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
      */
187 187
     private function checkTableName($tableName = null) {
188 188
         if ($tableName === null) {
189
-            if (count($this->dbRows) > 1) {
189
+            if (count($this->dbRows)>1) {
190 190
                 throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
191 191
             } elseif (count($this->dbRows) === 1) {
192 192
                 $tableName = array_keys($this->dbRows)[0];
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
     protected function set($var, $value, $tableName = null)
214 214
     {
215 215
         if ($tableName === null) {
216
-            if (count($this->dbRows) > 1) {
216
+            if (count($this->dbRows)>1) {
217 217
                 throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
218 218
             } elseif (count($this->dbRows) === 1) {
219 219
                 $tableName = array_keys($this->dbRows)[0];
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
     protected function setRef($foreignKeyName, AbstractTDBMObject $bean, $tableName = null)
240 240
     {
241 241
         if ($tableName === null) {
242
-            if (count($this->dbRows) > 1) {
242
+            if (count($this->dbRows)>1) {
243 243
                 throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
244 244
             } elseif (count($this->dbRows) === 1) {
245 245
                 $tableName = array_keys($this->dbRows)[0];
Please login to merge, or discard this patch.
Indentation   +595 added lines, -595 removed lines patch added patch discarded remove patch
@@ -31,604 +31,604 @@
 block discarded – undo
31 31
  */
32 32
 abstract class AbstractTDBMObject implements JsonSerializable
33 33
 {
34
-    /**
35
-     * The service this object is bound to.
36
-     *
37
-     * @var TDBMService
38
-     */
39
-    protected $tdbmService;
40
-
41
-    /**
42
-     * An array of DbRow, indexed by table name.
43
-     *
44
-     * @var DbRow[]
45
-     */
46
-    protected $dbRows = array();
47
-
48
-    /**
49
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
50
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
51
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
52
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
53
-     *
54
-     * @var string
55
-     */
56
-    private $status;
57
-
58
-    /**
59
-     * Array storing beans related via many to many relationships (pivot tables).
60
-     *
61
-     * @var \SplObjectStorage[] Key: pivot table name, value: SplObjectStorage
62
-     */
63
-    private $relationships = [];
64
-
65
-    /**
66
-     * @var bool[] Key: pivot table name, value: whether a query was performed to load the data
67
-     */
68
-    private $loadedRelationships = [];
69
-
70
-    /**
71
-     * Array storing beans related via many to one relationships (this bean is pointed by external beans).
72
-     *
73
-     * @var AlterableResultIterator[] Key: [external_table]___[external_column], value: SplObjectStorage
74
-     */
75
-    private $manyToOneRelationships = [];
76
-
77
-    /**
78
-     * Used with $primaryKeys when we want to retrieve an existing object
79
-     * and $primaryKeys=[] if we want a new object.
80
-     *
81
-     * @param string      $tableName
82
-     * @param array       $primaryKeys
83
-     * @param TDBMService $tdbmService
84
-     *
85
-     * @throws TDBMException
86
-     * @throws TDBMInvalidOperationException
87
-     */
88
-    public function __construct($tableName = null, array $primaryKeys = array(), TDBMService $tdbmService = null)
89
-    {
90
-        // FIXME: lazy loading should be forbidden on tables with inheritance and dynamic type assignation...
91
-        if (!empty($tableName)) {
92
-            $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
93
-        }
94
-
95
-        if ($tdbmService === null) {
96
-            $this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
97
-        } else {
98
-            $this->_attach($tdbmService);
99
-            if (!empty($primaryKeys)) {
100
-                $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
101
-            } else {
102
-                $this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
103
-            }
104
-        }
105
-    }
106
-
107
-    /**
108
-     * Alternative constructor called when data is fetched from database via a SELECT.
109
-     *
110
-     * @param array       $beanData    array<table, array<column, value>>
111
-     * @param TDBMService $tdbmService
112
-     */
113
-    public function _constructFromData(array $beanData, TDBMService $tdbmService)
114
-    {
115
-        $this->tdbmService = $tdbmService;
116
-
117
-        foreach ($beanData as $table => $columns) {
118
-            $this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
119
-        }
120
-
121
-        $this->status = TDBMObjectStateEnum::STATE_LOADED;
122
-    }
123
-
124
-    /**
125
-     * Alternative constructor called when bean is lazily loaded.
126
-     *
127
-     * @param string      $tableName
128
-     * @param array       $primaryKeys
129
-     * @param TDBMService $tdbmService
130
-     */
131
-    public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
132
-    {
133
-        $this->tdbmService = $tdbmService;
134
-
135
-        $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
136
-
137
-        $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
138
-    }
139
-
140
-    public function _attach(TDBMService $tdbmService)
141
-    {
142
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
143
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
144
-        }
145
-        $this->tdbmService = $tdbmService;
146
-
147
-        // If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
148
-        $tableNames = $this->getUsedTables();
149
-
150
-        $newDbRows = [];
151
-
152
-        foreach ($tableNames as $table) {
153
-            if (!isset($this->dbRows[$table])) {
154
-                $this->registerTable($table);
155
-            }
156
-            $newDbRows[$table] = $this->dbRows[$table];
157
-        }
158
-        $this->dbRows = $newDbRows;
159
-
160
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
161
-        foreach ($this->dbRows as $dbRow) {
162
-            $dbRow->_attach($tdbmService);
163
-        }
164
-    }
165
-
166
-    /**
167
-     * Sets the state of the TDBM Object
168
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
169
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
170
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
171
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
172
-     *
173
-     * @param string $state
174
-     */
175
-    public function _setStatus($state)
176
-    {
177
-        $this->status = $state;
178
-
179
-        // TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
180
-        foreach ($this->dbRows as $dbRow) {
181
-            $dbRow->_setStatus($state);
182
-        }
183
-    }
184
-
185
-    /**
186
-     * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
187
-     * or throws an error.
188
-     *
189
-     * @param string $tableName
190
-     *
191
-     * @return string
192
-     */
193
-    private function checkTableName($tableName = null)
194
-    {
195
-        if ($tableName === null) {
196
-            if (count($this->dbRows) > 1) {
197
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
198
-            } elseif (count($this->dbRows) === 1) {
199
-                $tableName = array_keys($this->dbRows)[0];
200
-            }
201
-        }
202
-
203
-        if (!isset($this->dbRows[$tableName])) {
204
-            if (count($this->dbRows === 0)) {
205
-                throw new TDBMException('Object is not yet bound to any table.');
206
-            } else {
207
-                throw new TDBMException('Unknown table "'.$tableName.'"" in object.');
208
-            }
209
-        }
210
-
211
-        return $tableName;
212
-    }
213
-
214
-    protected function get($var, $tableName = null)
215
-    {
216
-        $tableName = $this->checkTableName($tableName);
217
-
218
-        return $this->dbRows[$tableName]->get($var);
219
-    }
220
-
221
-    protected function set($var, $value, $tableName = null)
222
-    {
223
-        if ($tableName === null) {
224
-            if (count($this->dbRows) > 1) {
225
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226
-            } elseif (count($this->dbRows) === 1) {
227
-                $tableName = array_keys($this->dbRows)[0];
228
-            } else {
229
-                throw new TDBMException('Please specify a table for this object.');
230
-            }
231
-        }
232
-
233
-        if (!isset($this->dbRows[$tableName])) {
234
-            $this->registerTable($tableName);
235
-        }
236
-
237
-        $this->dbRows[$tableName]->set($var, $value);
238
-        if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
239
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
240
-        }
241
-    }
242
-
243
-    /**
244
-     * @param string             $foreignKeyName
245
-     * @param AbstractTDBMObject $bean
246
-     */
247
-    protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248
-    {
249
-        if ($tableName === null) {
250
-            if (count($this->dbRows) > 1) {
251
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252
-            } elseif (count($this->dbRows) === 1) {
253
-                $tableName = array_keys($this->dbRows)[0];
254
-            } else {
255
-                throw new TDBMException('Please specify a table for this object.');
256
-            }
257
-        }
258
-
259
-        if (!isset($this->dbRows[$tableName])) {
260
-            $this->registerTable($tableName);
261
-        }
262
-
263
-        $oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
264
-        if ($oldLinkedBean !== null) {
265
-            $oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
266
-        }
267
-
268
-        $this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
269
-        if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
270
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
271
-        }
272
-
273
-        if ($bean !== null) {
274
-            $bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    protected function getRef($foreignKeyName, $tableName = null)
284
-    {
285
-        $tableName = $this->checkTableName($tableName);
286
-
287
-        return $this->dbRows[$tableName]->getRef($foreignKeyName);
288
-    }
289
-
290
-    /**
291
-     * Adds a many to many relationship to this bean.
292
-     *
293
-     * @param string             $pivotTableName
294
-     * @param AbstractTDBMObject $remoteBean
295
-     */
296
-    protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
297
-    {
298
-        $this->setRelationship($pivotTableName, $remoteBean, 'new');
299
-    }
300
-
301
-    /**
302
-     * Returns true if there is a relationship to this bean.
303
-     *
304
-     * @param string             $pivotTableName
305
-     * @param AbstractTDBMObject $remoteBean
306
-     *
307
-     * @return bool
308
-     */
309
-    protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
310
-    {
311
-        $storage = $this->retrieveRelationshipsStorage($pivotTableName);
312
-
313
-        if ($storage->contains($remoteBean)) {
314
-            if ($storage[$remoteBean]['status'] !== 'delete') {
315
-                return true;
316
-            }
317
-        }
318
-
319
-        return false;
320
-    }
321
-
322
-    /**
323
-     * Internal TDBM method. Removes a many to many relationship from this bean.
324
-     *
325
-     * @param string             $pivotTableName
326
-     * @param AbstractTDBMObject $remoteBean
327
-     */
328
-    public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
329
-    {
330
-        if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
331
-            unset($this->relationships[$pivotTableName][$remoteBean]);
332
-            unset($remoteBean->relationships[$pivotTableName][$this]);
333
-        } else {
334
-            $this->setRelationship($pivotTableName, $remoteBean, 'delete');
335
-        }
336
-    }
337
-
338
-    /**
339
-     * Sets many to many relationships for this bean.
340
-     * Adds new relationships and removes unused ones.
341
-     *
342
-     * @param $pivotTableName
343
-     * @param array $remoteBeans
344
-     */
345
-    protected function setRelationships($pivotTableName, array $remoteBeans)
346
-    {
347
-        $storage = $this->retrieveRelationshipsStorage($pivotTableName);
348
-
349
-        foreach ($storage as $oldRemoteBean) {
350
-            if (!in_array($oldRemoteBean, $remoteBeans, true)) {
351
-                // $oldRemoteBean must be removed
352
-                $this->_removeRelationship($pivotTableName, $oldRemoteBean);
353
-            }
354
-        }
355
-
356
-        foreach ($remoteBeans as $remoteBean) {
357
-            if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
358
-                // $remoteBean must be added
359
-                $this->addRelationship($pivotTableName, $remoteBean);
360
-            }
361
-        }
362
-    }
363
-
364
-    /**
365
-     * Returns the list of objects linked to this bean via $pivotTableName.
366
-     *
367
-     * @param $pivotTableName
368
-     *
369
-     * @return \SplObjectStorage
370
-     */
371
-    private function retrieveRelationshipsStorage($pivotTableName)
372
-    {
373
-        $storage = $this->getRelationshipStorage($pivotTableName);
374
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
375
-            return $storage;
376
-        }
377
-
378
-        $beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
379
-        $this->loadedRelationships[$pivotTableName] = true;
380
-
381
-        foreach ($beans as $bean) {
382
-            if (isset($storage[$bean])) {
383
-                $oldStatus = $storage[$bean]['status'];
384
-                if ($oldStatus === 'delete') {
385
-                    // Keep deleted things deleted
386
-                    continue;
387
-                }
388
-            }
389
-            $this->setRelationship($pivotTableName, $bean, 'loaded');
390
-        }
391
-
392
-        return $storage;
393
-    }
394
-
395
-    /**
396
-     * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
397
-     *
398
-     * @param $pivotTableName
399
-     *
400
-     * @return AbstractTDBMObject[]
401
-     */
402
-    public function _getRelationships($pivotTableName)
403
-    {
404
-        return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
405
-    }
406
-
407
-    private function relationshipStorageToArray(\SplObjectStorage $storage)
408
-    {
409
-        $beans = [];
410
-        foreach ($storage as $bean) {
411
-            $statusArr = $storage[$bean];
412
-            if ($statusArr['status'] !== 'delete') {
413
-                $beans[] = $bean;
414
-            }
415
-        }
416
-
417
-        return $beans;
418
-    }
419
-
420
-    /**
421
-     * Declares a relationship between.
422
-     *
423
-     * @param string             $pivotTableName
424
-     * @param AbstractTDBMObject $remoteBean
425
-     * @param string             $status
426
-     */
427
-    private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
428
-    {
429
-        $storage = $this->getRelationshipStorage($pivotTableName);
430
-        $storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
431
-        if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
432
-            $this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
433
-        }
434
-
435
-        $remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
436
-        $remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
437
-    }
438
-
439
-    /**
440
-     * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
441
-     *
442
-     * @param string $pivotTableName
443
-     *
444
-     * @return \SplObjectStorage
445
-     */
446
-    private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
447
-    {
448
-        return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
449
-    }
450
-
451
-    /**
452
-     * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
453
-     *
454
-     * @param string $tableName
455
-     * @param string $foreignKeyName
456
-     *
457
-     * @return AlterableResultIterator
458
-     */
459
-    private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
460
-    {
461
-        $key = $tableName.'___'.$foreignKeyName;
462
-
463
-        return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
464
-    }
465
-
466
-    /**
467
-     * Declares a relationship between this bean and the bean pointing to it.
468
-     *
469
-     * @param string             $tableName
470
-     * @param string             $foreignKeyName
471
-     * @param AbstractTDBMObject $remoteBean
472
-     */
473
-    private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
474
-    {
475
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
476
-        $alterableResultIterator->add($remoteBean);
477
-    }
478
-
479
-    /**
480
-     * Declares a relationship between this bean and the bean pointing to it.
481
-     *
482
-     * @param string             $tableName
483
-     * @param string             $foreignKeyName
484
-     * @param AbstractTDBMObject $remoteBean
485
-     */
486
-    private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
487
-    {
488
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
489
-        $alterableResultIterator->remove($remoteBean);
490
-    }
491
-
492
-    /**
493
-     * Returns the list of objects linked to this bean via a given foreign key.
494
-     *
495
-     * @param string $tableName
496
-     * @param string $foreignKeyName
497
-     * @param string $searchTableName
498
-     * @param array  $searchFilter
499
-     * @param string $orderString     The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
500
-     *
501
-     * @return AlterableResultIterator
502
-     */
503
-    protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
504
-    {
505
-        $key = $tableName.'___'.$foreignKeyName;
506
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
507
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
508
-            return $alterableResultIterator;
509
-        }
510
-
511
-        $unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
512
-
513
-        $alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
514
-
515
-        return $alterableResultIterator;
516
-    }
517
-
518
-    /**
519
-     * Reverts any changes made to the object and resumes it to its DB state.
520
-     * This can only be called on objects that come from database and that have not been deleted.
521
-     * Otherwise, this will throw an exception.
522
-     *
523
-     * @throws TDBMException
524
-     */
525
-    public function discardChanges()
526
-    {
527
-        if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
528
-            throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
529
-        }
530
-
531
-        if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
532
-            throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
533
-        }
534
-
535
-        $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
536
-    }
537
-
538
-    /**
539
-     * Method used internally by TDBM. You should not use it directly.
540
-     * This method returns the status of the TDBMObject.
541
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
542
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
543
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
544
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
545
-     *
546
-     * @return string
547
-     */
548
-    public function _getStatus()
549
-    {
550
-        return $this->status;
551
-    }
552
-
553
-    /**
554
-     * Override the native php clone function for TDBMObjects.
555
-     */
556
-    public function __clone()
557
-    {
558
-        // Let's clone the many to many relationships
559
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
560
-            $pivotTableList = array_keys($this->relationships);
561
-        } else {
562
-            $pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
563
-        }
564
-
565
-        foreach ($pivotTableList as $pivotTable) {
566
-            $storage = $this->retrieveRelationshipsStorage($pivotTable);
567
-
568
-            // Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
569
-            /*foreach ($storage as $remoteBean) {
34
+	/**
35
+	 * The service this object is bound to.
36
+	 *
37
+	 * @var TDBMService
38
+	 */
39
+	protected $tdbmService;
40
+
41
+	/**
42
+	 * An array of DbRow, indexed by table name.
43
+	 *
44
+	 * @var DbRow[]
45
+	 */
46
+	protected $dbRows = array();
47
+
48
+	/**
49
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
50
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
51
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
52
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
53
+	 *
54
+	 * @var string
55
+	 */
56
+	private $status;
57
+
58
+	/**
59
+	 * Array storing beans related via many to many relationships (pivot tables).
60
+	 *
61
+	 * @var \SplObjectStorage[] Key: pivot table name, value: SplObjectStorage
62
+	 */
63
+	private $relationships = [];
64
+
65
+	/**
66
+	 * @var bool[] Key: pivot table name, value: whether a query was performed to load the data
67
+	 */
68
+	private $loadedRelationships = [];
69
+
70
+	/**
71
+	 * Array storing beans related via many to one relationships (this bean is pointed by external beans).
72
+	 *
73
+	 * @var AlterableResultIterator[] Key: [external_table]___[external_column], value: SplObjectStorage
74
+	 */
75
+	private $manyToOneRelationships = [];
76
+
77
+	/**
78
+	 * Used with $primaryKeys when we want to retrieve an existing object
79
+	 * and $primaryKeys=[] if we want a new object.
80
+	 *
81
+	 * @param string      $tableName
82
+	 * @param array       $primaryKeys
83
+	 * @param TDBMService $tdbmService
84
+	 *
85
+	 * @throws TDBMException
86
+	 * @throws TDBMInvalidOperationException
87
+	 */
88
+	public function __construct($tableName = null, array $primaryKeys = array(), TDBMService $tdbmService = null)
89
+	{
90
+		// FIXME: lazy loading should be forbidden on tables with inheritance and dynamic type assignation...
91
+		if (!empty($tableName)) {
92
+			$this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
93
+		}
94
+
95
+		if ($tdbmService === null) {
96
+			$this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
97
+		} else {
98
+			$this->_attach($tdbmService);
99
+			if (!empty($primaryKeys)) {
100
+				$this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
101
+			} else {
102
+				$this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
103
+			}
104
+		}
105
+	}
106
+
107
+	/**
108
+	 * Alternative constructor called when data is fetched from database via a SELECT.
109
+	 *
110
+	 * @param array       $beanData    array<table, array<column, value>>
111
+	 * @param TDBMService $tdbmService
112
+	 */
113
+	public function _constructFromData(array $beanData, TDBMService $tdbmService)
114
+	{
115
+		$this->tdbmService = $tdbmService;
116
+
117
+		foreach ($beanData as $table => $columns) {
118
+			$this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
119
+		}
120
+
121
+		$this->status = TDBMObjectStateEnum::STATE_LOADED;
122
+	}
123
+
124
+	/**
125
+	 * Alternative constructor called when bean is lazily loaded.
126
+	 *
127
+	 * @param string      $tableName
128
+	 * @param array       $primaryKeys
129
+	 * @param TDBMService $tdbmService
130
+	 */
131
+	public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
132
+	{
133
+		$this->tdbmService = $tdbmService;
134
+
135
+		$this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
136
+
137
+		$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
138
+	}
139
+
140
+	public function _attach(TDBMService $tdbmService)
141
+	{
142
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
143
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
144
+		}
145
+		$this->tdbmService = $tdbmService;
146
+
147
+		// If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
148
+		$tableNames = $this->getUsedTables();
149
+
150
+		$newDbRows = [];
151
+
152
+		foreach ($tableNames as $table) {
153
+			if (!isset($this->dbRows[$table])) {
154
+				$this->registerTable($table);
155
+			}
156
+			$newDbRows[$table] = $this->dbRows[$table];
157
+		}
158
+		$this->dbRows = $newDbRows;
159
+
160
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
161
+		foreach ($this->dbRows as $dbRow) {
162
+			$dbRow->_attach($tdbmService);
163
+		}
164
+	}
165
+
166
+	/**
167
+	 * Sets the state of the TDBM Object
168
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
169
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
170
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
171
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
172
+	 *
173
+	 * @param string $state
174
+	 */
175
+	public function _setStatus($state)
176
+	{
177
+		$this->status = $state;
178
+
179
+		// TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
180
+		foreach ($this->dbRows as $dbRow) {
181
+			$dbRow->_setStatus($state);
182
+		}
183
+	}
184
+
185
+	/**
186
+	 * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
187
+	 * or throws an error.
188
+	 *
189
+	 * @param string $tableName
190
+	 *
191
+	 * @return string
192
+	 */
193
+	private function checkTableName($tableName = null)
194
+	{
195
+		if ($tableName === null) {
196
+			if (count($this->dbRows) > 1) {
197
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
198
+			} elseif (count($this->dbRows) === 1) {
199
+				$tableName = array_keys($this->dbRows)[0];
200
+			}
201
+		}
202
+
203
+		if (!isset($this->dbRows[$tableName])) {
204
+			if (count($this->dbRows === 0)) {
205
+				throw new TDBMException('Object is not yet bound to any table.');
206
+			} else {
207
+				throw new TDBMException('Unknown table "'.$tableName.'"" in object.');
208
+			}
209
+		}
210
+
211
+		return $tableName;
212
+	}
213
+
214
+	protected function get($var, $tableName = null)
215
+	{
216
+		$tableName = $this->checkTableName($tableName);
217
+
218
+		return $this->dbRows[$tableName]->get($var);
219
+	}
220
+
221
+	protected function set($var, $value, $tableName = null)
222
+	{
223
+		if ($tableName === null) {
224
+			if (count($this->dbRows) > 1) {
225
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226
+			} elseif (count($this->dbRows) === 1) {
227
+				$tableName = array_keys($this->dbRows)[0];
228
+			} else {
229
+				throw new TDBMException('Please specify a table for this object.');
230
+			}
231
+		}
232
+
233
+		if (!isset($this->dbRows[$tableName])) {
234
+			$this->registerTable($tableName);
235
+		}
236
+
237
+		$this->dbRows[$tableName]->set($var, $value);
238
+		if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
239
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
240
+		}
241
+	}
242
+
243
+	/**
244
+	 * @param string             $foreignKeyName
245
+	 * @param AbstractTDBMObject $bean
246
+	 */
247
+	protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248
+	{
249
+		if ($tableName === null) {
250
+			if (count($this->dbRows) > 1) {
251
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252
+			} elseif (count($this->dbRows) === 1) {
253
+				$tableName = array_keys($this->dbRows)[0];
254
+			} else {
255
+				throw new TDBMException('Please specify a table for this object.');
256
+			}
257
+		}
258
+
259
+		if (!isset($this->dbRows[$tableName])) {
260
+			$this->registerTable($tableName);
261
+		}
262
+
263
+		$oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
264
+		if ($oldLinkedBean !== null) {
265
+			$oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
266
+		}
267
+
268
+		$this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
269
+		if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
270
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
271
+		}
272
+
273
+		if ($bean !== null) {
274
+			$bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	protected function getRef($foreignKeyName, $tableName = null)
284
+	{
285
+		$tableName = $this->checkTableName($tableName);
286
+
287
+		return $this->dbRows[$tableName]->getRef($foreignKeyName);
288
+	}
289
+
290
+	/**
291
+	 * Adds a many to many relationship to this bean.
292
+	 *
293
+	 * @param string             $pivotTableName
294
+	 * @param AbstractTDBMObject $remoteBean
295
+	 */
296
+	protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
297
+	{
298
+		$this->setRelationship($pivotTableName, $remoteBean, 'new');
299
+	}
300
+
301
+	/**
302
+	 * Returns true if there is a relationship to this bean.
303
+	 *
304
+	 * @param string             $pivotTableName
305
+	 * @param AbstractTDBMObject $remoteBean
306
+	 *
307
+	 * @return bool
308
+	 */
309
+	protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
310
+	{
311
+		$storage = $this->retrieveRelationshipsStorage($pivotTableName);
312
+
313
+		if ($storage->contains($remoteBean)) {
314
+			if ($storage[$remoteBean]['status'] !== 'delete') {
315
+				return true;
316
+			}
317
+		}
318
+
319
+		return false;
320
+	}
321
+
322
+	/**
323
+	 * Internal TDBM method. Removes a many to many relationship from this bean.
324
+	 *
325
+	 * @param string             $pivotTableName
326
+	 * @param AbstractTDBMObject $remoteBean
327
+	 */
328
+	public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
329
+	{
330
+		if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
331
+			unset($this->relationships[$pivotTableName][$remoteBean]);
332
+			unset($remoteBean->relationships[$pivotTableName][$this]);
333
+		} else {
334
+			$this->setRelationship($pivotTableName, $remoteBean, 'delete');
335
+		}
336
+	}
337
+
338
+	/**
339
+	 * Sets many to many relationships for this bean.
340
+	 * Adds new relationships and removes unused ones.
341
+	 *
342
+	 * @param $pivotTableName
343
+	 * @param array $remoteBeans
344
+	 */
345
+	protected function setRelationships($pivotTableName, array $remoteBeans)
346
+	{
347
+		$storage = $this->retrieveRelationshipsStorage($pivotTableName);
348
+
349
+		foreach ($storage as $oldRemoteBean) {
350
+			if (!in_array($oldRemoteBean, $remoteBeans, true)) {
351
+				// $oldRemoteBean must be removed
352
+				$this->_removeRelationship($pivotTableName, $oldRemoteBean);
353
+			}
354
+		}
355
+
356
+		foreach ($remoteBeans as $remoteBean) {
357
+			if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
358
+				// $remoteBean must be added
359
+				$this->addRelationship($pivotTableName, $remoteBean);
360
+			}
361
+		}
362
+	}
363
+
364
+	/**
365
+	 * Returns the list of objects linked to this bean via $pivotTableName.
366
+	 *
367
+	 * @param $pivotTableName
368
+	 *
369
+	 * @return \SplObjectStorage
370
+	 */
371
+	private function retrieveRelationshipsStorage($pivotTableName)
372
+	{
373
+		$storage = $this->getRelationshipStorage($pivotTableName);
374
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
375
+			return $storage;
376
+		}
377
+
378
+		$beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
379
+		$this->loadedRelationships[$pivotTableName] = true;
380
+
381
+		foreach ($beans as $bean) {
382
+			if (isset($storage[$bean])) {
383
+				$oldStatus = $storage[$bean]['status'];
384
+				if ($oldStatus === 'delete') {
385
+					// Keep deleted things deleted
386
+					continue;
387
+				}
388
+			}
389
+			$this->setRelationship($pivotTableName, $bean, 'loaded');
390
+		}
391
+
392
+		return $storage;
393
+	}
394
+
395
+	/**
396
+	 * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
397
+	 *
398
+	 * @param $pivotTableName
399
+	 *
400
+	 * @return AbstractTDBMObject[]
401
+	 */
402
+	public function _getRelationships($pivotTableName)
403
+	{
404
+		return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
405
+	}
406
+
407
+	private function relationshipStorageToArray(\SplObjectStorage $storage)
408
+	{
409
+		$beans = [];
410
+		foreach ($storage as $bean) {
411
+			$statusArr = $storage[$bean];
412
+			if ($statusArr['status'] !== 'delete') {
413
+				$beans[] = $bean;
414
+			}
415
+		}
416
+
417
+		return $beans;
418
+	}
419
+
420
+	/**
421
+	 * Declares a relationship between.
422
+	 *
423
+	 * @param string             $pivotTableName
424
+	 * @param AbstractTDBMObject $remoteBean
425
+	 * @param string             $status
426
+	 */
427
+	private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
428
+	{
429
+		$storage = $this->getRelationshipStorage($pivotTableName);
430
+		$storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
431
+		if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
432
+			$this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
433
+		}
434
+
435
+		$remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
436
+		$remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
437
+	}
438
+
439
+	/**
440
+	 * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
441
+	 *
442
+	 * @param string $pivotTableName
443
+	 *
444
+	 * @return \SplObjectStorage
445
+	 */
446
+	private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
447
+	{
448
+		return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
449
+	}
450
+
451
+	/**
452
+	 * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
453
+	 *
454
+	 * @param string $tableName
455
+	 * @param string $foreignKeyName
456
+	 *
457
+	 * @return AlterableResultIterator
458
+	 */
459
+	private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
460
+	{
461
+		$key = $tableName.'___'.$foreignKeyName;
462
+
463
+		return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
464
+	}
465
+
466
+	/**
467
+	 * Declares a relationship between this bean and the bean pointing to it.
468
+	 *
469
+	 * @param string             $tableName
470
+	 * @param string             $foreignKeyName
471
+	 * @param AbstractTDBMObject $remoteBean
472
+	 */
473
+	private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
474
+	{
475
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
476
+		$alterableResultIterator->add($remoteBean);
477
+	}
478
+
479
+	/**
480
+	 * Declares a relationship between this bean and the bean pointing to it.
481
+	 *
482
+	 * @param string             $tableName
483
+	 * @param string             $foreignKeyName
484
+	 * @param AbstractTDBMObject $remoteBean
485
+	 */
486
+	private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
487
+	{
488
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
489
+		$alterableResultIterator->remove($remoteBean);
490
+	}
491
+
492
+	/**
493
+	 * Returns the list of objects linked to this bean via a given foreign key.
494
+	 *
495
+	 * @param string $tableName
496
+	 * @param string $foreignKeyName
497
+	 * @param string $searchTableName
498
+	 * @param array  $searchFilter
499
+	 * @param string $orderString     The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
500
+	 *
501
+	 * @return AlterableResultIterator
502
+	 */
503
+	protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
504
+	{
505
+		$key = $tableName.'___'.$foreignKeyName;
506
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
507
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
508
+			return $alterableResultIterator;
509
+		}
510
+
511
+		$unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
512
+
513
+		$alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
514
+
515
+		return $alterableResultIterator;
516
+	}
517
+
518
+	/**
519
+	 * Reverts any changes made to the object and resumes it to its DB state.
520
+	 * This can only be called on objects that come from database and that have not been deleted.
521
+	 * Otherwise, this will throw an exception.
522
+	 *
523
+	 * @throws TDBMException
524
+	 */
525
+	public function discardChanges()
526
+	{
527
+		if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
528
+			throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
529
+		}
530
+
531
+		if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
532
+			throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
533
+		}
534
+
535
+		$this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
536
+	}
537
+
538
+	/**
539
+	 * Method used internally by TDBM. You should not use it directly.
540
+	 * This method returns the status of the TDBMObject.
541
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
542
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
543
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
544
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
545
+	 *
546
+	 * @return string
547
+	 */
548
+	public function _getStatus()
549
+	{
550
+		return $this->status;
551
+	}
552
+
553
+	/**
554
+	 * Override the native php clone function for TDBMObjects.
555
+	 */
556
+	public function __clone()
557
+	{
558
+		// Let's clone the many to many relationships
559
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
560
+			$pivotTableList = array_keys($this->relationships);
561
+		} else {
562
+			$pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
563
+		}
564
+
565
+		foreach ($pivotTableList as $pivotTable) {
566
+			$storage = $this->retrieveRelationshipsStorage($pivotTable);
567
+
568
+			// Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
569
+			/*foreach ($storage as $remoteBean) {
570 570
                 $metadata = $storage[$remoteBean];
571 571
 
572 572
                 $remoteStorage = $remoteBean->getRelationshipStorage($pivotTable);
573 573
                 $remoteStorage->attach($this, ['status' => $metadata['status'], 'reverse' => !$metadata['reverse']]);
574 574
             }*/
575
-        }
576
-
577
-        // Let's clone each row
578
-        foreach ($this->dbRows as $key => &$dbRow) {
579
-            $dbRow = clone $dbRow;
580
-            $dbRow->setTDBMObject($this);
581
-        }
582
-
583
-        $this->manyToOneRelationships = [];
584
-
585
-        // Let's set the status to new (to enter the save function)
586
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
587
-    }
588
-
589
-    /**
590
-     * Returns raw database rows.
591
-     *
592
-     * @return DbRow[] Key: table name, Value: DbRow object
593
-     */
594
-    public function _getDbRows()
595
-    {
596
-        return $this->dbRows;
597
-    }
598
-
599
-    private function registerTable($tableName)
600
-    {
601
-        $dbRow = new DbRow($this, $tableName);
602
-
603
-        if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
604
-            // Let's get the primary key for the new table
605
-            $anotherDbRow = array_values($this->dbRows)[0];
606
-            /* @var $anotherDbRow DbRow */
607
-            $indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
608
-            $primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
609
-            $dbRow->_setPrimaryKeys($primaryKeys);
610
-        }
611
-
612
-        $dbRow->_setStatus($this->status);
613
-
614
-        $this->dbRows[$tableName] = $dbRow;
615
-        // TODO: look at status (if not new)=> get primary key from tdbmservice
616
-    }
617
-
618
-    /**
619
-     * Internal function: return the list of relationships.
620
-     *
621
-     * @return \SplObjectStorage[]
622
-     */
623
-    public function _getCachedRelationships()
624
-    {
625
-        return $this->relationships;
626
-    }
627
-
628
-    /**
629
-     * Returns an array of used tables by this bean (from parent to child relationship).
630
-     *
631
-     * @return string[]
632
-     */
633
-    abstract protected function getUsedTables();
575
+		}
576
+
577
+		// Let's clone each row
578
+		foreach ($this->dbRows as $key => &$dbRow) {
579
+			$dbRow = clone $dbRow;
580
+			$dbRow->setTDBMObject($this);
581
+		}
582
+
583
+		$this->manyToOneRelationships = [];
584
+
585
+		// Let's set the status to new (to enter the save function)
586
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
587
+	}
588
+
589
+	/**
590
+	 * Returns raw database rows.
591
+	 *
592
+	 * @return DbRow[] Key: table name, Value: DbRow object
593
+	 */
594
+	public function _getDbRows()
595
+	{
596
+		return $this->dbRows;
597
+	}
598
+
599
+	private function registerTable($tableName)
600
+	{
601
+		$dbRow = new DbRow($this, $tableName);
602
+
603
+		if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
604
+			// Let's get the primary key for the new table
605
+			$anotherDbRow = array_values($this->dbRows)[0];
606
+			/* @var $anotherDbRow DbRow */
607
+			$indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
608
+			$primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
609
+			$dbRow->_setPrimaryKeys($primaryKeys);
610
+		}
611
+
612
+		$dbRow->_setStatus($this->status);
613
+
614
+		$this->dbRows[$tableName] = $dbRow;
615
+		// TODO: look at status (if not new)=> get primary key from tdbmservice
616
+	}
617
+
618
+	/**
619
+	 * Internal function: return the list of relationships.
620
+	 *
621
+	 * @return \SplObjectStorage[]
622
+	 */
623
+	public function _getCachedRelationships()
624
+	{
625
+		return $this->relationships;
626
+	}
627
+
628
+	/**
629
+	 * Returns an array of used tables by this bean (from parent to child relationship).
630
+	 *
631
+	 * @return string[]
632
+	 */
633
+	abstract protected function getUsedTables();
634 634
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmController.php 2 patches
Doc Comments   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
      * @Action
87 87
      *
88 88
      * @param string $name
89
-     * @param bool   $selfedit
89
+     * @param string|boolean   $selfedit
90 90
      */
91 91
     public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
92 92
     {
@@ -109,6 +109,8 @@  discard block
 block discarded – undo
109 109
      * @param string      $daofactoryinstancename
110 110
      * @param string      $selfedit
111 111
      * @param bool        $storeInUtc
112
+     * @param boolean $useCustomComposer
113
+     * @param string $composerFile
112 114
      *
113 115
      * @throws \Mouf\MoufException
114 116
      */
Please login to merge, or discard this patch.
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -18,148 +18,148 @@
 block discarded – undo
18 18
  */
19 19
 class TdbmController extends AbstractMoufInstanceController
20 20
 {
21
-    /**
22
-     * @var HtmlBlock
23
-     */
24
-    public $content;
25
-
26
-    protected $daoNamespace;
27
-    protected $beanNamespace;
28
-    protected $daoFactoryName;
29
-    protected $daoFactoryInstanceName;
30
-    protected $autoloadDetected;
31
-    protected $storeInUtc;
32
-    protected $useCustomComposer;
33
-
34
-    /**
35
-     * Admin page used to display the DAO generation form.
36
-     *
37
-     * @Action
38
-     */
39
-    public function defaultAction($name, $selfedit = 'false')
40
-    {
41
-        $this->initController($name, $selfedit);
42
-
43
-        // Fill variables
44
-        if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) {
45
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name);
46
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name);
47
-            $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name);
48
-            $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name);
49
-            $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name);
50
-            $this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer_'.$name);
51
-            $this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile_'.$name);
52
-        } else {
53
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace');
54
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace');
55
-            $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName');
56
-            $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName');
57
-            $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc');
58
-            $this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer');
59
-            $this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile');
60
-        }
61
-
62
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
63
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
64
-
65
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
66
-            if ($autoloadNamespaces) {
67
-                $this->autoloadDetected = true;
68
-                $rootNamespace = $autoloadNamespaces[0];
69
-                $this->daoNamespace = $rootNamespace.'Dao';
70
-                $this->beanNamespace = $rootNamespace.'Dao\\Bean';
71
-            } else {
72
-                $this->autoloadDetected = false;
73
-                $this->daoNamespace = 'YourApplication\\Dao';
74
-                $this->beanNamespace = 'YourApplication\\Dao\\Bean';
75
-            }
76
-        } else {
77
-            $this->autoloadDetected = true;
78
-        }
79
-
80
-        $this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
81
-        $this->template->toHtml();
82
-    }
83
-
84
-    /**
85
-     * This action generates the DAOs and Beans for the TDBM service passed in parameter.
86
-     *
87
-     * @Action
88
-     *
89
-     * @param string $name
90
-     * @param bool   $selfedit
91
-     */
92
-    public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
93
-    {
94
-        $this->initController($name, $selfedit);
95
-
96
-        self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc, $useCustomComposer, $composerFile);
97
-
98
-        // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
99
-        header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
100
-    }
101
-
102
-    /**
103
-     * This function generates the DAOs and Beans for the TDBM service passed in parameter.
104
-     *
105
-     * @param MoufManager $moufManager
106
-     * @param string      $name
107
-     * @param string      $daonamespace
108
-     * @param string      $beannamespace
109
-     * @param string      $daofactoryclassname
110
-     * @param string      $daofactoryinstancename
111
-     * @param string      $selfedit
112
-     * @param bool        $storeInUtc
113
-     *
114
-     * @throws \Mouf\MoufException
115
-     */
116
-    public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null, $useCustomComposer = null, $composerFile = null)
117
-    {
118
-        $moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace);
119
-        $moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace);
120
-        $moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname);
121
-        $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename);
122
-        $moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc);
123
-        $moufManager->setVariable('tdbmDefaultUseCustomComposer_'.$name, $useCustomComposer);
124
-        $moufManager->setVariable('tdbmDefaultComposerFile_'.$name, $composerFile);
125
-
126
-        // In case of instance renaming, let's use the last used settings
127
-        $moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace);
128
-        $moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace);
129
-        $moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname);
130
-        $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename);
131
-        $moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc);
132
-        $moufManager->setVariable('tdbmDefaultUseCustomComposer', $useCustomComposer);
133
-        $moufManager->setVariable('tdbmDefaultComposerFile', $composerFile);
134
-
135
-        // Remove first and last slash in namespace.
136
-        $daonamespace = trim($daonamespace, '\\');
137
-        $beannamespace = trim($beannamespace, '\\');
138
-
139
-        $tdbmService = new InstanceProxy($name);
140
-        /* @var $tdbmService TDBMService */
141
-        $tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc, ($useCustomComposer ? $composerFile : null));
142
-
143
-        $moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\Generated\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
144
-
145
-        $tableToBeanMap = [];
146
-
147
-        //$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService');
148
-
149
-        foreach ($tables as $table) {
150
-            $daoName = TDBMDaoGenerator::getDaoNameFromTableName($table);
151
-
152
-            $instanceName = TDBMDaoGenerator::toVariableName($daoName);
153
-            if (!$moufManager->instanceExists($instanceName)) {
154
-                $moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName);
155
-            }
156
-            $moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object');
157
-            $moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName);
158
-
159
-            $tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table);
160
-        }
161
-        $tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name);
162
-        $tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap);
163
-        $moufManager->rewriteMouf();
164
-    }
21
+	/**
22
+	 * @var HtmlBlock
23
+	 */
24
+	public $content;
25
+
26
+	protected $daoNamespace;
27
+	protected $beanNamespace;
28
+	protected $daoFactoryName;
29
+	protected $daoFactoryInstanceName;
30
+	protected $autoloadDetected;
31
+	protected $storeInUtc;
32
+	protected $useCustomComposer;
33
+
34
+	/**
35
+	 * Admin page used to display the DAO generation form.
36
+	 *
37
+	 * @Action
38
+	 */
39
+	public function defaultAction($name, $selfedit = 'false')
40
+	{
41
+		$this->initController($name, $selfedit);
42
+
43
+		// Fill variables
44
+		if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) {
45
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name);
46
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name);
47
+			$this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name);
48
+			$this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name);
49
+			$this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name);
50
+			$this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer_'.$name);
51
+			$this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile_'.$name);
52
+		} else {
53
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace');
54
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace');
55
+			$this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName');
56
+			$this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName');
57
+			$this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc');
58
+			$this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer');
59
+			$this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile');
60
+		}
61
+
62
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
63
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
64
+
65
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
66
+			if ($autoloadNamespaces) {
67
+				$this->autoloadDetected = true;
68
+				$rootNamespace = $autoloadNamespaces[0];
69
+				$this->daoNamespace = $rootNamespace.'Dao';
70
+				$this->beanNamespace = $rootNamespace.'Dao\\Bean';
71
+			} else {
72
+				$this->autoloadDetected = false;
73
+				$this->daoNamespace = 'YourApplication\\Dao';
74
+				$this->beanNamespace = 'YourApplication\\Dao\\Bean';
75
+			}
76
+		} else {
77
+			$this->autoloadDetected = true;
78
+		}
79
+
80
+		$this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
81
+		$this->template->toHtml();
82
+	}
83
+
84
+	/**
85
+	 * This action generates the DAOs and Beans for the TDBM service passed in parameter.
86
+	 *
87
+	 * @Action
88
+	 *
89
+	 * @param string $name
90
+	 * @param bool   $selfedit
91
+	 */
92
+	public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
93
+	{
94
+		$this->initController($name, $selfedit);
95
+
96
+		self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc, $useCustomComposer, $composerFile);
97
+
98
+		// TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
99
+		header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
100
+	}
101
+
102
+	/**
103
+	 * This function generates the DAOs and Beans for the TDBM service passed in parameter.
104
+	 *
105
+	 * @param MoufManager $moufManager
106
+	 * @param string      $name
107
+	 * @param string      $daonamespace
108
+	 * @param string      $beannamespace
109
+	 * @param string      $daofactoryclassname
110
+	 * @param string      $daofactoryinstancename
111
+	 * @param string      $selfedit
112
+	 * @param bool        $storeInUtc
113
+	 *
114
+	 * @throws \Mouf\MoufException
115
+	 */
116
+	public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null, $useCustomComposer = null, $composerFile = null)
117
+	{
118
+		$moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace);
119
+		$moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace);
120
+		$moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname);
121
+		$moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename);
122
+		$moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc);
123
+		$moufManager->setVariable('tdbmDefaultUseCustomComposer_'.$name, $useCustomComposer);
124
+		$moufManager->setVariable('tdbmDefaultComposerFile_'.$name, $composerFile);
125
+
126
+		// In case of instance renaming, let's use the last used settings
127
+		$moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace);
128
+		$moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace);
129
+		$moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname);
130
+		$moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename);
131
+		$moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc);
132
+		$moufManager->setVariable('tdbmDefaultUseCustomComposer', $useCustomComposer);
133
+		$moufManager->setVariable('tdbmDefaultComposerFile', $composerFile);
134
+
135
+		// Remove first and last slash in namespace.
136
+		$daonamespace = trim($daonamespace, '\\');
137
+		$beannamespace = trim($beannamespace, '\\');
138
+
139
+		$tdbmService = new InstanceProxy($name);
140
+		/* @var $tdbmService TDBMService */
141
+		$tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc, ($useCustomComposer ? $composerFile : null));
142
+
143
+		$moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\Generated\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
144
+
145
+		$tableToBeanMap = [];
146
+
147
+		//$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService');
148
+
149
+		foreach ($tables as $table) {
150
+			$daoName = TDBMDaoGenerator::getDaoNameFromTableName($table);
151
+
152
+			$instanceName = TDBMDaoGenerator::toVariableName($daoName);
153
+			if (!$moufManager->instanceExists($instanceName)) {
154
+				$moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName);
155
+			}
156
+			$moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object');
157
+			$moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName);
158
+
159
+			$tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table);
160
+		}
161
+		$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name);
162
+		$tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap);
163
+		$moufManager->rewriteMouf();
164
+	}
165 165
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/AbstractBeanPropertyDescriptor.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -9,131 +9,131 @@
 block discarded – undo
9 9
  */
10 10
 abstract class AbstractBeanPropertyDescriptor
11 11
 {
12
-    /**
13
-     * @var Table
14
-     */
15
-    protected $table;
16
-
17
-    /**
18
-     * Whether to use the more complex name in case of conflict.
19
-     *
20
-     * @var bool
21
-     */
22
-    protected $alternativeName = false;
23
-
24
-    /**
25
-     * @param Table $table
26
-     */
27
-    public function __construct(Table $table)
28
-    {
29
-        $this->table = $table;
30
-    }
31
-
32
-    /**
33
-     * Use the more complex name in case of conflict.
34
-     */
35
-    public function useAlternativeName()
36
-    {
37
-        $this->alternativeName = true;
38
-    }
39
-
40
-    /**
41
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
42
-     *
43
-     * @return null|string
44
-     */
45
-    abstract public function getClassName();
46
-
47
-    /**
48
-     * Returns the param annotation for this property (useful for constructor).
49
-     *
50
-     * @return string
51
-     */
52
-    abstract public function getParamAnnotation();
53
-
54
-    public function getVariableName()
55
-    {
56
-        return '$'.$this->getLowerCamelCaseName();
57
-    }
58
-
59
-    public function getLowerCamelCaseName()
60
-    {
61
-        return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
62
-    }
63
-
64
-    abstract public function getUpperCamelCaseName();
65
-
66
-    public function getSetterName()
67
-    {
68
-        return 'set'.$this->getUpperCamelCaseName();
69
-    }
70
-
71
-    public function getGetterName()
72
-    {
73
-        return 'get'.$this->getUpperCamelCaseName();
74
-    }
75
-
76
-    /**
77
-     * Returns the PHP code used in the ben constructor for this property.
78
-     *
79
-     * @return string
80
-     */
81
-    public function getConstructorAssignCode()
82
-    {
83
-        $str = '        $this->%s(%s);';
84
-
85
-        return sprintf($str, $this->getSetterName(), $this->getVariableName());
86
-    }
87
-
88
-    /**
89
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
90
-     *
91
-     * @return bool
92
-     */
93
-    abstract public function isCompulsory();
94
-
95
-    /**
96
-     * Returns true if the property has a default value.
97
-     *
98
-     * @return bool
99
-     */
100
-    abstract public function hasDefault();
101
-
102
-    /**
103
-     * Returns the code that assigns a value to its default value.
104
-     *
105
-     * @return string
106
-     *
107
-     * @throws \TDBMException
108
-     */
109
-    abstract public function assignToDefaultCode();
110
-
111
-    /**
112
-     * Returns true if the property is the primary key.
113
-     *
114
-     * @return bool
115
-     */
116
-    abstract public function isPrimaryKey();
117
-
118
-    /**
119
-     * @return Table
120
-     */
121
-    public function getTable()
122
-    {
123
-        return $this->table;
124
-    }
125
-
126
-    /**
127
-     * Returns the PHP code for getters and setters.
128
-     *
129
-     * @return string
130
-     */
131
-    abstract public function getGetterSetterCode();
132
-
133
-    /**
134
-     * Returns the part of code useful when doing json serialization.
135
-     *
136
-     * @return string
137
-     */
138
-    abstract public function getJsonSerializeCode();
12
+	/**
13
+	 * @var Table
14
+	 */
15
+	protected $table;
16
+
17
+	/**
18
+	 * Whether to use the more complex name in case of conflict.
19
+	 *
20
+	 * @var bool
21
+	 */
22
+	protected $alternativeName = false;
23
+
24
+	/**
25
+	 * @param Table $table
26
+	 */
27
+	public function __construct(Table $table)
28
+	{
29
+		$this->table = $table;
30
+	}
31
+
32
+	/**
33
+	 * Use the more complex name in case of conflict.
34
+	 */
35
+	public function useAlternativeName()
36
+	{
37
+		$this->alternativeName = true;
38
+	}
39
+
40
+	/**
41
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
42
+	 *
43
+	 * @return null|string
44
+	 */
45
+	abstract public function getClassName();
46
+
47
+	/**
48
+	 * Returns the param annotation for this property (useful for constructor).
49
+	 *
50
+	 * @return string
51
+	 */
52
+	abstract public function getParamAnnotation();
53
+
54
+	public function getVariableName()
55
+	{
56
+		return '$'.$this->getLowerCamelCaseName();
57
+	}
58
+
59
+	public function getLowerCamelCaseName()
60
+	{
61
+		return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
62
+	}
63
+
64
+	abstract public function getUpperCamelCaseName();
65
+
66
+	public function getSetterName()
67
+	{
68
+		return 'set'.$this->getUpperCamelCaseName();
69
+	}
70
+
71
+	public function getGetterName()
72
+	{
73
+		return 'get'.$this->getUpperCamelCaseName();
74
+	}
75
+
76
+	/**
77
+	 * Returns the PHP code used in the ben constructor for this property.
78
+	 *
79
+	 * @return string
80
+	 */
81
+	public function getConstructorAssignCode()
82
+	{
83
+		$str = '        $this->%s(%s);';
84
+
85
+		return sprintf($str, $this->getSetterName(), $this->getVariableName());
86
+	}
87
+
88
+	/**
89
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
90
+	 *
91
+	 * @return bool
92
+	 */
93
+	abstract public function isCompulsory();
94
+
95
+	/**
96
+	 * Returns true if the property has a default value.
97
+	 *
98
+	 * @return bool
99
+	 */
100
+	abstract public function hasDefault();
101
+
102
+	/**
103
+	 * Returns the code that assigns a value to its default value.
104
+	 *
105
+	 * @return string
106
+	 *
107
+	 * @throws \TDBMException
108
+	 */
109
+	abstract public function assignToDefaultCode();
110
+
111
+	/**
112
+	 * Returns true if the property is the primary key.
113
+	 *
114
+	 * @return bool
115
+	 */
116
+	abstract public function isPrimaryKey();
117
+
118
+	/**
119
+	 * @return Table
120
+	 */
121
+	public function getTable()
122
+	{
123
+		return $this->table;
124
+	}
125
+
126
+	/**
127
+	 * Returns the PHP code for getters and setters.
128
+	 *
129
+	 * @return string
130
+	 */
131
+	abstract public function getGetterSetterCode();
132
+
133
+	/**
134
+	 * Returns the part of code useful when doing json serialization.
135
+	 *
136
+	 * @return string
137
+	 */
138
+	abstract public function getJsonSerializeCode();
139 139
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/ResultIterator.php 3 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -245,7 +245,7 @@
 block discarded – undo
245 245
      */
246 246
     public function jsonSerialize($stopRecursion = false)
247 247
     {
248
-        return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
248
+        return array_map(function(AbstractTDBMObject $item) use ($stopRecursion) {
249 249
             return $item->jsonSerialize($stopRecursion);
250 250
         }, $this->toArray());
251 251
     }
Please login to merge, or discard this patch.
Doc Comments   +7 added lines patch added patch discarded remove patch
@@ -69,6 +69,12 @@  discard block
 block discarded – undo
69 69
 
70 70
     private $logger;
71 71
 
72
+    /**
73
+     * @param string $magicSql
74
+     * @param string $magicSqlCount
75
+     * @param string|null $className
76
+     * @param integer $mode
77
+     */
72 78
     public function __construct($magicSql, $magicSqlCount, array $parameters, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode, LoggerInterface $logger)
73 79
     {
74 80
         $this->magicSql = $magicSql;
@@ -152,6 +158,7 @@  discard block
 block discarded – undo
152 158
 
153 159
     /**
154 160
      * @param int $offset
161
+     * @param integer $limit
155 162
      *
156 163
      * @return PageIterator
157 164
      */
Please login to merge, or discard this patch.
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -31,243 +31,243 @@
 block discarded – undo
31 31
  */
32 32
 class ResultIterator implements Result, \ArrayAccess, \JsonSerializable
33 33
 {
34
-    /**
35
-     * @var Statement
36
-     */
37
-    protected $statement;
38
-
39
-    protected $fetchStarted = false;
40
-    private $objectStorage;
41
-    private $className;
42
-
43
-    private $tdbmService;
44
-    private $magicSql;
45
-    private $magicSqlCount;
46
-    private $parameters;
47
-    private $columnDescriptors;
48
-    private $magicQuery;
49
-
50
-    /**
51
-     * @var InnerResultIterator
52
-     */
53
-    private $innerResultIterator;
54
-
55
-    /**
56
-     * The key of the current retrieved object.
57
-     *
58
-     * @var int
59
-     */
60
-    protected $key = -1;
61
-
62
-    protected $current = null;
63
-
64
-    private $databasePlatform;
65
-
66
-    private $totalCount;
67
-
68
-    private $mode;
69
-
70
-    private $logger;
71
-
72
-    public function __construct($magicSql, $magicSqlCount, array $parameters, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode, LoggerInterface $logger)
73
-    {
74
-        $this->magicSql = $magicSql;
75
-        $this->magicSqlCount = $magicSqlCount;
76
-        $this->objectStorage = $objectStorage;
77
-        $this->className = $className;
78
-        $this->tdbmService = $tdbmService;
79
-        $this->parameters = $parameters;
80
-        $this->columnDescriptors = $columnDescriptors;
81
-        $this->magicQuery = $magicQuery;
82
-        $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
83
-        $this->mode = $mode;
84
-        $this->logger = $logger;
85
-    }
86
-
87
-    protected function executeCountQuery()
88
-    {
89
-        $sql = $this->magicQuery->build($this->magicSqlCount, $this->parameters);
90
-        $this->logger->debug('Running count query: '.$sql);
91
-        $this->totalCount = $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters);
92
-    }
93
-
94
-    /**
95
-     * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
96
-     *
97
-     * @return int
98
-     */
99
-    public function count()
100
-    {
101
-        if ($this->totalCount === null) {
102
-            $this->executeCountQuery();
103
-        }
104
-
105
-        return $this->totalCount;
106
-    }
107
-
108
-    /**
109
-     * Casts the result set to a PHP array.
110
-     *
111
-     * @return array
112
-     */
113
-    public function toArray()
114
-    {
115
-        return iterator_to_array($this->getIterator());
116
-    }
117
-
118
-    /**
119
-     * Returns a new iterator mapping any call using the $callable function.
120
-     *
121
-     * @param callable $callable
122
-     *
123
-     * @return MapIterator
124
-     */
125
-    public function map(callable $callable)
126
-    {
127
-        return new MapIterator($this->getIterator(), $callable);
128
-    }
129
-
130
-    /**
131
-     * Retrieve an external iterator.
132
-     *
133
-     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
134
-     *
135
-     * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or
136
-     *                             <b>Traversable</b>
137
-     *
138
-     * @since 5.0.0
139
-     */
140
-    public function getIterator()
141
-    {
142
-        if ($this->innerResultIterator === null) {
143
-            if ($this->mode === TDBMService::MODE_CURSOR) {
144
-                $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
145
-            } else {
146
-                $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
147
-            }
148
-        }
149
-
150
-        return $this->innerResultIterator;
151
-    }
152
-
153
-    /**
154
-     * @param int $offset
155
-     *
156
-     * @return PageIterator
157
-     */
158
-    public function take($offset, $limit)
159
-    {
160
-        return new PageIterator($this, $this->magicSql, $this->parameters, $limit, $offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->mode, $this->logger);
161
-    }
162
-
163
-    /**
164
-     * Whether a offset exists.
165
-     *
166
-     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
167
-     *
168
-     * @param mixed $offset <p>
169
-     *                      An offset to check for.
170
-     *                      </p>
171
-     *
172
-     * @return bool true on success or false on failure.
173
-     *              </p>
174
-     *              <p>
175
-     *              The return value will be casted to boolean if non-boolean was returned
176
-     *
177
-     * @since 5.0.0
178
-     */
179
-    public function offsetExists($offset)
180
-    {
181
-        return $this->getIterator()->offsetExists($offset);
182
-    }
183
-
184
-    /**
185
-     * Offset to retrieve.
186
-     *
187
-     * @link http://php.net/manual/en/arrayaccess.offsetget.php
188
-     *
189
-     * @param mixed $offset <p>
190
-     *                      The offset to retrieve.
191
-     *                      </p>
192
-     *
193
-     * @return mixed Can return all value types
194
-     *
195
-     * @since 5.0.0
196
-     */
197
-    public function offsetGet($offset)
198
-    {
199
-        return $this->getIterator()->offsetGet($offset);
200
-    }
201
-
202
-    /**
203
-     * Offset to set.
204
-     *
205
-     * @link http://php.net/manual/en/arrayaccess.offsetset.php
206
-     *
207
-     * @param mixed $offset <p>
208
-     *                      The offset to assign the value to.
209
-     *                      </p>
210
-     * @param mixed $value  <p>
211
-     *                      The value to set.
212
-     *                      </p>
213
-     *
214
-     * @since 5.0.0
215
-     */
216
-    public function offsetSet($offset, $value)
217
-    {
218
-        return $this->getIterator()->offsetSet($offset, $value);
219
-    }
220
-
221
-    /**
222
-     * Offset to unset.
223
-     *
224
-     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
225
-     *
226
-     * @param mixed $offset <p>
227
-     *                      The offset to unset.
228
-     *                      </p>
229
-     *
230
-     * @since 5.0.0
231
-     */
232
-    public function offsetUnset($offset)
233
-    {
234
-        return $this->getIterator()->offsetUnset($offset);
235
-    }
236
-
237
-    /**
238
-     * Specify data which should be serialized to JSON.
239
-     *
240
-     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
241
-     *
242
-     * @param bool $stopRecursion Parameter used internally by TDBM to
243
-     *                            stop embedded objects from embedding
244
-     *                            other objects
245
-     *
246
-     * @return mixed data which can be serialized by <b>json_encode</b>,
247
-     *               which is a value of any type other than a resource
248
-     *
249
-     * @since 5.4.0
250
-     */
251
-    public function jsonSerialize($stopRecursion = false)
252
-    {
253
-        return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
254
-            return $item->jsonSerialize($stopRecursion);
255
-        }, $this->toArray());
256
-    }
257
-
258
-    /**
259
-     * Returns only one value (the first) of the result set.
260
-     * Returns null if no value exists.
261
-     *
262
-     * @return mixed|null
263
-     */
264
-    public function first()
265
-    {
266
-        $page = $this->take(0, 1);
267
-        foreach ($page as $bean) {
268
-            return $bean;
269
-        }
270
-
271
-        return;
272
-    }
34
+	/**
35
+	 * @var Statement
36
+	 */
37
+	protected $statement;
38
+
39
+	protected $fetchStarted = false;
40
+	private $objectStorage;
41
+	private $className;
42
+
43
+	private $tdbmService;
44
+	private $magicSql;
45
+	private $magicSqlCount;
46
+	private $parameters;
47
+	private $columnDescriptors;
48
+	private $magicQuery;
49
+
50
+	/**
51
+	 * @var InnerResultIterator
52
+	 */
53
+	private $innerResultIterator;
54
+
55
+	/**
56
+	 * The key of the current retrieved object.
57
+	 *
58
+	 * @var int
59
+	 */
60
+	protected $key = -1;
61
+
62
+	protected $current = null;
63
+
64
+	private $databasePlatform;
65
+
66
+	private $totalCount;
67
+
68
+	private $mode;
69
+
70
+	private $logger;
71
+
72
+	public function __construct($magicSql, $magicSqlCount, array $parameters, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode, LoggerInterface $logger)
73
+	{
74
+		$this->magicSql = $magicSql;
75
+		$this->magicSqlCount = $magicSqlCount;
76
+		$this->objectStorage = $objectStorage;
77
+		$this->className = $className;
78
+		$this->tdbmService = $tdbmService;
79
+		$this->parameters = $parameters;
80
+		$this->columnDescriptors = $columnDescriptors;
81
+		$this->magicQuery = $magicQuery;
82
+		$this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
83
+		$this->mode = $mode;
84
+		$this->logger = $logger;
85
+	}
86
+
87
+	protected function executeCountQuery()
88
+	{
89
+		$sql = $this->magicQuery->build($this->magicSqlCount, $this->parameters);
90
+		$this->logger->debug('Running count query: '.$sql);
91
+		$this->totalCount = $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters);
92
+	}
93
+
94
+	/**
95
+	 * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
96
+	 *
97
+	 * @return int
98
+	 */
99
+	public function count()
100
+	{
101
+		if ($this->totalCount === null) {
102
+			$this->executeCountQuery();
103
+		}
104
+
105
+		return $this->totalCount;
106
+	}
107
+
108
+	/**
109
+	 * Casts the result set to a PHP array.
110
+	 *
111
+	 * @return array
112
+	 */
113
+	public function toArray()
114
+	{
115
+		return iterator_to_array($this->getIterator());
116
+	}
117
+
118
+	/**
119
+	 * Returns a new iterator mapping any call using the $callable function.
120
+	 *
121
+	 * @param callable $callable
122
+	 *
123
+	 * @return MapIterator
124
+	 */
125
+	public function map(callable $callable)
126
+	{
127
+		return new MapIterator($this->getIterator(), $callable);
128
+	}
129
+
130
+	/**
131
+	 * Retrieve an external iterator.
132
+	 *
133
+	 * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
134
+	 *
135
+	 * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or
136
+	 *                             <b>Traversable</b>
137
+	 *
138
+	 * @since 5.0.0
139
+	 */
140
+	public function getIterator()
141
+	{
142
+		if ($this->innerResultIterator === null) {
143
+			if ($this->mode === TDBMService::MODE_CURSOR) {
144
+				$this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
145
+			} else {
146
+				$this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
147
+			}
148
+		}
149
+
150
+		return $this->innerResultIterator;
151
+	}
152
+
153
+	/**
154
+	 * @param int $offset
155
+	 *
156
+	 * @return PageIterator
157
+	 */
158
+	public function take($offset, $limit)
159
+	{
160
+		return new PageIterator($this, $this->magicSql, $this->parameters, $limit, $offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->mode, $this->logger);
161
+	}
162
+
163
+	/**
164
+	 * Whether a offset exists.
165
+	 *
166
+	 * @link http://php.net/manual/en/arrayaccess.offsetexists.php
167
+	 *
168
+	 * @param mixed $offset <p>
169
+	 *                      An offset to check for.
170
+	 *                      </p>
171
+	 *
172
+	 * @return bool true on success or false on failure.
173
+	 *              </p>
174
+	 *              <p>
175
+	 *              The return value will be casted to boolean if non-boolean was returned
176
+	 *
177
+	 * @since 5.0.0
178
+	 */
179
+	public function offsetExists($offset)
180
+	{
181
+		return $this->getIterator()->offsetExists($offset);
182
+	}
183
+
184
+	/**
185
+	 * Offset to retrieve.
186
+	 *
187
+	 * @link http://php.net/manual/en/arrayaccess.offsetget.php
188
+	 *
189
+	 * @param mixed $offset <p>
190
+	 *                      The offset to retrieve.
191
+	 *                      </p>
192
+	 *
193
+	 * @return mixed Can return all value types
194
+	 *
195
+	 * @since 5.0.0
196
+	 */
197
+	public function offsetGet($offset)
198
+	{
199
+		return $this->getIterator()->offsetGet($offset);
200
+	}
201
+
202
+	/**
203
+	 * Offset to set.
204
+	 *
205
+	 * @link http://php.net/manual/en/arrayaccess.offsetset.php
206
+	 *
207
+	 * @param mixed $offset <p>
208
+	 *                      The offset to assign the value to.
209
+	 *                      </p>
210
+	 * @param mixed $value  <p>
211
+	 *                      The value to set.
212
+	 *                      </p>
213
+	 *
214
+	 * @since 5.0.0
215
+	 */
216
+	public function offsetSet($offset, $value)
217
+	{
218
+		return $this->getIterator()->offsetSet($offset, $value);
219
+	}
220
+
221
+	/**
222
+	 * Offset to unset.
223
+	 *
224
+	 * @link http://php.net/manual/en/arrayaccess.offsetunset.php
225
+	 *
226
+	 * @param mixed $offset <p>
227
+	 *                      The offset to unset.
228
+	 *                      </p>
229
+	 *
230
+	 * @since 5.0.0
231
+	 */
232
+	public function offsetUnset($offset)
233
+	{
234
+		return $this->getIterator()->offsetUnset($offset);
235
+	}
236
+
237
+	/**
238
+	 * Specify data which should be serialized to JSON.
239
+	 *
240
+	 * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
241
+	 *
242
+	 * @param bool $stopRecursion Parameter used internally by TDBM to
243
+	 *                            stop embedded objects from embedding
244
+	 *                            other objects
245
+	 *
246
+	 * @return mixed data which can be serialized by <b>json_encode</b>,
247
+	 *               which is a value of any type other than a resource
248
+	 *
249
+	 * @since 5.4.0
250
+	 */
251
+	public function jsonSerialize($stopRecursion = false)
252
+	{
253
+		return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
254
+			return $item->jsonSerialize($stopRecursion);
255
+		}, $this->toArray());
256
+	}
257
+
258
+	/**
259
+	 * Returns only one value (the first) of the result set.
260
+	 * Returns null if no value exists.
261
+	 *
262
+	 * @return mixed|null
263
+	 */
264
+	public function first()
265
+	{
266
+		$page = $this->take(0, 1);
267
+		foreach ($page as $bean) {
268
+			return $bean;
269
+		}
270
+
271
+		return;
272
+	}
273 273
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/DbRow.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -374,11 +374,11 @@
 block discarded – undo
374 374
                 $refDbRows = $reference->_getDbRows();
375 375
                 $firstRefDbRow = reset($refDbRows);
376 376
                 $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
377
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
+                for ($i = 0, $count = count($localColumns); $i<$count; ++$i) {
378 378
                     $dbRow[$localColumns[$i]] = $pkValues[$i];
379 379
                 }
380 380
             } else {
381
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
381
+                for ($i = 0, $count = count($localColumns); $i<$count; ++$i) {
382 382
                     $dbRow[$localColumns[$i]] = null;
383 383
                 }
384 384
             }
Please login to merge, or discard this patch.
Indentation   +379 added lines, -379 removed lines patch added patch discarded remove patch
@@ -27,170 +27,170 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class DbRow
29 29
 {
30
-    /**
31
-     * The service this object is bound to.
32
-     *
33
-     * @var TDBMService
34
-     */
35
-    protected $tdbmService;
36
-
37
-    /**
38
-     * The object containing this db row.
39
-     *
40
-     * @var AbstractTDBMObject
41
-     */
42
-    private $object;
43
-
44
-    /**
45
-     * The name of the table the object if issued from.
46
-     *
47
-     * @var string
48
-     */
49
-    private $dbTableName;
50
-
51
-    /**
52
-     * The array of columns returned from database.
53
-     *
54
-     * @var array
55
-     */
56
-    private $dbRow = array();
57
-
58
-    /**
59
-     * @var AbstractTDBMObject[]
60
-     */
61
-    private $references = array();
62
-
63
-    /**
64
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
-     *
69
-     * @var string
70
-     */
71
-    private $status;
72
-
73
-    /**
74
-     * The values of the primary key.
75
-     * This is set when the object is in "loaded" state.
76
-     *
77
-     * @var array An array of column => value
78
-     */
79
-    private $primaryKeys;
80
-
81
-    /**
82
-     * You should never call the constructor directly. Instead, you should use the
83
-     * TDBMService class that will create TDBMObjects for you.
84
-     *
85
-     * Used with id!=false when we want to retrieve an existing object
86
-     * and id==false if we want a new object
87
-     *
88
-     * @param AbstractTDBMObject $object      The object containing this db row
89
-     * @param string             $table_name
90
-     * @param array              $primaryKeys
91
-     * @param TDBMService        $tdbmService
92
-     *
93
-     * @throws TDBMException
94
-     * @throws TDBMInvalidOperationException
95
-     */
96
-    public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
-    {
98
-        $this->object = $object;
99
-        $this->dbTableName = $table_name;
100
-
101
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
-
103
-        if ($tdbmService === null) {
104
-            if (!empty($primaryKeys)) {
105
-                throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
-            }
107
-        } else {
108
-            $this->tdbmService = $tdbmService;
109
-
110
-            if (!empty($primaryKeys)) {
111
-                $this->_setPrimaryKeys($primaryKeys);
112
-                if (!empty($dbRow)) {
113
-                    $this->dbRow = $dbRow;
114
-                    $this->status = TDBMObjectStateEnum::STATE_LOADED;
115
-                } else {
116
-                    $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
-                }
118
-                $tdbmService->_addToCache($this);
119
-            } else {
120
-                $this->status = TDBMObjectStateEnum::STATE_NEW;
121
-                $this->tdbmService->_addToToSaveObjectList($this);
122
-            }
123
-        }
124
-    }
125
-
126
-    public function _attach(TDBMService $tdbmService)
127
-    {
128
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
-        }
131
-        $this->tdbmService = $tdbmService;
132
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
133
-        $this->tdbmService->_addToToSaveObjectList($this);
134
-    }
135
-
136
-    /**
137
-     * Sets the state of the TDBM Object
138
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
-     *
143
-     * @param string $state
144
-     */
145
-    public function _setStatus($state)
146
-    {
147
-        $this->status = $state;
148
-    }
149
-
150
-    /**
151
-     * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
-     * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
-     *
154
-     * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
-     * cannot be found).
156
-     */
157
-    public function _dbLoadIfNotLoaded()
158
-    {
159
-        if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
-            $connection = $this->tdbmService->getConnection();
161
-
162
-            /// buildFilterFromFilterBag($filter_bag)
163
-            list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
-
165
-            $sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
-            $result = $connection->executeQuery($sql, $parameters);
167
-
168
-            if ($result->rowCount() === 0) {
169
-                throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
-            }
171
-
172
-            $row = $result->fetch(\PDO::FETCH_ASSOC);
173
-
174
-            $this->dbRow = [];
175
-            $types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
-
177
-            foreach ($row as $key => $value) {
178
-                $this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
-            }
180
-
181
-            $result->closeCursor();
182
-
183
-            $this->status = TDBMObjectStateEnum::STATE_LOADED;
184
-        }
185
-    }
186
-
187
-    public function get($var)
188
-    {
189
-        $this->_dbLoadIfNotLoaded();
190
-
191
-        // Let's first check if the key exist.
192
-        if (!isset($this->dbRow[$var])) {
193
-            /*
30
+	/**
31
+	 * The service this object is bound to.
32
+	 *
33
+	 * @var TDBMService
34
+	 */
35
+	protected $tdbmService;
36
+
37
+	/**
38
+	 * The object containing this db row.
39
+	 *
40
+	 * @var AbstractTDBMObject
41
+	 */
42
+	private $object;
43
+
44
+	/**
45
+	 * The name of the table the object if issued from.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	private $dbTableName;
50
+
51
+	/**
52
+	 * The array of columns returned from database.
53
+	 *
54
+	 * @var array
55
+	 */
56
+	private $dbRow = array();
57
+
58
+	/**
59
+	 * @var AbstractTDBMObject[]
60
+	 */
61
+	private $references = array();
62
+
63
+	/**
64
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
+	 *
69
+	 * @var string
70
+	 */
71
+	private $status;
72
+
73
+	/**
74
+	 * The values of the primary key.
75
+	 * This is set when the object is in "loaded" state.
76
+	 *
77
+	 * @var array An array of column => value
78
+	 */
79
+	private $primaryKeys;
80
+
81
+	/**
82
+	 * You should never call the constructor directly. Instead, you should use the
83
+	 * TDBMService class that will create TDBMObjects for you.
84
+	 *
85
+	 * Used with id!=false when we want to retrieve an existing object
86
+	 * and id==false if we want a new object
87
+	 *
88
+	 * @param AbstractTDBMObject $object      The object containing this db row
89
+	 * @param string             $table_name
90
+	 * @param array              $primaryKeys
91
+	 * @param TDBMService        $tdbmService
92
+	 *
93
+	 * @throws TDBMException
94
+	 * @throws TDBMInvalidOperationException
95
+	 */
96
+	public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
+	{
98
+		$this->object = $object;
99
+		$this->dbTableName = $table_name;
100
+
101
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
+
103
+		if ($tdbmService === null) {
104
+			if (!empty($primaryKeys)) {
105
+				throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
+			}
107
+		} else {
108
+			$this->tdbmService = $tdbmService;
109
+
110
+			if (!empty($primaryKeys)) {
111
+				$this->_setPrimaryKeys($primaryKeys);
112
+				if (!empty($dbRow)) {
113
+					$this->dbRow = $dbRow;
114
+					$this->status = TDBMObjectStateEnum::STATE_LOADED;
115
+				} else {
116
+					$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
+				}
118
+				$tdbmService->_addToCache($this);
119
+			} else {
120
+				$this->status = TDBMObjectStateEnum::STATE_NEW;
121
+				$this->tdbmService->_addToToSaveObjectList($this);
122
+			}
123
+		}
124
+	}
125
+
126
+	public function _attach(TDBMService $tdbmService)
127
+	{
128
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
+		}
131
+		$this->tdbmService = $tdbmService;
132
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
133
+		$this->tdbmService->_addToToSaveObjectList($this);
134
+	}
135
+
136
+	/**
137
+	 * Sets the state of the TDBM Object
138
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
+	 *
143
+	 * @param string $state
144
+	 */
145
+	public function _setStatus($state)
146
+	{
147
+		$this->status = $state;
148
+	}
149
+
150
+	/**
151
+	 * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
+	 * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
+	 *
154
+	 * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
+	 * cannot be found).
156
+	 */
157
+	public function _dbLoadIfNotLoaded()
158
+	{
159
+		if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
+			$connection = $this->tdbmService->getConnection();
161
+
162
+			/// buildFilterFromFilterBag($filter_bag)
163
+			list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
+
165
+			$sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
+			$result = $connection->executeQuery($sql, $parameters);
167
+
168
+			if ($result->rowCount() === 0) {
169
+				throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
+			}
171
+
172
+			$row = $result->fetch(\PDO::FETCH_ASSOC);
173
+
174
+			$this->dbRow = [];
175
+			$types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
+
177
+			foreach ($row as $key => $value) {
178
+				$this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
+			}
180
+
181
+			$result->closeCursor();
182
+
183
+			$this->status = TDBMObjectStateEnum::STATE_LOADED;
184
+		}
185
+	}
186
+
187
+	public function get($var)
188
+	{
189
+		$this->_dbLoadIfNotLoaded();
190
+
191
+		// Let's first check if the key exist.
192
+		if (!isset($this->dbRow[$var])) {
193
+			/*
194 194
             // Unable to find column.... this is an error if the object has been retrieved from database.
195 195
             // If it's a new object, well, that may not be an error after all!
196 196
             // Let's check if the column does exist in the table
@@ -210,39 +210,39 @@  discard block
 block discarded – undo
210 210
             $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
211 211
 
212 212
             throw new TDBMException($str);*/
213
-            return;
214
-        }
215
-
216
-        $value = $this->dbRow[$var];
217
-        if ($value instanceof \DateTime) {
218
-            if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
-                return \DateTimeImmutable::createFromMutable($value);
220
-            } else {
221
-                return new \DateTimeImmutable($value->format('c'));
222
-            }
223
-        }
224
-
225
-        return $this->dbRow[$var];
226
-    }
227
-
228
-    /**
229
-     * Returns true if a column is set, false otherwise.
230
-     *
231
-     * @param string $var
232
-     *
233
-     * @return bool
234
-     */
235
-    /*public function has($var) {
213
+			return;
214
+		}
215
+
216
+		$value = $this->dbRow[$var];
217
+		if ($value instanceof \DateTime) {
218
+			if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
+				return \DateTimeImmutable::createFromMutable($value);
220
+			} else {
221
+				return new \DateTimeImmutable($value->format('c'));
222
+			}
223
+		}
224
+
225
+		return $this->dbRow[$var];
226
+	}
227
+
228
+	/**
229
+	 * Returns true if a column is set, false otherwise.
230
+	 *
231
+	 * @param string $var
232
+	 *
233
+	 * @return bool
234
+	 */
235
+	/*public function has($var) {
236 236
         $this->_dbLoadIfNotLoaded();
237 237
 
238 238
         return isset($this->dbRow[$var]);
239 239
     }*/
240 240
 
241
-    public function set($var, $value)
242
-    {
243
-        $this->_dbLoadIfNotLoaded();
241
+	public function set($var, $value)
242
+	{
243
+		$this->_dbLoadIfNotLoaded();
244 244
 
245
-        /*
245
+		/*
246 246
         // Ok, let's start by checking the column type
247 247
         $type = $this->db_connection->getColumnType($this->dbTableName, $var);
248 248
 
@@ -252,193 +252,193 @@  discard block
 block discarded – undo
252 252
         }
253 253
         */
254 254
 
255
-        /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
255
+		/*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
256 256
             throw new TDBMException("Error! Changing primary key value is forbidden.");*/
257
-        $this->dbRow[$var] = $value;
258
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
-            $this->tdbmService->_addToToSaveObjectList($this);
261
-        }
262
-    }
263
-
264
-    /**
265
-     * @param string             $foreignKeyName
266
-     * @param AbstractTDBMObject $bean
267
-     */
268
-    public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
-    {
270
-        $this->references[$foreignKeyName] = $bean;
271
-
272
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
-            $this->tdbmService->_addToToSaveObjectList($this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    public function getRef($foreignKeyName)
284
-    {
285
-        if (array_key_exists($foreignKeyName, $this->references)) {
286
-            return $this->references[$foreignKeyName];
287
-        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
288
-            // If the object is new and has no property, then it has to be empty.
289
-            return;
290
-        } else {
291
-            $this->_dbLoadIfNotLoaded();
292
-
293
-            // Let's match the name of the columns to the primary key values
294
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
-
296
-            $values = [];
297
-            foreach ($fk->getLocalColumns() as $column) {
298
-                if (!isset($this->dbRow[$column])) {
299
-                    return;
300
-                }
301
-                $values[] = $this->dbRow[$column];
302
-            }
303
-
304
-            $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
-
306
-            return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
-        }
308
-    }
309
-
310
-    /**
311
-     * Returns the name of the table this object comes from.
312
-     *
313
-     * @return string
314
-     */
315
-    public function _getDbTableName()
316
-    {
317
-        return $this->dbTableName;
318
-    }
319
-
320
-    /**
321
-     * Method used internally by TDBM. You should not use it directly.
322
-     * This method returns the status of the TDBMObject.
323
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
-     *
328
-     * @return string
329
-     */
330
-    public function _getStatus()
331
-    {
332
-        return $this->status;
333
-    }
334
-
335
-    /**
336
-     * Override the native php clone function for TDBMObjects.
337
-     */
338
-    public function __clone()
339
-    {
340
-        // Let's load the row (before we lose the ID!)
341
-        $this->_dbLoadIfNotLoaded();
342
-
343
-        //Let's set the status to detached
344
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
-
346
-        $this->primaryKeys = [];
347
-
348
-        //Now unset the PK from the row
349
-        if ($this->tdbmService) {
350
-            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
-            foreach ($pk_array as $pk) {
352
-                $this->dbRow[$pk] = null;
353
-            }
354
-        }
355
-    }
356
-
357
-    /**
358
-     * Returns raw database row.
359
-     *
360
-     * @return array
361
-     */
362
-    public function _getDbRow()
363
-    {
364
-        // Let's merge $dbRow and $references
365
-        $dbRow = $this->dbRow;
366
-
367
-        foreach ($this->references as $foreignKeyName => $reference) {
368
-            // Let's match the name of the columns to the primary key values
369
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
370
-            $localColumns = $fk->getLocalColumns();
371
-
372
-            if ($reference !== null) {
373
-                $refDbRows = $reference->_getDbRows();
374
-                $firstRefDbRow = reset($refDbRows);
375
-                $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
376
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
-                    $dbRow[$localColumns[$i]] = $pkValues[$i];
378
-                }
379
-            } else {
380
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
381
-                    $dbRow[$localColumns[$i]] = null;
382
-                }
383
-            }
384
-        }
385
-
386
-        return $dbRow;
387
-    }
388
-
389
-    /**
390
-     * Returns references array.
391
-     *
392
-     * @return AbstractTDBMObject[]
393
-     */
394
-    public function _getReferences()
395
-    {
396
-        return $this->references;
397
-    }
398
-
399
-    /**
400
-     * Returns the values of the primary key.
401
-     * This is set when the object is in "loaded" state.
402
-     *
403
-     * @return array
404
-     */
405
-    public function _getPrimaryKeys()
406
-    {
407
-        return $this->primaryKeys;
408
-    }
409
-
410
-    /**
411
-     * Sets the values of the primary key.
412
-     * This is set when the object is in "loaded" state.
413
-     *
414
-     * @param array $primaryKeys
415
-     */
416
-    public function _setPrimaryKeys(array $primaryKeys)
417
-    {
418
-        $this->primaryKeys = $primaryKeys;
419
-        foreach ($this->primaryKeys as $column => $value) {
420
-            $this->dbRow[$column] = $value;
421
-        }
422
-    }
423
-
424
-    /**
425
-     * Returns the TDBMObject this bean is associated to.
426
-     *
427
-     * @return AbstractTDBMObject
428
-     */
429
-    public function getTDBMObject()
430
-    {
431
-        return $this->object;
432
-    }
433
-
434
-    /**
435
-     * Sets the TDBMObject this bean is associated to.
436
-     * Only used when cloning.
437
-     *
438
-     * @param AbstractTDBMObject $object
439
-     */
440
-    public function setTDBMObject(AbstractTDBMObject $object)
441
-    {
442
-        $this->object = $object;
443
-    }
257
+		$this->dbRow[$var] = $value;
258
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
+			$this->tdbmService->_addToToSaveObjectList($this);
261
+		}
262
+	}
263
+
264
+	/**
265
+	 * @param string             $foreignKeyName
266
+	 * @param AbstractTDBMObject $bean
267
+	 */
268
+	public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
+	{
270
+		$this->references[$foreignKeyName] = $bean;
271
+
272
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
+			$this->tdbmService->_addToToSaveObjectList($this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	public function getRef($foreignKeyName)
284
+	{
285
+		if (array_key_exists($foreignKeyName, $this->references)) {
286
+			return $this->references[$foreignKeyName];
287
+		} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
288
+			// If the object is new and has no property, then it has to be empty.
289
+			return;
290
+		} else {
291
+			$this->_dbLoadIfNotLoaded();
292
+
293
+			// Let's match the name of the columns to the primary key values
294
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
+
296
+			$values = [];
297
+			foreach ($fk->getLocalColumns() as $column) {
298
+				if (!isset($this->dbRow[$column])) {
299
+					return;
300
+				}
301
+				$values[] = $this->dbRow[$column];
302
+			}
303
+
304
+			$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
+
306
+			return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
+		}
308
+	}
309
+
310
+	/**
311
+	 * Returns the name of the table this object comes from.
312
+	 *
313
+	 * @return string
314
+	 */
315
+	public function _getDbTableName()
316
+	{
317
+		return $this->dbTableName;
318
+	}
319
+
320
+	/**
321
+	 * Method used internally by TDBM. You should not use it directly.
322
+	 * This method returns the status of the TDBMObject.
323
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
+	 *
328
+	 * @return string
329
+	 */
330
+	public function _getStatus()
331
+	{
332
+		return $this->status;
333
+	}
334
+
335
+	/**
336
+	 * Override the native php clone function for TDBMObjects.
337
+	 */
338
+	public function __clone()
339
+	{
340
+		// Let's load the row (before we lose the ID!)
341
+		$this->_dbLoadIfNotLoaded();
342
+
343
+		//Let's set the status to detached
344
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
+
346
+		$this->primaryKeys = [];
347
+
348
+		//Now unset the PK from the row
349
+		if ($this->tdbmService) {
350
+			$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
+			foreach ($pk_array as $pk) {
352
+				$this->dbRow[$pk] = null;
353
+			}
354
+		}
355
+	}
356
+
357
+	/**
358
+	 * Returns raw database row.
359
+	 *
360
+	 * @return array
361
+	 */
362
+	public function _getDbRow()
363
+	{
364
+		// Let's merge $dbRow and $references
365
+		$dbRow = $this->dbRow;
366
+
367
+		foreach ($this->references as $foreignKeyName => $reference) {
368
+			// Let's match the name of the columns to the primary key values
369
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
370
+			$localColumns = $fk->getLocalColumns();
371
+
372
+			if ($reference !== null) {
373
+				$refDbRows = $reference->_getDbRows();
374
+				$firstRefDbRow = reset($refDbRows);
375
+				$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
376
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
+					$dbRow[$localColumns[$i]] = $pkValues[$i];
378
+				}
379
+			} else {
380
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
381
+					$dbRow[$localColumns[$i]] = null;
382
+				}
383
+			}
384
+		}
385
+
386
+		return $dbRow;
387
+	}
388
+
389
+	/**
390
+	 * Returns references array.
391
+	 *
392
+	 * @return AbstractTDBMObject[]
393
+	 */
394
+	public function _getReferences()
395
+	{
396
+		return $this->references;
397
+	}
398
+
399
+	/**
400
+	 * Returns the values of the primary key.
401
+	 * This is set when the object is in "loaded" state.
402
+	 *
403
+	 * @return array
404
+	 */
405
+	public function _getPrimaryKeys()
406
+	{
407
+		return $this->primaryKeys;
408
+	}
409
+
410
+	/**
411
+	 * Sets the values of the primary key.
412
+	 * This is set when the object is in "loaded" state.
413
+	 *
414
+	 * @param array $primaryKeys
415
+	 */
416
+	public function _setPrimaryKeys(array $primaryKeys)
417
+	{
418
+		$this->primaryKeys = $primaryKeys;
419
+		foreach ($this->primaryKeys as $column => $value) {
420
+			$this->dbRow[$column] = $value;
421
+		}
422
+	}
423
+
424
+	/**
425
+	 * Returns the TDBMObject this bean is associated to.
426
+	 *
427
+	 * @return AbstractTDBMObject
428
+	 */
429
+	public function getTDBMObject()
430
+	{
431
+		return $this->object;
432
+	}
433
+
434
+	/**
435
+	 * Sets the TDBMObject this bean is associated to.
436
+	 * Only used when cloning.
437
+	 *
438
+	 * @param AbstractTDBMObject $object
439
+	 */
440
+	public function setTDBMObject(AbstractTDBMObject $object)
441
+	{
442
+		$this->object = $object;
443
+	}
444 444
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/AlterableResultIterator.php 2 patches
Doc Comments   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
     /**
69 69
      * Adds an additional object to the result set (if not already available).
70 70
      *
71
-     * @param $object
71
+     * @param AbstractTDBMObject $object
72 72
      */
73 73
     public function add($object)
74 74
     {
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
     /**
86 86
      * Removes an object from the result set.
87 87
      *
88
-     * @param $object
88
+     * @param AbstractTDBMObject $object
89 89
      */
90 90
     public function remove($object)
91 91
     {
@@ -205,6 +205,7 @@  discard block
 block discarded – undo
205 205
 
206 206
     /**
207 207
      * @param int $offset
208
+     * @param integer $limit
208 209
      *
209 210
      * @return \Porpaginas\Page
210 211
      */
@@ -227,7 +228,7 @@  discard block
 block discarded – undo
227 228
     /**
228 229
      * Return an iterator over all results of the paginatable.
229 230
      *
230
-     * @return Iterator
231
+     * @return \Iterator
231 232
      */
232 233
     public function getIterator()
233 234
     {
Please login to merge, or discard this patch.
Indentation   +245 added lines, -245 removed lines patch added patch discarded remove patch
@@ -14,274 +14,274 @@
 block discarded – undo
14 14
  */
15 15
 class AlterableResultIterator implements Result, \ArrayAccess, \JsonSerializable
16 16
 {
17
-    /**
18
-     * @var \Iterator|null
19
-     */
20
-    private $resultIterator;
17
+	/**
18
+	 * @var \Iterator|null
19
+	 */
20
+	private $resultIterator;
21 21
 
22
-    /**
23
-     * Key: the object to alter in the result set.
24
-     * Value: "add" => the object will be added to the resultset (if it is not found in it)
25
-     *        "delete" => the object will be removed from the resultset (if found).
26
-     *
27
-     * @var \SplObjectStorage
28
-     */
29
-    private $alterations;
22
+	/**
23
+	 * Key: the object to alter in the result set.
24
+	 * Value: "add" => the object will be added to the resultset (if it is not found in it)
25
+	 *        "delete" => the object will be removed from the resultset (if found).
26
+	 *
27
+	 * @var \SplObjectStorage
28
+	 */
29
+	private $alterations;
30 30
 
31
-    /**
32
-     * The result array from the result set.
33
-     *
34
-     * @var array|null
35
-     */
36
-    private $resultArray;
31
+	/**
32
+	 * The result array from the result set.
33
+	 *
34
+	 * @var array|null
35
+	 */
36
+	private $resultArray;
37 37
 
38
-    /**
39
-     * @param \Iterator|null $resultIterator
40
-     */
41
-    public function __construct(\Iterator $resultIterator = null)
42
-    {
43
-        $this->resultIterator = $resultIterator;
44
-        $this->alterations = new \SplObjectStorage();
45
-    }
38
+	/**
39
+	 * @param \Iterator|null $resultIterator
40
+	 */
41
+	public function __construct(\Iterator $resultIterator = null)
42
+	{
43
+		$this->resultIterator = $resultIterator;
44
+		$this->alterations = new \SplObjectStorage();
45
+	}
46 46
 
47
-    /**
48
-     * Sets a new iterator as the base iterator to be altered.
49
-     *
50
-     * @param \Iterator $resultIterator
51
-     */
52
-    public function setResultIterator(\Iterator $resultIterator)
53
-    {
54
-        $this->resultIterator = $resultIterator;
55
-        $this->resultArray = null;
56
-    }
47
+	/**
48
+	 * Sets a new iterator as the base iterator to be altered.
49
+	 *
50
+	 * @param \Iterator $resultIterator
51
+	 */
52
+	public function setResultIterator(\Iterator $resultIterator)
53
+	{
54
+		$this->resultIterator = $resultIterator;
55
+		$this->resultArray = null;
56
+	}
57 57
 
58
-    /**
59
-     * Returns the non altered result iterator (or null if none exist).
60
-     *
61
-     * @return \Iterator|null
62
-     */
63
-    public function getUnderlyingResultIterator()
64
-    {
65
-        return $this->resultIterator;
66
-    }
58
+	/**
59
+	 * Returns the non altered result iterator (or null if none exist).
60
+	 *
61
+	 * @return \Iterator|null
62
+	 */
63
+	public function getUnderlyingResultIterator()
64
+	{
65
+		return $this->resultIterator;
66
+	}
67 67
 
68
-    /**
69
-     * Adds an additional object to the result set (if not already available).
70
-     *
71
-     * @param $object
72
-     */
73
-    public function add($object)
74
-    {
75
-        $this->alterations->attach($object, 'add');
68
+	/**
69
+	 * Adds an additional object to the result set (if not already available).
70
+	 *
71
+	 * @param $object
72
+	 */
73
+	public function add($object)
74
+	{
75
+		$this->alterations->attach($object, 'add');
76 76
 
77
-        if ($this->resultArray !== null) {
78
-            $foundKey = array_search($object, $this->resultArray, true);
79
-            if ($foundKey === false) {
80
-                $this->resultArray[] = $object;
81
-            }
82
-        }
83
-    }
77
+		if ($this->resultArray !== null) {
78
+			$foundKey = array_search($object, $this->resultArray, true);
79
+			if ($foundKey === false) {
80
+				$this->resultArray[] = $object;
81
+			}
82
+		}
83
+	}
84 84
 
85
-    /**
86
-     * Removes an object from the result set.
87
-     *
88
-     * @param $object
89
-     */
90
-    public function remove($object)
91
-    {
92
-        $this->alterations->attach($object, 'delete');
85
+	/**
86
+	 * Removes an object from the result set.
87
+	 *
88
+	 * @param $object
89
+	 */
90
+	public function remove($object)
91
+	{
92
+		$this->alterations->attach($object, 'delete');
93 93
 
94
-        if ($this->resultArray !== null) {
95
-            $foundKey = array_search($object, $this->resultArray, true);
96
-            if ($foundKey !== false) {
97
-                unset($this->resultArray[$foundKey]);
98
-            }
99
-        }
100
-    }
94
+		if ($this->resultArray !== null) {
95
+			$foundKey = array_search($object, $this->resultArray, true);
96
+			if ($foundKey !== false) {
97
+				unset($this->resultArray[$foundKey]);
98
+			}
99
+		}
100
+	}
101 101
 
102
-    /**
103
-     * Casts the result set to a PHP array.
104
-     *
105
-     * @return array
106
-     */
107
-    public function toArray()
108
-    {
109
-        if ($this->resultArray === null) {
110
-            if ($this->resultIterator !== null) {
111
-                $this->resultArray = iterator_to_array($this->resultIterator);
112
-            } else {
113
-                $this->resultArray = [];
114
-            }
102
+	/**
103
+	 * Casts the result set to a PHP array.
104
+	 *
105
+	 * @return array
106
+	 */
107
+	public function toArray()
108
+	{
109
+		if ($this->resultArray === null) {
110
+			if ($this->resultIterator !== null) {
111
+				$this->resultArray = iterator_to_array($this->resultIterator);
112
+			} else {
113
+				$this->resultArray = [];
114
+			}
115 115
 
116
-            foreach ($this->alterations as $obj) {
117
-                $action = $this->alterations->getInfo(); // return, if exists, associated with cur. obj. data; else NULL
116
+			foreach ($this->alterations as $obj) {
117
+				$action = $this->alterations->getInfo(); // return, if exists, associated with cur. obj. data; else NULL
118 118
 
119
-                $foundKey = array_search($obj, $this->resultArray, true);
119
+				$foundKey = array_search($obj, $this->resultArray, true);
120 120
 
121
-                if ($action === 'add' && $foundKey === false) {
122
-                    $this->resultArray[] = $obj;
123
-                } elseif ($action === 'delete' && $foundKey !== false) {
124
-                    unset($this->resultArray[$foundKey]);
125
-                }
126
-            }
127
-        }
121
+				if ($action === 'add' && $foundKey === false) {
122
+					$this->resultArray[] = $obj;
123
+				} elseif ($action === 'delete' && $foundKey !== false) {
124
+					unset($this->resultArray[$foundKey]);
125
+				}
126
+			}
127
+		}
128 128
 
129
-        return array_values($this->resultArray);
130
-    }
129
+		return array_values($this->resultArray);
130
+	}
131 131
 
132
-    /**
133
-     * Whether a offset exists.
134
-     *
135
-     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
136
-     *
137
-     * @param mixed $offset <p>
138
-     *                      An offset to check for.
139
-     *                      </p>
140
-     *
141
-     * @return bool true on success or false on failure.
142
-     *              </p>
143
-     *              <p>
144
-     *              The return value will be casted to boolean if non-boolean was returned.
145
-     *
146
-     * @since 5.0.0
147
-     */
148
-    public function offsetExists($offset)
149
-    {
150
-        return isset($this->toArray()[$offset]);
151
-    }
132
+	/**
133
+	 * Whether a offset exists.
134
+	 *
135
+	 * @link http://php.net/manual/en/arrayaccess.offsetexists.php
136
+	 *
137
+	 * @param mixed $offset <p>
138
+	 *                      An offset to check for.
139
+	 *                      </p>
140
+	 *
141
+	 * @return bool true on success or false on failure.
142
+	 *              </p>
143
+	 *              <p>
144
+	 *              The return value will be casted to boolean if non-boolean was returned.
145
+	 *
146
+	 * @since 5.0.0
147
+	 */
148
+	public function offsetExists($offset)
149
+	{
150
+		return isset($this->toArray()[$offset]);
151
+	}
152 152
 
153
-    /**
154
-     * Offset to retrieve.
155
-     *
156
-     * @link http://php.net/manual/en/arrayaccess.offsetget.php
157
-     *
158
-     * @param mixed $offset <p>
159
-     *                      The offset to retrieve.
160
-     *                      </p>
161
-     *
162
-     * @return mixed Can return all value types.
163
-     *
164
-     * @since 5.0.0
165
-     */
166
-    public function offsetGet($offset)
167
-    {
168
-        return $this->toArray()[$offset];
169
-    }
153
+	/**
154
+	 * Offset to retrieve.
155
+	 *
156
+	 * @link http://php.net/manual/en/arrayaccess.offsetget.php
157
+	 *
158
+	 * @param mixed $offset <p>
159
+	 *                      The offset to retrieve.
160
+	 *                      </p>
161
+	 *
162
+	 * @return mixed Can return all value types.
163
+	 *
164
+	 * @since 5.0.0
165
+	 */
166
+	public function offsetGet($offset)
167
+	{
168
+		return $this->toArray()[$offset];
169
+	}
170 170
 
171
-    /**
172
-     * Offset to set.
173
-     *
174
-     * @link http://php.net/manual/en/arrayaccess.offsetset.php
175
-     *
176
-     * @param mixed $offset <p>
177
-     *                      The offset to assign the value to.
178
-     *                      </p>
179
-     * @param mixed $value  <p>
180
-     *                      The value to set.
181
-     *                      </p>
182
-     *
183
-     * @since 5.0.0
184
-     */
185
-    public function offsetSet($offset, $value)
186
-    {
187
-        throw new TDBMInvalidOperationException('You can set values in a TDBM result set, even in an alterable one. Use the add method instead.');
188
-    }
171
+	/**
172
+	 * Offset to set.
173
+	 *
174
+	 * @link http://php.net/manual/en/arrayaccess.offsetset.php
175
+	 *
176
+	 * @param mixed $offset <p>
177
+	 *                      The offset to assign the value to.
178
+	 *                      </p>
179
+	 * @param mixed $value  <p>
180
+	 *                      The value to set.
181
+	 *                      </p>
182
+	 *
183
+	 * @since 5.0.0
184
+	 */
185
+	public function offsetSet($offset, $value)
186
+	{
187
+		throw new TDBMInvalidOperationException('You can set values in a TDBM result set, even in an alterable one. Use the add method instead.');
188
+	}
189 189
 
190
-    /**
191
-     * Offset to unset.
192
-     *
193
-     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
194
-     *
195
-     * @param mixed $offset <p>
196
-     *                      The offset to unset.
197
-     *                      </p>
198
-     *
199
-     * @since 5.0.0
200
-     */
201
-    public function offsetUnset($offset)
202
-    {
203
-        throw new TDBMInvalidOperationException('You can unset values in a TDBM result set, even in an alterable one. Use the delete method instead.');
204
-    }
190
+	/**
191
+	 * Offset to unset.
192
+	 *
193
+	 * @link http://php.net/manual/en/arrayaccess.offsetunset.php
194
+	 *
195
+	 * @param mixed $offset <p>
196
+	 *                      The offset to unset.
197
+	 *                      </p>
198
+	 *
199
+	 * @since 5.0.0
200
+	 */
201
+	public function offsetUnset($offset)
202
+	{
203
+		throw new TDBMInvalidOperationException('You can unset values in a TDBM result set, even in an alterable one. Use the delete method instead.');
204
+	}
205 205
 
206
-    /**
207
-     * @param int $offset
208
-     *
209
-     * @return \Porpaginas\Page
210
-     */
211
-    public function take($offset, $limit)
212
-    {
213
-        // TODO: replace this with a class implementing the map method.
214
-        return new ArrayPage(array_slice($this->toArray(), $offset, $limit), $offset, $limit, count($this->toArray()));
215
-    }
206
+	/**
207
+	 * @param int $offset
208
+	 *
209
+	 * @return \Porpaginas\Page
210
+	 */
211
+	public function take($offset, $limit)
212
+	{
213
+		// TODO: replace this with a class implementing the map method.
214
+		return new ArrayPage(array_slice($this->toArray(), $offset, $limit), $offset, $limit, count($this->toArray()));
215
+	}
216 216
 
217
-    /**
218
-     * Return the number of all results in the paginatable.
219
-     *
220
-     * @return int
221
-     */
222
-    public function count()
223
-    {
224
-        return count($this->toArray());
225
-    }
217
+	/**
218
+	 * Return the number of all results in the paginatable.
219
+	 *
220
+	 * @return int
221
+	 */
222
+	public function count()
223
+	{
224
+		return count($this->toArray());
225
+	}
226 226
 
227
-    /**
228
-     * Return an iterator over all results of the paginatable.
229
-     *
230
-     * @return Iterator
231
-     */
232
-    public function getIterator()
233
-    {
234
-        if ($this->alterations->count() === 0) {
235
-            if ($this->resultIterator !== null) {
236
-                return $this->resultIterator;
237
-            } else {
238
-                return new \ArrayIterator([]);
239
-            }
240
-        } else {
241
-            return new \ArrayIterator($this->toArray());
242
-        }
243
-    }
227
+	/**
228
+	 * Return an iterator over all results of the paginatable.
229
+	 *
230
+	 * @return Iterator
231
+	 */
232
+	public function getIterator()
233
+	{
234
+		if ($this->alterations->count() === 0) {
235
+			if ($this->resultIterator !== null) {
236
+				return $this->resultIterator;
237
+			} else {
238
+				return new \ArrayIterator([]);
239
+			}
240
+		} else {
241
+			return new \ArrayIterator($this->toArray());
242
+		}
243
+	}
244 244
 
245
-    /**
246
-     * Specify data which should be serialized to JSON.
247
-     *
248
-     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
249
-     *
250
-     * @return mixed data which can be serialized by <b>json_encode</b>,
251
-     *               which is a value of any type other than a resource.
252
-     *
253
-     * @since 5.4.0
254
-     */
255
-    public function jsonSerialize()
256
-    {
257
-        return $this->toArray();
258
-    }
245
+	/**
246
+	 * Specify data which should be serialized to JSON.
247
+	 *
248
+	 * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
249
+	 *
250
+	 * @return mixed data which can be serialized by <b>json_encode</b>,
251
+	 *               which is a value of any type other than a resource.
252
+	 *
253
+	 * @since 5.4.0
254
+	 */
255
+	public function jsonSerialize()
256
+	{
257
+		return $this->toArray();
258
+	}
259 259
 
260
-    /**
261
-     * Returns only one value (the first) of the result set.
262
-     * Returns null if no value exists.
263
-     *
264
-     * @return mixed|null
265
-     */
266
-    public function first()
267
-    {
268
-        $page = $this->take(0, 1);
269
-        foreach ($page as $bean) {
270
-            return $bean;
271
-        }
260
+	/**
261
+	 * Returns only one value (the first) of the result set.
262
+	 * Returns null if no value exists.
263
+	 *
264
+	 * @return mixed|null
265
+	 */
266
+	public function first()
267
+	{
268
+		$page = $this->take(0, 1);
269
+		foreach ($page as $bean) {
270
+			return $bean;
271
+		}
272 272
 
273
-        return;
274
-    }
273
+		return;
274
+	}
275 275
 
276
-    /**
277
-     * Returns a new iterator mapping any call using the $callable function.
278
-     *
279
-     * @param callable $callable
280
-     *
281
-     * @return MapIterator
282
-     */
283
-    public function map(callable $callable)
284
-    {
285
-        return new MapIterator($this->getIterator(), $callable);
286
-    }
276
+	/**
277
+	 * Returns a new iterator mapping any call using the $callable function.
278
+	 *
279
+	 * @param callable $callable
280
+	 *
281
+	 * @return MapIterator
282
+	 */
283
+	public function map(callable $callable)
284
+	{
285
+		return new MapIterator($this->getIterator(), $callable);
286
+	}
287 287
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMService.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1718,7 +1718,7 @@
 block discarded – undo
1718 1718
      * @param $pivotTableName
1719 1719
      * @param AbstractTDBMObject $bean
1720 1720
      *
1721
-     * @return AbstractTDBMObject[]
1721
+     * @return ResultIterator
1722 1722
      */
1723 1723
     public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1724 1724
     {
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
         sort($tables);
1057 1057
 
1058 1058
         return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1059
-            function () use ($tables) {
1059
+            function() use ($tables) {
1060 1060
                 return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1061 1061
             });
1062 1062
     }
@@ -1103,7 +1103,7 @@  discard block
 block discarded – undo
1103 1103
      */
1104 1104
     public function _getRelatedTablesByInheritance($table)
1105 1105
     {
1106
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1106
+        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function() use ($table) {
1107 1107
             return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1108 1108
         });
1109 1109
     }
@@ -1162,7 +1162,7 @@  discard block
 block discarded – undo
1162 1162
      */
1163 1163
     private function getParentRelationshipForeignKeys($tableName)
1164 1164
     {
1165
-        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
1165
+        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function() use ($tableName) {
1166 1166
             return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
1167 1167
         });
1168 1168
     }
@@ -1191,7 +1191,7 @@  discard block
 block discarded – undo
1191 1191
      */
1192 1192
     private function getChildrenRelationshipForeignKeys($tableName)
1193 1193
     {
1194
-        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
1194
+        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function() use ($tableName) {
1195 1195
             return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
1196 1196
         });
1197 1197
     }
@@ -1206,7 +1206,7 @@  discard block
 block discarded – undo
1206 1206
         $children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
1207 1207
 
1208 1208
         if (!empty($children)) {
1209
-            $fksTables = array_map(function (ForeignKeyConstraint $fk) {
1209
+            $fksTables = array_map(function(ForeignKeyConstraint $fk) {
1210 1210
                 return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
1211 1211
             }, $children);
1212 1212
 
@@ -1321,7 +1321,7 @@  discard block
 block discarded – undo
1321 1321
 
1322 1322
         $schema = $this->tdbmSchemaAnalyzer->getSchema();
1323 1323
         $pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1324
-        $pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1324
+        $pkColumnNames = array_map(function($pkColumn) use ($mainTable) {
1325 1325
             return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1326 1326
         }, $pkColumnNames);
1327 1327
 
@@ -1389,17 +1389,17 @@  discard block
 block discarded – undo
1389 1389
             ];
1390 1390
         }
1391 1391
 
1392
-        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) use ($mainTable) {
1392
+        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function($columnDesc) use ($mainTable) {
1393 1393
             return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($columnDesc['column']);
1394 1394
         }, $columnDescList)).' FROM '.$from;
1395 1395
 
1396
-        if (count($allFetchedTables) > 1) {
1396
+        if (count($allFetchedTables)>1) {
1397 1397
             list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, []);
1398 1398
         }
1399 1399
 
1400 1400
         // Let's compute the COUNT.
1401 1401
         $pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1402
-        $pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1402
+        $pkColumnNames = array_map(function($pkColumn) use ($mainTable) {
1403 1403
             return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1404 1404
         }, $pkColumnNames);
1405 1405
 
@@ -1583,7 +1583,7 @@  discard block
 block discarded – undo
1583 1583
         $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1584 1584
         $page = $objects->take(0, 2);
1585 1585
         $count = $page->count();
1586
-        if ($count > 1) {
1586
+        if ($count>1) {
1587 1587
             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.");
1588 1588
         } elseif ($count === 0) {
1589 1589
             return;
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
         $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1611 1611
         $page = $objects->take(0, 2);
1612 1612
         $count = $page->count();
1613
-        if ($count > 1) {
1613
+        if ($count>1) {
1614 1614
             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.");
1615 1615
         } elseif ($count === 0) {
1616 1616
             return;
@@ -1728,7 +1728,7 @@  discard block
 block discarded – undo
1728 1728
         $remoteTable = $remoteFk->getForeignTableName();
1729 1729
 
1730 1730
         $primaryKeys = $this->getPrimaryKeyValues($bean);
1731
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1731
+        $columnNames = array_map(function($name) use ($pivotTableName) {
1732 1732
             return $pivotTableName.'.'.$name;
1733 1733
         }, $localFk->getLocalColumns());
1734 1734
 
@@ -1751,7 +1751,7 @@  discard block
 block discarded – undo
1751 1751
         $table1 = $fks[0]->getForeignTableName();
1752 1752
         $table2 = $fks[1]->getForeignTableName();
1753 1753
 
1754
-        $beanTables = array_map(function (DbRow $dbRow) {
1754
+        $beanTables = array_map(function(DbRow $dbRow) {
1755 1755
             return $dbRow->_getDbTableName();
1756 1756
         }, $bean->_getDbRows());
1757 1757
 
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
     {
1810 1810
         if (!isset($typesForTable[$tableName])) {
1811 1811
             $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1812
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1812
+            $typesForTable[$tableName] = array_map(function(Column $column) {
1813 1813
                 return $column->getType();
1814 1814
             }, $columns);
1815 1815
         }
Please login to merge, or discard this patch.
Indentation   +1634 added lines, -1634 removed lines patch added patch discarded remove patch
@@ -45,236 +45,236 @@  discard block
 block discarded – undo
45 45
  */
46 46
 class TDBMService
47 47
 {
48
-    const MODE_CURSOR = 1;
49
-    const MODE_ARRAY = 2;
50
-
51
-    /**
52
-     * The database connection.
53
-     *
54
-     * @var Connection
55
-     */
56
-    private $connection;
57
-
58
-    /**
59
-     * @var SchemaAnalyzer
60
-     */
61
-    private $schemaAnalyzer;
62
-
63
-    /**
64
-     * @var MagicQuery
65
-     */
66
-    private $magicQuery;
67
-
68
-    /**
69
-     * @var TDBMSchemaAnalyzer
70
-     */
71
-    private $tdbmSchemaAnalyzer;
72
-
73
-    /**
74
-     * @var string
75
-     */
76
-    private $cachePrefix;
77
-
78
-    /**
79
-     * Cache of table of primary keys.
80
-     * Primary keys are stored by tables, as an array of column.
81
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
82
-     *
83
-     * @var string[]
84
-     */
85
-    private $primaryKeysColumns;
86
-
87
-    /**
88
-     * Service storing objects in memory.
89
-     * Access is done by table name and then by primary key.
90
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
91
-     *
92
-     * @var StandardObjectStorage|WeakrefObjectStorage
93
-     */
94
-    private $objectStorage;
95
-
96
-    /**
97
-     * The fetch mode of the result sets returned by `getObjects`.
98
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
99
-     *
100
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
101
-     * 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,
102
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
103
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
104
-     * You can access the array by key, or using foreach, several times.
105
-     *
106
-     * @var int
107
-     */
108
-    private $mode = self::MODE_ARRAY;
109
-
110
-    /**
111
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
112
-     *
113
-     * @var \SplObjectStorage of DbRow objects
114
-     */
115
-    private $toSaveObjects;
116
-
117
-    /**
118
-     * A cache service to be used.
119
-     *
120
-     * @var Cache|null
121
-     */
122
-    private $cache;
123
-
124
-    /**
125
-     * Map associating a table name to a fully qualified Bean class name.
126
-     *
127
-     * @var array
128
-     */
129
-    private $tableToBeanMap = [];
130
-
131
-    /**
132
-     * @var \ReflectionClass[]
133
-     */
134
-    private $reflectionClassCache = array();
135
-
136
-    /**
137
-     * @var LoggerInterface
138
-     */
139
-    private $rootLogger;
140
-
141
-    /**
142
-     * @var MinLogLevelFilter|NullLogger
143
-     */
144
-    private $logger;
145
-
146
-    /**
147
-     * @var OrderByAnalyzer
148
-     */
149
-    private $orderByAnalyzer;
150
-
151
-    /**
152
-     * @param Connection     $connection     The DBAL DB connection to use
153
-     * @param Cache|null     $cache          A cache service to be used
154
-     * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
155
-     *                                       Will be automatically created if not passed
156
-     */
157
-    public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
158
-    {
159
-        if (extension_loaded('weakref')) {
160
-            $this->objectStorage = new WeakrefObjectStorage();
161
-        } else {
162
-            $this->objectStorage = new StandardObjectStorage();
163
-        }
164
-        $this->connection = $connection;
165
-        if ($cache !== null) {
166
-            $this->cache = $cache;
167
-        } else {
168
-            $this->cache = new VoidCache();
169
-        }
170
-        if ($schemaAnalyzer) {
171
-            $this->schemaAnalyzer = $schemaAnalyzer;
172
-        } else {
173
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
174
-        }
175
-
176
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
177
-
178
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
179
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
180
-
181
-        $this->toSaveObjects = new \SplObjectStorage();
182
-        if ($logger === null) {
183
-            $this->logger = new NullLogger();
184
-            $this->rootLogger = new NullLogger();
185
-        } else {
186
-            $this->rootLogger = $logger;
187
-            $this->setLogLevel(LogLevel::WARNING);
188
-        }
189
-        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
190
-    }
191
-
192
-    /**
193
-     * Returns the object used to connect to the database.
194
-     *
195
-     * @return Connection
196
-     */
197
-    public function getConnection()
198
-    {
199
-        return $this->connection;
200
-    }
201
-
202
-    /**
203
-     * Creates a unique cache key for the current connection.
204
-     *
205
-     * @return string
206
-     */
207
-    private function getConnectionUniqueId()
208
-    {
209
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
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
-     * Returns a TDBMObject associated from table "$table_name".
238
-     * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
239
-     * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
240
-     *
241
-     * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
242
-     * 			$user = $tdbmService->getObject('users',1);
243
-     * 			echo $user->name;
244
-     * will return the name of the user whose user_id is one.
245
-     *
246
-     * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
247
-     * For instance:
248
-     * 			$group = $tdbmService->getObject('groups',array(1,2));
249
-     *
250
-     * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
251
-     * will be the same.
252
-     *
253
-     * For instance:
254
-     * 			$user1 = $tdbmService->getObject('users',1);
255
-     * 			$user2 = $tdbmService->getObject('users',1);
256
-     * 			$user1->name = 'John Doe';
257
-     * 			echo $user2->name;
258
-     * will return 'John Doe'.
259
-     *
260
-     * You can use filters instead of passing the primary key. For instance:
261
-     * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
262
-     * This will return the user whose login is 'jdoe'.
263
-     * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
264
-     *
265
-     * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
266
-     * For instance:
267
-     *  	$user = $tdbmService->getObject('users',1,'User');
268
-     * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
269
-     * Please be sure not to override any method or any property unless you perfectly know what you are doing!
270
-     *
271
-     * @param string $table_name   The name of the table we retrieve an object from
272
-     * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
273
-     * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
274
-     * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
275
-     *
276
-     * @return TDBMObject
277
-     */
48
+	const MODE_CURSOR = 1;
49
+	const MODE_ARRAY = 2;
50
+
51
+	/**
52
+	 * The database connection.
53
+	 *
54
+	 * @var Connection
55
+	 */
56
+	private $connection;
57
+
58
+	/**
59
+	 * @var SchemaAnalyzer
60
+	 */
61
+	private $schemaAnalyzer;
62
+
63
+	/**
64
+	 * @var MagicQuery
65
+	 */
66
+	private $magicQuery;
67
+
68
+	/**
69
+	 * @var TDBMSchemaAnalyzer
70
+	 */
71
+	private $tdbmSchemaAnalyzer;
72
+
73
+	/**
74
+	 * @var string
75
+	 */
76
+	private $cachePrefix;
77
+
78
+	/**
79
+	 * Cache of table of primary keys.
80
+	 * Primary keys are stored by tables, as an array of column.
81
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
82
+	 *
83
+	 * @var string[]
84
+	 */
85
+	private $primaryKeysColumns;
86
+
87
+	/**
88
+	 * Service storing objects in memory.
89
+	 * Access is done by table name and then by primary key.
90
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
91
+	 *
92
+	 * @var StandardObjectStorage|WeakrefObjectStorage
93
+	 */
94
+	private $objectStorage;
95
+
96
+	/**
97
+	 * The fetch mode of the result sets returned by `getObjects`.
98
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
99
+	 *
100
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
101
+	 * 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,
102
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
103
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
104
+	 * You can access the array by key, or using foreach, several times.
105
+	 *
106
+	 * @var int
107
+	 */
108
+	private $mode = self::MODE_ARRAY;
109
+
110
+	/**
111
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
112
+	 *
113
+	 * @var \SplObjectStorage of DbRow objects
114
+	 */
115
+	private $toSaveObjects;
116
+
117
+	/**
118
+	 * A cache service to be used.
119
+	 *
120
+	 * @var Cache|null
121
+	 */
122
+	private $cache;
123
+
124
+	/**
125
+	 * Map associating a table name to a fully qualified Bean class name.
126
+	 *
127
+	 * @var array
128
+	 */
129
+	private $tableToBeanMap = [];
130
+
131
+	/**
132
+	 * @var \ReflectionClass[]
133
+	 */
134
+	private $reflectionClassCache = array();
135
+
136
+	/**
137
+	 * @var LoggerInterface
138
+	 */
139
+	private $rootLogger;
140
+
141
+	/**
142
+	 * @var MinLogLevelFilter|NullLogger
143
+	 */
144
+	private $logger;
145
+
146
+	/**
147
+	 * @var OrderByAnalyzer
148
+	 */
149
+	private $orderByAnalyzer;
150
+
151
+	/**
152
+	 * @param Connection     $connection     The DBAL DB connection to use
153
+	 * @param Cache|null     $cache          A cache service to be used
154
+	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
155
+	 *                                       Will be automatically created if not passed
156
+	 */
157
+	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
158
+	{
159
+		if (extension_loaded('weakref')) {
160
+			$this->objectStorage = new WeakrefObjectStorage();
161
+		} else {
162
+			$this->objectStorage = new StandardObjectStorage();
163
+		}
164
+		$this->connection = $connection;
165
+		if ($cache !== null) {
166
+			$this->cache = $cache;
167
+		} else {
168
+			$this->cache = new VoidCache();
169
+		}
170
+		if ($schemaAnalyzer) {
171
+			$this->schemaAnalyzer = $schemaAnalyzer;
172
+		} else {
173
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
174
+		}
175
+
176
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
177
+
178
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
179
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
180
+
181
+		$this->toSaveObjects = new \SplObjectStorage();
182
+		if ($logger === null) {
183
+			$this->logger = new NullLogger();
184
+			$this->rootLogger = new NullLogger();
185
+		} else {
186
+			$this->rootLogger = $logger;
187
+			$this->setLogLevel(LogLevel::WARNING);
188
+		}
189
+		$this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
190
+	}
191
+
192
+	/**
193
+	 * Returns the object used to connect to the database.
194
+	 *
195
+	 * @return Connection
196
+	 */
197
+	public function getConnection()
198
+	{
199
+		return $this->connection;
200
+	}
201
+
202
+	/**
203
+	 * Creates a unique cache key for the current connection.
204
+	 *
205
+	 * @return string
206
+	 */
207
+	private function getConnectionUniqueId()
208
+	{
209
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
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
+	 * Returns a TDBMObject associated from table "$table_name".
238
+	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
239
+	 * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
240
+	 *
241
+	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
242
+	 * 			$user = $tdbmService->getObject('users',1);
243
+	 * 			echo $user->name;
244
+	 * will return the name of the user whose user_id is one.
245
+	 *
246
+	 * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
247
+	 * For instance:
248
+	 * 			$group = $tdbmService->getObject('groups',array(1,2));
249
+	 *
250
+	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
251
+	 * will be the same.
252
+	 *
253
+	 * For instance:
254
+	 * 			$user1 = $tdbmService->getObject('users',1);
255
+	 * 			$user2 = $tdbmService->getObject('users',1);
256
+	 * 			$user1->name = 'John Doe';
257
+	 * 			echo $user2->name;
258
+	 * will return 'John Doe'.
259
+	 *
260
+	 * You can use filters instead of passing the primary key. For instance:
261
+	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
262
+	 * This will return the user whose login is 'jdoe'.
263
+	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
264
+	 *
265
+	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
266
+	 * For instance:
267
+	 *  	$user = $tdbmService->getObject('users',1,'User');
268
+	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
269
+	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
270
+	 *
271
+	 * @param string $table_name   The name of the table we retrieve an object from
272
+	 * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
273
+	 * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
274
+	 * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
275
+	 *
276
+	 * @return TDBMObject
277
+	 */
278 278
 /*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
279 279
 
280 280
         if (is_array($filters) || $filters instanceof FilterInterface) {
@@ -360,199 +360,199 @@  discard block
 block discarded – undo
360 360
         return $obj;
361 361
     }*/
362 362
 
363
-    /**
364
-     * Removes the given object from database.
365
-     * This cannot be called on an object that is not attached to this TDBMService
366
-     * (will throw a TDBMInvalidOperationException).
367
-     *
368
-     * @param AbstractTDBMObject $object the object to delete
369
-     *
370
-     * @throws TDBMException
371
-     * @throws TDBMInvalidOperationException
372
-     */
373
-    public function delete(AbstractTDBMObject $object)
374
-    {
375
-        switch ($object->_getStatus()) {
376
-            case TDBMObjectStateEnum::STATE_DELETED:
377
-                // Nothing to do, object already deleted.
378
-                return;
379
-            case TDBMObjectStateEnum::STATE_DETACHED:
380
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
381
-            case TDBMObjectStateEnum::STATE_NEW:
382
-                $this->deleteManyToManyRelationships($object);
383
-                foreach ($object->_getDbRows() as $dbRow) {
384
-                    $this->removeFromToSaveObjectList($dbRow);
385
-                }
386
-                break;
387
-            case TDBMObjectStateEnum::STATE_DIRTY:
388
-                foreach ($object->_getDbRows() as $dbRow) {
389
-                    $this->removeFromToSaveObjectList($dbRow);
390
-                }
391
-                // And continue deleting...
392
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
393
-            case TDBMObjectStateEnum::STATE_LOADED:
394
-                $this->deleteManyToManyRelationships($object);
395
-                // Let's delete db rows, in reverse order.
396
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
397
-                    $tableName = $dbRow->_getDbTableName();
398
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
399
-                    $this->connection->delete($tableName, $primaryKeys);
400
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
401
-                }
402
-                break;
403
-            // @codeCoverageIgnoreStart
404
-            default:
405
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
406
-            // @codeCoverageIgnoreEnd
407
-        }
408
-
409
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
410
-    }
411
-
412
-    /**
413
-     * Removes all many to many relationships for this object.
414
-     *
415
-     * @param AbstractTDBMObject $object
416
-     */
417
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
418
-    {
419
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
420
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
421
-            foreach ($pivotTables as $pivotTable) {
422
-                $remoteBeans = $object->_getRelationships($pivotTable);
423
-                foreach ($remoteBeans as $remoteBean) {
424
-                    $object->_removeRelationship($pivotTable, $remoteBean);
425
-                }
426
-            }
427
-        }
428
-        $this->persistManyToManyRelationships($object);
429
-    }
430
-
431
-    /**
432
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
433
-     * by parameter before all.
434
-     *
435
-     * Notice: if the object has a multiple primary key, the function will not work.
436
-     *
437
-     * @param AbstractTDBMObject $objToDelete
438
-     */
439
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
440
-    {
441
-        $this->deleteAllConstraintWithThisObject($objToDelete);
442
-        $this->delete($objToDelete);
443
-    }
444
-
445
-    /**
446
-     * This function is used only in TDBMService (private function)
447
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
448
-     *
449
-     * @param AbstractTDBMObject $obj
450
-     */
451
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
452
-    {
453
-        $dbRows = $obj->_getDbRows();
454
-        foreach ($dbRows as $dbRow) {
455
-            $tableName = $dbRow->_getDbTableName();
456
-            $pks = array_values($dbRow->_getPrimaryKeys());
457
-            if (!empty($pks)) {
458
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
459
-
460
-                foreach ($incomingFks as $incomingFk) {
461
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
462
-
463
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
464
-
465
-                    foreach ($results as $bean) {
466
-                        $this->deleteCascade($bean);
467
-                    }
468
-                }
469
-            }
470
-        }
471
-    }
472
-
473
-    /**
474
-     * This function performs a save() of all the objects that have been modified.
475
-     */
476
-    public function completeSave()
477
-    {
478
-        foreach ($this->toSaveObjects as $dbRow) {
479
-            $this->save($dbRow->getTDBMObject());
480
-        }
481
-    }
482
-
483
-    /**
484
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
485
-     * and gives back a proper Filter object.
486
-     *
487
-     * @param mixed $filter_bag
488
-     * @param int   $counter
489
-     *
490
-     * @return array First item: filter string, second item: parameters
491
-     *
492
-     * @throws TDBMException
493
-     */
494
-    public function buildFilterFromFilterBag($filter_bag, $counter = 1)
495
-    {
496
-        if ($filter_bag === null) {
497
-            return ['', []];
498
-        } elseif (is_string($filter_bag)) {
499
-            return [$filter_bag, []];
500
-        } elseif (is_array($filter_bag)) {
501
-            $sqlParts = [];
502
-            $parameters = [];
503
-            foreach ($filter_bag as $column => $value) {
504
-                if (is_int($column)) {
505
-                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
506
-                    $sqlParts[] = $subSqlPart;
507
-                    $parameters += $subParameters;
508
-                } else {
509
-                    $paramName = 'tdbmparam'.$counter;
510
-                    if (is_array($value)) {
511
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
512
-                    } else {
513
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
514
-                    }
515
-                    $parameters[$paramName] = $value;
516
-                    ++$counter;
517
-                }
518
-            }
519
-
520
-            return [implode(' AND ', $sqlParts), $parameters];
521
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
522
-            $sqlParts = [];
523
-            $parameters = [];
524
-            $dbRows = $filter_bag->_getDbRows();
525
-            $dbRow = reset($dbRows);
526
-            $primaryKeys = $dbRow->_getPrimaryKeys();
527
-
528
-            foreach ($primaryKeys as $column => $value) {
529
-                $paramName = 'tdbmparam'.$counter;
530
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
531
-                $parameters[$paramName] = $value;
532
-                ++$counter;
533
-            }
534
-
535
-            return [implode(' AND ', $sqlParts), $parameters];
536
-        } elseif ($filter_bag instanceof \Iterator) {
537
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
538
-        } else {
539
-            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.');
540
-        }
541
-    }
542
-
543
-    /**
544
-     * @param string $table
545
-     *
546
-     * @return string[]
547
-     */
548
-    public function getPrimaryKeyColumns($table)
549
-    {
550
-        if (!isset($this->primaryKeysColumns[$table])) {
551
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
552
-
553
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
554
-
555
-            /*$arr = array();
363
+	/**
364
+	 * Removes the given object from database.
365
+	 * This cannot be called on an object that is not attached to this TDBMService
366
+	 * (will throw a TDBMInvalidOperationException).
367
+	 *
368
+	 * @param AbstractTDBMObject $object the object to delete
369
+	 *
370
+	 * @throws TDBMException
371
+	 * @throws TDBMInvalidOperationException
372
+	 */
373
+	public function delete(AbstractTDBMObject $object)
374
+	{
375
+		switch ($object->_getStatus()) {
376
+			case TDBMObjectStateEnum::STATE_DELETED:
377
+				// Nothing to do, object already deleted.
378
+				return;
379
+			case TDBMObjectStateEnum::STATE_DETACHED:
380
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
381
+			case TDBMObjectStateEnum::STATE_NEW:
382
+				$this->deleteManyToManyRelationships($object);
383
+				foreach ($object->_getDbRows() as $dbRow) {
384
+					$this->removeFromToSaveObjectList($dbRow);
385
+				}
386
+				break;
387
+			case TDBMObjectStateEnum::STATE_DIRTY:
388
+				foreach ($object->_getDbRows() as $dbRow) {
389
+					$this->removeFromToSaveObjectList($dbRow);
390
+				}
391
+				// And continue deleting...
392
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
393
+			case TDBMObjectStateEnum::STATE_LOADED:
394
+				$this->deleteManyToManyRelationships($object);
395
+				// Let's delete db rows, in reverse order.
396
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
397
+					$tableName = $dbRow->_getDbTableName();
398
+					$primaryKeys = $dbRow->_getPrimaryKeys();
399
+					$this->connection->delete($tableName, $primaryKeys);
400
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
401
+				}
402
+				break;
403
+			// @codeCoverageIgnoreStart
404
+			default:
405
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
406
+			// @codeCoverageIgnoreEnd
407
+		}
408
+
409
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
410
+	}
411
+
412
+	/**
413
+	 * Removes all many to many relationships for this object.
414
+	 *
415
+	 * @param AbstractTDBMObject $object
416
+	 */
417
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
418
+	{
419
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
420
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
421
+			foreach ($pivotTables as $pivotTable) {
422
+				$remoteBeans = $object->_getRelationships($pivotTable);
423
+				foreach ($remoteBeans as $remoteBean) {
424
+					$object->_removeRelationship($pivotTable, $remoteBean);
425
+				}
426
+			}
427
+		}
428
+		$this->persistManyToManyRelationships($object);
429
+	}
430
+
431
+	/**
432
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
433
+	 * by parameter before all.
434
+	 *
435
+	 * Notice: if the object has a multiple primary key, the function will not work.
436
+	 *
437
+	 * @param AbstractTDBMObject $objToDelete
438
+	 */
439
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
440
+	{
441
+		$this->deleteAllConstraintWithThisObject($objToDelete);
442
+		$this->delete($objToDelete);
443
+	}
444
+
445
+	/**
446
+	 * This function is used only in TDBMService (private function)
447
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
448
+	 *
449
+	 * @param AbstractTDBMObject $obj
450
+	 */
451
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
452
+	{
453
+		$dbRows = $obj->_getDbRows();
454
+		foreach ($dbRows as $dbRow) {
455
+			$tableName = $dbRow->_getDbTableName();
456
+			$pks = array_values($dbRow->_getPrimaryKeys());
457
+			if (!empty($pks)) {
458
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
459
+
460
+				foreach ($incomingFks as $incomingFk) {
461
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
462
+
463
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
464
+
465
+					foreach ($results as $bean) {
466
+						$this->deleteCascade($bean);
467
+					}
468
+				}
469
+			}
470
+		}
471
+	}
472
+
473
+	/**
474
+	 * This function performs a save() of all the objects that have been modified.
475
+	 */
476
+	public function completeSave()
477
+	{
478
+		foreach ($this->toSaveObjects as $dbRow) {
479
+			$this->save($dbRow->getTDBMObject());
480
+		}
481
+	}
482
+
483
+	/**
484
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
485
+	 * and gives back a proper Filter object.
486
+	 *
487
+	 * @param mixed $filter_bag
488
+	 * @param int   $counter
489
+	 *
490
+	 * @return array First item: filter string, second item: parameters
491
+	 *
492
+	 * @throws TDBMException
493
+	 */
494
+	public function buildFilterFromFilterBag($filter_bag, $counter = 1)
495
+	{
496
+		if ($filter_bag === null) {
497
+			return ['', []];
498
+		} elseif (is_string($filter_bag)) {
499
+			return [$filter_bag, []];
500
+		} elseif (is_array($filter_bag)) {
501
+			$sqlParts = [];
502
+			$parameters = [];
503
+			foreach ($filter_bag as $column => $value) {
504
+				if (is_int($column)) {
505
+					list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
506
+					$sqlParts[] = $subSqlPart;
507
+					$parameters += $subParameters;
508
+				} else {
509
+					$paramName = 'tdbmparam'.$counter;
510
+					if (is_array($value)) {
511
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
512
+					} else {
513
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
514
+					}
515
+					$parameters[$paramName] = $value;
516
+					++$counter;
517
+				}
518
+			}
519
+
520
+			return [implode(' AND ', $sqlParts), $parameters];
521
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
522
+			$sqlParts = [];
523
+			$parameters = [];
524
+			$dbRows = $filter_bag->_getDbRows();
525
+			$dbRow = reset($dbRows);
526
+			$primaryKeys = $dbRow->_getPrimaryKeys();
527
+
528
+			foreach ($primaryKeys as $column => $value) {
529
+				$paramName = 'tdbmparam'.$counter;
530
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
531
+				$parameters[$paramName] = $value;
532
+				++$counter;
533
+			}
534
+
535
+			return [implode(' AND ', $sqlParts), $parameters];
536
+		} elseif ($filter_bag instanceof \Iterator) {
537
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
538
+		} else {
539
+			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.');
540
+		}
541
+	}
542
+
543
+	/**
544
+	 * @param string $table
545
+	 *
546
+	 * @return string[]
547
+	 */
548
+	public function getPrimaryKeyColumns($table)
549
+	{
550
+		if (!isset($this->primaryKeysColumns[$table])) {
551
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
552
+
553
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
554
+
555
+			/*$arr = array();
556 556
             foreach ($this->connection->getPrimaryKey($table) as $col) {
557 557
                 $arr[] = $col->name;
558 558
             }
@@ -573,141 +573,141 @@  discard block
 block discarded – undo
573 573
                     throw new TDBMException($str);
574 574
                 }
575 575
             }*/
576
-        }
577
-
578
-        return $this->primaryKeysColumns[$table];
579
-    }
580
-
581
-    /**
582
-     * This is an internal function, you should not use it in your application.
583
-     * This is used internally by TDBM to add an object to the object cache.
584
-     *
585
-     * @param DbRow $dbRow
586
-     */
587
-    public function _addToCache(DbRow $dbRow)
588
-    {
589
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
590
-        $hash = $this->getObjectHash($primaryKey);
591
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
592
-    }
593
-
594
-    /**
595
-     * This is an internal function, you should not use it in your application.
596
-     * This is used internally by TDBM to remove the object from the list of objects that have been
597
-     * created/updated but not saved yet.
598
-     *
599
-     * @param DbRow $myObject
600
-     */
601
-    private function removeFromToSaveObjectList(DbRow $myObject)
602
-    {
603
-        unset($this->toSaveObjects[$myObject]);
604
-    }
605
-
606
-    /**
607
-     * This is an internal function, you should not use it in your application.
608
-     * This is used internally by TDBM to add an object to the list of objects that have been
609
-     * created/updated but not saved yet.
610
-     *
611
-     * @param AbstractTDBMObject $myObject
612
-     */
613
-    public function _addToToSaveObjectList(DbRow $myObject)
614
-    {
615
-        $this->toSaveObjects[$myObject] = true;
616
-    }
617
-
618
-    /**
619
-     * Generates all the daos and beans.
620
-     *
621
-     * @param string $daoFactoryClassName The classe name of the DAO factory
622
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
623
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
624
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
625
-     * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
626
-     *
627
-     * @return \string[] the list of tables
628
-     */
629
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
630
-    {
631
-        // Purge cache before generating anything.
632
-        $this->cache->deleteAll();
633
-
634
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
635
-        if (null !== $composerFile) {
636
-            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
637
-        }
638
-
639
-        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
640
-    }
641
-
642
-    /**
643
-     * @param array<string, string> $tableToBeanMap
644
-     */
645
-    public function setTableToBeanMap(array $tableToBeanMap)
646
-    {
647
-        $this->tableToBeanMap = $tableToBeanMap;
648
-    }
649
-
650
-    /**
651
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
652
-     *
653
-     * @param AbstractTDBMObject $object
654
-     *
655
-     * @throws TDBMException
656
-     */
657
-    public function save(AbstractTDBMObject $object)
658
-    {
659
-        $status = $object->_getStatus();
660
-
661
-        if ($status === null) {
662
-            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)));
663
-        }
664
-
665
-        // Let's attach this object if it is in detached state.
666
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
667
-            $object->_attach($this);
668
-            $status = $object->_getStatus();
669
-        }
670
-
671
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
672
-            $dbRows = $object->_getDbRows();
673
-
674
-            $unindexedPrimaryKeys = array();
675
-
676
-            foreach ($dbRows as $dbRow) {
677
-                $tableName = $dbRow->_getDbTableName();
678
-
679
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
680
-                $tableDescriptor = $schema->getTable($tableName);
681
-
682
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
683
-
684
-                if (empty($unindexedPrimaryKeys)) {
685
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
686
-                } else {
687
-                    // First insert, the children must have the same primary key as the parent.
688
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
689
-                    $dbRow->_setPrimaryKeys($primaryKeys);
690
-                }
691
-
692
-                $references = $dbRow->_getReferences();
693
-
694
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
695
-                foreach ($references as $fkName => $reference) {
696
-                    if ($reference !== null) {
697
-                        $refStatus = $reference->_getStatus();
698
-                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
699
-                            $this->save($reference);
700
-                        }
701
-                    }
702
-                }
703
-
704
-                $dbRowData = $dbRow->_getDbRow();
705
-
706
-                // Let's see if the columns for primary key have been set before inserting.
707
-                // We assume that if one of the value of the PK has been set, the PK is set.
708
-                $isPkSet = !empty($primaryKeys);
709
-
710
-                /*if (!$isPkSet) {
576
+		}
577
+
578
+		return $this->primaryKeysColumns[$table];
579
+	}
580
+
581
+	/**
582
+	 * This is an internal function, you should not use it in your application.
583
+	 * This is used internally by TDBM to add an object to the object cache.
584
+	 *
585
+	 * @param DbRow $dbRow
586
+	 */
587
+	public function _addToCache(DbRow $dbRow)
588
+	{
589
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
590
+		$hash = $this->getObjectHash($primaryKey);
591
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
592
+	}
593
+
594
+	/**
595
+	 * This is an internal function, you should not use it in your application.
596
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
597
+	 * created/updated but not saved yet.
598
+	 *
599
+	 * @param DbRow $myObject
600
+	 */
601
+	private function removeFromToSaveObjectList(DbRow $myObject)
602
+	{
603
+		unset($this->toSaveObjects[$myObject]);
604
+	}
605
+
606
+	/**
607
+	 * This is an internal function, you should not use it in your application.
608
+	 * This is used internally by TDBM to add an object to the list of objects that have been
609
+	 * created/updated but not saved yet.
610
+	 *
611
+	 * @param AbstractTDBMObject $myObject
612
+	 */
613
+	public function _addToToSaveObjectList(DbRow $myObject)
614
+	{
615
+		$this->toSaveObjects[$myObject] = true;
616
+	}
617
+
618
+	/**
619
+	 * Generates all the daos and beans.
620
+	 *
621
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
622
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
623
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
624
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
625
+	 * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
626
+	 *
627
+	 * @return \string[] the list of tables
628
+	 */
629
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
630
+	{
631
+		// Purge cache before generating anything.
632
+		$this->cache->deleteAll();
633
+
634
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
635
+		if (null !== $composerFile) {
636
+			$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
637
+		}
638
+
639
+		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
640
+	}
641
+
642
+	/**
643
+	 * @param array<string, string> $tableToBeanMap
644
+	 */
645
+	public function setTableToBeanMap(array $tableToBeanMap)
646
+	{
647
+		$this->tableToBeanMap = $tableToBeanMap;
648
+	}
649
+
650
+	/**
651
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
652
+	 *
653
+	 * @param AbstractTDBMObject $object
654
+	 *
655
+	 * @throws TDBMException
656
+	 */
657
+	public function save(AbstractTDBMObject $object)
658
+	{
659
+		$status = $object->_getStatus();
660
+
661
+		if ($status === null) {
662
+			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)));
663
+		}
664
+
665
+		// Let's attach this object if it is in detached state.
666
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
667
+			$object->_attach($this);
668
+			$status = $object->_getStatus();
669
+		}
670
+
671
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
672
+			$dbRows = $object->_getDbRows();
673
+
674
+			$unindexedPrimaryKeys = array();
675
+
676
+			foreach ($dbRows as $dbRow) {
677
+				$tableName = $dbRow->_getDbTableName();
678
+
679
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
680
+				$tableDescriptor = $schema->getTable($tableName);
681
+
682
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
683
+
684
+				if (empty($unindexedPrimaryKeys)) {
685
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
686
+				} else {
687
+					// First insert, the children must have the same primary key as the parent.
688
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
689
+					$dbRow->_setPrimaryKeys($primaryKeys);
690
+				}
691
+
692
+				$references = $dbRow->_getReferences();
693
+
694
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
695
+				foreach ($references as $fkName => $reference) {
696
+					if ($reference !== null) {
697
+						$refStatus = $reference->_getStatus();
698
+						if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
699
+							$this->save($reference);
700
+						}
701
+					}
702
+				}
703
+
704
+				$dbRowData = $dbRow->_getDbRow();
705
+
706
+				// Let's see if the columns for primary key have been set before inserting.
707
+				// We assume that if one of the value of the PK has been set, the PK is set.
708
+				$isPkSet = !empty($primaryKeys);
709
+
710
+				/*if (!$isPkSet) {
711 711
                     // if there is no autoincrement and no pk set, let's go in error.
712 712
                     $isAutoIncrement = true;
713 713
 
@@ -725,27 +725,27 @@  discard block
 block discarded – undo
725 725
 
726 726
                 }*/
727 727
 
728
-                $types = [];
729
-                $escapedDbRowData = [];
728
+				$types = [];
729
+				$escapedDbRowData = [];
730 730
 
731
-                foreach ($dbRowData as $columnName => $value) {
732
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
733
-                    $types[] = $columnDescriptor->getType();
734
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
735
-                }
731
+				foreach ($dbRowData as $columnName => $value) {
732
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
733
+					$types[] = $columnDescriptor->getType();
734
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
735
+				}
736 736
 
737
-                $this->connection->insert($tableName, $escapedDbRowData, $types);
737
+				$this->connection->insert($tableName, $escapedDbRowData, $types);
738 738
 
739
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
740
-                    $id = $this->connection->lastInsertId();
741
-                    $primaryKeys[$primaryKeyColumns[0]] = $id;
742
-                }
739
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
740
+					$id = $this->connection->lastInsertId();
741
+					$primaryKeys[$primaryKeyColumns[0]] = $id;
742
+				}
743 743
 
744
-                // TODO: change this to some private magic accessor in future
745
-                $dbRow->_setPrimaryKeys($primaryKeys);
746
-                $unindexedPrimaryKeys = array_values($primaryKeys);
744
+				// TODO: change this to some private magic accessor in future
745
+				$dbRow->_setPrimaryKeys($primaryKeys);
746
+				$unindexedPrimaryKeys = array_values($primaryKeys);
747 747
 
748
-                /*
748
+				/*
749 749
                  * When attached, on "save", we check if the column updated is part of a primary key
750 750
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
751 751
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
                  *
756 756
                  */
757 757
 
758
-                /*try {
758
+				/*try {
759 759
                     $this->db_connection->exec($sql);
760 760
                 } catch (TDBMException $e) {
761 761
                     $this->db_onerror = true;
@@ -774,468 +774,468 @@  discard block
 block discarded – undo
774 774
                     }
775 775
                 }*/
776 776
 
777
-                // Let's remove this object from the $new_objects static table.
778
-                $this->removeFromToSaveObjectList($dbRow);
779
-
780
-                // TODO: change this behaviour to something more sensible performance-wise
781
-                // Maybe a setting to trigger this globally?
782
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
783
-                //$this->db_modified_state = false;
784
-                //$dbRow = array();
785
-
786
-                // Let's add this object to the list of objects in cache.
787
-                $this->_addToCache($dbRow);
788
-            }
789
-
790
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
791
-        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
792
-            $dbRows = $object->_getDbRows();
793
-
794
-            foreach ($dbRows as $dbRow) {
795
-                $references = $dbRow->_getReferences();
796
-
797
-                // Let's save all references in NEW state (we need their primary key)
798
-                foreach ($references as $fkName => $reference) {
799
-                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
800
-                        $this->save($reference);
801
-                    }
802
-                }
803
-
804
-                // Let's first get the primary keys
805
-                $tableName = $dbRow->_getDbTableName();
806
-                $dbRowData = $dbRow->_getDbRow();
807
-
808
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
809
-                $tableDescriptor = $schema->getTable($tableName);
810
-
811
-                $primaryKeys = $dbRow->_getPrimaryKeys();
812
-
813
-                $types = [];
814
-                $escapedDbRowData = [];
815
-                $escapedPrimaryKeys = [];
816
-
817
-                foreach ($dbRowData as $columnName => $value) {
818
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
819
-                    $types[] = $columnDescriptor->getType();
820
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
821
-                }
822
-                foreach ($primaryKeys as $columnName => $value) {
823
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
824
-                    $types[] = $columnDescriptor->getType();
825
-                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
826
-                }
827
-
828
-                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
829
-
830
-                // Let's check if the primary key has been updated...
831
-                $needsUpdatePk = false;
832
-                foreach ($primaryKeys as $column => $value) {
833
-                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
834
-                        $needsUpdatePk = true;
835
-                        break;
836
-                    }
837
-                }
838
-                if ($needsUpdatePk) {
839
-                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
840
-                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
841
-                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
842
-                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
843
-                }
844
-
845
-                // Let's remove this object from the list of objects to save.
846
-                $this->removeFromToSaveObjectList($dbRow);
847
-            }
848
-
849
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
850
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
851
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
852
-        }
853
-
854
-        // Finally, let's save all the many to many relationships to this bean.
855
-        $this->persistManyToManyRelationships($object);
856
-    }
857
-
858
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
859
-    {
860
-        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
861
-            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
862
-            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
863
-
864
-            $toRemoveFromStorage = [];
865
-
866
-            foreach ($storage as $remoteBean) {
867
-                /* @var $remoteBean AbstractTDBMObject */
868
-                $statusArr = $storage[$remoteBean];
869
-                $status = $statusArr['status'];
870
-                $reverse = $statusArr['reverse'];
871
-                if ($reverse) {
872
-                    continue;
873
-                }
874
-
875
-                if ($status === 'new') {
876
-                    $remoteBeanStatus = $remoteBean->_getStatus();
877
-                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
878
-                        // Let's save remote bean if needed.
879
-                        $this->save($remoteBean);
880
-                    }
881
-
882
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
883
-
884
-                    $types = [];
885
-                    $escapedFilters = [];
886
-
887
-                    foreach ($filters as $columnName => $value) {
888
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
889
-                        $types[] = $columnDescriptor->getType();
890
-                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
891
-                    }
892
-
893
-                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
894
-
895
-                    // Finally, let's mark relationships as saved.
896
-                    $statusArr['status'] = 'loaded';
897
-                    $storage[$remoteBean] = $statusArr;
898
-                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
899
-                    $remoteStatusArr = $remoteStorage[$object];
900
-                    $remoteStatusArr['status'] = 'loaded';
901
-                    $remoteStorage[$object] = $remoteStatusArr;
902
-                } elseif ($status === 'delete') {
903
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
904
-
905
-                    $types = [];
906
-
907
-                    foreach ($filters as $columnName => $value) {
908
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
909
-                        $types[] = $columnDescriptor->getType();
910
-                    }
911
-
912
-                    $this->connection->delete($pivotTableName, $filters, $types);
913
-
914
-                    // Finally, let's remove relationships completely from bean.
915
-                    $toRemoveFromStorage[] = $remoteBean;
916
-
917
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
918
-                }
919
-            }
920
-
921
-            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
922
-            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
923
-            foreach ($toRemoveFromStorage as $remoteBean) {
924
-                $storage->detach($remoteBean);
925
-            }
926
-        }
927
-    }
928
-
929
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
930
-    {
931
-        $localBeanPk = $this->getPrimaryKeyValues($localBean);
932
-        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
933
-        $localColumns = $localFk->getLocalColumns();
934
-        $remoteColumns = $remoteFk->getLocalColumns();
935
-
936
-        $localFilters = array_combine($localColumns, $localBeanPk);
937
-        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
938
-
939
-        return array_merge($localFilters, $remoteFilters);
940
-    }
941
-
942
-    /**
943
-     * Returns the "values" of the primary key.
944
-     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
945
-     *
946
-     * @param AbstractTDBMObject $bean
947
-     *
948
-     * @return array numerically indexed array of values
949
-     */
950
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
951
-    {
952
-        $dbRows = $bean->_getDbRows();
953
-        $dbRow = reset($dbRows);
954
-
955
-        return array_values($dbRow->_getPrimaryKeys());
956
-    }
957
-
958
-    /**
959
-     * Returns a unique hash used to store the object based on its primary key.
960
-     * If the array contains only one value, then the value is returned.
961
-     * Otherwise, a hash representing the array is returned.
962
-     *
963
-     * @param array $primaryKeys An array of columns => values forming the primary key
964
-     *
965
-     * @return string
966
-     */
967
-    public function getObjectHash(array $primaryKeys)
968
-    {
969
-        if (count($primaryKeys) === 1) {
970
-            return reset($primaryKeys);
971
-        } else {
972
-            ksort($primaryKeys);
973
-
974
-            return md5(json_encode($primaryKeys));
975
-        }
976
-    }
977
-
978
-    /**
979
-     * Returns an array of primary keys from the object.
980
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
981
-     * $primaryKeys variable of the object.
982
-     *
983
-     * @param DbRow $dbRow
984
-     *
985
-     * @return array Returns an array of column => value
986
-     */
987
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
988
-    {
989
-        $table = $dbRow->_getDbTableName();
990
-        $dbRowData = $dbRow->_getDbRow();
991
-
992
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
993
-    }
994
-
995
-    /**
996
-     * Returns an array of primary keys for the given row.
997
-     * The primary keys are extracted from the object columns.
998
-     *
999
-     * @param $table
1000
-     * @param array $columns
1001
-     *
1002
-     * @return array
1003
-     */
1004
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
1005
-    {
1006
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1007
-        $values = array();
1008
-        foreach ($primaryKeyColumns as $column) {
1009
-            if (isset($columns[$column])) {
1010
-                $values[$column] = $columns[$column];
1011
-            }
1012
-        }
1013
-
1014
-        return $values;
1015
-    }
1016
-
1017
-    /**
1018
-     * Attaches $object to this TDBMService.
1019
-     * The $object must be in DETACHED state and will pass in NEW state.
1020
-     *
1021
-     * @param AbstractTDBMObject $object
1022
-     *
1023
-     * @throws TDBMInvalidOperationException
1024
-     */
1025
-    public function attach(AbstractTDBMObject $object)
1026
-    {
1027
-        $object->_attach($this);
1028
-    }
1029
-
1030
-    /**
1031
-     * Returns an associative array (column => value) for the primary keys from the table name and an
1032
-     * indexed array of primary key values.
1033
-     *
1034
-     * @param string $tableName
1035
-     * @param array  $indexedPrimaryKeys
1036
-     */
1037
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1038
-    {
1039
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1040
-
1041
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1042
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
777
+				// Let's remove this object from the $new_objects static table.
778
+				$this->removeFromToSaveObjectList($dbRow);
779
+
780
+				// TODO: change this behaviour to something more sensible performance-wise
781
+				// Maybe a setting to trigger this globally?
782
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
783
+				//$this->db_modified_state = false;
784
+				//$dbRow = array();
785
+
786
+				// Let's add this object to the list of objects in cache.
787
+				$this->_addToCache($dbRow);
788
+			}
789
+
790
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
791
+		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
792
+			$dbRows = $object->_getDbRows();
793
+
794
+			foreach ($dbRows as $dbRow) {
795
+				$references = $dbRow->_getReferences();
796
+
797
+				// Let's save all references in NEW state (we need their primary key)
798
+				foreach ($references as $fkName => $reference) {
799
+					if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
800
+						$this->save($reference);
801
+					}
802
+				}
803
+
804
+				// Let's first get the primary keys
805
+				$tableName = $dbRow->_getDbTableName();
806
+				$dbRowData = $dbRow->_getDbRow();
807
+
808
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
809
+				$tableDescriptor = $schema->getTable($tableName);
810
+
811
+				$primaryKeys = $dbRow->_getPrimaryKeys();
812
+
813
+				$types = [];
814
+				$escapedDbRowData = [];
815
+				$escapedPrimaryKeys = [];
816
+
817
+				foreach ($dbRowData as $columnName => $value) {
818
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
819
+					$types[] = $columnDescriptor->getType();
820
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
821
+				}
822
+				foreach ($primaryKeys as $columnName => $value) {
823
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
824
+					$types[] = $columnDescriptor->getType();
825
+					$escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
826
+				}
827
+
828
+				$this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
829
+
830
+				// Let's check if the primary key has been updated...
831
+				$needsUpdatePk = false;
832
+				foreach ($primaryKeys as $column => $value) {
833
+					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
834
+						$needsUpdatePk = true;
835
+						break;
836
+					}
837
+				}
838
+				if ($needsUpdatePk) {
839
+					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
840
+					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
841
+					$dbRow->_setPrimaryKeys($newPrimaryKeys);
842
+					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
843
+				}
844
+
845
+				// Let's remove this object from the list of objects to save.
846
+				$this->removeFromToSaveObjectList($dbRow);
847
+			}
848
+
849
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
850
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
851
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
852
+		}
853
+
854
+		// Finally, let's save all the many to many relationships to this bean.
855
+		$this->persistManyToManyRelationships($object);
856
+	}
857
+
858
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
859
+	{
860
+		foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
861
+			$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
862
+			list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
863
+
864
+			$toRemoveFromStorage = [];
865
+
866
+			foreach ($storage as $remoteBean) {
867
+				/* @var $remoteBean AbstractTDBMObject */
868
+				$statusArr = $storage[$remoteBean];
869
+				$status = $statusArr['status'];
870
+				$reverse = $statusArr['reverse'];
871
+				if ($reverse) {
872
+					continue;
873
+				}
874
+
875
+				if ($status === 'new') {
876
+					$remoteBeanStatus = $remoteBean->_getStatus();
877
+					if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
878
+						// Let's save remote bean if needed.
879
+						$this->save($remoteBean);
880
+					}
881
+
882
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
883
+
884
+					$types = [];
885
+					$escapedFilters = [];
886
+
887
+					foreach ($filters as $columnName => $value) {
888
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
889
+						$types[] = $columnDescriptor->getType();
890
+						$escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
891
+					}
892
+
893
+					$this->connection->insert($pivotTableName, $escapedFilters, $types);
894
+
895
+					// Finally, let's mark relationships as saved.
896
+					$statusArr['status'] = 'loaded';
897
+					$storage[$remoteBean] = $statusArr;
898
+					$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
899
+					$remoteStatusArr = $remoteStorage[$object];
900
+					$remoteStatusArr['status'] = 'loaded';
901
+					$remoteStorage[$object] = $remoteStatusArr;
902
+				} elseif ($status === 'delete') {
903
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
904
+
905
+					$types = [];
906
+
907
+					foreach ($filters as $columnName => $value) {
908
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
909
+						$types[] = $columnDescriptor->getType();
910
+					}
911
+
912
+					$this->connection->delete($pivotTableName, $filters, $types);
913
+
914
+					// Finally, let's remove relationships completely from bean.
915
+					$toRemoveFromStorage[] = $remoteBean;
916
+
917
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
918
+				}
919
+			}
920
+
921
+			// Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
922
+			// Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
923
+			foreach ($toRemoveFromStorage as $remoteBean) {
924
+				$storage->detach($remoteBean);
925
+			}
926
+		}
927
+	}
928
+
929
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
930
+	{
931
+		$localBeanPk = $this->getPrimaryKeyValues($localBean);
932
+		$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
933
+		$localColumns = $localFk->getLocalColumns();
934
+		$remoteColumns = $remoteFk->getLocalColumns();
935
+
936
+		$localFilters = array_combine($localColumns, $localBeanPk);
937
+		$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
938
+
939
+		return array_merge($localFilters, $remoteFilters);
940
+	}
941
+
942
+	/**
943
+	 * Returns the "values" of the primary key.
944
+	 * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
945
+	 *
946
+	 * @param AbstractTDBMObject $bean
947
+	 *
948
+	 * @return array numerically indexed array of values
949
+	 */
950
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
951
+	{
952
+		$dbRows = $bean->_getDbRows();
953
+		$dbRow = reset($dbRows);
954
+
955
+		return array_values($dbRow->_getPrimaryKeys());
956
+	}
957
+
958
+	/**
959
+	 * Returns a unique hash used to store the object based on its primary key.
960
+	 * If the array contains only one value, then the value is returned.
961
+	 * Otherwise, a hash representing the array is returned.
962
+	 *
963
+	 * @param array $primaryKeys An array of columns => values forming the primary key
964
+	 *
965
+	 * @return string
966
+	 */
967
+	public function getObjectHash(array $primaryKeys)
968
+	{
969
+		if (count($primaryKeys) === 1) {
970
+			return reset($primaryKeys);
971
+		} else {
972
+			ksort($primaryKeys);
973
+
974
+			return md5(json_encode($primaryKeys));
975
+		}
976
+	}
977
+
978
+	/**
979
+	 * Returns an array of primary keys from the object.
980
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
981
+	 * $primaryKeys variable of the object.
982
+	 *
983
+	 * @param DbRow $dbRow
984
+	 *
985
+	 * @return array Returns an array of column => value
986
+	 */
987
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
988
+	{
989
+		$table = $dbRow->_getDbTableName();
990
+		$dbRowData = $dbRow->_getDbRow();
991
+
992
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
993
+	}
994
+
995
+	/**
996
+	 * Returns an array of primary keys for the given row.
997
+	 * The primary keys are extracted from the object columns.
998
+	 *
999
+	 * @param $table
1000
+	 * @param array $columns
1001
+	 *
1002
+	 * @return array
1003
+	 */
1004
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
1005
+	{
1006
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1007
+		$values = array();
1008
+		foreach ($primaryKeyColumns as $column) {
1009
+			if (isset($columns[$column])) {
1010
+				$values[$column] = $columns[$column];
1011
+			}
1012
+		}
1013
+
1014
+		return $values;
1015
+	}
1016
+
1017
+	/**
1018
+	 * Attaches $object to this TDBMService.
1019
+	 * The $object must be in DETACHED state and will pass in NEW state.
1020
+	 *
1021
+	 * @param AbstractTDBMObject $object
1022
+	 *
1023
+	 * @throws TDBMInvalidOperationException
1024
+	 */
1025
+	public function attach(AbstractTDBMObject $object)
1026
+	{
1027
+		$object->_attach($this);
1028
+	}
1029
+
1030
+	/**
1031
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
1032
+	 * indexed array of primary key values.
1033
+	 *
1034
+	 * @param string $tableName
1035
+	 * @param array  $indexedPrimaryKeys
1036
+	 */
1037
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1038
+	{
1039
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1040
+
1041
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1042
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1043 1043
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1044
-        }
1045
-
1046
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1047
-    }
1048
-
1049
-    /**
1050
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1051
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1052
-     *
1053
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1054
-     * we must be able to find all other tables.
1055
-     *
1056
-     * @param string[] $tables
1057
-     *
1058
-     * @return string[]
1059
-     */
1060
-    public function _getLinkBetweenInheritedTables(array $tables)
1061
-    {
1062
-        sort($tables);
1063
-
1064
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1065
-            function () use ($tables) {
1066
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1067
-            });
1068
-    }
1069
-
1070
-    /**
1071
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1072
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1073
-     *
1074
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1075
-     * we must be able to find all other tables.
1076
-     *
1077
-     * @param string[] $tables
1078
-     *
1079
-     * @return string[]
1080
-     */
1081
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1082
-    {
1083
-        $schemaAnalyzer = $this->schemaAnalyzer;
1084
-
1085
-        foreach ($tables as $currentTable) {
1086
-            $allParents = [$currentTable];
1087
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1088
-                $currentTable = $currentFk->getForeignTableName();
1089
-                $allParents[] = $currentTable;
1090
-            }
1091
-
1092
-            // Now, does the $allParents contain all the tables we want?
1093
-            $notFoundTables = array_diff($tables, $allParents);
1094
-            if (empty($notFoundTables)) {
1095
-                // We have a winner!
1096
-                return $allParents;
1097
-            }
1098
-        }
1099
-
1100
-        throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1101
-    }
1102
-
1103
-    /**
1104
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1105
-     *
1106
-     * @param string $table
1107
-     *
1108
-     * @return string[]
1109
-     */
1110
-    public function _getRelatedTablesByInheritance($table)
1111
-    {
1112
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1113
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1114
-        });
1115
-    }
1116
-
1117
-    /**
1118
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1119
-     *
1120
-     * @param string $table
1121
-     *
1122
-     * @return string[]
1123
-     */
1124
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1125
-    {
1126
-        $schemaAnalyzer = $this->schemaAnalyzer;
1127
-
1128
-        // Let's scan the parent tables
1129
-        $currentTable = $table;
1130
-
1131
-        $parentTables = [];
1132
-
1133
-        // Get parent relationship
1134
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1135
-            $currentTable = $currentFk->getForeignTableName();
1136
-            $parentTables[] = $currentTable;
1137
-        }
1138
-
1139
-        // Let's recurse in children
1140
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1141
-
1142
-        return array_merge(array_reverse($parentTables), $childrenTables);
1143
-    }
1144
-
1145
-    /**
1146
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1147
-     *
1148
-     * @param string $table
1149
-     *
1150
-     * @return string[]
1151
-     */
1152
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1153
-    {
1154
-        $tables = [$table];
1155
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1156
-
1157
-        foreach ($keys as $key) {
1158
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1159
-        }
1160
-
1161
-        return $tables;
1162
-    }
1163
-
1164
-    /**
1165
-     * @param string $tableName
1166
-     *
1167
-     * @return ForeignKeyConstraint[]
1168
-     */
1169
-    private function getParentRelationshipForeignKeys($tableName)
1170
-    {
1171
-        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
1172
-            return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
1173
-        });
1174
-    }
1175
-
1176
-    /**
1177
-     * @param string $tableName
1178
-     *
1179
-     * @return ForeignKeyConstraint[]
1180
-     */
1181
-    private function getParentRelationshipForeignKeysWithoutCache($tableName)
1182
-    {
1183
-        $parentFks = [];
1184
-        $currentTable = $tableName;
1185
-        while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
1186
-            $currentTable = $currentFk->getForeignTableName();
1187
-            $parentFks[] = $currentFk;
1188
-        }
1189
-
1190
-        return $parentFks;
1191
-    }
1192
-
1193
-    /**
1194
-     * @param string $tableName
1195
-     *
1196
-     * @return ForeignKeyConstraint[]
1197
-     */
1198
-    private function getChildrenRelationshipForeignKeys($tableName)
1199
-    {
1200
-        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
1201
-            return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
1202
-        });
1203
-    }
1204
-
1205
-    /**
1206
-     * @param string $tableName
1207
-     *
1208
-     * @return ForeignKeyConstraint[]
1209
-     */
1210
-    private function getChildrenRelationshipForeignKeysWithoutCache($tableName)
1211
-    {
1212
-        $children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
1213
-
1214
-        if (!empty($children)) {
1215
-            $fksTables = array_map(function (ForeignKeyConstraint $fk) {
1216
-                return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
1217
-            }, $children);
1218
-
1219
-            $fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
1220
-
1221
-            return $fks;
1222
-        } else {
1223
-            return [];
1224
-        }
1225
-    }
1226
-
1227
-    /**
1228
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1229
-     * The returned value does contain only one table. For instance:.
1230
-     *
1231
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1232
-     *
1233
-     * @param ForeignKeyConstraint $fk
1234
-     * @param bool                 $leftTableIsLocal
1235
-     *
1236
-     * @return string
1237
-     */
1238
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1044
+		}
1045
+
1046
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1047
+	}
1048
+
1049
+	/**
1050
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1051
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1052
+	 *
1053
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1054
+	 * we must be able to find all other tables.
1055
+	 *
1056
+	 * @param string[] $tables
1057
+	 *
1058
+	 * @return string[]
1059
+	 */
1060
+	public function _getLinkBetweenInheritedTables(array $tables)
1061
+	{
1062
+		sort($tables);
1063
+
1064
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1065
+			function () use ($tables) {
1066
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1067
+			});
1068
+	}
1069
+
1070
+	/**
1071
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1072
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1073
+	 *
1074
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1075
+	 * we must be able to find all other tables.
1076
+	 *
1077
+	 * @param string[] $tables
1078
+	 *
1079
+	 * @return string[]
1080
+	 */
1081
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1082
+	{
1083
+		$schemaAnalyzer = $this->schemaAnalyzer;
1084
+
1085
+		foreach ($tables as $currentTable) {
1086
+			$allParents = [$currentTable];
1087
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1088
+				$currentTable = $currentFk->getForeignTableName();
1089
+				$allParents[] = $currentTable;
1090
+			}
1091
+
1092
+			// Now, does the $allParents contain all the tables we want?
1093
+			$notFoundTables = array_diff($tables, $allParents);
1094
+			if (empty($notFoundTables)) {
1095
+				// We have a winner!
1096
+				return $allParents;
1097
+			}
1098
+		}
1099
+
1100
+		throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1101
+	}
1102
+
1103
+	/**
1104
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1105
+	 *
1106
+	 * @param string $table
1107
+	 *
1108
+	 * @return string[]
1109
+	 */
1110
+	public function _getRelatedTablesByInheritance($table)
1111
+	{
1112
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1113
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1114
+		});
1115
+	}
1116
+
1117
+	/**
1118
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1119
+	 *
1120
+	 * @param string $table
1121
+	 *
1122
+	 * @return string[]
1123
+	 */
1124
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1125
+	{
1126
+		$schemaAnalyzer = $this->schemaAnalyzer;
1127
+
1128
+		// Let's scan the parent tables
1129
+		$currentTable = $table;
1130
+
1131
+		$parentTables = [];
1132
+
1133
+		// Get parent relationship
1134
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1135
+			$currentTable = $currentFk->getForeignTableName();
1136
+			$parentTables[] = $currentTable;
1137
+		}
1138
+
1139
+		// Let's recurse in children
1140
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1141
+
1142
+		return array_merge(array_reverse($parentTables), $childrenTables);
1143
+	}
1144
+
1145
+	/**
1146
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1147
+	 *
1148
+	 * @param string $table
1149
+	 *
1150
+	 * @return string[]
1151
+	 */
1152
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1153
+	{
1154
+		$tables = [$table];
1155
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1156
+
1157
+		foreach ($keys as $key) {
1158
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1159
+		}
1160
+
1161
+		return $tables;
1162
+	}
1163
+
1164
+	/**
1165
+	 * @param string $tableName
1166
+	 *
1167
+	 * @return ForeignKeyConstraint[]
1168
+	 */
1169
+	private function getParentRelationshipForeignKeys($tableName)
1170
+	{
1171
+		return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
1172
+			return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
1173
+		});
1174
+	}
1175
+
1176
+	/**
1177
+	 * @param string $tableName
1178
+	 *
1179
+	 * @return ForeignKeyConstraint[]
1180
+	 */
1181
+	private function getParentRelationshipForeignKeysWithoutCache($tableName)
1182
+	{
1183
+		$parentFks = [];
1184
+		$currentTable = $tableName;
1185
+		while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
1186
+			$currentTable = $currentFk->getForeignTableName();
1187
+			$parentFks[] = $currentFk;
1188
+		}
1189
+
1190
+		return $parentFks;
1191
+	}
1192
+
1193
+	/**
1194
+	 * @param string $tableName
1195
+	 *
1196
+	 * @return ForeignKeyConstraint[]
1197
+	 */
1198
+	private function getChildrenRelationshipForeignKeys($tableName)
1199
+	{
1200
+		return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
1201
+			return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
1202
+		});
1203
+	}
1204
+
1205
+	/**
1206
+	 * @param string $tableName
1207
+	 *
1208
+	 * @return ForeignKeyConstraint[]
1209
+	 */
1210
+	private function getChildrenRelationshipForeignKeysWithoutCache($tableName)
1211
+	{
1212
+		$children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
1213
+
1214
+		if (!empty($children)) {
1215
+			$fksTables = array_map(function (ForeignKeyConstraint $fk) {
1216
+				return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
1217
+			}, $children);
1218
+
1219
+			$fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
1220
+
1221
+			return $fks;
1222
+		} else {
1223
+			return [];
1224
+		}
1225
+	}
1226
+
1227
+	/**
1228
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1229
+	 * The returned value does contain only one table. For instance:.
1230
+	 *
1231
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1232
+	 *
1233
+	 * @param ForeignKeyConstraint $fk
1234
+	 * @param bool                 $leftTableIsLocal
1235
+	 *
1236
+	 * @return string
1237
+	 */
1238
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1239 1239
         $onClauses = [];
1240 1240
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1241 1241
         $foreignColumns = $fk->getForeignColumns();
@@ -1261,602 +1261,602 @@  discard block
 block discarded – undo
1261 1261
         }
1262 1262
     }*/
1263 1263
 
1264
-    /**
1265
-     * Returns an identifier for the group of tables passed in parameter.
1266
-     *
1267
-     * @param string[] $relatedTables
1268
-     *
1269
-     * @return string
1270
-     */
1271
-    private function getTableGroupName(array $relatedTables)
1272
-    {
1273
-        sort($relatedTables);
1274
-
1275
-        return implode('_``_', $relatedTables);
1276
-    }
1277
-
1278
-    /**
1279
-     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1280
-     *
1281
-     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1282
-     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1283
-     *
1284
-     * The findObjects method takes in parameter:
1285
-     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1286
-     * 			`$mainTable` parameter should be the name of an existing table in database.
1287
-     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1288
-     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1289
-     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1290
-     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1291
-     *          Instead, please consider passing parameters (see documentation for more details).
1292
-     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1293
-     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1294
-     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1295
-     *
1296
-     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1297
-     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1298
-     *
1299
-     * Finally, if filter_bag is null, the whole table is returned.
1300
-     *
1301
-     * @param string            $mainTable             The name of the table queried
1302
-     * @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)
1303
-     * @param array             $parameters
1304
-     * @param string|null       $orderString           The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1305
-     * @param array             $additionalTablesFetch
1306
-     * @param int               $mode
1307
-     * @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
1308
-     *
1309
-     * @return ResultIterator An object representing an array of results
1310
-     *
1311
-     * @throws TDBMException
1312
-     */
1313
-    public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null)
1314
-    {
1315
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1316
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1317
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1318
-        }
1319
-
1320
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1321
-
1322
-        $parameters = array_merge($parameters, $additionalParameters);
1323
-
1324
-        list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, $additionalTablesFetch, $orderString);
1325
-
1326
-        $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')';
1327
-
1328
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1329
-        $pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1330
-        $pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1331
-            return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1332
-        }, $pkColumnNames);
1333
-
1334
-        $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$mainTable.')';
1335
-
1336
-        if (!empty($filterString)) {
1337
-            $sql .= ' WHERE '.$filterString;
1338
-            $countSql .= ' WHERE '.$filterString;
1339
-        }
1340
-
1341
-        if (!empty($orderString)) {
1342
-            $sql .= ' ORDER BY '.$orderString;
1343
-        }
1344
-
1345
-        if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1346
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1347
-        }
1348
-
1349
-        $mode = $mode ?: $this->mode;
1350
-
1351
-        return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1352
-    }
1353
-
1354
-    /**
1355
-     * @param string            $mainTable   The name of the table queried
1356
-     * @param string            $from        The from sql statement
1357
-     * @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)
1358
-     * @param array             $parameters
1359
-     * @param string|null       $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1360
-     * @param int               $mode
1361
-     * @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
1362
-     *
1363
-     * @return ResultIterator An object representing an array of results
1364
-     *
1365
-     * @throws TDBMException
1366
-     */
1367
-    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), string $orderString = null, $mode = null, string $className = null)
1368
-    {
1369
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1370
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1371
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1372
-        }
1373
-
1374
-        $columnsList = null;
1375
-
1376
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1377
-
1378
-        $parameters = array_merge($parameters, $additionalParameters);
1379
-
1380
-        $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1381
-
1382
-        $columnDescList = [];
1383
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1384
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
1385
-
1386
-        foreach ($schema->getTable($mainTable)->getColumns() as $column) {
1387
-            $columnName = $column->getName();
1388
-            $columnDescList[] = [
1389
-                'as' => $columnName,
1390
-                'table' => $mainTable,
1391
-                'column' => $columnName,
1392
-                'type' => $column->getType(),
1393
-                'tableGroup' => $tableGroupName,
1394
-            ];
1395
-        }
1396
-
1397
-        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) use ($mainTable) {
1398
-            return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($columnDesc['column']);
1399
-        }, $columnDescList)).' FROM '.$from;
1400
-
1401
-        if (count($allFetchedTables) > 1) {
1402
-            list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, [], $orderString);
1403
-        }
1404
-
1405
-        // Let's compute the COUNT.
1406
-        $pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1407
-        $pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1408
-            return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1409
-        }, $pkColumnNames);
1410
-
1411
-        $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$from;
1412
-
1413
-        if (!empty($filterString)) {
1414
-            $sql .= ' WHERE '.$filterString;
1415
-            $countSql .= ' WHERE '.$filterString;
1416
-        }
1417
-
1418
-        if (!empty($orderString)) {
1419
-            $sql .= ' ORDER BY '.$orderString;
1420
-            $countSql .= ' ORDER BY '.$orderString;
1421
-        }
1422
-
1423
-        if (stripos($countSql, 'GROUP BY') !== false) {
1424
-            throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
1425
-        }
1426
-
1427
-        if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1428
-            throw new TDBMException("Unknown fetch mode: '".$mode."'");
1429
-        }
1430
-
1431
-        if ($columnsList !== null) {
1432
-            $joinSql = '';
1433
-            $parentFks = $this->getParentRelationshipForeignKeys($mainTable);
1434
-            foreach ($parentFks as $fk) {
1435
-                $joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
1436
-                    $this->connection->quoteIdentifier($fk->getForeignTableName()),
1437
-                    $this->connection->quoteIdentifier($fk->getLocalTableName()),
1438
-                    $this->connection->quoteIdentifier($fk->getLocalColumns()[0]),
1439
-                    $this->connection->quoteIdentifier($fk->getForeignTableName()),
1440
-                    $this->connection->quoteIdentifier($fk->getForeignColumns()[0])
1441
-                    );
1442
-            }
1443
-
1444
-            $childrenFks = $this->getChildrenRelationshipForeignKeys($mainTable);
1445
-            foreach ($childrenFks as $fk) {
1446
-                $joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
1447
-                    $this->connection->quoteIdentifier($fk->getLocalTableName()),
1448
-                    $this->connection->quoteIdentifier($fk->getForeignTableName()),
1449
-                    $this->connection->quoteIdentifier($fk->getForeignColumns()[0]),
1450
-                    $this->connection->quoteIdentifier($fk->getLocalTableName()),
1451
-                    $this->connection->quoteIdentifier($fk->getLocalColumns()[0])
1452
-                );
1453
-            }
1454
-
1455
-            $sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$mainTable.' '.$joinSql;
1456
-        }
1457
-
1458
-        $mode = $mode ?: $this->mode;
1459
-
1460
-        return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1461
-    }
1462
-
1463
-    /**
1464
-     * Returns the column list that must be fetched for the SQL request.
1465
-     *
1466
-     * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
1467
-     *
1468
-     * @param string      $mainTable
1469
-     * @param array       $additionalTablesFetch
1470
-     * @param string|null $orderBy
1471
-     *
1472
-     * @return array
1473
-     *
1474
-     * @throws \Doctrine\DBAL\Schema\SchemaException
1475
-     */
1476
-    private function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), string $orderBy = null)
1477
-    {
1478
-        // From the table name and the additional tables we want to fetch, let's build a list of all tables
1479
-        // that must be part of the select columns.
1480
-
1481
-        $tableGroups = [];
1482
-        $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1483
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
1484
-        foreach ($allFetchedTables as $table) {
1485
-            $tableGroups[$table] = $tableGroupName;
1486
-        }
1487
-
1488
-        $columnsList = [];
1489
-        $columnDescList = [];
1490
-        $sortColumn = 0;
1491
-
1492
-        // Now, let's deal with "order by columns"
1493
-        if ($orderBy !== null) {
1494
-            $orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
1495
-
1496
-            // If we sort by a column, there is a high chance we will fetch the bean containing this column.
1497
-            // Hence, we should add the table to the $additionalTablesFetch
1498
-            foreach ($orderByColumns as $orderByColumn) {
1499
-                if ($orderByColumn['type'] === 'colref' && $orderByColumn['table'] !== null) {
1500
-                    $additionalTablesFetch[] = $orderByColumn['table'];
1501
-                } elseif ($orderByColumn['type'] === 'expr') {
1502
-                    $sortColumnName = 'sort_column_'.$sortColumn;
1503
-                    $columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
1504
-                    $columnDescList[] = [
1505
-                        'tableGroup' => null,
1506
-                    ];
1507
-                    ++$sortColumn;
1508
-                }
1509
-            }
1510
-        }
1511
-
1512
-        foreach ($additionalTablesFetch as $additionalTable) {
1513
-            $relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1514
-            $tableGroupName = $this->getTableGroupName($relatedTables);
1515
-            foreach ($relatedTables as $table) {
1516
-                $tableGroups[$table] = $tableGroupName;
1517
-            }
1518
-            $allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1519
-        }
1520
-
1521
-        // Let's remove any duplicate
1522
-        $allFetchedTables = array_flip(array_flip($allFetchedTables));
1523
-
1524
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1525
-
1526
-        // Now, let's build the column list
1527
-        foreach ($allFetchedTables as $table) {
1528
-            foreach ($schema->getTable($table)->getColumns() as $column) {
1529
-                $columnName = $column->getName();
1530
-                $columnDescList[] = [
1531
-                    'as' => $table.'____'.$columnName,
1532
-                    'table' => $table,
1533
-                    'column' => $columnName,
1534
-                    'type' => $column->getType(),
1535
-                    'tableGroup' => $tableGroups[$table],
1536
-                ];
1537
-                $columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1538
-                    $this->connection->quoteIdentifier($table.'____'.$columnName);
1539
-            }
1540
-        }
1541
-
1542
-        return [$columnDescList, $columnsList];
1543
-    }
1544
-
1545
-    /**
1546
-     * @param $table
1547
-     * @param array  $primaryKeys
1548
-     * @param array  $additionalTablesFetch
1549
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1550
-     * @param string $className
1551
-     *
1552
-     * @return AbstractTDBMObject
1553
-     *
1554
-     * @throws TDBMException
1555
-     */
1556
-    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1557
-    {
1558
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1559
-        $hash = $this->getObjectHash($primaryKeys);
1560
-
1561
-        if ($this->objectStorage->has($table, $hash)) {
1562
-            $dbRow = $this->objectStorage->get($table, $hash);
1563
-            $bean = $dbRow->getTDBMObject();
1564
-            if ($className !== null && !is_a($bean, $className)) {
1565
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1566
-            }
1567
-
1568
-            return $bean;
1569
-        }
1570
-
1571
-        // Are we performing lazy fetching?
1572
-        if ($lazy === true) {
1573
-            // Can we perform lazy fetching?
1574
-            $tables = $this->_getRelatedTablesByInheritance($table);
1575
-            // Only allowed if no inheritance.
1576
-            if (count($tables) === 1) {
1577
-                if ($className === null) {
1578
-                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1579
-                }
1580
-
1581
-                // Let's construct the bean
1582
-                if (!isset($this->reflectionClassCache[$className])) {
1583
-                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1584
-                }
1585
-                // Let's bypass the constructor when creating the bean!
1586
-                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1587
-                /* @var $bean AbstractTDBMObject */
1588
-                $bean->_constructLazy($table, $primaryKeys, $this);
1589
-
1590
-                return $bean;
1591
-            }
1592
-        }
1593
-
1594
-        // Did not find the object in cache? Let's query it!
1595
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1596
-    }
1597
-
1598
-    /**
1599
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1600
-     *
1601
-     * @param string            $mainTable             The name of the table queried
1602
-     * @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)
1603
-     * @param array             $parameters
1604
-     * @param array             $additionalTablesFetch
1605
-     * @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
1606
-     *
1607
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1608
-     *
1609
-     * @throws TDBMException
1610
-     */
1611
-    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1612
-    {
1613
-        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1614
-        $page = $objects->take(0, 2);
1615
-        $count = $page->count();
1616
-        if ($count > 1) {
1617
-            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.");
1618
-        } elseif ($count === 0) {
1619
-            return;
1620
-        }
1621
-
1622
-        return $page[0];
1623
-    }
1624
-
1625
-    /**
1626
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1627
-     *
1628
-     * @param string            $mainTable  The name of the table queried
1629
-     * @param string            $from       The from sql statement
1630
-     * @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)
1631
-     * @param array             $parameters
1632
-     * @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
1633
-     *
1634
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1635
-     *
1636
-     * @throws TDBMException
1637
-     */
1638
-    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1639
-    {
1640
-        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1641
-        $page = $objects->take(0, 2);
1642
-        $count = $page->count();
1643
-        if ($count > 1) {
1644
-            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.");
1645
-        } elseif ($count === 0) {
1646
-            return;
1647
-        }
1648
-
1649
-        return $page[0];
1650
-    }
1651
-
1652
-    /**
1653
-     * Returns a unique bean according to the filters passed in parameter.
1654
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1655
-     *
1656
-     * @param string            $mainTable             The name of the table queried
1657
-     * @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)
1658
-     * @param array             $parameters
1659
-     * @param array             $additionalTablesFetch
1660
-     * @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
1661
-     *
1662
-     * @return AbstractTDBMObject The object we want
1663
-     *
1664
-     * @throws TDBMException
1665
-     */
1666
-    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1667
-    {
1668
-        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1669
-        if ($bean === null) {
1670
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1671
-        }
1672
-
1673
-        return $bean;
1674
-    }
1675
-
1676
-    /**
1677
-     * @param array $beanData An array of data: array<table, array<column, value>>
1678
-     *
1679
-     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1680
-     */
1681
-    public function _getClassNameFromBeanData(array $beanData)
1682
-    {
1683
-        if (count($beanData) === 1) {
1684
-            $tableName = array_keys($beanData)[0];
1685
-            $allTables = [$tableName];
1686
-        } else {
1687
-            $tables = [];
1688
-            foreach ($beanData as $table => $row) {
1689
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1690
-                $pkSet = false;
1691
-                foreach ($primaryKeyColumns as $columnName) {
1692
-                    if ($row[$columnName] !== null) {
1693
-                        $pkSet = true;
1694
-                        break;
1695
-                    }
1696
-                }
1697
-                if ($pkSet) {
1698
-                    $tables[] = $table;
1699
-                }
1700
-            }
1701
-
1702
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1703
-            $allTables = $this->_getLinkBetweenInheritedTables($tables);
1704
-            $tableName = $allTables[0];
1705
-        }
1706
-
1707
-        // Only one table in this bean. Life is sweat, let's look at its type:
1708
-        if (isset($this->tableToBeanMap[$tableName])) {
1709
-            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1710
-        } else {
1711
-            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1712
-        }
1713
-    }
1714
-
1715
-    /**
1716
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1717
-     *
1718
-     * @param string   $key
1719
-     * @param callable $closure
1720
-     *
1721
-     * @return mixed
1722
-     */
1723
-    private function fromCache(string $key, callable $closure)
1724
-    {
1725
-        $item = $this->cache->fetch($key);
1726
-        if ($item === false) {
1727
-            $item = $closure();
1728
-            $this->cache->save($key, $item);
1729
-        }
1730
-
1731
-        return $item;
1732
-    }
1733
-
1734
-    /**
1735
-     * Returns the foreign key object.
1736
-     *
1737
-     * @param string $table
1738
-     * @param string $fkName
1739
-     *
1740
-     * @return ForeignKeyConstraint
1741
-     */
1742
-    public function _getForeignKeyByName(string $table, string $fkName)
1743
-    {
1744
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1745
-    }
1746
-
1747
-    /**
1748
-     * @param $pivotTableName
1749
-     * @param AbstractTDBMObject $bean
1750
-     *
1751
-     * @return AbstractTDBMObject[]
1752
-     */
1753
-    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1754
-    {
1755
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1756
-        /* @var $localFk ForeignKeyConstraint */
1757
-        /* @var $remoteFk ForeignKeyConstraint */
1758
-        $remoteTable = $remoteFk->getForeignTableName();
1759
-
1760
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1761
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1762
-            return $pivotTableName.'.'.$name;
1763
-        }, $localFk->getLocalColumns());
1764
-
1765
-        $filter = array_combine($columnNames, $primaryKeys);
1766
-
1767
-        return $this->findObjects($remoteTable, $filter);
1768
-    }
1769
-
1770
-    /**
1771
-     * @param $pivotTableName
1772
-     * @param AbstractTDBMObject $bean The LOCAL bean
1773
-     *
1774
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1775
-     *
1776
-     * @throws TDBMException
1777
-     */
1778
-    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1779
-    {
1780
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1781
-        $table1 = $fks[0]->getForeignTableName();
1782
-        $table2 = $fks[1]->getForeignTableName();
1783
-
1784
-        $beanTables = array_map(function (DbRow $dbRow) {
1785
-            return $dbRow->_getDbTableName();
1786
-        }, $bean->_getDbRows());
1787
-
1788
-        if (in_array($table1, $beanTables)) {
1789
-            return [$fks[0], $fks[1]];
1790
-        } elseif (in_array($table2, $beanTables)) {
1791
-            return [$fks[1], $fks[0]];
1792
-        } else {
1793
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1794
-        }
1795
-    }
1796
-
1797
-    /**
1798
-     * Returns a list of pivot tables linked to $bean.
1799
-     *
1800
-     * @param AbstractTDBMObject $bean
1801
-     *
1802
-     * @return string[]
1803
-     */
1804
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1805
-    {
1806
-        $junctionTables = [];
1807
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1808
-        foreach ($bean->_getDbRows() as $dbRow) {
1809
-            foreach ($allJunctionTables as $table) {
1810
-                // There are exactly 2 FKs since this is a pivot table.
1811
-                $fks = array_values($table->getForeignKeys());
1812
-
1813
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1814
-                    $junctionTables[] = $table->getName();
1815
-                }
1816
-            }
1817
-        }
1818
-
1819
-        return $junctionTables;
1820
-    }
1821
-
1822
-    /**
1823
-     * Array of types for tables.
1824
-     * Key: table name
1825
-     * Value: array of types indexed by column.
1826
-     *
1827
-     * @var array[]
1828
-     */
1829
-    private $typesForTable = [];
1830
-
1831
-    /**
1832
-     * @internal
1833
-     *
1834
-     * @param string $tableName
1835
-     *
1836
-     * @return Type[]
1837
-     */
1838
-    public function _getColumnTypesForTable(string $tableName)
1839
-    {
1840
-        if (!isset($typesForTable[$tableName])) {
1841
-            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1842
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1843
-                return $column->getType();
1844
-            }, $columns);
1845
-        }
1846
-
1847
-        return $typesForTable[$tableName];
1848
-    }
1849
-
1850
-    /**
1851
-     * Sets the minimum log level.
1852
-     * $level must be one of Psr\Log\LogLevel::xxx.
1853
-     *
1854
-     * Defaults to LogLevel::WARNING
1855
-     *
1856
-     * @param string $level
1857
-     */
1858
-    public function setLogLevel(string $level)
1859
-    {
1860
-        $this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1861
-    }
1264
+	/**
1265
+	 * Returns an identifier for the group of tables passed in parameter.
1266
+	 *
1267
+	 * @param string[] $relatedTables
1268
+	 *
1269
+	 * @return string
1270
+	 */
1271
+	private function getTableGroupName(array $relatedTables)
1272
+	{
1273
+		sort($relatedTables);
1274
+
1275
+		return implode('_``_', $relatedTables);
1276
+	}
1277
+
1278
+	/**
1279
+	 * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1280
+	 *
1281
+	 * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1282
+	 * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1283
+	 *
1284
+	 * The findObjects method takes in parameter:
1285
+	 * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1286
+	 * 			`$mainTable` parameter should be the name of an existing table in database.
1287
+	 *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1288
+	 *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1289
+	 *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1290
+	 *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1291
+	 *          Instead, please consider passing parameters (see documentation for more details).
1292
+	 *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1293
+	 *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1294
+	 *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1295
+	 *
1296
+	 * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1297
+	 * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1298
+	 *
1299
+	 * Finally, if filter_bag is null, the whole table is returned.
1300
+	 *
1301
+	 * @param string            $mainTable             The name of the table queried
1302
+	 * @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)
1303
+	 * @param array             $parameters
1304
+	 * @param string|null       $orderString           The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1305
+	 * @param array             $additionalTablesFetch
1306
+	 * @param int               $mode
1307
+	 * @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
1308
+	 *
1309
+	 * @return ResultIterator An object representing an array of results
1310
+	 *
1311
+	 * @throws TDBMException
1312
+	 */
1313
+	public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null)
1314
+	{
1315
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1316
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1317
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1318
+		}
1319
+
1320
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1321
+
1322
+		$parameters = array_merge($parameters, $additionalParameters);
1323
+
1324
+		list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, $additionalTablesFetch, $orderString);
1325
+
1326
+		$sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')';
1327
+
1328
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1329
+		$pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1330
+		$pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1331
+			return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1332
+		}, $pkColumnNames);
1333
+
1334
+		$countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$mainTable.')';
1335
+
1336
+		if (!empty($filterString)) {
1337
+			$sql .= ' WHERE '.$filterString;
1338
+			$countSql .= ' WHERE '.$filterString;
1339
+		}
1340
+
1341
+		if (!empty($orderString)) {
1342
+			$sql .= ' ORDER BY '.$orderString;
1343
+		}
1344
+
1345
+		if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1346
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1347
+		}
1348
+
1349
+		$mode = $mode ?: $this->mode;
1350
+
1351
+		return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1352
+	}
1353
+
1354
+	/**
1355
+	 * @param string            $mainTable   The name of the table queried
1356
+	 * @param string            $from        The from sql statement
1357
+	 * @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)
1358
+	 * @param array             $parameters
1359
+	 * @param string|null       $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1360
+	 * @param int               $mode
1361
+	 * @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
1362
+	 *
1363
+	 * @return ResultIterator An object representing an array of results
1364
+	 *
1365
+	 * @throws TDBMException
1366
+	 */
1367
+	public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), string $orderString = null, $mode = null, string $className = null)
1368
+	{
1369
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1370
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1371
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1372
+		}
1373
+
1374
+		$columnsList = null;
1375
+
1376
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1377
+
1378
+		$parameters = array_merge($parameters, $additionalParameters);
1379
+
1380
+		$allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1381
+
1382
+		$columnDescList = [];
1383
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1384
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
1385
+
1386
+		foreach ($schema->getTable($mainTable)->getColumns() as $column) {
1387
+			$columnName = $column->getName();
1388
+			$columnDescList[] = [
1389
+				'as' => $columnName,
1390
+				'table' => $mainTable,
1391
+				'column' => $columnName,
1392
+				'type' => $column->getType(),
1393
+				'tableGroup' => $tableGroupName,
1394
+			];
1395
+		}
1396
+
1397
+		$sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) use ($mainTable) {
1398
+			return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($columnDesc['column']);
1399
+		}, $columnDescList)).' FROM '.$from;
1400
+
1401
+		if (count($allFetchedTables) > 1) {
1402
+			list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, [], $orderString);
1403
+		}
1404
+
1405
+		// Let's compute the COUNT.
1406
+		$pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1407
+		$pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1408
+			return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1409
+		}, $pkColumnNames);
1410
+
1411
+		$countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$from;
1412
+
1413
+		if (!empty($filterString)) {
1414
+			$sql .= ' WHERE '.$filterString;
1415
+			$countSql .= ' WHERE '.$filterString;
1416
+		}
1417
+
1418
+		if (!empty($orderString)) {
1419
+			$sql .= ' ORDER BY '.$orderString;
1420
+			$countSql .= ' ORDER BY '.$orderString;
1421
+		}
1422
+
1423
+		if (stripos($countSql, 'GROUP BY') !== false) {
1424
+			throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
1425
+		}
1426
+
1427
+		if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1428
+			throw new TDBMException("Unknown fetch mode: '".$mode."'");
1429
+		}
1430
+
1431
+		if ($columnsList !== null) {
1432
+			$joinSql = '';
1433
+			$parentFks = $this->getParentRelationshipForeignKeys($mainTable);
1434
+			foreach ($parentFks as $fk) {
1435
+				$joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
1436
+					$this->connection->quoteIdentifier($fk->getForeignTableName()),
1437
+					$this->connection->quoteIdentifier($fk->getLocalTableName()),
1438
+					$this->connection->quoteIdentifier($fk->getLocalColumns()[0]),
1439
+					$this->connection->quoteIdentifier($fk->getForeignTableName()),
1440
+					$this->connection->quoteIdentifier($fk->getForeignColumns()[0])
1441
+					);
1442
+			}
1443
+
1444
+			$childrenFks = $this->getChildrenRelationshipForeignKeys($mainTable);
1445
+			foreach ($childrenFks as $fk) {
1446
+				$joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
1447
+					$this->connection->quoteIdentifier($fk->getLocalTableName()),
1448
+					$this->connection->quoteIdentifier($fk->getForeignTableName()),
1449
+					$this->connection->quoteIdentifier($fk->getForeignColumns()[0]),
1450
+					$this->connection->quoteIdentifier($fk->getLocalTableName()),
1451
+					$this->connection->quoteIdentifier($fk->getLocalColumns()[0])
1452
+				);
1453
+			}
1454
+
1455
+			$sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$mainTable.' '.$joinSql;
1456
+		}
1457
+
1458
+		$mode = $mode ?: $this->mode;
1459
+
1460
+		return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1461
+	}
1462
+
1463
+	/**
1464
+	 * Returns the column list that must be fetched for the SQL request.
1465
+	 *
1466
+	 * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
1467
+	 *
1468
+	 * @param string      $mainTable
1469
+	 * @param array       $additionalTablesFetch
1470
+	 * @param string|null $orderBy
1471
+	 *
1472
+	 * @return array
1473
+	 *
1474
+	 * @throws \Doctrine\DBAL\Schema\SchemaException
1475
+	 */
1476
+	private function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), string $orderBy = null)
1477
+	{
1478
+		// From the table name and the additional tables we want to fetch, let's build a list of all tables
1479
+		// that must be part of the select columns.
1480
+
1481
+		$tableGroups = [];
1482
+		$allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1483
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
1484
+		foreach ($allFetchedTables as $table) {
1485
+			$tableGroups[$table] = $tableGroupName;
1486
+		}
1487
+
1488
+		$columnsList = [];
1489
+		$columnDescList = [];
1490
+		$sortColumn = 0;
1491
+
1492
+		// Now, let's deal with "order by columns"
1493
+		if ($orderBy !== null) {
1494
+			$orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
1495
+
1496
+			// If we sort by a column, there is a high chance we will fetch the bean containing this column.
1497
+			// Hence, we should add the table to the $additionalTablesFetch
1498
+			foreach ($orderByColumns as $orderByColumn) {
1499
+				if ($orderByColumn['type'] === 'colref' && $orderByColumn['table'] !== null) {
1500
+					$additionalTablesFetch[] = $orderByColumn['table'];
1501
+				} elseif ($orderByColumn['type'] === 'expr') {
1502
+					$sortColumnName = 'sort_column_'.$sortColumn;
1503
+					$columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
1504
+					$columnDescList[] = [
1505
+						'tableGroup' => null,
1506
+					];
1507
+					++$sortColumn;
1508
+				}
1509
+			}
1510
+		}
1511
+
1512
+		foreach ($additionalTablesFetch as $additionalTable) {
1513
+			$relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1514
+			$tableGroupName = $this->getTableGroupName($relatedTables);
1515
+			foreach ($relatedTables as $table) {
1516
+				$tableGroups[$table] = $tableGroupName;
1517
+			}
1518
+			$allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1519
+		}
1520
+
1521
+		// Let's remove any duplicate
1522
+		$allFetchedTables = array_flip(array_flip($allFetchedTables));
1523
+
1524
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1525
+
1526
+		// Now, let's build the column list
1527
+		foreach ($allFetchedTables as $table) {
1528
+			foreach ($schema->getTable($table)->getColumns() as $column) {
1529
+				$columnName = $column->getName();
1530
+				$columnDescList[] = [
1531
+					'as' => $table.'____'.$columnName,
1532
+					'table' => $table,
1533
+					'column' => $columnName,
1534
+					'type' => $column->getType(),
1535
+					'tableGroup' => $tableGroups[$table],
1536
+				];
1537
+				$columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1538
+					$this->connection->quoteIdentifier($table.'____'.$columnName);
1539
+			}
1540
+		}
1541
+
1542
+		return [$columnDescList, $columnsList];
1543
+	}
1544
+
1545
+	/**
1546
+	 * @param $table
1547
+	 * @param array  $primaryKeys
1548
+	 * @param array  $additionalTablesFetch
1549
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1550
+	 * @param string $className
1551
+	 *
1552
+	 * @return AbstractTDBMObject
1553
+	 *
1554
+	 * @throws TDBMException
1555
+	 */
1556
+	public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1557
+	{
1558
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1559
+		$hash = $this->getObjectHash($primaryKeys);
1560
+
1561
+		if ($this->objectStorage->has($table, $hash)) {
1562
+			$dbRow = $this->objectStorage->get($table, $hash);
1563
+			$bean = $dbRow->getTDBMObject();
1564
+			if ($className !== null && !is_a($bean, $className)) {
1565
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1566
+			}
1567
+
1568
+			return $bean;
1569
+		}
1570
+
1571
+		// Are we performing lazy fetching?
1572
+		if ($lazy === true) {
1573
+			// Can we perform lazy fetching?
1574
+			$tables = $this->_getRelatedTablesByInheritance($table);
1575
+			// Only allowed if no inheritance.
1576
+			if (count($tables) === 1) {
1577
+				if ($className === null) {
1578
+					$className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1579
+				}
1580
+
1581
+				// Let's construct the bean
1582
+				if (!isset($this->reflectionClassCache[$className])) {
1583
+					$this->reflectionClassCache[$className] = new \ReflectionClass($className);
1584
+				}
1585
+				// Let's bypass the constructor when creating the bean!
1586
+				$bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1587
+				/* @var $bean AbstractTDBMObject */
1588
+				$bean->_constructLazy($table, $primaryKeys, $this);
1589
+
1590
+				return $bean;
1591
+			}
1592
+		}
1593
+
1594
+		// Did not find the object in cache? Let's query it!
1595
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1596
+	}
1597
+
1598
+	/**
1599
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1600
+	 *
1601
+	 * @param string            $mainTable             The name of the table queried
1602
+	 * @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)
1603
+	 * @param array             $parameters
1604
+	 * @param array             $additionalTablesFetch
1605
+	 * @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
1606
+	 *
1607
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1608
+	 *
1609
+	 * @throws TDBMException
1610
+	 */
1611
+	public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1612
+	{
1613
+		$objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1614
+		$page = $objects->take(0, 2);
1615
+		$count = $page->count();
1616
+		if ($count > 1) {
1617
+			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.");
1618
+		} elseif ($count === 0) {
1619
+			return;
1620
+		}
1621
+
1622
+		return $page[0];
1623
+	}
1624
+
1625
+	/**
1626
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1627
+	 *
1628
+	 * @param string            $mainTable  The name of the table queried
1629
+	 * @param string            $from       The from sql statement
1630
+	 * @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)
1631
+	 * @param array             $parameters
1632
+	 * @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
1633
+	 *
1634
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1635
+	 *
1636
+	 * @throws TDBMException
1637
+	 */
1638
+	public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1639
+	{
1640
+		$objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1641
+		$page = $objects->take(0, 2);
1642
+		$count = $page->count();
1643
+		if ($count > 1) {
1644
+			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.");
1645
+		} elseif ($count === 0) {
1646
+			return;
1647
+		}
1648
+
1649
+		return $page[0];
1650
+	}
1651
+
1652
+	/**
1653
+	 * Returns a unique bean according to the filters passed in parameter.
1654
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1655
+	 *
1656
+	 * @param string            $mainTable             The name of the table queried
1657
+	 * @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)
1658
+	 * @param array             $parameters
1659
+	 * @param array             $additionalTablesFetch
1660
+	 * @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
1661
+	 *
1662
+	 * @return AbstractTDBMObject The object we want
1663
+	 *
1664
+	 * @throws TDBMException
1665
+	 */
1666
+	public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1667
+	{
1668
+		$bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1669
+		if ($bean === null) {
1670
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1671
+		}
1672
+
1673
+		return $bean;
1674
+	}
1675
+
1676
+	/**
1677
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1678
+	 *
1679
+	 * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1680
+	 */
1681
+	public function _getClassNameFromBeanData(array $beanData)
1682
+	{
1683
+		if (count($beanData) === 1) {
1684
+			$tableName = array_keys($beanData)[0];
1685
+			$allTables = [$tableName];
1686
+		} else {
1687
+			$tables = [];
1688
+			foreach ($beanData as $table => $row) {
1689
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1690
+				$pkSet = false;
1691
+				foreach ($primaryKeyColumns as $columnName) {
1692
+					if ($row[$columnName] !== null) {
1693
+						$pkSet = true;
1694
+						break;
1695
+					}
1696
+				}
1697
+				if ($pkSet) {
1698
+					$tables[] = $table;
1699
+				}
1700
+			}
1701
+
1702
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1703
+			$allTables = $this->_getLinkBetweenInheritedTables($tables);
1704
+			$tableName = $allTables[0];
1705
+		}
1706
+
1707
+		// Only one table in this bean. Life is sweat, let's look at its type:
1708
+		if (isset($this->tableToBeanMap[$tableName])) {
1709
+			return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1710
+		} else {
1711
+			return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1712
+		}
1713
+	}
1714
+
1715
+	/**
1716
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1717
+	 *
1718
+	 * @param string   $key
1719
+	 * @param callable $closure
1720
+	 *
1721
+	 * @return mixed
1722
+	 */
1723
+	private function fromCache(string $key, callable $closure)
1724
+	{
1725
+		$item = $this->cache->fetch($key);
1726
+		if ($item === false) {
1727
+			$item = $closure();
1728
+			$this->cache->save($key, $item);
1729
+		}
1730
+
1731
+		return $item;
1732
+	}
1733
+
1734
+	/**
1735
+	 * Returns the foreign key object.
1736
+	 *
1737
+	 * @param string $table
1738
+	 * @param string $fkName
1739
+	 *
1740
+	 * @return ForeignKeyConstraint
1741
+	 */
1742
+	public function _getForeignKeyByName(string $table, string $fkName)
1743
+	{
1744
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1745
+	}
1746
+
1747
+	/**
1748
+	 * @param $pivotTableName
1749
+	 * @param AbstractTDBMObject $bean
1750
+	 *
1751
+	 * @return AbstractTDBMObject[]
1752
+	 */
1753
+	public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1754
+	{
1755
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1756
+		/* @var $localFk ForeignKeyConstraint */
1757
+		/* @var $remoteFk ForeignKeyConstraint */
1758
+		$remoteTable = $remoteFk->getForeignTableName();
1759
+
1760
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1761
+		$columnNames = array_map(function ($name) use ($pivotTableName) {
1762
+			return $pivotTableName.'.'.$name;
1763
+		}, $localFk->getLocalColumns());
1764
+
1765
+		$filter = array_combine($columnNames, $primaryKeys);
1766
+
1767
+		return $this->findObjects($remoteTable, $filter);
1768
+	}
1769
+
1770
+	/**
1771
+	 * @param $pivotTableName
1772
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1773
+	 *
1774
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1775
+	 *
1776
+	 * @throws TDBMException
1777
+	 */
1778
+	private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1779
+	{
1780
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1781
+		$table1 = $fks[0]->getForeignTableName();
1782
+		$table2 = $fks[1]->getForeignTableName();
1783
+
1784
+		$beanTables = array_map(function (DbRow $dbRow) {
1785
+			return $dbRow->_getDbTableName();
1786
+		}, $bean->_getDbRows());
1787
+
1788
+		if (in_array($table1, $beanTables)) {
1789
+			return [$fks[0], $fks[1]];
1790
+		} elseif (in_array($table2, $beanTables)) {
1791
+			return [$fks[1], $fks[0]];
1792
+		} else {
1793
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1794
+		}
1795
+	}
1796
+
1797
+	/**
1798
+	 * Returns a list of pivot tables linked to $bean.
1799
+	 *
1800
+	 * @param AbstractTDBMObject $bean
1801
+	 *
1802
+	 * @return string[]
1803
+	 */
1804
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1805
+	{
1806
+		$junctionTables = [];
1807
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1808
+		foreach ($bean->_getDbRows() as $dbRow) {
1809
+			foreach ($allJunctionTables as $table) {
1810
+				// There are exactly 2 FKs since this is a pivot table.
1811
+				$fks = array_values($table->getForeignKeys());
1812
+
1813
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1814
+					$junctionTables[] = $table->getName();
1815
+				}
1816
+			}
1817
+		}
1818
+
1819
+		return $junctionTables;
1820
+	}
1821
+
1822
+	/**
1823
+	 * Array of types for tables.
1824
+	 * Key: table name
1825
+	 * Value: array of types indexed by column.
1826
+	 *
1827
+	 * @var array[]
1828
+	 */
1829
+	private $typesForTable = [];
1830
+
1831
+	/**
1832
+	 * @internal
1833
+	 *
1834
+	 * @param string $tableName
1835
+	 *
1836
+	 * @return Type[]
1837
+	 */
1838
+	public function _getColumnTypesForTable(string $tableName)
1839
+	{
1840
+		if (!isset($typesForTable[$tableName])) {
1841
+			$columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1842
+			$typesForTable[$tableName] = array_map(function (Column $column) {
1843
+				return $column->getType();
1844
+			}, $columns);
1845
+		}
1846
+
1847
+		return $typesForTable[$tableName];
1848
+	}
1849
+
1850
+	/**
1851
+	 * Sets the minimum log level.
1852
+	 * $level must be one of Psr\Log\LogLevel::xxx.
1853
+	 *
1854
+	 * Defaults to LogLevel::WARNING
1855
+	 *
1856
+	 * @param string $level
1857
+	 */
1858
+	public function setLogLevel(string $level)
1859
+	{
1860
+		$this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1861
+	}
1862 1862
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/ScalarBeanPropertyDescriptor.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -11,125 +11,125 @@  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
-    public function __construct(Table $table, Column $column)
20
-    {
21
-        parent::__construct($table);
22
-        $this->table = $table;
23
-        $this->column = $column;
24
-    }
25
-
26
-    /**
27
-     * Returns the foreign-key the column is part of, if any. null otherwise.
28
-     *
29
-     * @return ForeignKeyConstraint|null
30
-     */
31
-    public function getForeignKey()
32
-    {
33
-        return false;
34
-    }
35
-
36
-    /**
37
-     * Returns the param annotation for this property (useful for constructor).
38
-     *
39
-     * @return string
40
-     */
41
-    public function getParamAnnotation()
42
-    {
43
-        $className = $this->getClassName();
44
-        $paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
45
-
46
-        $str = '     * @param %s %s';
47
-
48
-        return sprintf($str, $paramType, $this->getVariableName());
49
-    }
50
-
51
-    public function getUpperCamelCaseName()
52
-    {
53
-        return TDBMDaoGenerator::toCamelCase($this->column->getName());
54
-    }
55
-
56
-    /**
57
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
58
-     *
59
-     * @return null|string
60
-     */
61
-    public function getClassName()
62
-    {
63
-        return;
64
-    }
65
-
66
-    /**
67
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
68
-     *
69
-     * @return bool
70
-     */
71
-    public function isCompulsory()
72
-    {
73
-        return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
74
-    }
75
-
76
-    /**
77
-     * Returns true if the property has a default value.
78
-     *
79
-     * @return bool
80
-     */
81
-    public function hasDefault()
82
-    {
83
-        return $this->column->getDefault() !== null;
84
-    }
85
-
86
-    /**
87
-     * Returns the code that assigns a value to its default value.
88
-     *
89
-     * @return string
90
-     */
91
-    public function assignToDefaultCode()
92
-    {
93
-        $str = '        $this->%s(%s);';
94
-
95
-        $default = $this->column->getDefault();
96
-
97
-        if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
98
-            $defaultCode = 'new \DateTimeImmutable()';
99
-        } else {
100
-            $defaultCode = var_export($this->column->getDefault(), true);
101
-        }
102
-
103
-        return sprintf($str, $this->getSetterName(), $defaultCode);
104
-    }
105
-
106
-    /**
107
-     * Returns true if the property is the primary key.
108
-     *
109
-     * @return bool
110
-     */
111
-    public function isPrimaryKey()
112
-    {
113
-        return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
114
-    }
115
-
116
-    /**
117
-     * Returns the PHP code for getters and setters.
118
-     *
119
-     * @return string
120
-     */
121
-    public function getGetterSetterCode()
122
-    {
123
-        $type = $this->column->getType();
124
-        $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
125
-
126
-        $columnGetterName = $this->getGetterName();
127
-        $columnSetterName = $this->getSetterName();
128
-
129
-        // A column type can be forced if it is not nullable and not auto-incrmentable (for auto-increment columns, we can get "null" as long as the bean is not saved).
130
-        $canForceGetterReturnType = $this->column->getNotnull() && !$this->column->getAutoincrement();
131
-
132
-        $getterAndSetterCode = '    /**
14
+	/**
15
+	 * @var Column
16
+	 */
17
+	private $column;
18
+
19
+	public function __construct(Table $table, Column $column)
20
+	{
21
+		parent::__construct($table);
22
+		$this->table = $table;
23
+		$this->column = $column;
24
+	}
25
+
26
+	/**
27
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
28
+	 *
29
+	 * @return ForeignKeyConstraint|null
30
+	 */
31
+	public function getForeignKey()
32
+	{
33
+		return false;
34
+	}
35
+
36
+	/**
37
+	 * Returns the param annotation for this property (useful for constructor).
38
+	 *
39
+	 * @return string
40
+	 */
41
+	public function getParamAnnotation()
42
+	{
43
+		$className = $this->getClassName();
44
+		$paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
45
+
46
+		$str = '     * @param %s %s';
47
+
48
+		return sprintf($str, $paramType, $this->getVariableName());
49
+	}
50
+
51
+	public function getUpperCamelCaseName()
52
+	{
53
+		return TDBMDaoGenerator::toCamelCase($this->column->getName());
54
+	}
55
+
56
+	/**
57
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
58
+	 *
59
+	 * @return null|string
60
+	 */
61
+	public function getClassName()
62
+	{
63
+		return;
64
+	}
65
+
66
+	/**
67
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
68
+	 *
69
+	 * @return bool
70
+	 */
71
+	public function isCompulsory()
72
+	{
73
+		return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
74
+	}
75
+
76
+	/**
77
+	 * Returns true if the property has a default value.
78
+	 *
79
+	 * @return bool
80
+	 */
81
+	public function hasDefault()
82
+	{
83
+		return $this->column->getDefault() !== null;
84
+	}
85
+
86
+	/**
87
+	 * Returns the code that assigns a value to its default value.
88
+	 *
89
+	 * @return string
90
+	 */
91
+	public function assignToDefaultCode()
92
+	{
93
+		$str = '        $this->%s(%s);';
94
+
95
+		$default = $this->column->getDefault();
96
+
97
+		if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
98
+			$defaultCode = 'new \DateTimeImmutable()';
99
+		} else {
100
+			$defaultCode = var_export($this->column->getDefault(), true);
101
+		}
102
+
103
+		return sprintf($str, $this->getSetterName(), $defaultCode);
104
+	}
105
+
106
+	/**
107
+	 * Returns true if the property is the primary key.
108
+	 *
109
+	 * @return bool
110
+	 */
111
+	public function isPrimaryKey()
112
+	{
113
+		return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
114
+	}
115
+
116
+	/**
117
+	 * Returns the PHP code for getters and setters.
118
+	 *
119
+	 * @return string
120
+	 */
121
+	public function getGetterSetterCode()
122
+	{
123
+		$type = $this->column->getType();
124
+		$normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
125
+
126
+		$columnGetterName = $this->getGetterName();
127
+		$columnSetterName = $this->getSetterName();
128
+
129
+		// A column type can be forced if it is not nullable and not auto-incrmentable (for auto-increment columns, we can get "null" as long as the bean is not saved).
130
+		$canForceGetterReturnType = $this->column->getNotnull() && !$this->column->getAutoincrement();
131
+
132
+		$getterAndSetterCode = '    /**
133 133
      * The getter for the "%s" column.
134 134
      *
135 135
      * @return %s
@@ -151,52 +151,52 @@  discard block
 block discarded – undo
151 151
 
152 152
 ';
153 153
 
154
-        return sprintf($getterAndSetterCode,
155
-            // Getter
156
-            $this->column->getName(),
157
-            $normalizedType.($canForceGetterReturnType ? '' : '|null'),
158
-            $columnGetterName,
159
-            ($canForceGetterReturnType ? ' : '.$normalizedType : ''),
160
-            var_export($this->column->getName(), true),
161
-            var_export($this->table->getName(), true),
162
-            // Setter
163
-            $this->column->getName(),
164
-            $normalizedType,
165
-            $this->column->getName(),
166
-            $columnSetterName,
167
-            $normalizedType,
168
-            //$castTo,
169
-            $this->column->getName().($this->column->getNotnull() ? '' : ' = null'),
170
-            var_export($this->column->getName(), true),
171
-            $this->column->getName(),
172
-            var_export($this->table->getName(), true)
173
-        );
174
-    }
175
-
176
-    /**
177
-     * Returns the part of code useful when doing json serialization.
178
-     *
179
-     * @return string
180
-     */
181
-    public function getJsonSerializeCode()
182
-    {
183
-        $type = $this->column->getType();
184
-        $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
185
-
186
-        if ($normalizedType == '\\DateTimeInterface') {
187
-            return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null)?null:$this->'.$this->getGetterName()."()->format('c');\n";
188
-        } else {
189
-            return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
190
-        }
191
-    }
192
-
193
-    /**
194
-     * Returns the column name.
195
-     *
196
-     * @return string
197
-     */
198
-    public function getColumnName()
199
-    {
200
-        return $this->column->getName();
201
-    }
154
+		return sprintf($getterAndSetterCode,
155
+			// Getter
156
+			$this->column->getName(),
157
+			$normalizedType.($canForceGetterReturnType ? '' : '|null'),
158
+			$columnGetterName,
159
+			($canForceGetterReturnType ? ' : '.$normalizedType : ''),
160
+			var_export($this->column->getName(), true),
161
+			var_export($this->table->getName(), true),
162
+			// Setter
163
+			$this->column->getName(),
164
+			$normalizedType,
165
+			$this->column->getName(),
166
+			$columnSetterName,
167
+			$normalizedType,
168
+			//$castTo,
169
+			$this->column->getName().($this->column->getNotnull() ? '' : ' = null'),
170
+			var_export($this->column->getName(), true),
171
+			$this->column->getName(),
172
+			var_export($this->table->getName(), true)
173
+		);
174
+	}
175
+
176
+	/**
177
+	 * Returns the part of code useful when doing json serialization.
178
+	 *
179
+	 * @return string
180
+	 */
181
+	public function getJsonSerializeCode()
182
+	{
183
+		$type = $this->column->getType();
184
+		$normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
185
+
186
+		if ($normalizedType == '\\DateTimeInterface') {
187
+			return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null)?null:$this->'.$this->getGetterName()."()->format('c');\n";
188
+		} else {
189
+			return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
190
+		}
191
+	}
192
+
193
+	/**
194
+	 * Returns the column name.
195
+	 *
196
+	 * @return string
197
+	 */
198
+	public function getColumnName()
199
+	{
200
+		return $this->column->getName();
201
+	}
202 202
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/BeanDescriptor.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
      */
93 93
     public function getConstructorProperties()
94 94
     {
95
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
95
+        $constructorProperties = array_filter($this->beanPropertyDescriptors, function(AbstractBeanPropertyDescriptor $property) {
96 96
             return $property->isCompulsory();
97 97
         });
98 98
 
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
     public function getPropertiesWithDefault()
108 108
     {
109 109
         $properties = $this->getPropertiesForTable($this->table);
110
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
110
+        $defaultProperties = array_filter($properties, function(AbstractBeanPropertyDescriptor $property) {
111 111
             return $property->hasDefault();
112 112
         });
113 113
 
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
      */
122 122
     public function getExposedProperties()
123 123
     {
124
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
124
+        $exposedProperties = array_filter($this->beanPropertyDescriptors, function(AbstractBeanPropertyDescriptor $property) {
125 125
             return $property->getTable()->getName() == $this->table->getName();
126 126
         });
127 127
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         $fksByMethodName = [];
292 292
 
293 293
         foreach ($fksByTable as $tableName => $fksForTable) {
294
-            if (count($fksForTable) > 1) {
294
+            if (count($fksForTable)>1) {
295 295
                 foreach ($fksForTable as $fk) {
296 296
                     $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
297 297
 
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 
400 400
         $finalDescs = [];
401 401
         foreach ($descs as $descArray) {
402
-            if (count($descArray) > 1) {
402
+            if (count($descArray)>1) {
403 403
                 foreach ($descArray as $desc) {
404 404
                     $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
405 405
                     $finalDescs[] = $desc;
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
 
588 588
         $classes = $this->generateExtendsAndUseStatements($parentFk);
589 589
 
590
-        $uses = array_map(function ($className) use ($beannamespace) {
590
+        $uses = array_map(function($className) use ($beannamespace) {
591 591
             return 'use '.$beannamespace.'\\'.$className.";\n";
592 592
         }, $classes);
593 593
         $use = implode('', $uses);
Please login to merge, or discard this patch.
Indentation   +619 added lines, -619 removed lines patch added patch discarded remove patch
@@ -17,228 +17,228 @@  discard block
 block discarded – undo
17 17
  */
18 18
 class BeanDescriptor
19 19
 {
20
-    /**
21
-     * @var Table
22
-     */
23
-    private $table;
24
-
25
-    /**
26
-     * @var SchemaAnalyzer
27
-     */
28
-    private $schemaAnalyzer;
29
-
30
-    /**
31
-     * @var Schema
32
-     */
33
-    private $schema;
34
-
35
-    /**
36
-     * @var AbstractBeanPropertyDescriptor[]
37
-     */
38
-    private $beanPropertyDescriptors = [];
39
-
40
-    /**
41
-     * @var TDBMSchemaAnalyzer
42
-     */
43
-    private $tdbmSchemaAnalyzer;
44
-
45
-    public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
46
-    {
47
-        $this->table = $table;
48
-        $this->schemaAnalyzer = $schemaAnalyzer;
49
-        $this->schema = $schema;
50
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
51
-        $this->initBeanPropertyDescriptors();
52
-    }
53
-
54
-    private function initBeanPropertyDescriptors()
55
-    {
56
-        $this->beanPropertyDescriptors = $this->getProperties($this->table);
57
-    }
58
-
59
-    /**
60
-     * Returns the foreign-key the column is part of, if any. null otherwise.
61
-     *
62
-     * @param Table  $table
63
-     * @param Column $column
64
-     *
65
-     * @return ForeignKeyConstraint|null
66
-     */
67
-    private function isPartOfForeignKey(Table $table, Column $column)
68
-    {
69
-        $localColumnName = $column->getName();
70
-        foreach ($table->getForeignKeys() as $foreignKey) {
71
-            foreach ($foreignKey->getColumns() as $columnName) {
72
-                if ($columnName === $localColumnName) {
73
-                    return $foreignKey;
74
-                }
75
-            }
76
-        }
77
-
78
-        return;
79
-    }
80
-
81
-    /**
82
-     * @return AbstractBeanPropertyDescriptor[]
83
-     */
84
-    public function getBeanPropertyDescriptors()
85
-    {
86
-        return $this->beanPropertyDescriptors;
87
-    }
88
-
89
-    /**
90
-     * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
91
-     *
92
-     * @return AbstractBeanPropertyDescriptor[]
93
-     */
94
-    public function getConstructorProperties()
95
-    {
96
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
97
-            return $property->isCompulsory();
98
-        });
99
-
100
-        return $constructorProperties;
101
-    }
102
-
103
-    /**
104
-     * Returns the list of columns that have default values for a given table.
105
-     *
106
-     * @return AbstractBeanPropertyDescriptor[]
107
-     */
108
-    public function getPropertiesWithDefault()
109
-    {
110
-        $properties = $this->getPropertiesForTable($this->table);
111
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
112
-            return $property->hasDefault();
113
-        });
114
-
115
-        return $defaultProperties;
116
-    }
117
-
118
-    /**
119
-     * Returns the list of properties exposed as getters and setters in this class.
120
-     *
121
-     * @return AbstractBeanPropertyDescriptor[]
122
-     */
123
-    public function getExposedProperties()
124
-    {
125
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
126
-            return $property->getTable()->getName() == $this->table->getName();
127
-        });
128
-
129
-        return $exposedProperties;
130
-    }
131
-
132
-    /**
133
-     * Returns the list of properties for this table (including parent tables).
134
-     *
135
-     * @param Table $table
136
-     *
137
-     * @return AbstractBeanPropertyDescriptor[]
138
-     */
139
-    private function getProperties(Table $table)
140
-    {
141
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
142
-        if ($parentRelationship) {
143
-            $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
144
-            $properties = $this->getProperties($parentTable);
145
-            // we merge properties by overriding property names.
146
-            $localProperties = $this->getPropertiesForTable($table);
147
-            foreach ($localProperties as $name => $property) {
148
-                // We do not override properties if this is a primary key!
149
-                if ($property->isPrimaryKey()) {
150
-                    continue;
151
-                }
152
-                $properties[$name] = $property;
153
-            }
154
-        } else {
155
-            $properties = $this->getPropertiesForTable($table);
156
-        }
157
-
158
-        return $properties;
159
-    }
160
-
161
-    /**
162
-     * Returns the list of properties for this table (ignoring parent tables).
163
-     *
164
-     * @param Table $table
165
-     *
166
-     * @return AbstractBeanPropertyDescriptor[]
167
-     */
168
-    private function getPropertiesForTable(Table $table)
169
-    {
170
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
171
-        if ($parentRelationship) {
172
-            $ignoreColumns = $parentRelationship->getLocalColumns();
173
-        } else {
174
-            $ignoreColumns = [];
175
-        }
176
-
177
-        $beanPropertyDescriptors = [];
178
-
179
-        foreach ($table->getColumns() as $column) {
180
-            if (array_search($column->getName(), $ignoreColumns) !== false) {
181
-                continue;
182
-            }
183
-
184
-            $fk = $this->isPartOfForeignKey($table, $column);
185
-            if ($fk !== null) {
186
-                // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
187
-                foreach ($beanPropertyDescriptors as $beanDescriptor) {
188
-                    if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
189
-                        continue 2;
190
-                    }
191
-                }
192
-                // Check that this property is not an inheritance relationship
193
-                $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
194
-                if ($parentRelationship === $fk) {
195
-                    continue;
196
-                }
197
-
198
-                $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
199
-            } else {
200
-                $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
201
-            }
202
-        }
203
-
204
-        // Now, let's get the name of all properties and let's check there is no duplicate.
205
-        /** @var $names AbstractBeanPropertyDescriptor[] */
206
-        $names = [];
207
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
208
-            $name = $beanDescriptor->getUpperCamelCaseName();
209
-            if (isset($names[$name])) {
210
-                $names[$name]->useAlternativeName();
211
-                $beanDescriptor->useAlternativeName();
212
-            } else {
213
-                $names[$name] = $beanDescriptor;
214
-            }
215
-        }
216
-
217
-        // Final check (throw exceptions if problem arises)
218
-        $names = [];
219
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
220
-            $name = $beanDescriptor->getUpperCamelCaseName();
221
-            if (isset($names[$name])) {
222
-                throw new TDBMException('Unsolvable name conflict while generating method name');
223
-            } else {
224
-                $names[$name] = $beanDescriptor;
225
-            }
226
-        }
227
-
228
-        // Last step, let's rebuild the list with a map:
229
-        $beanPropertyDescriptorsMap = [];
230
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
231
-            $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
232
-        }
233
-
234
-        return $beanPropertyDescriptorsMap;
235
-    }
236
-
237
-    public function generateBeanConstructor()
238
-    {
239
-        $constructorProperties = $this->getConstructorProperties();
240
-
241
-        $constructorCode = '    /**
20
+	/**
21
+	 * @var Table
22
+	 */
23
+	private $table;
24
+
25
+	/**
26
+	 * @var SchemaAnalyzer
27
+	 */
28
+	private $schemaAnalyzer;
29
+
30
+	/**
31
+	 * @var Schema
32
+	 */
33
+	private $schema;
34
+
35
+	/**
36
+	 * @var AbstractBeanPropertyDescriptor[]
37
+	 */
38
+	private $beanPropertyDescriptors = [];
39
+
40
+	/**
41
+	 * @var TDBMSchemaAnalyzer
42
+	 */
43
+	private $tdbmSchemaAnalyzer;
44
+
45
+	public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
46
+	{
47
+		$this->table = $table;
48
+		$this->schemaAnalyzer = $schemaAnalyzer;
49
+		$this->schema = $schema;
50
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
51
+		$this->initBeanPropertyDescriptors();
52
+	}
53
+
54
+	private function initBeanPropertyDescriptors()
55
+	{
56
+		$this->beanPropertyDescriptors = $this->getProperties($this->table);
57
+	}
58
+
59
+	/**
60
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
61
+	 *
62
+	 * @param Table  $table
63
+	 * @param Column $column
64
+	 *
65
+	 * @return ForeignKeyConstraint|null
66
+	 */
67
+	private function isPartOfForeignKey(Table $table, Column $column)
68
+	{
69
+		$localColumnName = $column->getName();
70
+		foreach ($table->getForeignKeys() as $foreignKey) {
71
+			foreach ($foreignKey->getColumns() as $columnName) {
72
+				if ($columnName === $localColumnName) {
73
+					return $foreignKey;
74
+				}
75
+			}
76
+		}
77
+
78
+		return;
79
+	}
80
+
81
+	/**
82
+	 * @return AbstractBeanPropertyDescriptor[]
83
+	 */
84
+	public function getBeanPropertyDescriptors()
85
+	{
86
+		return $this->beanPropertyDescriptors;
87
+	}
88
+
89
+	/**
90
+	 * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
91
+	 *
92
+	 * @return AbstractBeanPropertyDescriptor[]
93
+	 */
94
+	public function getConstructorProperties()
95
+	{
96
+		$constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
97
+			return $property->isCompulsory();
98
+		});
99
+
100
+		return $constructorProperties;
101
+	}
102
+
103
+	/**
104
+	 * Returns the list of columns that have default values for a given table.
105
+	 *
106
+	 * @return AbstractBeanPropertyDescriptor[]
107
+	 */
108
+	public function getPropertiesWithDefault()
109
+	{
110
+		$properties = $this->getPropertiesForTable($this->table);
111
+		$defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
112
+			return $property->hasDefault();
113
+		});
114
+
115
+		return $defaultProperties;
116
+	}
117
+
118
+	/**
119
+	 * Returns the list of properties exposed as getters and setters in this class.
120
+	 *
121
+	 * @return AbstractBeanPropertyDescriptor[]
122
+	 */
123
+	public function getExposedProperties()
124
+	{
125
+		$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
126
+			return $property->getTable()->getName() == $this->table->getName();
127
+		});
128
+
129
+		return $exposedProperties;
130
+	}
131
+
132
+	/**
133
+	 * Returns the list of properties for this table (including parent tables).
134
+	 *
135
+	 * @param Table $table
136
+	 *
137
+	 * @return AbstractBeanPropertyDescriptor[]
138
+	 */
139
+	private function getProperties(Table $table)
140
+	{
141
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
142
+		if ($parentRelationship) {
143
+			$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
144
+			$properties = $this->getProperties($parentTable);
145
+			// we merge properties by overriding property names.
146
+			$localProperties = $this->getPropertiesForTable($table);
147
+			foreach ($localProperties as $name => $property) {
148
+				// We do not override properties if this is a primary key!
149
+				if ($property->isPrimaryKey()) {
150
+					continue;
151
+				}
152
+				$properties[$name] = $property;
153
+			}
154
+		} else {
155
+			$properties = $this->getPropertiesForTable($table);
156
+		}
157
+
158
+		return $properties;
159
+	}
160
+
161
+	/**
162
+	 * Returns the list of properties for this table (ignoring parent tables).
163
+	 *
164
+	 * @param Table $table
165
+	 *
166
+	 * @return AbstractBeanPropertyDescriptor[]
167
+	 */
168
+	private function getPropertiesForTable(Table $table)
169
+	{
170
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
171
+		if ($parentRelationship) {
172
+			$ignoreColumns = $parentRelationship->getLocalColumns();
173
+		} else {
174
+			$ignoreColumns = [];
175
+		}
176
+
177
+		$beanPropertyDescriptors = [];
178
+
179
+		foreach ($table->getColumns() as $column) {
180
+			if (array_search($column->getName(), $ignoreColumns) !== false) {
181
+				continue;
182
+			}
183
+
184
+			$fk = $this->isPartOfForeignKey($table, $column);
185
+			if ($fk !== null) {
186
+				// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
187
+				foreach ($beanPropertyDescriptors as $beanDescriptor) {
188
+					if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
189
+						continue 2;
190
+					}
191
+				}
192
+				// Check that this property is not an inheritance relationship
193
+				$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
194
+				if ($parentRelationship === $fk) {
195
+					continue;
196
+				}
197
+
198
+				$beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
199
+			} else {
200
+				$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
201
+			}
202
+		}
203
+
204
+		// Now, let's get the name of all properties and let's check there is no duplicate.
205
+		/** @var $names AbstractBeanPropertyDescriptor[] */
206
+		$names = [];
207
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
208
+			$name = $beanDescriptor->getUpperCamelCaseName();
209
+			if (isset($names[$name])) {
210
+				$names[$name]->useAlternativeName();
211
+				$beanDescriptor->useAlternativeName();
212
+			} else {
213
+				$names[$name] = $beanDescriptor;
214
+			}
215
+		}
216
+
217
+		// Final check (throw exceptions if problem arises)
218
+		$names = [];
219
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
220
+			$name = $beanDescriptor->getUpperCamelCaseName();
221
+			if (isset($names[$name])) {
222
+				throw new TDBMException('Unsolvable name conflict while generating method name');
223
+			} else {
224
+				$names[$name] = $beanDescriptor;
225
+			}
226
+		}
227
+
228
+		// Last step, let's rebuild the list with a map:
229
+		$beanPropertyDescriptorsMap = [];
230
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
231
+			$beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
232
+		}
233
+
234
+		return $beanPropertyDescriptorsMap;
235
+	}
236
+
237
+	public function generateBeanConstructor()
238
+	{
239
+		$constructorProperties = $this->getConstructorProperties();
240
+
241
+		$constructorCode = '    /**
242 242
      * The constructor takes all compulsory arguments.
243 243
      *
244 244
 %s
@@ -248,70 +248,70 @@  discard block
 block discarded – undo
248 248
 %s    }
249 249
     ';
250 250
 
251
-        $paramAnnotations = [];
252
-        $arguments = [];
253
-        $assigns = [];
254
-        $parentConstructorArguments = [];
255
-
256
-        foreach ($constructorProperties as $property) {
257
-            $className = $property->getClassName();
258
-            if ($className) {
259
-                $arguments[] = $className.' '.$property->getVariableName();
260
-            } else {
261
-                $arguments[] = $property->getVariableName();
262
-            }
263
-            $paramAnnotations[] = $property->getParamAnnotation();
264
-            if ($property->getTable()->getName() === $this->table->getName()) {
265
-                $assigns[] = $property->getConstructorAssignCode();
266
-            } else {
267
-                $parentConstructorArguments[] = $property->getVariableName();
268
-            }
269
-        }
270
-
271
-        $parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
272
-
273
-        $defaultAssigns = [];
274
-        foreach ($this->getPropertiesWithDefault() as $property) {
275
-            $defaultAssigns[] = $property->assignToDefaultCode();
276
-        }
277
-
278
-        return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode("\n", $assigns), implode("\n", $defaultAssigns));
279
-    }
280
-
281
-    public function generateDirectForeignKeysCode()
282
-    {
283
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
284
-
285
-        $fksByTable = [];
286
-
287
-        foreach ($fks as $fk) {
288
-            $fksByTable[$fk->getLocalTableName()][] = $fk;
289
-        }
290
-
291
-        /* @var $fksByMethodName ForeignKeyConstraint[] */
292
-        $fksByMethodName = [];
293
-
294
-        foreach ($fksByTable as $tableName => $fksForTable) {
295
-            if (count($fksForTable) > 1) {
296
-                foreach ($fksForTable as $fk) {
297
-                    $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
298
-
299
-                    $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $fk->getLocalColumns());
300
-
301
-                    $methodName .= implode('And', $camelizedColumns);
302
-
303
-                    $fksByMethodName[$methodName] = $fk;
304
-                }
305
-            } else {
306
-                $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fksForTable[0]->getLocalTableName());
307
-                $fksByMethodName[$methodName] = $fksForTable[0];
308
-            }
309
-        }
310
-
311
-        $code = '';
312
-
313
-        foreach ($fksByMethodName as $methodName => $fk) {
314
-            $getterCode = '    /**
251
+		$paramAnnotations = [];
252
+		$arguments = [];
253
+		$assigns = [];
254
+		$parentConstructorArguments = [];
255
+
256
+		foreach ($constructorProperties as $property) {
257
+			$className = $property->getClassName();
258
+			if ($className) {
259
+				$arguments[] = $className.' '.$property->getVariableName();
260
+			} else {
261
+				$arguments[] = $property->getVariableName();
262
+			}
263
+			$paramAnnotations[] = $property->getParamAnnotation();
264
+			if ($property->getTable()->getName() === $this->table->getName()) {
265
+				$assigns[] = $property->getConstructorAssignCode();
266
+			} else {
267
+				$parentConstructorArguments[] = $property->getVariableName();
268
+			}
269
+		}
270
+
271
+		$parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
272
+
273
+		$defaultAssigns = [];
274
+		foreach ($this->getPropertiesWithDefault() as $property) {
275
+			$defaultAssigns[] = $property->assignToDefaultCode();
276
+		}
277
+
278
+		return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode("\n", $assigns), implode("\n", $defaultAssigns));
279
+	}
280
+
281
+	public function generateDirectForeignKeysCode()
282
+	{
283
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
284
+
285
+		$fksByTable = [];
286
+
287
+		foreach ($fks as $fk) {
288
+			$fksByTable[$fk->getLocalTableName()][] = $fk;
289
+		}
290
+
291
+		/* @var $fksByMethodName ForeignKeyConstraint[] */
292
+		$fksByMethodName = [];
293
+
294
+		foreach ($fksByTable as $tableName => $fksForTable) {
295
+			if (count($fksForTable) > 1) {
296
+				foreach ($fksForTable as $fk) {
297
+					$methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
298
+
299
+					$camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $fk->getLocalColumns());
300
+
301
+					$methodName .= implode('And', $camelizedColumns);
302
+
303
+					$fksByMethodName[$methodName] = $fk;
304
+				}
305
+			} else {
306
+				$methodName = 'get'.TDBMDaoGenerator::toCamelCase($fksForTable[0]->getLocalTableName());
307
+				$fksByMethodName[$methodName] = $fksForTable[0];
308
+			}
309
+		}
310
+
311
+		$code = '';
312
+
313
+		foreach ($fksByMethodName as $methodName => $fk) {
314
+			$getterCode = '    /**
315 315
      * Returns the list of %s pointing to this bean via the %s column.
316 316
      *
317 317
      * @return %s[]|AlterableResultIterator
@@ -323,107 +323,107 @@  discard block
 block discarded – undo
323 323
 
324 324
 ';
325 325
 
326
-            $beanClass = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
327
-            $code .= sprintf($getterCode,
328
-                $beanClass,
329
-                implode(', ', $fk->getColumns()),
330
-                $beanClass,
331
-                $methodName,
332
-                var_export($fk->getLocalTableName(), true),
333
-                var_export($fk->getName(), true),
334
-                var_export($fk->getLocalTableName(), true),
335
-                $this->getFilters($fk)
336
-            );
337
-        }
338
-
339
-        return $code;
340
-    }
341
-
342
-    private function getFilters(ForeignKeyConstraint $fk) : string
343
-    {
344
-        $counter = 0;
345
-        $parameters = [];
346
-
347
-        $pkColumns = $this->table->getPrimaryKeyColumns();
348
-
349
-        foreach ($fk->getLocalColumns() as $columnName) {
350
-            $pkColumn = $pkColumns[$counter];
351
-            $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->table->getName(), true));
352
-            ++$counter;
353
-        }
354
-        $parametersCode = '[ '.implode(', ', $parameters).' ]';
355
-
356
-        return $parametersCode;
357
-    }
358
-
359
-    /**
360
-     * Generate code section about pivot tables.
361
-     *
362
-     * @return string
363
-     */
364
-    public function generatePivotTableCode()
365
-    {
366
-        $finalDescs = $this->getPivotTableDescriptors();
367
-
368
-        $code = '';
369
-
370
-        foreach ($finalDescs as $desc) {
371
-            $code .= $this->getPivotTableCode($desc['name'], $desc['table'], $desc['localFK'], $desc['remoteFK']);
372
-        }
373
-
374
-        return $code;
375
-    }
376
-
377
-    private function getPivotTableDescriptors()
378
-    {
379
-        $descs = [];
380
-        foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
381
-            // There are exactly 2 FKs since this is a pivot table.
382
-            $fks = array_values($table->getForeignKeys());
383
-
384
-            if ($fks[0]->getForeignTableName() === $this->table->getName()) {
385
-                $localFK = $fks[0];
386
-                $remoteFK = $fks[1];
387
-            } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
388
-                $localFK = $fks[1];
389
-                $remoteFK = $fks[0];
390
-            } else {
391
-                continue;
392
-            }
393
-
394
-            $descs[$remoteFK->getForeignTableName()][] = [
395
-                'table' => $table,
396
-                'localFK' => $localFK,
397
-                'remoteFK' => $remoteFK,
398
-            ];
399
-        }
400
-
401
-        $finalDescs = [];
402
-        foreach ($descs as $descArray) {
403
-            if (count($descArray) > 1) {
404
-                foreach ($descArray as $desc) {
405
-                    $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
406
-                    $finalDescs[] = $desc;
407
-                }
408
-            } else {
409
-                $desc = $descArray[0];
410
-                $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName());
411
-                $finalDescs[] = $desc;
412
-            }
413
-        }
414
-
415
-        return $finalDescs;
416
-    }
417
-
418
-    public function getPivotTableCode($name, Table $table, ForeignKeyConstraint $localFK, ForeignKeyConstraint $remoteFK)
419
-    {
420
-        $singularName = TDBMDaoGenerator::toSingular($name);
421
-        $pluralName = $name;
422
-        $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
423
-        $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
424
-        $pluralVariableName = $variableName.'s';
425
-
426
-        $str = '    /**
326
+			$beanClass = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
327
+			$code .= sprintf($getterCode,
328
+				$beanClass,
329
+				implode(', ', $fk->getColumns()),
330
+				$beanClass,
331
+				$methodName,
332
+				var_export($fk->getLocalTableName(), true),
333
+				var_export($fk->getName(), true),
334
+				var_export($fk->getLocalTableName(), true),
335
+				$this->getFilters($fk)
336
+			);
337
+		}
338
+
339
+		return $code;
340
+	}
341
+
342
+	private function getFilters(ForeignKeyConstraint $fk) : string
343
+	{
344
+		$counter = 0;
345
+		$parameters = [];
346
+
347
+		$pkColumns = $this->table->getPrimaryKeyColumns();
348
+
349
+		foreach ($fk->getLocalColumns() as $columnName) {
350
+			$pkColumn = $pkColumns[$counter];
351
+			$parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->table->getName(), true));
352
+			++$counter;
353
+		}
354
+		$parametersCode = '[ '.implode(', ', $parameters).' ]';
355
+
356
+		return $parametersCode;
357
+	}
358
+
359
+	/**
360
+	 * Generate code section about pivot tables.
361
+	 *
362
+	 * @return string
363
+	 */
364
+	public function generatePivotTableCode()
365
+	{
366
+		$finalDescs = $this->getPivotTableDescriptors();
367
+
368
+		$code = '';
369
+
370
+		foreach ($finalDescs as $desc) {
371
+			$code .= $this->getPivotTableCode($desc['name'], $desc['table'], $desc['localFK'], $desc['remoteFK']);
372
+		}
373
+
374
+		return $code;
375
+	}
376
+
377
+	private function getPivotTableDescriptors()
378
+	{
379
+		$descs = [];
380
+		foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
381
+			// There are exactly 2 FKs since this is a pivot table.
382
+			$fks = array_values($table->getForeignKeys());
383
+
384
+			if ($fks[0]->getForeignTableName() === $this->table->getName()) {
385
+				$localFK = $fks[0];
386
+				$remoteFK = $fks[1];
387
+			} elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
388
+				$localFK = $fks[1];
389
+				$remoteFK = $fks[0];
390
+			} else {
391
+				continue;
392
+			}
393
+
394
+			$descs[$remoteFK->getForeignTableName()][] = [
395
+				'table' => $table,
396
+				'localFK' => $localFK,
397
+				'remoteFK' => $remoteFK,
398
+			];
399
+		}
400
+
401
+		$finalDescs = [];
402
+		foreach ($descs as $descArray) {
403
+			if (count($descArray) > 1) {
404
+				foreach ($descArray as $desc) {
405
+					$desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
406
+					$finalDescs[] = $desc;
407
+				}
408
+			} else {
409
+				$desc = $descArray[0];
410
+				$desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName());
411
+				$finalDescs[] = $desc;
412
+			}
413
+		}
414
+
415
+		return $finalDescs;
416
+	}
417
+
418
+	public function getPivotTableCode($name, Table $table, ForeignKeyConstraint $localFK, ForeignKeyConstraint $remoteFK)
419
+	{
420
+		$singularName = TDBMDaoGenerator::toSingular($name);
421
+		$pluralName = $name;
422
+		$remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
423
+		$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
424
+		$pluralVariableName = $variableName.'s';
425
+
426
+		$str = '    /**
427 427
      * Returns the list of %s associated to this bean via the %s pivot table.
428 428
      *
429 429
      * @return %s[]
@@ -433,9 +433,9 @@  discard block
 block discarded – undo
433 433
     }
434 434
 ';
435 435
 
436
-        $getterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $name, var_export($remoteFK->getLocalTableName(), true));
436
+		$getterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $name, var_export($remoteFK->getLocalTableName(), true));
437 437
 
438
-        $str = '    /**
438
+		$str = '    /**
439 439
      * Adds a relationship with %s associated to this bean via the %s pivot table.
440 440
      *
441 441
      * @param %s %s
@@ -445,9 +445,9 @@  discard block
 block discarded – undo
445 445
     }
446 446
 ';
447 447
 
448
-        $adderCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
448
+		$adderCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
449 449
 
450
-        $str = '    /**
450
+		$str = '    /**
451 451
      * Deletes the relationship with %s associated to this bean via the %s pivot table.
452 452
      *
453 453
      * @param %s %s
@@ -457,9 +457,9 @@  discard block
 block discarded – undo
457 457
     }
458 458
 ';
459 459
 
460
-        $removerCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
460
+		$removerCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
461 461
 
462
-        $str = '    /**
462
+		$str = '    /**
463 463
      * Returns whether this bean is associated with %s via the %s pivot table.
464 464
      *
465 465
      * @param %s %s
@@ -470,9 +470,9 @@  discard block
 block discarded – undo
470 470
     }
471 471
 ';
472 472
 
473
-        $hasCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
473
+		$hasCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
474 474
 
475
-        $str = '    /**
475
+		$str = '    /**
476 476
      * Sets all relationships with %s associated to this bean via the %s pivot table.
477 477
      * Exiting relationships will be removed and replaced by the provided relationships.
478 478
      *
@@ -483,24 +483,24 @@  discard block
 block discarded – undo
483 483
     }
484 484
 ';
485 485
 
486
-        $setterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($remoteFK->getLocalTableName(), true), $pluralVariableName);
486
+		$setterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($remoteFK->getLocalTableName(), true), $pluralVariableName);
487 487
 
488
-        $code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode;
488
+		$code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode;
489 489
 
490
-        return $code;
491
-    }
490
+		return $code;
491
+	}
492 492
 
493
-    public function generateJsonSerialize()
494
-    {
495
-        $tableName = $this->table->getName();
496
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
497
-        if ($parentFk !== null) {
498
-            $initializer = '$array = parent::jsonSerialize($stopRecursion);';
499
-        } else {
500
-            $initializer = '$array = [];';
501
-        }
493
+	public function generateJsonSerialize()
494
+	{
495
+		$tableName = $this->table->getName();
496
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
497
+		if ($parentFk !== null) {
498
+			$initializer = '$array = parent::jsonSerialize($stopRecursion);';
499
+		} else {
500
+			$initializer = '$array = [];';
501
+		}
502 502
 
503
-        $str = '
503
+		$str = '
504 504
     /**
505 505
      * Serializes the object for JSON encoding
506 506
      *
@@ -516,97 +516,97 @@  discard block
 block discarded – undo
516 516
     }
517 517
 ';
518 518
 
519
-        $propertiesCode = '';
520
-        foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
521
-            $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
522
-        }
519
+		$propertiesCode = '';
520
+		foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
521
+			$propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
522
+		}
523 523
 
524
-        // Many to many relationships:
524
+		// Many to many relationships:
525 525
 
526
-        $descs = $this->getPivotTableDescriptors();
526
+		$descs = $this->getPivotTableDescriptors();
527 527
 
528
-        $many2manyCode = '';
528
+		$many2manyCode = '';
529 529
 
530
-        foreach ($descs as $desc) {
531
-            $remoteFK = $desc['remoteFK'];
532
-            $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
533
-            $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
530
+		foreach ($descs as $desc) {
531
+			$remoteFK = $desc['remoteFK'];
532
+			$remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
533
+			$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
534 534
 
535
-            $many2manyCode .= '        if (!$stopRecursion) {
535
+			$many2manyCode .= '        if (!$stopRecursion) {
536 536
             $array[\''.lcfirst($desc['name']).'\'] = array_map(function('.$remoteBeanName.' '.$variableName.') {
537 537
                 return '.$variableName.'->jsonSerialize(true);
538 538
             }, $this->get'.$desc['name'].'());
539 539
         }
540 540
         ';
541
-        }
542
-
543
-        return sprintf($str, $initializer, $propertiesCode, $many2manyCode);
544
-    }
545
-
546
-    /**
547
-     * Returns as an array the class we need to extend from and the list of use statements.
548
-     *
549
-     * @return array
550
-     */
551
-    private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
552
-    {
553
-        $classes = [];
554
-        if ($parentFk !== null) {
555
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
556
-            $classes[] = $extends;
557
-        }
558
-
559
-        foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
560
-            $className = $beanPropertyDescriptor->getClassName();
561
-            if (null !== $className) {
562
-                $classes[] = $beanPropertyDescriptor->getClassName();
563
-            }
564
-        }
565
-
566
-        foreach ($this->getPivotTableDescriptors() as $descriptor) {
567
-            /* @var $fk ForeignKeyConstraint */
568
-            $fk = $descriptor['remoteFK'];
569
-            $classes[] = TDBMDaoGenerator::getBeanNameFromTableName($fk->getForeignTableName());
570
-        }
571
-
572
-        // Many-to-one relationships
573
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
574
-        foreach ($fks as $fk) {
575
-            $classes[] = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
576
-        }
577
-
578
-        $classes = array_unique($classes);
579
-
580
-        return $classes;
581
-    }
582
-
583
-    /**
584
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
585
-     *
586
-     * @param string $beannamespace The namespace of the bean
587
-     */
588
-    public function generatePhpCode($beannamespace)
589
-    {
590
-        $tableName = $this->table->getName();
591
-        $baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
592
-        $className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
593
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
594
-
595
-        $classes = $this->generateExtendsAndUseStatements($parentFk);
596
-
597
-        $uses = array_map(function ($className) use ($beannamespace) {
598
-            return 'use '.$beannamespace.'\\'.$className.";\n";
599
-        }, $classes);
600
-        $use = implode('', $uses);
601
-
602
-        if ($parentFk !== null) {
603
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
604
-        } else {
605
-            $extends = 'AbstractTDBMObject';
606
-            $use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
607
-        }
608
-
609
-        $str = "<?php
541
+		}
542
+
543
+		return sprintf($str, $initializer, $propertiesCode, $many2manyCode);
544
+	}
545
+
546
+	/**
547
+	 * Returns as an array the class we need to extend from and the list of use statements.
548
+	 *
549
+	 * @return array
550
+	 */
551
+	private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
552
+	{
553
+		$classes = [];
554
+		if ($parentFk !== null) {
555
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
556
+			$classes[] = $extends;
557
+		}
558
+
559
+		foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
560
+			$className = $beanPropertyDescriptor->getClassName();
561
+			if (null !== $className) {
562
+				$classes[] = $beanPropertyDescriptor->getClassName();
563
+			}
564
+		}
565
+
566
+		foreach ($this->getPivotTableDescriptors() as $descriptor) {
567
+			/* @var $fk ForeignKeyConstraint */
568
+			$fk = $descriptor['remoteFK'];
569
+			$classes[] = TDBMDaoGenerator::getBeanNameFromTableName($fk->getForeignTableName());
570
+		}
571
+
572
+		// Many-to-one relationships
573
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
574
+		foreach ($fks as $fk) {
575
+			$classes[] = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
576
+		}
577
+
578
+		$classes = array_unique($classes);
579
+
580
+		return $classes;
581
+	}
582
+
583
+	/**
584
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
585
+	 *
586
+	 * @param string $beannamespace The namespace of the bean
587
+	 */
588
+	public function generatePhpCode($beannamespace)
589
+	{
590
+		$tableName = $this->table->getName();
591
+		$baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
592
+		$className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
593
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
594
+
595
+		$classes = $this->generateExtendsAndUseStatements($parentFk);
596
+
597
+		$uses = array_map(function ($className) use ($beannamespace) {
598
+			return 'use '.$beannamespace.'\\'.$className.";\n";
599
+		}, $classes);
600
+		$use = implode('', $uses);
601
+
602
+		if ($parentFk !== null) {
603
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
604
+		} else {
605
+			$extends = 'AbstractTDBMObject';
606
+			$use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
607
+		}
608
+
609
+		$str = "<?php
610 610
 namespace {$beannamespace}\\Generated;
611 611
 
612 612
 use Mouf\\Database\\TDBM\\ResultIterator;
@@ -626,126 +626,126 @@  discard block
 block discarded – undo
626 626
 {
627 627
 ";
628 628
 
629
-        $str .= $this->generateBeanConstructor();
629
+		$str .= $this->generateBeanConstructor();
630 630
 
631
-        foreach ($this->getExposedProperties() as $property) {
632
-            $str .= $property->getGetterSetterCode();
633
-        }
631
+		foreach ($this->getExposedProperties() as $property) {
632
+			$str .= $property->getGetterSetterCode();
633
+		}
634 634
 
635
-        $str .= $this->generateDirectForeignKeysCode();
636
-        $str .= $this->generatePivotTableCode();
637
-        $str .= $this->generateJsonSerialize();
635
+		$str .= $this->generateDirectForeignKeysCode();
636
+		$str .= $this->generatePivotTableCode();
637
+		$str .= $this->generateJsonSerialize();
638 638
 
639
-        $str .= $this->generateGetUsedTablesCode();
639
+		$str .= $this->generateGetUsedTablesCode();
640 640
 
641
-        $str .= '}
641
+		$str .= '}
642 642
 ';
643 643
 
644
-        return $str;
645
-    }
646
-
647
-    /**
648
-     * @param string $beanNamespace
649
-     * @param string $beanClassName
650
-     *
651
-     * @return array first element: list of used beans, second item: PHP code as a string
652
-     */
653
-    public function generateFindByDaoCode($beanNamespace, $beanClassName)
654
-    {
655
-        $code = '';
656
-        $usedBeans = [];
657
-        foreach ($this->table->getIndexes() as $index) {
658
-            if (!$index->isPrimary()) {
659
-                list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
660
-                $code .= $codeForIndex;
661
-                $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
662
-            }
663
-        }
664
-
665
-        return [$usedBeans, $code];
666
-    }
667
-
668
-    /**
669
-     * @param Index  $index
670
-     * @param string $beanNamespace
671
-     * @param string $beanClassName
672
-     *
673
-     * @return array first element: list of used beans, second item: PHP code as a string
674
-     */
675
-    private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
676
-    {
677
-        $columns = $index->getColumns();
678
-        $usedBeans = [];
679
-
680
-        /*
644
+		return $str;
645
+	}
646
+
647
+	/**
648
+	 * @param string $beanNamespace
649
+	 * @param string $beanClassName
650
+	 *
651
+	 * @return array first element: list of used beans, second item: PHP code as a string
652
+	 */
653
+	public function generateFindByDaoCode($beanNamespace, $beanClassName)
654
+	{
655
+		$code = '';
656
+		$usedBeans = [];
657
+		foreach ($this->table->getIndexes() as $index) {
658
+			if (!$index->isPrimary()) {
659
+				list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
660
+				$code .= $codeForIndex;
661
+				$usedBeans = array_merge($usedBeans, $usedBeansForIndex);
662
+			}
663
+		}
664
+
665
+		return [$usedBeans, $code];
666
+	}
667
+
668
+	/**
669
+	 * @param Index  $index
670
+	 * @param string $beanNamespace
671
+	 * @param string $beanClassName
672
+	 *
673
+	 * @return array first element: list of used beans, second item: PHP code as a string
674
+	 */
675
+	private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
676
+	{
677
+		$columns = $index->getColumns();
678
+		$usedBeans = [];
679
+
680
+		/*
681 681
          * The list of elements building this index (expressed as columns or foreign keys)
682 682
          * @var AbstractBeanPropertyDescriptor[]
683 683
          */
684
-        $elements = [];
685
-
686
-        foreach ($columns as $column) {
687
-            $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
688
-            if ($fk !== null) {
689
-                if (!in_array($fk, $elements)) {
690
-                    $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
691
-                }
692
-            } else {
693
-                $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
694
-            }
695
-        }
696
-
697
-        // If the index is actually only a foreign key, let's bypass it entirely.
698
-        if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
699
-            return [[], ''];
700
-        }
701
-
702
-        $methodNameComponent = [];
703
-        $functionParameters = [];
704
-        $first = true;
705
-        foreach ($elements as $element) {
706
-            $methodNameComponent[] = $element->getUpperCamelCaseName();
707
-            $functionParameter = $element->getClassName();
708
-            if ($functionParameter) {
709
-                $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
710
-                $functionParameter .= ' ';
711
-            }
712
-            $functionParameter .= $element->getVariableName();
713
-            if ($first) {
714
-                $first = false;
715
-            } else {
716
-                $functionParameter .= ' = null';
717
-            }
718
-            $functionParameters[] = $functionParameter;
719
-        }
720
-        if ($index->isUnique()) {
721
-            $methodName = 'findOneBy'.implode('And', $methodNameComponent);
722
-            $calledMethod = 'findOne';
723
-            $returnType = "{$beanClassName}";
724
-        } else {
725
-            $methodName = 'findBy'.implode('And', $methodNameComponent);
726
-            $returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
727
-            $calledMethod = 'find';
728
-        }
729
-        $functionParametersString = implode(', ', $functionParameters);
730
-
731
-        $count = 0;
732
-
733
-        $params = [];
734
-        $filterArrayCode = '';
735
-        $commentArguments = [];
736
-        foreach ($elements as $element) {
737
-            $params[] = $element->getParamAnnotation();
738
-            if ($element instanceof ScalarBeanPropertyDescriptor) {
739
-                $filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
740
-            } else {
741
-                ++$count;
742
-                $filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
743
-            }
744
-            $commentArguments[] = substr($element->getVariableName(), 1);
745
-        }
746
-        $paramsString = implode("\n", $params);
747
-
748
-        $code = "
684
+		$elements = [];
685
+
686
+		foreach ($columns as $column) {
687
+			$fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
688
+			if ($fk !== null) {
689
+				if (!in_array($fk, $elements)) {
690
+					$elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
691
+				}
692
+			} else {
693
+				$elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
694
+			}
695
+		}
696
+
697
+		// If the index is actually only a foreign key, let's bypass it entirely.
698
+		if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
699
+			return [[], ''];
700
+		}
701
+
702
+		$methodNameComponent = [];
703
+		$functionParameters = [];
704
+		$first = true;
705
+		foreach ($elements as $element) {
706
+			$methodNameComponent[] = $element->getUpperCamelCaseName();
707
+			$functionParameter = $element->getClassName();
708
+			if ($functionParameter) {
709
+				$usedBeans[] = $beanNamespace.'\\'.$functionParameter;
710
+				$functionParameter .= ' ';
711
+			}
712
+			$functionParameter .= $element->getVariableName();
713
+			if ($first) {
714
+				$first = false;
715
+			} else {
716
+				$functionParameter .= ' = null';
717
+			}
718
+			$functionParameters[] = $functionParameter;
719
+		}
720
+		if ($index->isUnique()) {
721
+			$methodName = 'findOneBy'.implode('And', $methodNameComponent);
722
+			$calledMethod = 'findOne';
723
+			$returnType = "{$beanClassName}";
724
+		} else {
725
+			$methodName = 'findBy'.implode('And', $methodNameComponent);
726
+			$returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
727
+			$calledMethod = 'find';
728
+		}
729
+		$functionParametersString = implode(', ', $functionParameters);
730
+
731
+		$count = 0;
732
+
733
+		$params = [];
734
+		$filterArrayCode = '';
735
+		$commentArguments = [];
736
+		foreach ($elements as $element) {
737
+			$params[] = $element->getParamAnnotation();
738
+			if ($element instanceof ScalarBeanPropertyDescriptor) {
739
+				$filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
740
+			} else {
741
+				++$count;
742
+				$filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
743
+			}
744
+			$commentArguments[] = substr($element->getVariableName(), 1);
745
+		}
746
+		$paramsString = implode("\n", $params);
747
+
748
+		$code = "
749 749
     /**
750 750
      * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
751 751
      *
@@ -763,27 +763,27 @@  discard block
 block discarded – undo
763 763
     }
764 764
 ";
765 765
 
766
-        return [$usedBeans, $code];
767
-    }
768
-
769
-    /**
770
-     * Generates the code for the getUsedTable protected method.
771
-     *
772
-     * @return string
773
-     */
774
-    private function generateGetUsedTablesCode()
775
-    {
776
-        $hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
777
-        if ($hasParentRelationship) {
778
-            $code = sprintf('        $tables = parent::getUsedTables();
766
+		return [$usedBeans, $code];
767
+	}
768
+
769
+	/**
770
+	 * Generates the code for the getUsedTable protected method.
771
+	 *
772
+	 * @return string
773
+	 */
774
+	private function generateGetUsedTablesCode()
775
+	{
776
+		$hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
777
+		if ($hasParentRelationship) {
778
+			$code = sprintf('        $tables = parent::getUsedTables();
779 779
         $tables[] = %s;
780 780
         
781 781
         return $tables;', var_export($this->table->getName(), true));
782
-        } else {
783
-            $code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
784
-        }
782
+		} else {
783
+			$code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
784
+		}
785 785
 
786
-        return sprintf('
786
+		return sprintf('
787 787
     /**
788 788
      * Returns an array of used tables by this bean (from parent to child relationship).
789 789
      *
@@ -794,5 +794,5 @@  discard block
 block discarded – undo
794 794
 %s    
795 795
     }
796 796
 ', $code);
797
-    }
797
+	}
798 798
 }
Please login to merge, or discard this patch.