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