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