Completed
Push — 4.2 ( 45e35c...5a6593 )
by David
01:05
created

TDBMService::getBeanClassName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
/*
4
 Copyright (C) 2006-2016 David Négrier - THE CODING MACHINE
5
6
This program is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2 of the License, or
9
(at your option) any later version.
10
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
GNU General Public License for more details.
15
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
*/
20
21
namespace Mouf\Database\TDBM;
22
23
use Doctrine\Common\Cache\Cache;
24
use Doctrine\Common\Cache\VoidCache;
25
use Doctrine\DBAL\Connection;
26
use Doctrine\DBAL\Schema\Column;
27
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
28
use Doctrine\DBAL\Schema\Schema;
29
use Doctrine\DBAL\Schema\Table;
30
use Doctrine\DBAL\Types\Type;
31
use Logger\Filters\MinLogLevelFilter;
32
use Mouf\Database\MagicQuery;
33
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
34
use Mouf\Database\TDBM\QueryFactory\FindObjectsFromSqlQueryFactory;
35
use Mouf\Database\TDBM\QueryFactory\FindObjectsQueryFactory;
36
use Mouf\Database\TDBM\Utils\TDBMDaoGenerator;
37
use Psr\Log\LoggerInterface;
38
use Psr\Log\LogLevel;
39
use Psr\Log\NullLogger;
40
41
/**
42
 * The TDBMService class is the main TDBM class. It provides methods to retrieve TDBMObject instances
43
 * from the database.
44
 *
45
 * @author David Negrier
46
 * @ExtendedAction {"name":"Generate DAOs", "url":"tdbmadmin/", "default":false}
47
 */
48
class TDBMService
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
     */
280
/*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
281
282
        if (is_array($filters) || $filters instanceof FilterInterface) {
283
            $isFilterBag = false;
284
            if (is_array($filters)) {
285
                // Is this a multiple primary key or a filter bag?
286
                // Let's have a look at the first item of the array to decide.
287
                foreach ($filters as $filter) {
288
                    if (is_array($filter) || $filter instanceof FilterInterface) {
289
                        $isFilterBag = true;
290
                    }
291
                    break;
292
                }
293
            } else {
294
                $isFilterBag = true;
295
            }
296
297
            if ($isFilterBag == true) {
298
                // If a filter bag was passer in parameter, let's perform a findObjects.
299
                $objects = $this->findObjects($table_name, $filters, null, null, null, $className);
300
                if (count($objects) == 0) {
301
                    return null;
302
                } elseif (count($objects) > 1) {
303
                    throw new DuplicateRowException("Error while querying an object for table '$table_name': ".count($objects)." rows have been returned, but we should have received at most one.");
304
                }
305
                // Return the first and only object.
306
                if ($objects instanceof \Generator) {
307
                    return $objects->current();
308
                } else {
309
                    return $objects[0];
310
                }
311
            }
312
        }
313
        $id = $filters;
314
        if ($this->connection == null) {
315
            throw new TDBMException("Error while calling TdbmService->getObject(): No connection has been established on the database!");
316
        }
317
        $table_name = $this->connection->toStandardcase($table_name);
318
319
        // If the ID is null, let's throw an exception
320
        if ($id === null) {
321
            throw new TDBMException("The ID you passed to TdbmService->getObject is null for the object of type '$table_name'. Objects primary keys cannot be null.");
322
        }
323
324
        // If the primary key is split over many columns, the IDs are passed in an array. Let's serialize this array to store it.
325
        if (is_array($id)) {
326
            $id = serialize($id);
327
        }
328
329
        if ($className === null) {
330
            if (isset($this->tableToBeanMap[$table_name])) {
331
                $className = $this->tableToBeanMap[$table_name];
332
            } else {
333
                $className = "Mouf\\Database\\TDBM\\TDBMObject";
334
            }
335
        }
336
337
        if ($this->objectStorage->has($table_name, $id)) {
338
            $obj = $this->objectStorage->get($table_name, $id);
339
            if (is_a($obj, $className)) {
340
                return $obj;
341
            } else {
342
                throw new TDBMException("Error! The object with ID '$id' for table '$table_name' has already been retrieved. The type for this object is '".get_class($obj)."'' which is not a subtype of '$className'");
343
            }
344
        }
345
346
        if ($className != "Mouf\\Database\\TDBM\\TDBMObject" && !is_subclass_of($className, "Mouf\\Database\\TDBM\\TDBMObject")) {
347
            if (!class_exists($className)) {
348
                throw new TDBMException("Error while calling TDBMService->getObject: The class ".$className." does not exist.");
349
            } else {
350
                throw new TDBMException("Error while calling TDBMService->getObject: The class ".$className." should extend TDBMObject.");
351
            }
352
        }
353
        $obj = new $className($this, $table_name, $id);
354
355
        if ($lazy_loading == false) {
356
            // If we are not doing lazy loading, let's load the object:
357
            $obj->_dbLoadIfNotLoaded();
358
        }
359
360
        $this->objectStorage->set($table_name, $id, $obj);
361
362
        return $obj;
363
    }*/
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...
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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
            foreach ($this->connection->getPrimaryKey($table) as $col) {
559
                $arr[] = $col->name;
560
            }
561
            // The primaryKeysColumns contains only the column's name, not the DB_Column object.
562
            $this->primaryKeysColumns[$table] = $arr;
563
            if (empty($this->primaryKeysColumns[$table]))
564
            {
565
                // Unable to find primary key.... this is an error
566
                // Let's try to be precise in error reporting. Let's try to find the table.
567
                $tables = $this->connection->checkTableExist($table);
568
                if ($tables === true)
569
                throw new TDBMException("Could not find table primary key for table '$table'. Please define a primary key for this table.");
570
                elseif ($tables !== null) {
571
                    if (count($tables)==1)
572
                    $str = "Could not find table '$table'. Maybe you meant this table: '".$tables[0]."'";
573
                    else
574
                    $str = "Could not find table '$table'. Maybe you meant one of those tables: '".implode("', '",$tables)."'";
575
                    throw new TDBMException($str);
576
                }
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();
0 ignored issues
show
Bug introduced by
The method deleteAll() does not exist on Doctrine\Common\Cache\Cache. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
635
636
        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
        if (null !== $composerFile) {
638
            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
        }
640
641
        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
    }
643
644
    /**
645
     * @param array<string, string> $tableToBeanMap
646
     */
647
    public function setTableToBeanMap(array $tableToBeanMap)
648
    {
649
        $this->tableToBeanMap = $tableToBeanMap;
650
    }
651
652
    /**
653
     * Returns the fully qualified class name of the bean associated with table $tableName.
654
     *
655
     *
656
     * @param string $tableName
657
     * @return string
658
     */
659
    public function getBeanClassName(string $tableName) : string
660
    {
661
        if (isset($this->tableToBeanMap[$tableName])) {
662
            return $this->tableToBeanMap[$tableName];
663
        } else {
664
            throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
665
        }
666
    }
667
668
    /**
669
     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
670
     *
671
     * @param AbstractTDBMObject $object
672
     *
673
     * @throws TDBMException
674
     */
675
    public function save(AbstractTDBMObject $object)
676
    {
677
        $status = $object->_getStatus();
678
679
        if ($status === null) {
680
            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)));
681
        }
682
683
        // Let's attach this object if it is in detached state.
684
        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
685
            $object->_attach($this);
686
            $status = $object->_getStatus();
687
        }
688
689
        if ($status === TDBMObjectStateEnum::STATE_NEW) {
690
            $dbRows = $object->_getDbRows();
691
692
            $unindexedPrimaryKeys = array();
693
694
            foreach ($dbRows as $dbRow) {
695
                $tableName = $dbRow->_getDbTableName();
696
697
                $schema = $this->tdbmSchemaAnalyzer->getSchema();
698
                $tableDescriptor = $schema->getTable($tableName);
699
700
                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
701
702
                if (empty($unindexedPrimaryKeys)) {
703
                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
704
                } else {
705
                    // First insert, the children must have the same primary key as the parent.
706
                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
707
                    $dbRow->_setPrimaryKeys($primaryKeys);
708
                }
709
710
                $references = $dbRow->_getReferences();
711
712
                // Let's save all references in NEW or DETACHED state (we need their primary key)
713
                foreach ($references as $fkName => $reference) {
714
                    if ($reference !== null) {
715
                        $refStatus = $reference->_getStatus();
716
                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
717
                            $this->save($reference);
718
                        }
719
                    }
720
                }
721
722
                $dbRowData = $dbRow->_getDbRow();
723
724
                // Let's see if the columns for primary key have been set before inserting.
725
                // We assume that if one of the value of the PK has been set, the PK is set.
726
                $isPkSet = !empty($primaryKeys);
727
728
                /*if (!$isPkSet) {
729
                    // if there is no autoincrement and no pk set, let's go in error.
730
                    $isAutoIncrement = true;
731
732
                    foreach ($primaryKeyColumns as $pkColumnName) {
733
                        $pkColumn = $tableDescriptor->getColumn($pkColumnName);
734
                        if (!$pkColumn->getAutoincrement()) {
735
                            $isAutoIncrement = false;
736
                        }
737
                    }
738
739
                    if (!$isAutoIncrement) {
740
                        $msg = "Error! You did not set the primary key(s) for the new object of type '$tableName'. The primary key is not set to 'autoincrement' so you must either set the primary key in the object or modify the DB model to create an primary key with auto-increment.";
741
                        throw new TDBMException($msg);
742
                    }
743
744
                }*/
745
746
                $types = [];
747
                $escapedDbRowData = [];
748
749 View Code Duplication
                foreach ($dbRowData as $columnName => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
750
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
751
                    $types[] = $columnDescriptor->getType();
752
                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
753
                }
754
755
                $this->connection->insert($tableName, $escapedDbRowData, $types);
756
757
                if (!$isPkSet && count($primaryKeyColumns) == 1) {
758
                    $id = $this->connection->lastInsertId();
759
                    $primaryKeys[$primaryKeyColumns[0]] = $id;
760
                }
761
762
                // TODO: change this to some private magic accessor in future
763
                $dbRow->_setPrimaryKeys($primaryKeys);
764
                $unindexedPrimaryKeys = array_values($primaryKeys);
765
766
                /*
767
                 * When attached, on "save", we check if the column updated is part of a primary key
768
                 * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
769
                 * This method should first verify that the id is not already used (and is not auto-incremented)
770
                 *
771
                 * In the object, the key is stored in an array of  (column => value), that can be directly used to update the record.
772
                 *
773
                 *
774
                 */
775
776
                /*try {
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
777
                    $this->db_connection->exec($sql);
778
                } catch (TDBMException $e) {
779
                    $this->db_onerror = true;
780
781
                    // Strange..... if we do not have the line below, bad inserts are not catched.
782
                    // It seems that destructors are called before the registered shutdown function (PHP >=5.0.5)
783
                    //if ($this->tdbmService->isProgramExiting())
784
                    //	trigger_error("program exiting");
785
                    trigger_error($e->getMessage(), E_USER_ERROR);
786
787
                    if (!$this->tdbmService->isProgramExiting())
788
                        throw $e;
789
                    else
790
                    {
791
                        trigger_error($e->getMessage(), E_USER_ERROR);
792
                    }
793
                }*/
794
795
                // Let's remove this object from the $new_objects static table.
796
                $this->removeFromToSaveObjectList($dbRow);
797
798
                // TODO: change this behaviour to something more sensible performance-wise
799
                // Maybe a setting to trigger this globally?
800
                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
801
                //$this->db_modified_state = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
802
                //$dbRow = array();
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
803
804
                // Let's add this object to the list of objects in cache.
805
                $this->_addToCache($dbRow);
806
            }
807
808
            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
809
        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
810
            $dbRows = $object->_getDbRows();
811
812
            foreach ($dbRows as $dbRow) {
813
                $references = $dbRow->_getReferences();
814
815
                // Let's save all references in NEW state (we need their primary key)
816
                foreach ($references as $fkName => $reference) {
817
                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
818
                        $this->save($reference);
819
                    }
820
                }
821
822
                // Let's first get the primary keys
823
                $tableName = $dbRow->_getDbTableName();
824
                $dbRowData = $dbRow->_getDbRow();
825
826
                $schema = $this->tdbmSchemaAnalyzer->getSchema();
827
                $tableDescriptor = $schema->getTable($tableName);
828
829
                $primaryKeys = $dbRow->_getPrimaryKeys();
830
831
                $types = [];
832
                $escapedDbRowData = [];
833
                $escapedPrimaryKeys = [];
834
835 View Code Duplication
                foreach ($dbRowData as $columnName => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
836
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
837
                    $types[] = $columnDescriptor->getType();
838
                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
839
                }
840 View Code Duplication
                foreach ($primaryKeys as $columnName => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
841
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
842
                    $types[] = $columnDescriptor->getType();
843
                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
844
                }
845
846
                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
847
848
                // Let's check if the primary key has been updated...
849
                $needsUpdatePk = false;
850
                foreach ($primaryKeys as $column => $value) {
851
                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
852
                        $needsUpdatePk = true;
853
                        break;
854
                    }
855
                }
856
                if ($needsUpdatePk) {
857
                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
858
                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
859
                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
860
                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
861
                }
862
863
                // Let's remove this object from the list of objects to save.
864
                $this->removeFromToSaveObjectList($dbRow);
865
            }
866
867
            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
868
        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
869
            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
870
        }
871
872
        // Finally, let's save all the many to many relationships to this bean.
873
        $this->persistManyToManyRelationships($object);
874
    }
875
876
    private function persistManyToManyRelationships(AbstractTDBMObject $object)
877
    {
878
        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
879
            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
880
            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
881
882
            $toRemoveFromStorage = [];
883
884
            foreach ($storage as $remoteBean) {
885
                /* @var $remoteBean AbstractTDBMObject */
886
                $statusArr = $storage[$remoteBean];
887
                $status = $statusArr['status'];
888
                $reverse = $statusArr['reverse'];
889
                if ($reverse) {
890
                    continue;
891
                }
892
893
                if ($status === 'new') {
894
                    $remoteBeanStatus = $remoteBean->_getStatus();
895
                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
896
                        // Let's save remote bean if needed.
897
                        $this->save($remoteBean);
898
                    }
899
900
                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
901
902
                    $types = [];
903
                    $escapedFilters = [];
904
905 View Code Duplication
                    foreach ($filters as $columnName => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
906
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
907
                        $types[] = $columnDescriptor->getType();
908
                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
909
                    }
910
911
                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
912
913
                    // Finally, let's mark relationships as saved.
914
                    $statusArr['status'] = 'loaded';
915
                    $storage[$remoteBean] = $statusArr;
916
                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
917
                    $remoteStatusArr = $remoteStorage[$object];
918
                    $remoteStatusArr['status'] = 'loaded';
919
                    $remoteStorage[$object] = $remoteStatusArr;
920
                } elseif ($status === 'delete') {
921
                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
922
923
                    $types = [];
924
925
                    foreach ($filters as $columnName => $value) {
926
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
927
                        $types[] = $columnDescriptor->getType();
928
                    }
929
930
                    $this->connection->delete($pivotTableName, $filters, $types);
931
932
                    // Finally, let's remove relationships completely from bean.
933
                    $toRemoveFromStorage[] = $remoteBean;
934
935
                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
936
                }
937
            }
938
939
            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
940
            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
941
            foreach ($toRemoveFromStorage as $remoteBean) {
942
                $storage->detach($remoteBean);
943
            }
944
        }
945
    }
946
947
    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
948
    {
949
        $localBeanPk = $this->getPrimaryKeyValues($localBean);
950
        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
951
        $localColumns = $localFk->getLocalColumns();
952
        $remoteColumns = $remoteFk->getLocalColumns();
953
954
        $localFilters = array_combine($localColumns, $localBeanPk);
955
        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
956
957
        return array_merge($localFilters, $remoteFilters);
958
    }
959
960
    /**
961
     * Returns the "values" of the primary key.
962
     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
963
     *
964
     * @param AbstractTDBMObject $bean
965
     *
966
     * @return array numerically indexed array of values
967
     */
968
    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
969
    {
970
        $dbRows = $bean->_getDbRows();
971
        $dbRow = reset($dbRows);
972
973
        return array_values($dbRow->_getPrimaryKeys());
974
    }
975
976
    /**
977
     * Returns a unique hash used to store the object based on its primary key.
978
     * If the array contains only one value, then the value is returned.
979
     * Otherwise, a hash representing the array is returned.
980
     *
981
     * @param array $primaryKeys An array of columns => values forming the primary key
982
     *
983
     * @return string
984
     */
985
    public function getObjectHash(array $primaryKeys)
986
    {
987
        if (count($primaryKeys) === 1) {
988
            return reset($primaryKeys);
989
        } else {
990
            ksort($primaryKeys);
991
992
            return md5(json_encode($primaryKeys));
993
        }
994
    }
995
996
    /**
997
     * Returns an array of primary keys from the object.
998
     * The primary keys are extracted from the object columns and not from the primary keys stored in the
999
     * $primaryKeys variable of the object.
1000
     *
1001
     * @param DbRow $dbRow
1002
     *
1003
     * @return array Returns an array of column => value
1004
     */
1005
    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1006
    {
1007
        $table = $dbRow->_getDbTableName();
1008
        $dbRowData = $dbRow->_getDbRow();
1009
1010
        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1011
    }
1012
1013
    /**
1014
     * Returns an array of primary keys for the given row.
1015
     * The primary keys are extracted from the object columns.
1016
     *
1017
     * @param $table
1018
     * @param array $columns
1019
     *
1020
     * @return array
1021
     */
1022
    public function _getPrimaryKeysFromObjectData($table, array $columns)
1023
    {
1024
        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1025
        $values = array();
1026
        foreach ($primaryKeyColumns as $column) {
0 ignored issues
show
Bug introduced by
The expression $primaryKeyColumns of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1027
            if (isset($columns[$column])) {
1028
                $values[$column] = $columns[$column];
1029
            }
1030
        }
1031
1032
        return $values;
1033
    }
1034
1035
    /**
1036
     * Attaches $object to this TDBMService.
1037
     * The $object must be in DETACHED state and will pass in NEW state.
1038
     *
1039
     * @param AbstractTDBMObject $object
1040
     *
1041
     * @throws TDBMInvalidOperationException
1042
     */
1043
    public function attach(AbstractTDBMObject $object)
1044
    {
1045
        $object->_attach($this);
1046
    }
1047
1048
    /**
1049
     * Returns an associative array (column => value) for the primary keys from the table name and an
1050
     * indexed array of primary key values.
1051
     *
1052
     * @param string $tableName
1053
     * @param array  $indexedPrimaryKeys
1054
     */
1055
    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1056
    {
1057
        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1058
1059
        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1060
            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1061
			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1062
        }
1063
1064
        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1065
    }
1066
1067
    /**
1068
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1069
     * Tables must be in a single line of inheritance. The method will find missing tables.
1070
     *
1071
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1072
     * we must be able to find all other tables.
1073
     *
1074
     * @param string[] $tables
1075
     *
1076
     * @return string[]
1077
     */
1078
    public function _getLinkBetweenInheritedTables(array $tables)
1079
    {
1080
        sort($tables);
1081
1082
        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1083
            function () use ($tables) {
1084
                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1085
            });
1086
    }
1087
1088
    /**
1089
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1090
     * Tables must be in a single line of inheritance. The method will find missing tables.
1091
     *
1092
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1093
     * we must be able to find all other tables.
1094
     *
1095
     * @param string[] $tables
1096
     *
1097
     * @return string[]
1098
     */
1099
    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1100
    {
1101
        $schemaAnalyzer = $this->schemaAnalyzer;
1102
1103
        foreach ($tables as $currentTable) {
1104
            $allParents = [$currentTable];
1105
            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1106
                $currentTable = $currentFk->getForeignTableName();
1107
                $allParents[] = $currentTable;
1108
            }
1109
1110
            // Now, does the $allParents contain all the tables we want?
1111
            $notFoundTables = array_diff($tables, $allParents);
1112
            if (empty($notFoundTables)) {
1113
                // We have a winner!
1114
                return $allParents;
1115
            }
1116
        }
1117
1118
        throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1119
    }
1120
1121
    /**
1122
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1123
     *
1124
     * @param string $table
1125
     *
1126
     * @return string[]
1127
     */
1128
    public function _getRelatedTablesByInheritance($table)
1129
    {
1130
        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1131
            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1132
        });
1133
    }
1134
1135
    /**
1136
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1137
     *
1138
     * @param string $table
1139
     *
1140
     * @return string[]
1141
     */
1142
    private function _getRelatedTablesByInheritanceWithoutCache($table)
1143
    {
1144
        $schemaAnalyzer = $this->schemaAnalyzer;
1145
1146
        // Let's scan the parent tables
1147
        $currentTable = $table;
1148
1149
        $parentTables = [];
1150
1151
        // Get parent relationship
1152
        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1153
            $currentTable = $currentFk->getForeignTableName();
1154
            $parentTables[] = $currentTable;
1155
        }
1156
1157
        // Let's recurse in children
1158
        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1159
1160
        return array_merge(array_reverse($parentTables), $childrenTables);
1161
    }
1162
1163
    /**
1164
     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1165
     *
1166
     * @param string $table
1167
     *
1168
     * @return string[]
1169
     */
1170
    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1171
    {
1172
        $tables = [$table];
1173
        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1174
1175
        foreach ($keys as $key) {
1176
            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1177
        }
1178
1179
        return $tables;
1180
    }
1181
1182
    /**
1183
     * Casts a foreign key into SQL, assuming table name is used with no alias.
1184
     * The returned value does contain only one table. For instance:.
1185
     *
1186
     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1187
     *
1188
     * @param ForeignKeyConstraint $fk
1189
     * @param bool                 $leftTableIsLocal
1190
     *
1191
     * @return string
1192
     */
1193
    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1194
        $onClauses = [];
1195
        $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1196
        $foreignColumns = $fk->getForeignColumns();
1197
        $localTableName = $this->connection->quoteIdentifier($fk->getLocalTableName());
1198
        $localColumns = $fk->getLocalColumns();
1199
        $columnCount = count($localTableName);
1200
1201
        for ($i = 0; $i < $columnCount; $i++) {
1202
            $onClauses[] = sprintf("%s.%s = %s.%s",
1203
                $localTableName,
1204
                $this->connection->quoteIdentifier($localColumns[$i]),
1205
                $foreignColumns,
1206
                $this->connection->quoteIdentifier($foreignColumns[$i])
1207
                );
1208
        }
1209
1210
        $onClause = implode(' AND ', $onClauses);
1211
1212
        if ($leftTableIsLocal) {
1213
            return sprintf(" LEFT JOIN %s ON (%s)", $foreignTableName, $onClause);
1214
        } else {
1215
            return sprintf(" LEFT JOIN %s ON (%s)", $localTableName, $onClause);
1216
        }
1217
    }*/
1218
1219
    /**
1220
     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1221
     *
1222
     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1223
     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1224
     *
1225
     * The findObjects method takes in parameter:
1226
     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1227
     * 			`$mainTable` parameter should be the name of an existing table in database.
1228
     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1229
     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1230
     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1231
     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1232
     *          Instead, please consider passing parameters (see documentation for more details).
1233
     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1234
     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1235
     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1236
     *
1237
     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1238
     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1239
     *
1240
     * Finally, if filter_bag is null, the whole table is returned.
1241
     *
1242
     * @param string                       $mainTable             The name of the table queried
1243
     * @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)
1244
     * @param array                        $parameters
1245
     * @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)
1246
     * @param array                        $additionalTablesFetch
1247
     * @param int                          $mode
1248
     * @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
1249
     *
1250
     * @return ResultIterator An object representing an array of results
1251
     *
1252
     * @throws TDBMException
1253
     */
1254
    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1255
    {
1256
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1257
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1258
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1259
        }
1260
1261
        $mode = $mode ?: $this->mode;
1262
1263
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1264
1265
        $parameters = array_merge($parameters, $additionalParameters);
1266
1267
        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1268
1269
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1270
    }
1271
1272
    /**
1273
     * @param string                       $mainTable   The name of the table queried
1274
     * @param string                       $from        The from sql statement
1275
     * @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)
1276
     * @param array                        $parameters
1277
     * @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)
1278
     * @param int                          $mode
1279
     * @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
1280
     *
1281
     * @return ResultIterator An object representing an array of results
1282
     *
1283
     * @throws TDBMException
1284
     */
1285
    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1286
    {
1287
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1288
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1289
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1290
        }
1291
1292
        $mode = $mode ?: $this->mode;
1293
1294
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1295
1296
        $parameters = array_merge($parameters, $additionalParameters);
1297
1298
        $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
0 ignored issues
show
Bug introduced by
It seems like $this->cache can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1299
1300
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1301
    }
1302
1303
    /**
1304
     * @param $table
1305
     * @param array  $primaryKeys
1306
     * @param array  $additionalTablesFetch
1307
     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1308
     * @param string $className
1309
     *
1310
     * @return AbstractTDBMObject
1311
     *
1312
     * @throws TDBMException
1313
     */
1314
    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1315
    {
1316
        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1317
        $hash = $this->getObjectHash($primaryKeys);
1318
1319
        if ($this->objectStorage->has($table, $hash)) {
1320
            $dbRow = $this->objectStorage->get($table, $hash);
1321
            $bean = $dbRow->getTDBMObject();
1322
            if ($className !== null && !is_a($bean, $className)) {
1323
                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1324
            }
1325
1326
            return $bean;
1327
        }
1328
1329
        // Are we performing lazy fetching?
1330
        if ($lazy === true) {
1331
            // Can we perform lazy fetching?
1332
            $tables = $this->_getRelatedTablesByInheritance($table);
1333
            // Only allowed if no inheritance.
1334
            if (count($tables) === 1) {
1335
                if ($className === null) {
1336
                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1337
                }
1338
1339
                // Let's construct the bean
1340
                if (!isset($this->reflectionClassCache[$className])) {
1341
                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1342
                }
1343
                // Let's bypass the constructor when creating the bean!
1344
                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1345
                /* @var $bean AbstractTDBMObject */
1346
                $bean->_constructLazy($table, $primaryKeys, $this);
1347
1348
                return $bean;
1349
            }
1350
        }
1351
1352
        // Did not find the object in cache? Let's query it!
1353
        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1354
    }
1355
1356
    /**
1357
     * Returns a unique bean (or null) according to the filters passed in parameter.
1358
     *
1359
     * @param string            $mainTable             The name of the table queried
1360
     * @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)
1361
     * @param array             $parameters
1362
     * @param array             $additionalTablesFetch
1363
     * @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
1364
     *
1365
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1366
     *
1367
     * @throws TDBMException
1368
     */
1369 View Code Duplication
    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1370
    {
1371
        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1372
        $page = $objects->take(0, 2);
1373
        $count = $page->count();
1374
        if ($count > 1) {
1375
            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.");
1376
        } elseif ($count === 0) {
1377
            return;
1378
        }
1379
1380
        return $page[0];
1381
    }
1382
1383
    /**
1384
     * Returns a unique bean (or null) according to the filters passed in parameter.
1385
     *
1386
     * @param string            $mainTable  The name of the table queried
1387
     * @param string            $from       The from sql statement
1388
     * @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)
1389
     * @param array             $parameters
1390
     * @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
1391
     *
1392
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1393
     *
1394
     * @throws TDBMException
1395
     */
1396 View Code Duplication
    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1397
    {
1398
        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1399
        $page = $objects->take(0, 2);
1400
        $count = $page->count();
1401
        if ($count > 1) {
1402
            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.");
1403
        } elseif ($count === 0) {
1404
            return;
1405
        }
1406
1407
        return $page[0];
1408
    }
1409
1410
    /**
1411
     * Returns a unique bean according to the filters passed in parameter.
1412
     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1413
     *
1414
     * @param string            $mainTable             The name of the table queried
1415
     * @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)
1416
     * @param array             $parameters
1417
     * @param array             $additionalTablesFetch
1418
     * @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
1419
     *
1420
     * @return AbstractTDBMObject The object we want
1421
     *
1422
     * @throws TDBMException
1423
     */
1424
    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1425
    {
1426
        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1427
        if ($bean === null) {
1428
            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1429
        }
1430
1431
        return $bean;
1432
    }
1433
1434
    /**
1435
     * @param array $beanData An array of data: array<table, array<column, value>>
1436
     *
1437
     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1438
     */
1439
    public function _getClassNameFromBeanData(array $beanData)
1440
    {
1441
        if (count($beanData) === 1) {
1442
            $tableName = array_keys($beanData)[0];
1443
            $allTables = [$tableName];
1444
        } else {
1445
            $tables = [];
1446
            foreach ($beanData as $table => $row) {
1447
                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1448
                $pkSet = false;
1449
                foreach ($primaryKeyColumns as $columnName) {
0 ignored issues
show
Bug introduced by
The expression $primaryKeyColumns of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1450
                    if ($row[$columnName] !== null) {
1451
                        $pkSet = true;
1452
                        break;
1453
                    }
1454
                }
1455
                if ($pkSet) {
1456
                    $tables[] = $table;
1457
                }
1458
            }
1459
1460
            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1461
            $allTables = $this->_getLinkBetweenInheritedTables($tables);
1462
            $tableName = $allTables[0];
1463
        }
1464
1465
        // Only one table in this bean. Life is sweat, let's look at its type:
1466
        if (isset($this->tableToBeanMap[$tableName])) {
1467
            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1468
        } else {
1469
            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1470
        }
1471
    }
1472
1473
    /**
1474
     * Returns an item from cache or computes it using $closure and puts it in cache.
1475
     *
1476
     * @param string   $key
1477
     * @param callable $closure
1478
     *
1479
     * @return mixed
1480
     */
1481 View Code Duplication
    private function fromCache(string $key, callable $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1482
    {
1483
        $item = $this->cache->fetch($key);
1484
        if ($item === false) {
1485
            $item = $closure();
1486
            $this->cache->save($key, $item);
1487
        }
1488
1489
        return $item;
1490
    }
1491
1492
    /**
1493
     * Returns the foreign key object.
1494
     *
1495
     * @param string $table
1496
     * @param string $fkName
1497
     *
1498
     * @return ForeignKeyConstraint
1499
     */
1500
    public function _getForeignKeyByName(string $table, string $fkName)
1501
    {
1502
        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1503
    }
1504
1505
    /**
1506
     * @param $pivotTableName
1507
     * @param AbstractTDBMObject $bean
1508
     *
1509
     * @return AbstractTDBMObject[]
1510
     */
1511
    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1512
    {
1513
        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1514
        /* @var $localFk ForeignKeyConstraint */
1515
        /* @var $remoteFk ForeignKeyConstraint */
1516
        $remoteTable = $remoteFk->getForeignTableName();
1517
1518
        $primaryKeys = $this->getPrimaryKeyValues($bean);
1519
        $columnNames = array_map(function ($name) use ($pivotTableName) {
1520
            return $pivotTableName.'.'.$name;
1521
        }, $localFk->getLocalColumns());
1522
1523
        $filter = array_combine($columnNames, $primaryKeys);
1524
1525
        return $this->findObjects($remoteTable, $filter);
1526
    }
1527
1528
    /**
1529
     * @param $pivotTableName
1530
     * @param AbstractTDBMObject $bean The LOCAL bean
1531
     *
1532
     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1533
     *
1534
     * @throws TDBMException
1535
     */
1536
    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1537
    {
1538
        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1539
        $table1 = $fks[0]->getForeignTableName();
1540
        $table2 = $fks[1]->getForeignTableName();
1541
1542
        $beanTables = array_map(function (DbRow $dbRow) {
1543
            return $dbRow->_getDbTableName();
1544
        }, $bean->_getDbRows());
1545
1546
        if (in_array($table1, $beanTables)) {
1547
            return [$fks[0], $fks[1]];
1548
        } elseif (in_array($table2, $beanTables)) {
1549
            return [$fks[1], $fks[0]];
1550
        } else {
1551
            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1552
        }
1553
    }
1554
1555
    /**
1556
     * Returns a list of pivot tables linked to $bean.
1557
     *
1558
     * @param AbstractTDBMObject $bean
1559
     *
1560
     * @return string[]
1561
     */
1562
    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1563
    {
1564
        $junctionTables = [];
1565
        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1566
        foreach ($bean->_getDbRows() as $dbRow) {
1567
            foreach ($allJunctionTables as $table) {
1568
                // There are exactly 2 FKs since this is a pivot table.
1569
                $fks = array_values($table->getForeignKeys());
1570
1571
                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1572
                    $junctionTables[] = $table->getName();
1573
                }
1574
            }
1575
        }
1576
1577
        return $junctionTables;
1578
    }
1579
1580
    /**
1581
     * Array of types for tables.
1582
     * Key: table name
1583
     * Value: array of types indexed by column.
1584
     *
1585
     * @var array[]
1586
     */
1587
    private $typesForTable = [];
1588
1589
    /**
1590
     * @internal
1591
     *
1592
     * @param string $tableName
1593
     *
1594
     * @return Type[]
1595
     */
1596
    public function _getColumnTypesForTable(string $tableName)
1597
    {
1598
        if (!isset($typesForTable[$tableName])) {
0 ignored issues
show
Bug introduced by
The variable $typesForTable seems only to be defined at a later point. As such the call to isset() seems to always evaluate to false.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
1599
            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1600
            $typesForTable[$tableName] = array_map(function (Column $column) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
$typesForTable was never initialized. Although not strictly required by PHP, it is generally a good practice to add $typesForTable = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1601
                return $column->getType();
1602
            }, $columns);
1603
        }
1604
1605
        return $typesForTable[$tableName];
1606
    }
1607
1608
    /**
1609
     * Sets the minimum log level.
1610
     * $level must be one of Psr\Log\LogLevel::xxx.
1611
     *
1612
     * Defaults to LogLevel::WARNING
1613
     *
1614
     * @param string $level
1615
     */
1616
    public function setLogLevel(string $level)
1617
    {
1618
        $this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1619
    }
1620
}
1621