TDBMService   F
last analyzed

Complexity

Total Complexity 157

Size/Duplication

Total Lines 1591
Duplicated Lines 3.52 %

Coupling/Cohesion

Components 1
Dependencies 30

Importance

Changes 0
Metric Value
wmc 157
lcom 1
cbo 30
dl 56
loc 1591
rs 0.5217
c 0
b 0
f 0

45 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 34 5
A getConnection() 0 4 1
A getConnectionUniqueId() 0 4 1
A setFetchMode() 0 9 3
D delete() 0 38 10
A deleteManyToManyRelationships() 0 13 4
A deleteCascade() 0 5 1
B deleteAllConstraintWithThisObject() 0 21 5
A completeSave() 0 6 2
C buildFilterFromFilterBag() 0 48 10
B getPrimaryKeyColumns() 0 32 2
A _addToCache() 0 6 1
A removeFromToSaveObjectList() 0 4 1
A _addToToSaveObjectList() 0 4 1
A generateAllDaosAndBeans() 0 12 2
A setTableToBeanMap() 0 4 1
A getBeanClassName() 0 8 2
D save() 15 211 27
C persistManyToManyRelationships() 5 70 11
A getPivotFilters() 0 12 1
A getPrimaryKeyValues() 0 7 1
A getObjectHash() 0 10 2
A getPrimaryKeysForObjectFromDbRow() 0 7 1
A _getPrimaryKeysFromObjectData() 0 12 3
A attach() 0 4 1
A _getPrimaryKeysFromIndexedPrimaryKeys() 0 11 2
A _getLinkBetweenInheritedTables() 0 9 1
A _getLinkBetweenInheritedTablesWithoutCache() 0 21 4
A _getRelatedTablesByInheritance() 0 6 1
A _getRelatedTablesByInheritanceWithoutCache() 0 20 2
A exploreChildrenTablesRelationships() 0 11 2
A findObjects() 0 17 3
A findObjectsFromSql() 0 17 3
D findObjectByPk() 0 41 9
A findObject() 13 13 3
A findObjectFromSql() 13 13 3
A findObjectOrFail() 0 9 2
C _getClassNameFromBeanData() 0 37 8
A fromCache() 10 10 2
A _getForeignKeyByName() 0 4 1
A _getRelatedBeans() 0 16 1
A getPivotTableForeignKeys() 0 18 3
B _getPivotTablesLinkedToBean() 0 17 5
A _getColumnTypesForTable() 0 11 2
A setLogLevel() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like TDBMService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TDBMService, and based on these observations, apply Extract Interface, too.

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 Mouf\Database\MagicQuery;
32
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
33
use Mouf\Database\TDBM\QueryFactory\FindObjectsFromSqlQueryFactory;
34
use Mouf\Database\TDBM\QueryFactory\FindObjectsQueryFactory;
35
use Mouf\Database\TDBM\Utils\TDBMDaoGenerator;
36
use Phlib\Logger\LevelFilter;
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 LevelFilter|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
     *
658
     * @return string
659
     */
660
    public function getBeanClassName(string $tableName) : string
661
    {
662
        if (isset($this->tableToBeanMap[$tableName])) {
663
            return $this->tableToBeanMap[$tableName];
664
        } else {
665
            throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
666
        }
667
    }
668
669
    /**
670
     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
671
     *
672
     * @param AbstractTDBMObject $object
673
     *
674
     * @throws TDBMException
675
     */
676
    public function save(AbstractTDBMObject $object)
677
    {
678
        $status = $object->_getStatus();
679
680
        if ($status === null) {
681
            throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
682
        }
683
684
        // Let's attach this object if it is in detached state.
685
        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
686
            $object->_attach($this);
687
            $status = $object->_getStatus();
688
        }
689
690
        if ($status === TDBMObjectStateEnum::STATE_NEW) {
691
            $dbRows = $object->_getDbRows();
692
693
            $unindexedPrimaryKeys = array();
694
695
            foreach ($dbRows as $dbRow) {
696
                if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
697
                    throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
698
                }
699
                $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
700
                $tableName = $dbRow->_getDbTableName();
701
702
                $schema = $this->tdbmSchemaAnalyzer->getSchema();
703
                $tableDescriptor = $schema->getTable($tableName);
704
705
                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
706
707
                $references = $dbRow->_getReferences();
708
709
                // Let's save all references in NEW or DETACHED state (we need their primary key)
710
                foreach ($references as $fkName => $reference) {
711
                    if ($reference !== null) {
712
                        $refStatus = $reference->_getStatus();
713
                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
714
                            try {
715
                                $this->save($reference);
716
                            } catch (TDBMCyclicReferenceException $e) {
717
                                throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
718
                            }
719
                        }
720
                    }
721
                }
722
723
                if (empty($unindexedPrimaryKeys)) {
724
                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
725
                } else {
726
                    // First insert, the children must have the same primary key as the parent.
727
                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
728
                    $dbRow->_setPrimaryKeys($primaryKeys);
729
                }
730
731
                $dbRowData = $dbRow->_getDbRow();
732
733
                // Let's see if the columns for primary key have been set before inserting.
734
                // We assume that if one of the value of the PK has been set, the PK is set.
735
                $isPkSet = !empty($primaryKeys);
736
737
                /*if (!$isPkSet) {
738
                    // if there is no autoincrement and no pk set, let's go in error.
739
                    $isAutoIncrement = true;
740
741
                    foreach ($primaryKeyColumns as $pkColumnName) {
742
                        $pkColumn = $tableDescriptor->getColumn($pkColumnName);
743
                        if (!$pkColumn->getAutoincrement()) {
744
                            $isAutoIncrement = false;
745
                        }
746
                    }
747
748
                    if (!$isAutoIncrement) {
749
                        $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.";
750
                        throw new TDBMException($msg);
751
                    }
752
753
                }*/
754
755
                $types = [];
756
                $escapedDbRowData = [];
757
758 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...
759
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
760
                    $types[] = $columnDescriptor->getType();
761
                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
762
                }
763
764
                $this->connection->insert($tableName, $escapedDbRowData, $types);
765
766
                if (!$isPkSet && count($primaryKeyColumns) == 1) {
767
                    $id = $this->connection->lastInsertId();
768
                    $pkColumn = $primaryKeyColumns[0];
769
                    // lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
770
                    $id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
771
                    $primaryKeys[$pkColumn] = $id;
772
                }
773
774
                // TODO: change this to some private magic accessor in future
775
                $dbRow->_setPrimaryKeys($primaryKeys);
776
                $unindexedPrimaryKeys = array_values($primaryKeys);
777
778
                /*
779
                 * When attached, on "save", we check if the column updated is part of a primary key
780
                 * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
781
                 * This method should first verify that the id is not already used (and is not auto-incremented)
782
                 *
783
                 * In the object, the key is stored in an array of  (column => value), that can be directly used to update the record.
784
                 *
785
                 *
786
                 */
787
788
                /*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...
789
                    $this->db_connection->exec($sql);
790
                } catch (TDBMException $e) {
791
                    $this->db_onerror = true;
792
793
                    // Strange..... if we do not have the line below, bad inserts are not catched.
794
                    // It seems that destructors are called before the registered shutdown function (PHP >=5.0.5)
795
                    //if ($this->tdbmService->isProgramExiting())
796
                    //	trigger_error("program exiting");
797
                    trigger_error($e->getMessage(), E_USER_ERROR);
798
799
                    if (!$this->tdbmService->isProgramExiting())
800
                        throw $e;
801
                    else
802
                    {
803
                        trigger_error($e->getMessage(), E_USER_ERROR);
804
                    }
805
                }*/
806
807
                // Let's remove this object from the $new_objects static table.
808
                $this->removeFromToSaveObjectList($dbRow);
809
810
                // TODO: change this behaviour to something more sensible performance-wise
811
                // Maybe a setting to trigger this globally?
812
                //$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...
813
                //$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...
814
                //$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...
815
816
                // Let's add this object to the list of objects in cache.
817
                $this->_addToCache($dbRow);
818
            }
819
820
            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
821
        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
822
            $dbRows = $object->_getDbRows();
823
824
            foreach ($dbRows as $dbRow) {
825
                $references = $dbRow->_getReferences();
826
827
                // Let's save all references in NEW state (we need their primary key)
828
                foreach ($references as $fkName => $reference) {
829
                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
830
                        $this->save($reference);
831
                    }
832
                }
833
834
                // Let's first get the primary keys
835
                $tableName = $dbRow->_getDbTableName();
836
                $dbRowData = $dbRow->_getDbRow();
837
838
                $schema = $this->tdbmSchemaAnalyzer->getSchema();
839
                $tableDescriptor = $schema->getTable($tableName);
840
841
                $primaryKeys = $dbRow->_getPrimaryKeys();
842
843
                $types = [];
844
                $escapedDbRowData = [];
845
                $escapedPrimaryKeys = [];
846
847 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...
848
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
849
                    $types[] = $columnDescriptor->getType();
850
                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
851
                }
852 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...
853
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
854
                    $types[] = $columnDescriptor->getType();
855
                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
856
                }
857
858
                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
859
860
                // Let's check if the primary key has been updated...
861
                $needsUpdatePk = false;
862
                foreach ($primaryKeys as $column => $value) {
863
                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
864
                        $needsUpdatePk = true;
865
                        break;
866
                    }
867
                }
868
                if ($needsUpdatePk) {
869
                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
870
                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
871
                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
872
                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
873
                }
874
875
                // Let's remove this object from the list of objects to save.
876
                $this->removeFromToSaveObjectList($dbRow);
877
            }
878
879
            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
880
        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
881
            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
882
        }
883
884
        // Finally, let's save all the many to many relationships to this bean.
885
        $this->persistManyToManyRelationships($object);
886
    }
887
888
    private function persistManyToManyRelationships(AbstractTDBMObject $object)
889
    {
890
        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
891
            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
892
            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
893
894
            $toRemoveFromStorage = [];
895
896
            foreach ($storage as $remoteBean) {
897
                /* @var $remoteBean AbstractTDBMObject */
898
                $statusArr = $storage[$remoteBean];
899
                $status = $statusArr['status'];
900
                $reverse = $statusArr['reverse'];
901
                if ($reverse) {
902
                    continue;
903
                }
904
905
                if ($status === 'new') {
906
                    $remoteBeanStatus = $remoteBean->_getStatus();
907
                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
908
                        // Let's save remote bean if needed.
909
                        $this->save($remoteBean);
910
                    }
911
912
                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
913
914
                    $types = [];
915
                    $escapedFilters = [];
916
917 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...
918
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
919
                        $types[] = $columnDescriptor->getType();
920
                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
921
                    }
922
923
                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
924
925
                    // Finally, let's mark relationships as saved.
926
                    $statusArr['status'] = 'loaded';
927
                    $storage[$remoteBean] = $statusArr;
928
                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
929
                    $remoteStatusArr = $remoteStorage[$object];
930
                    $remoteStatusArr['status'] = 'loaded';
931
                    $remoteStorage[$object] = $remoteStatusArr;
932
                } elseif ($status === 'delete') {
933
                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
934
935
                    $types = [];
936
937
                    foreach ($filters as $columnName => $value) {
938
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
939
                        $types[] = $columnDescriptor->getType();
940
                    }
941
942
                    $this->connection->delete($pivotTableName, $filters, $types);
943
944
                    // Finally, let's remove relationships completely from bean.
945
                    $toRemoveFromStorage[] = $remoteBean;
946
947
                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
948
                }
949
            }
950
951
            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
952
            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
953
            foreach ($toRemoveFromStorage as $remoteBean) {
954
                $storage->detach($remoteBean);
955
            }
956
        }
957
    }
958
959
    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
960
    {
961
        $localBeanPk = $this->getPrimaryKeyValues($localBean);
962
        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
963
        $localColumns = $localFk->getLocalColumns();
964
        $remoteColumns = $remoteFk->getLocalColumns();
965
966
        $localFilters = array_combine($localColumns, $localBeanPk);
967
        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
968
969
        return array_merge($localFilters, $remoteFilters);
970
    }
971
972
    /**
973
     * Returns the "values" of the primary key.
974
     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
975
     *
976
     * @param AbstractTDBMObject $bean
977
     *
978
     * @return array numerically indexed array of values
979
     */
980
    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
981
    {
982
        $dbRows = $bean->_getDbRows();
983
        $dbRow = reset($dbRows);
984
985
        return array_values($dbRow->_getPrimaryKeys());
986
    }
987
988
    /**
989
     * Returns a unique hash used to store the object based on its primary key.
990
     * If the array contains only one value, then the value is returned.
991
     * Otherwise, a hash representing the array is returned.
992
     *
993
     * @param array $primaryKeys An array of columns => values forming the primary key
994
     *
995
     * @return string
996
     */
997
    public function getObjectHash(array $primaryKeys)
998
    {
999
        if (count($primaryKeys) === 1) {
1000
            return reset($primaryKeys);
1001
        } else {
1002
            ksort($primaryKeys);
1003
1004
            return md5(json_encode($primaryKeys));
1005
        }
1006
    }
1007
1008
    /**
1009
     * Returns an array of primary keys from the object.
1010
     * The primary keys are extracted from the object columns and not from the primary keys stored in the
1011
     * $primaryKeys variable of the object.
1012
     *
1013
     * @param DbRow $dbRow
1014
     *
1015
     * @return array Returns an array of column => value
1016
     */
1017
    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1018
    {
1019
        $table = $dbRow->_getDbTableName();
1020
        $dbRowData = $dbRow->_getDbRow();
1021
1022
        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1023
    }
1024
1025
    /**
1026
     * Returns an array of primary keys for the given row.
1027
     * The primary keys are extracted from the object columns.
1028
     *
1029
     * @param $table
1030
     * @param array $columns
1031
     *
1032
     * @return array
1033
     */
1034
    public function _getPrimaryKeysFromObjectData($table, array $columns)
1035
    {
1036
        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1037
        $values = array();
1038
        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...
1039
            if (isset($columns[$column])) {
1040
                $values[$column] = $columns[$column];
1041
            }
1042
        }
1043
1044
        return $values;
1045
    }
1046
1047
    /**
1048
     * Attaches $object to this TDBMService.
1049
     * The $object must be in DETACHED state and will pass in NEW state.
1050
     *
1051
     * @param AbstractTDBMObject $object
1052
     *
1053
     * @throws TDBMInvalidOperationException
1054
     */
1055
    public function attach(AbstractTDBMObject $object)
1056
    {
1057
        $object->_attach($this);
1058
    }
1059
1060
    /**
1061
     * Returns an associative array (column => value) for the primary keys from the table name and an
1062
     * indexed array of primary key values.
1063
     *
1064
     * @param string $tableName
1065
     * @param array  $indexedPrimaryKeys
1066
     */
1067
    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1068
    {
1069
        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1070
1071
        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1072
            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1073
			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1074
        }
1075
1076
        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1077
    }
1078
1079
    /**
1080
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1081
     * Tables must be in a single line of inheritance. The method will find missing tables.
1082
     *
1083
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1084
     * we must be able to find all other tables.
1085
     *
1086
     * @param string[] $tables
1087
     *
1088
     * @return string[]
1089
     */
1090
    public function _getLinkBetweenInheritedTables(array $tables)
1091
    {
1092
        sort($tables);
1093
1094
        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1095
            function () use ($tables) {
1096
                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1097
            });
1098
    }
1099
1100
    /**
1101
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1102
     * Tables must be in a single line of inheritance. The method will find missing tables.
1103
     *
1104
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1105
     * we must be able to find all other tables.
1106
     *
1107
     * @param string[] $tables
1108
     *
1109
     * @return string[]
1110
     */
1111
    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1112
    {
1113
        $schemaAnalyzer = $this->schemaAnalyzer;
1114
1115
        foreach ($tables as $currentTable) {
1116
            $allParents = [$currentTable];
1117
            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1118
                $currentTable = $currentFk->getForeignTableName();
1119
                $allParents[] = $currentTable;
1120
            }
1121
1122
            // Now, does the $allParents contain all the tables we want?
1123
            $notFoundTables = array_diff($tables, $allParents);
1124
            if (empty($notFoundTables)) {
1125
                // We have a winner!
1126
                return $allParents;
1127
            }
1128
        }
1129
1130
        throw TDBMInheritanceException::create($tables);
1131
    }
1132
1133
    /**
1134
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1135
     *
1136
     * @param string $table
1137
     *
1138
     * @return string[]
1139
     */
1140
    public function _getRelatedTablesByInheritance($table)
1141
    {
1142
        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1143
            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1144
        });
1145
    }
1146
1147
    /**
1148
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1149
     *
1150
     * @param string $table
1151
     *
1152
     * @return string[]
1153
     */
1154
    private function _getRelatedTablesByInheritanceWithoutCache($table)
1155
    {
1156
        $schemaAnalyzer = $this->schemaAnalyzer;
1157
1158
        // Let's scan the parent tables
1159
        $currentTable = $table;
1160
1161
        $parentTables = [];
1162
1163
        // Get parent relationship
1164
        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1165
            $currentTable = $currentFk->getForeignTableName();
1166
            $parentTables[] = $currentTable;
1167
        }
1168
1169
        // Let's recurse in children
1170
        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1171
1172
        return array_merge(array_reverse($parentTables), $childrenTables);
1173
    }
1174
1175
    /**
1176
     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1177
     *
1178
     * @param string $table
1179
     *
1180
     * @return string[]
1181
     */
1182
    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1183
    {
1184
        $tables = [$table];
1185
        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1186
1187
        foreach ($keys as $key) {
1188
            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1189
        }
1190
1191
        return $tables;
1192
    }
1193
1194
    /**
1195
     * Casts a foreign key into SQL, assuming table name is used with no alias.
1196
     * The returned value does contain only one table. For instance:.
1197
     *
1198
     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1199
     *
1200
     * @param ForeignKeyConstraint $fk
1201
     * @param bool                 $leftTableIsLocal
1202
     *
1203
     * @return string
1204
     */
1205
    /*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...
1206
        $onClauses = [];
1207
        $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1208
        $foreignColumns = $fk->getForeignColumns();
1209
        $localTableName = $this->connection->quoteIdentifier($fk->getLocalTableName());
1210
        $localColumns = $fk->getLocalColumns();
1211
        $columnCount = count($localTableName);
1212
1213
        for ($i = 0; $i < $columnCount; $i++) {
1214
            $onClauses[] = sprintf("%s.%s = %s.%s",
1215
                $localTableName,
1216
                $this->connection->quoteIdentifier($localColumns[$i]),
1217
                $foreignColumns,
1218
                $this->connection->quoteIdentifier($foreignColumns[$i])
1219
                );
1220
        }
1221
1222
        $onClause = implode(' AND ', $onClauses);
1223
1224
        if ($leftTableIsLocal) {
1225
            return sprintf(" LEFT JOIN %s ON (%s)", $foreignTableName, $onClause);
1226
        } else {
1227
            return sprintf(" LEFT JOIN %s ON (%s)", $localTableName, $onClause);
1228
        }
1229
    }*/
1230
1231
    /**
1232
     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1233
     *
1234
     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1235
     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1236
     *
1237
     * The findObjects method takes in parameter:
1238
     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1239
     * 			`$mainTable` parameter should be the name of an existing table in database.
1240
     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1241
     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1242
     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1243
     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1244
     *          Instead, please consider passing parameters (see documentation for more details).
1245
     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1246
     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1247
     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1248
     *
1249
     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1250
     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1251
     *
1252
     * Finally, if filter_bag is null, the whole table is returned.
1253
     *
1254
     * @param string                       $mainTable             The name of the table queried
1255
     * @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)
1256
     * @param array                        $parameters
1257
     * @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)
1258
     * @param array                        $additionalTablesFetch
1259
     * @param int                          $mode
1260
     * @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
1261
     *
1262
     * @return ResultIterator An object representing an array of results
1263
     *
1264
     * @throws TDBMException
1265
     */
1266
    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1267
    {
1268
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1269
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1270
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1271
        }
1272
1273
        $mode = $mode ?: $this->mode;
1274
1275
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1276
1277
        $parameters = array_merge($parameters, $additionalParameters);
1278
1279
        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1280
1281
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1282
    }
1283
1284
    /**
1285
     * @param string                       $mainTable   The name of the table queried
1286
     * @param string                       $from        The from sql statement
1287
     * @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)
1288
     * @param array                        $parameters
1289
     * @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)
1290
     * @param int                          $mode
1291
     * @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
1292
     *
1293
     * @return ResultIterator An object representing an array of results
1294
     *
1295
     * @throws TDBMException
1296
     */
1297
    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1298
    {
1299
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1300
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1301
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1302
        }
1303
1304
        $mode = $mode ?: $this->mode;
1305
1306
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1307
1308
        $parameters = array_merge($parameters, $additionalParameters);
1309
1310
        $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...
1311
1312
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1313
    }
1314
1315
    /**
1316
     * @param $table
1317
     * @param array  $primaryKeys
1318
     * @param array  $additionalTablesFetch
1319
     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1320
     * @param string $className
1321
     *
1322
     * @return AbstractTDBMObject
1323
     *
1324
     * @throws TDBMException
1325
     */
1326
    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1327
    {
1328
        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1329
        $hash = $this->getObjectHash($primaryKeys);
1330
1331
        if ($this->objectStorage->has($table, $hash)) {
1332
            $dbRow = $this->objectStorage->get($table, $hash);
1333
            $bean = $dbRow->getTDBMObject();
1334
            if ($className !== null && !is_a($bean, $className)) {
1335
                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1336
            }
1337
1338
            return $bean;
1339
        }
1340
1341
        // Are we performing lazy fetching?
1342
        if ($lazy === true) {
1343
            // Can we perform lazy fetching?
1344
            $tables = $this->_getRelatedTablesByInheritance($table);
1345
            // Only allowed if no inheritance.
1346
            if (count($tables) === 1) {
1347
                if ($className === null) {
1348
                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1349
                }
1350
1351
                // Let's construct the bean
1352
                if (!isset($this->reflectionClassCache[$className])) {
1353
                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1354
                }
1355
                // Let's bypass the constructor when creating the bean!
1356
                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1357
                /* @var $bean AbstractTDBMObject */
1358
                $bean->_constructLazy($table, $primaryKeys, $this);
1359
1360
                return $bean;
1361
            }
1362
        }
1363
1364
        // Did not find the object in cache? Let's query it!
1365
        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1366
    }
1367
1368
    /**
1369
     * Returns a unique bean (or null) according to the filters passed in parameter.
1370
     *
1371
     * @param string            $mainTable             The name of the table queried
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 array             $additionalTablesFetch
1375
     * @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
1376
     *
1377
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1378
     *
1379
     * @throws TDBMException
1380
     */
1381 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...
1382
    {
1383
        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1384
        $page = $objects->take(0, 2);
1385
        $count = $page->count();
1386
        if ($count > 1) {
1387
            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.");
1388
        } elseif ($count === 0) {
1389
            return;
1390
        }
1391
1392
        return $page[0];
1393
    }
1394
1395
    /**
1396
     * Returns a unique bean (or null) according to the filters passed in parameter.
1397
     *
1398
     * @param string            $mainTable  The name of the table queried
1399
     * @param string            $from       The from sql statement
1400
     * @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)
1401
     * @param array             $parameters
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|null The object we want, or null if no object matches the filters
1405
     *
1406
     * @throws TDBMException
1407
     */
1408 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...
1409
    {
1410
        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1411
        $page = $objects->take(0, 2);
1412
        $count = $page->count();
1413
        if ($count > 1) {
1414
            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.");
1415
        } elseif ($count === 0) {
1416
            return;
1417
        }
1418
1419
        return $page[0];
1420
    }
1421
1422
    /**
1423
     * Returns a unique bean according to the filters passed in parameter.
1424
     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1425
     *
1426
     * @param string            $mainTable             The name of the table queried
1427
     * @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)
1428
     * @param array             $parameters
1429
     * @param array             $additionalTablesFetch
1430
     * @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
1431
     *
1432
     * @return AbstractTDBMObject The object we want
1433
     *
1434
     * @throws TDBMException
1435
     */
1436
    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1437
    {
1438
        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1439
        if ($bean === null) {
1440
            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1441
        }
1442
1443
        return $bean;
1444
    }
1445
1446
    /**
1447
     * @param array $beanData An array of data: array<table, array<column, value>>
1448
     *
1449
     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1450
     *
1451
     * @throws TDBMInheritanceException
1452
     */
1453
    public function _getClassNameFromBeanData(array $beanData)
1454
    {
1455
        if (count($beanData) === 1) {
1456
            $tableName = array_keys($beanData)[0];
1457
            $allTables = [$tableName];
1458
        } else {
1459
            $tables = [];
1460
            foreach ($beanData as $table => $row) {
1461
                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1462
                $pkSet = false;
1463
                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...
1464
                    if ($row[$columnName] !== null) {
1465
                        $pkSet = true;
1466
                        break;
1467
                    }
1468
                }
1469
                if ($pkSet) {
1470
                    $tables[] = $table;
1471
                }
1472
            }
1473
1474
            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1475
            try {
1476
                $allTables = $this->_getLinkBetweenInheritedTables($tables);
1477
            } catch (TDBMInheritanceException $e) {
1478
                throw TDBMInheritanceException::extendException($e, $this, $beanData);
1479
            }
1480
            $tableName = $allTables[0];
1481
        }
1482
1483
        // Only one table in this bean. Life is sweat, let's look at its type:
1484
        if (isset($this->tableToBeanMap[$tableName])) {
1485
            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1486
        } else {
1487
            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1488
        }
1489
    }
1490
1491
    /**
1492
     * Returns an item from cache or computes it using $closure and puts it in cache.
1493
     *
1494
     * @param string   $key
1495
     * @param callable $closure
1496
     *
1497
     * @return mixed
1498
     */
1499 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...
1500
    {
1501
        $item = $this->cache->fetch($key);
1502
        if ($item === false) {
1503
            $item = $closure();
1504
            $this->cache->save($key, $item);
1505
        }
1506
1507
        return $item;
1508
    }
1509
1510
    /**
1511
     * Returns the foreign key object.
1512
     *
1513
     * @param string $table
1514
     * @param string $fkName
1515
     *
1516
     * @return ForeignKeyConstraint
1517
     */
1518
    public function _getForeignKeyByName(string $table, string $fkName)
1519
    {
1520
        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1521
    }
1522
1523
    /**
1524
     * @param $pivotTableName
1525
     * @param AbstractTDBMObject $bean
1526
     *
1527
     * @return AbstractTDBMObject[]
1528
     */
1529
    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1530
    {
1531
        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1532
        /* @var $localFk ForeignKeyConstraint */
1533
        /* @var $remoteFk ForeignKeyConstraint */
1534
        $remoteTable = $remoteFk->getForeignTableName();
1535
1536
        $primaryKeys = $this->getPrimaryKeyValues($bean);
1537
        $columnNames = array_map(function ($name) use ($pivotTableName) {
1538
            return $pivotTableName.'.'.$name;
1539
        }, $localFk->getLocalColumns());
1540
1541
        $filter = array_combine($columnNames, $primaryKeys);
1542
1543
        return $this->findObjects($remoteTable, $filter);
1544
    }
1545
1546
    /**
1547
     * @param $pivotTableName
1548
     * @param AbstractTDBMObject $bean The LOCAL bean
1549
     *
1550
     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1551
     *
1552
     * @throws TDBMException
1553
     */
1554
    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1555
    {
1556
        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1557
        $table1 = $fks[0]->getForeignTableName();
1558
        $table2 = $fks[1]->getForeignTableName();
1559
1560
        $beanTables = array_map(function (DbRow $dbRow) {
1561
            return $dbRow->_getDbTableName();
1562
        }, $bean->_getDbRows());
1563
1564
        if (in_array($table1, $beanTables)) {
1565
            return [$fks[0], $fks[1]];
1566
        } elseif (in_array($table2, $beanTables)) {
1567
            return [$fks[1], $fks[0]];
1568
        } else {
1569
            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1570
        }
1571
    }
1572
1573
    /**
1574
     * Returns a list of pivot tables linked to $bean.
1575
     *
1576
     * @param AbstractTDBMObject $bean
1577
     *
1578
     * @return string[]
1579
     */
1580
    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1581
    {
1582
        $junctionTables = [];
1583
        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1584
        foreach ($bean->_getDbRows() as $dbRow) {
1585
            foreach ($allJunctionTables as $table) {
1586
                // There are exactly 2 FKs since this is a pivot table.
1587
                $fks = array_values($table->getForeignKeys());
1588
1589
                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1590
                    $junctionTables[] = $table->getName();
1591
                }
1592
            }
1593
        }
1594
1595
        return $junctionTables;
1596
    }
1597
1598
    /**
1599
     * Array of types for tables.
1600
     * Key: table name
1601
     * Value: array of types indexed by column.
1602
     *
1603
     * @var array[]
1604
     */
1605
    private $typesForTable = [];
1606
1607
    /**
1608
     * @internal
1609
     *
1610
     * @param string $tableName
1611
     *
1612
     * @return Type[]
1613
     */
1614
    public function _getColumnTypesForTable(string $tableName)
1615
    {
1616
        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...
1617
            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1618
            $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...
1619
                return $column->getType();
1620
            }, $columns);
1621
        }
1622
1623
        return $typesForTable[$tableName];
1624
    }
1625
1626
    /**
1627
     * Sets the minimum log level.
1628
     * $level must be one of Psr\Log\LogLevel::xxx.
1629
     *
1630
     * Defaults to LogLevel::WARNING
1631
     *
1632
     * @param string $level
1633
     */
1634
    public function setLogLevel(string $level)
1635
    {
1636
        $this->logger = new LevelFilter($this->rootLogger, $level);
1637
    }
1638
}
1639