Completed
Push — master ( ef5aef...dc6a81 )
by David
13s
created

TDBMService   F

Complexity

Total Complexity 160

Size/Duplication

Total Lines 1485
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 34

Importance

Changes 0
Metric Value
dl 0
loc 1485
rs 0.5217
c 0
b 0
f 0
wmc 160
lcom 1
cbo 34

44 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 30 3
A getConnection() 0 4 1
A setFetchMode() 0 9 3
C delete() 0 51 12
A deleteManyToManyRelationships() 0 13 4
A deleteCascade() 0 5 1
B deleteAllConstraintWithThisObject() 0 21 5
A completeSave() 0 6 2
C buildFilterFromFilterBag() 0 49 10
B getPrimaryKeyColumns() 0 32 2
A _addToCache() 0 6 1
A removeFromToSaveObjectList() 0 4 1
A _addToToSaveObjectList() 0 4 1
A generateAllDaosAndBeans() 0 8 1
A getBeanClassName() 0 15 3
F save() 0 194 29
B persistManyToManyRelationships() 0 54 9
A getPivotFilters() 0 22 2
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 11 1
A _getLinkBetweenInheritedTablesWithoutCache() 0 21 4
A _getRelatedTablesByInheritance() 0 6 1
A _getRelatedTablesByInheritanceWithoutCache() 0 20 2
A exploreChildrenTablesRelationships() 0 11 2
A findObjects() 0 19 3
A findObjectsFromSql() 0 19 3
D findObjectByPk() 0 45 9
A findObject() 0 19 3
A findObjectFromSql() 0 13 3
A findObjectsFromRawSql() 0 13 3
A findObjectOrFail() 0 9 2
C _getClassNameFromBeanData() 0 39 8
A fromCache() 0 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 3
A setLogLevel() 0 4 1

How to fix   Complexity   

Complex Class

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-2017 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 TheCodingMachine\TDBM;
22
23
use Doctrine\Common\Cache\Cache;
24
use Doctrine\Common\Cache\VoidCache;
25
use Doctrine\DBAL\Connection;
26
use Doctrine\DBAL\DBALException;
27
use Doctrine\DBAL\Platforms\AbstractPlatform;
28
use Doctrine\DBAL\Platforms\MySqlPlatform;
29
use Doctrine\DBAL\Platforms\OraclePlatform;
30
use Doctrine\DBAL\Schema\Column;
31
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
32
use Doctrine\DBAL\Schema\Schema;
33
use Doctrine\DBAL\Schema\Table;
34
use Doctrine\DBAL\Types\Type;
35
use Mouf\Database\MagicQuery;
36
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
37
use TheCodingMachine\TDBM\QueryFactory\FindObjectsFromSqlQueryFactory;
38
use TheCodingMachine\TDBM\QueryFactory\FindObjectsQueryFactory;
39
use TheCodingMachine\TDBM\QueryFactory\FindObjectsFromRawSqlQueryFactory;
40
use TheCodingMachine\TDBM\Utils\NamingStrategyInterface;
41
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
42
use Phlib\Logger\LevelFilter;
43
use Psr\Log\LoggerInterface;
44
use Psr\Log\LogLevel;
45
use Psr\Log\NullLogger;
46
47
/**
48
 * The TDBMService class is the main TDBM class. It provides methods to retrieve TDBMObject instances
49
 * from the database.
50
 *
51
 * @author David Negrier
52
 * @ExtendedAction {"name":"Generate DAOs", "url":"tdbmadmin/", "default":false}
53
 */
54
class TDBMService
55
{
56
    const MODE_CURSOR = 1;
57
    const MODE_ARRAY = 2;
58
59
    /**
60
     * The database connection.
61
     *
62
     * @var Connection
63
     */
64
    private $connection;
65
66
    /**
67
     * @var SchemaAnalyzer
68
     */
69
    private $schemaAnalyzer;
70
71
    /**
72
     * @var MagicQuery
73
     */
74
    private $magicQuery;
75
76
    /**
77
     * @var TDBMSchemaAnalyzer
78
     */
79
    private $tdbmSchemaAnalyzer;
80
81
    /**
82
     * @var string
83
     */
84
    private $cachePrefix;
85
86
    /**
87
     * Cache of table of primary keys.
88
     * Primary keys are stored by tables, as an array of column.
89
     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
90
     *
91
     * @var string[]
92
     */
93
    private $primaryKeysColumns;
94
95
    /**
96
     * Service storing objects in memory.
97
     * Access is done by table name and then by primary key.
98
     * If the primary key is split on several columns, access is done by an array of columns, serialized.
99
     *
100
     * @var StandardObjectStorage|WeakrefObjectStorage
101
     */
102
    private $objectStorage;
103
104
    /**
105
     * The fetch mode of the result sets returned by `getObjects`.
106
     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
107
     *
108
     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
109
     * 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,
110
     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
111
     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
112
     * You can access the array by key, or using foreach, several times.
113
     *
114
     * @var int
115
     */
116
    private $mode = self::MODE_ARRAY;
117
118
    /**
119
     * Table of new objects not yet inserted in database or objects modified that must be saved.
120
     *
121
     * @var \SplObjectStorage of DbRow objects
122
     */
123
    private $toSaveObjects;
124
125
    /**
126
     * A cache service to be used.
127
     *
128
     * @var Cache|null
129
     */
130
    private $cache;
131
132
    /**
133
     * Map associating a table name to a fully qualified Bean class name.
134
     *
135
     * @var array
136
     */
137
    private $tableToBeanMap = [];
138
139
    /**
140
     * @var \ReflectionClass[]
141
     */
142
    private $reflectionClassCache = array();
143
144
    /**
145
     * @var LoggerInterface
146
     */
147
    private $rootLogger;
148
149
    /**
150
     * @var LevelFilter|NullLogger
151
     */
152
    private $logger;
153
154
    /**
155
     * @var OrderByAnalyzer
156
     */
157
    private $orderByAnalyzer;
158
159
    /**
160
     * @var string
161
     */
162
    private $beanNamespace;
163
164
    /**
165
     * @var NamingStrategyInterface
166
     */
167
    private $namingStrategy;
168
    /**
169
     * @var ConfigurationInterface
170
     */
171
    private $configuration;
172
173
    /**
174
     * @param ConfigurationInterface $configuration The configuration object
175
     */
176
    public function __construct(ConfigurationInterface $configuration)
177
    {
178
        if (extension_loaded('weakref')) {
179
            $this->objectStorage = new WeakrefObjectStorage();
180
        } else {
181
            $this->objectStorage = new StandardObjectStorage();
182
        }
183
        $this->connection = $configuration->getConnection();
184
        $this->cache = $configuration->getCache();
185
        $this->schemaAnalyzer = $configuration->getSchemaAnalyzer();
186
187
        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
188
189
        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->connection, $this->cache, $this->schemaAnalyzer);
190
        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
191
192
        $this->toSaveObjects = new \SplObjectStorage();
193
        $logger = $configuration->getLogger();
194
        if ($logger === null) {
195
            $this->logger = new NullLogger();
196
            $this->rootLogger = new NullLogger();
197
        } else {
198
            $this->rootLogger = $logger;
199
            $this->setLogLevel(LogLevel::WARNING);
200
        }
201
        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
202
        $this->beanNamespace = $configuration->getBeanNamespace();
203
        $this->namingStrategy = $configuration->getNamingStrategy();
204
        $this->configuration = $configuration;
205
    }
206
207
    /**
208
     * Returns the object used to connect to the database.
209
     *
210
     * @return Connection
211
     */
212
    public function getConnection(): Connection
213
    {
214
        return $this->connection;
215
    }
216
217
    /**
218
     * Sets the default fetch mode of the result sets returned by `findObjects`.
219
     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
220
     *
221
     * 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).
222
     * 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
223
     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
224
     *
225
     * @param int $mode
226
     *
227
     * @return $this
228
     *
229
     * @throws TDBMException
230
     */
231
    public function setFetchMode($mode)
232
    {
233
        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
234
            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
235
        }
236
        $this->mode = $mode;
237
238
        return $this;
239
    }
240
241
    /**
242
     * Removes the given object from database.
243
     * This cannot be called on an object that is not attached to this TDBMService
244
     * (will throw a TDBMInvalidOperationException).
245
     *
246
     * @param AbstractTDBMObject $object the object to delete
247
     *
248
     * @throws DBALException
249
     * @throws TDBMInvalidOperationException
250
     */
251
    public function delete(AbstractTDBMObject $object)
252
    {
253
        switch ($object->_getStatus()) {
254
            case TDBMObjectStateEnum::STATE_DELETED:
255
                // Nothing to do, object already deleted.
256
                return;
257
            case TDBMObjectStateEnum::STATE_DETACHED:
258
                throw new TDBMInvalidOperationException('Cannot delete a detached object');
259
            case TDBMObjectStateEnum::STATE_NEW:
260
                $this->deleteManyToManyRelationships($object);
261
                foreach ($object->_getDbRows() as $dbRow) {
262
                    $this->removeFromToSaveObjectList($dbRow);
263
                }
264
                break;
265
            case TDBMObjectStateEnum::STATE_DIRTY:
266
                foreach ($object->_getDbRows() as $dbRow) {
267
                    $this->removeFromToSaveObjectList($dbRow);
268
                }
269
            // 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...
270
            // no break
271
            case TDBMObjectStateEnum::STATE_NOT_LOADED:
272
            case TDBMObjectStateEnum::STATE_LOADED:
273
                $this->connection->beginTransaction();
274
                try {
275
                    $this->deleteManyToManyRelationships($object);
276
                    // Let's delete db rows, in reverse order.
277
                    foreach (array_reverse($object->_getDbRows()) as $dbRow) {
278
                        /* @var $dbRow DbRow */
279
                        $tableName = $dbRow->_getDbTableName();
280
                        $primaryKeys = $dbRow->_getPrimaryKeys();
281
                        $quotedPrimaryKeys = [];
282
                        foreach ($primaryKeys as $column => $value) {
283
                            $quotedPrimaryKeys[$this->connection->quoteIdentifier($column)] = $value;
284
                        }
285
                        $this->connection->delete($this->connection->quoteIdentifier($tableName), $quotedPrimaryKeys);
286
                        $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
287
                    }
288
                    $this->connection->commit();
289
                } catch (DBALException $e) {
290
                    $this->connection->rollBack();
291
                    throw $e;
292
                }
293
                break;
294
            // @codeCoverageIgnoreStart
295
            default:
296
                throw new TDBMInvalidOperationException('Unexpected status for bean');
297
            // @codeCoverageIgnoreEnd
298
        }
299
300
        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
301
    }
302
303
    /**
304
     * Removes all many to many relationships for this object.
305
     *
306
     * @param AbstractTDBMObject $object
307
     */
308
    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
309
    {
310
        foreach ($object->_getDbRows() as $tableName => $dbRow) {
311
            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
312
            foreach ($pivotTables as $pivotTable) {
313
                $remoteBeans = $object->_getRelationships($pivotTable);
314
                foreach ($remoteBeans as $remoteBean) {
315
                    $object->_removeRelationship($pivotTable, $remoteBean);
316
                }
317
            }
318
        }
319
        $this->persistManyToManyRelationships($object);
320
    }
321
322
    /**
323
     * This function removes the given object from the database. It will also remove all objects relied to the one given
324
     * by parameter before all.
325
     *
326
     * Notice: if the object has a multiple primary key, the function will not work.
327
     *
328
     * @param AbstractTDBMObject $objToDelete
329
     */
330
    public function deleteCascade(AbstractTDBMObject $objToDelete)
331
    {
332
        $this->deleteAllConstraintWithThisObject($objToDelete);
333
        $this->delete($objToDelete);
334
    }
335
336
    /**
337
     * This function is used only in TDBMService (private function)
338
     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
339
     *
340
     * @param AbstractTDBMObject $obj
341
     */
342
    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
343
    {
344
        $dbRows = $obj->_getDbRows();
345
        foreach ($dbRows as $dbRow) {
346
            $tableName = $dbRow->_getDbTableName();
347
            $pks = array_values($dbRow->_getPrimaryKeys());
348
            if (!empty($pks)) {
349
                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
350
351
                foreach ($incomingFks as $incomingFk) {
352
                    $filter = array_combine($incomingFk->getUnquotedLocalColumns(), $pks);
353
354
                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
355
356
                    foreach ($results as $bean) {
357
                        $this->deleteCascade($bean);
358
                    }
359
                }
360
            }
361
        }
362
    }
363
364
    /**
365
     * This function performs a save() of all the objects that have been modified.
366
     */
367
    public function completeSave()
368
    {
369
        foreach ($this->toSaveObjects as $dbRow) {
370
            $this->save($dbRow->getTDBMObject());
371
        }
372
    }
373
374
    /**
375
     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
376
     * and gives back a proper Filter object.
377
     *
378
     * @param mixed $filter_bag
379
     * @param AbstractPlatform $platform The platform used to quote identifiers
380
     * @param int $counter
381
     * @return array First item: filter string, second item: parameters
382
     *
383
     * @throws TDBMException
384
     */
385
    public function buildFilterFromFilterBag($filter_bag, AbstractPlatform $platform, $counter = 1)
386
    {
387
        if ($filter_bag === null) {
388
            return ['', []];
389
        } elseif (is_string($filter_bag)) {
390
            return [$filter_bag, []];
391
        } elseif (is_array($filter_bag)) {
392
            $sqlParts = [];
393
            $parameters = [];
394
395
            foreach ($filter_bag as $column => $value) {
396
                if (is_int($column)) {
397
                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $platform, $counter);
398
                    $sqlParts[] = $subSqlPart;
399
                    $parameters += $subParameters;
400
                } else {
401
                    $paramName = 'tdbmparam'.$counter;
402
                    if (is_array($value)) {
403
                        $sqlParts[] = $platform->quoteIdentifier($column).' IN :'.$paramName;
404
                    } else {
405
                        $sqlParts[] = $platform->quoteIdentifier($column).' = :'.$paramName;
406
                    }
407
                    $parameters[$paramName] = $value;
408
                    ++$counter;
409
                }
410
            }
411
412
            return [implode(' AND ', $sqlParts), $parameters];
413
        } elseif ($filter_bag instanceof AbstractTDBMObject) {
414
            $sqlParts = [];
415
            $parameters = [];
416
            $dbRows = $filter_bag->_getDbRows();
417
            $dbRow = reset($dbRows);
418
            $primaryKeys = $dbRow->_getPrimaryKeys();
419
420
            foreach ($primaryKeys as $column => $value) {
421
                $paramName = 'tdbmparam'.$counter;
422
                $sqlParts[] = $platform->quoteIdentifier($dbRow->_getDbTableName()).'.'.$platform->quoteIdentifier($column).' = :'.$paramName;
423
                $parameters[$paramName] = $value;
424
                ++$counter;
425
            }
426
427
            return [implode(' AND ', $sqlParts), $parameters];
428
        } elseif ($filter_bag instanceof \Iterator) {
429
            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $platform, $counter);
430
        } else {
431
            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.');
432
        }
433
    }
434
435
    /**
436
     * @param string $table
437
     *
438
     * @return string[]
439
     */
440
    public function getPrimaryKeyColumns($table)
441
    {
442
        if (!isset($this->primaryKeysColumns[$table])) {
443
            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKey()->getUnquotedColumns();
444
445
            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
446
447
            /*$arr = array();
448
            foreach ($this->connection->getPrimaryKey($table) as $col) {
449
                $arr[] = $col->name;
450
            }
451
            // The primaryKeysColumns contains only the column's name, not the DB_Column object.
452
            $this->primaryKeysColumns[$table] = $arr;
453
            if (empty($this->primaryKeysColumns[$table]))
454
            {
455
                // Unable to find primary key.... this is an error
456
                // Let's try to be precise in error reporting. Let's try to find the table.
457
                $tables = $this->connection->checkTableExist($table);
458
                if ($tables === true)
459
                throw new TDBMException("Could not find table primary key for table '$table'. Please define a primary key for this table.");
460
                elseif ($tables !== null) {
461
                    if (count($tables)==1)
462
                    $str = "Could not find table '$table'. Maybe you meant this table: '".$tables[0]."'";
463
                    else
464
                    $str = "Could not find table '$table'. Maybe you meant one of those tables: '".implode("', '",$tables)."'";
465
                    throw new TDBMException($str);
466
                }
467
            }*/
468
        }
469
470
        return $this->primaryKeysColumns[$table];
471
    }
472
473
    /**
474
     * This is an internal function, you should not use it in your application.
475
     * This is used internally by TDBM to add an object to the object cache.
476
     *
477
     * @param DbRow $dbRow
478
     */
479
    public function _addToCache(DbRow $dbRow)
480
    {
481
        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
482
        $hash = $this->getObjectHash($primaryKey);
483
        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
484
    }
485
486
    /**
487
     * This is an internal function, you should not use it in your application.
488
     * This is used internally by TDBM to remove the object from the list of objects that have been
489
     * created/updated but not saved yet.
490
     *
491
     * @param DbRow $myObject
492
     */
493
    private function removeFromToSaveObjectList(DbRow $myObject)
494
    {
495
        unset($this->toSaveObjects[$myObject]);
496
    }
497
498
    /**
499
     * This is an internal function, you should not use it in your application.
500
     * This is used internally by TDBM to add an object to the list of objects that have been
501
     * created/updated but not saved yet.
502
     *
503
     * @param DbRow $myObject
504
     */
505
    public function _addToToSaveObjectList(DbRow $myObject)
506
    {
507
        $this->toSaveObjects[$myObject] = true;
508
    }
509
510
    /**
511
     * Generates all the daos and beans.
512
     *
513
     * @return \string[] the list of tables (key) and bean name (value)
514
     */
515
    public function generateAllDaosAndBeans()
516
    {
517
        // Purge cache before generating anything.
518
        $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...
519
520
        $tdbmDaoGenerator = new TDBMDaoGenerator($this->configuration, $this->tdbmSchemaAnalyzer);
521
        $tdbmDaoGenerator->generateAllDaosAndBeans();
522
    }
523
524
    /**
525
     * Returns the fully qualified class name of the bean associated with table $tableName.
526
     *
527
     *
528
     * @param string $tableName
529
     *
530
     * @return string
531
     */
532
    public function getBeanClassName(string $tableName) : string
533
    {
534
        if (isset($this->tableToBeanMap[$tableName])) {
535
            return $this->tableToBeanMap[$tableName];
536
        } else {
537
            $className = $this->beanNamespace.'\\'.$this->namingStrategy->getBeanClassName($tableName);
538
539
            if (!class_exists($className)) {
540
                throw new TDBMInvalidArgumentException(sprintf('Could not find class "%s". Does table "%s" exist? If yes, consider regenerating the DAOs and beans.', $className, $tableName));
541
            }
542
543
            $this->tableToBeanMap[$tableName] = $className;
544
            return $className;
545
        }
546
    }
547
548
    /**
549
     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
550
     *
551
     * @param AbstractTDBMObject $object
552
     *
553
     * @throws TDBMException
554
     */
555
    public function save(AbstractTDBMObject $object)
556
    {
557
        $this->connection->beginTransaction();
558
        try {
559
            $status = $object->_getStatus();
560
561
            if ($status === null) {
562
                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)));
563
            }
564
565
            // Let's attach this object if it is in detached state.
566
            if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
567
                $object->_attach($this);
568
                $status = $object->_getStatus();
569
            }
570
571
            if ($status === TDBMObjectStateEnum::STATE_NEW) {
572
                $dbRows = $object->_getDbRows();
573
574
                $unindexedPrimaryKeys = array();
575
576
                foreach ($dbRows as $dbRow) {
577
                    if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
578
                        throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
579
                    }
580
                    $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
581
                    $tableName = $dbRow->_getDbTableName();
582
583
                    $schema = $this->tdbmSchemaAnalyzer->getSchema();
584
                    $tableDescriptor = $schema->getTable($tableName);
585
586
                    $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
587
588
                    $references = $dbRow->_getReferences();
589
590
                    // Let's save all references in NEW or DETACHED state (we need their primary key)
591
                    foreach ($references as $fkName => $reference) {
592
                        if ($reference !== null) {
593
                            $refStatus = $reference->_getStatus();
594
                            if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
595
                                try {
596
                                    $this->save($reference);
597
                                } catch (TDBMCyclicReferenceException $e) {
598
                                    throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
599
                                }
600
                            }
601
                        }
602
                    }
603
604
                    if (empty($unindexedPrimaryKeys)) {
605
                        $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
606
                    } else {
607
                        // First insert, the children must have the same primary key as the parent.
608
                        $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
609
                        $dbRow->_setPrimaryKeys($primaryKeys);
610
                    }
611
612
                    $dbRowData = $dbRow->_getDbRow();
613
614
                    // Let's see if the columns for primary key have been set before inserting.
615
                    // We assume that if one of the value of the PK has been set, the PK is set.
616
                    $isPkSet = !empty($primaryKeys);
617
618
                    /*if (!$isPkSet) {
619
                        // if there is no autoincrement and no pk set, let's go in error.
620
                        $isAutoIncrement = true;
621
622
                        foreach ($primaryKeyColumns as $pkColumnName) {
623
                            $pkColumn = $tableDescriptor->getColumn($pkColumnName);
624
                            if (!$pkColumn->getAutoincrement()) {
625
                                $isAutoIncrement = false;
626
                            }
627
                        }
628
629
                        if (!$isAutoIncrement) {
630
                            $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.";
631
                            throw new TDBMException($msg);
632
                        }
633
634
                    }*/
635
636
                    $types = [];
637
                    $escapedDbRowData = [];
638
639
                    foreach ($dbRowData as $columnName => $value) {
640
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
641
                        $types[] = $columnDescriptor->getType();
642
                        $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
643
                    }
644
645
                    $quotedTableName = $this->connection->quoteIdentifier($tableName);
646
                    $this->connection->insert($quotedTableName, $escapedDbRowData, $types);
647
648
                    if (!$isPkSet && count($primaryKeyColumns) === 1) {
649
                        $id = $this->connection->lastInsertId();
650
651
                        if ($id === false) {
652
                            // In Oracle (if we are in 11g), the lastInsertId will fail. We try again with the column.
653
                            $sequenceName = $this->connection->getDatabasePlatform()->getIdentitySequenceName(
654
                                $quotedTableName,
655
                                $this->connection->quoteIdentifier($primaryKeyColumns[0])
656
                            );
657
                            $id = $this->connection->lastInsertId($sequenceName);
658
                        }
659
660
                        $pkColumn = $primaryKeyColumns[0];
661
                        // lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
662
                        $id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
663
                        $primaryKeys[$pkColumn] = $id;
664
                    }
665
666
                    // TODO: change this to some private magic accessor in future
667
                    $dbRow->_setPrimaryKeys($primaryKeys);
668
                    $unindexedPrimaryKeys = array_values($primaryKeys);
669
670
                    // Let's remove this object from the $new_objects static table.
671
                    $this->removeFromToSaveObjectList($dbRow);
672
673
                    // Let's add this object to the list of objects in cache.
674
                    $this->_addToCache($dbRow);
675
                }
676
677
                $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
678
            } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
679
                $dbRows = $object->_getDbRows();
680
681
                foreach ($dbRows as $dbRow) {
682
                    $references = $dbRow->_getReferences();
683
684
                    // Let's save all references in NEW state (we need their primary key)
685
                    foreach ($references as $fkName => $reference) {
686
                        if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
687
                            $this->save($reference);
688
                        }
689
                    }
690
691
                    // Let's first get the primary keys
692
                    $tableName = $dbRow->_getDbTableName();
693
                    $dbRowData = $dbRow->_getDbRow();
694
695
                    $schema = $this->tdbmSchemaAnalyzer->getSchema();
696
                    $tableDescriptor = $schema->getTable($tableName);
697
698
                    $primaryKeys = $dbRow->_getPrimaryKeys();
699
700
                    $types = [];
701
                    $escapedDbRowData = [];
702
                    $escapedPrimaryKeys = [];
703
704
                    foreach ($dbRowData as $columnName => $value) {
705
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
706
                        $types[] = $columnDescriptor->getType();
707
                        $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
708
                    }
709
                    foreach ($primaryKeys as $columnName => $value) {
710
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
711
                        $types[] = $columnDescriptor->getType();
712
                        $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
713
                    }
714
715
                    $this->connection->update($this->connection->quoteIdentifier($tableName), $escapedDbRowData, $escapedPrimaryKeys, $types);
716
717
                    // Let's check if the primary key has been updated...
718
                    $needsUpdatePk = false;
719
                    foreach ($primaryKeys as $column => $value) {
720
                        if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
721
                            $needsUpdatePk = true;
722
                            break;
723
                        }
724
                    }
725
                    if ($needsUpdatePk) {
726
                        $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
727
                        $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
728
                        $dbRow->_setPrimaryKeys($newPrimaryKeys);
729
                        $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
730
                    }
731
732
                    // Let's remove this object from the list of objects to save.
733
                    $this->removeFromToSaveObjectList($dbRow);
734
                }
735
736
                $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
737
            } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
738
                throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
739
            }
740
741
            // Finally, let's save all the many to many relationships to this bean.
742
            $this->persistManyToManyRelationships($object);
743
            $this->connection->commit();
744
        } catch (\Throwable $t) {
745
            $this->connection->rollBack();
746
            throw $t;
747
        }
748
    }
749
750
    private function persistManyToManyRelationships(AbstractTDBMObject $object)
751
    {
752
        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
753
            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
754
            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
755
756
            $toRemoveFromStorage = [];
757
758
            foreach ($storage as $remoteBean) {
759
                /* @var $remoteBean AbstractTDBMObject */
760
                $statusArr = $storage[$remoteBean];
761
                $status = $statusArr['status'];
762
                $reverse = $statusArr['reverse'];
763
                if ($reverse) {
764
                    continue;
765
                }
766
767
                if ($status === 'new') {
768
                    $remoteBeanStatus = $remoteBean->_getStatus();
769
                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
770
                        // Let's save remote bean if needed.
771
                        $this->save($remoteBean);
772
                    }
773
774
                    ['filters' => $filters, 'types' => $types] = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk, $tableDescriptor);
0 ignored issues
show
Bug introduced by
The variable $filters does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $types does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
775
776
                    $this->connection->insert($this->connection->quoteIdentifier($pivotTableName), $filters, $types);
777
778
                    // Finally, let's mark relationships as saved.
779
                    $statusArr['status'] = 'loaded';
780
                    $storage[$remoteBean] = $statusArr;
781
                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
782
                    $remoteStatusArr = $remoteStorage[$object];
783
                    $remoteStatusArr['status'] = 'loaded';
784
                    $remoteStorage[$object] = $remoteStatusArr;
785
                } elseif ($status === 'delete') {
786
                    ['filters' => $filters, 'types' => $types] = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk, $tableDescriptor);
787
788
                    $this->connection->delete($this->connection->quoteIdentifier($pivotTableName), $filters, $types);
789
790
                    // Finally, let's remove relationships completely from bean.
791
                    $toRemoveFromStorage[] = $remoteBean;
792
793
                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
794
                }
795
            }
796
797
            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
798
            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
799
            foreach ($toRemoveFromStorage as $remoteBean) {
800
                $storage->detach($remoteBean);
801
            }
802
        }
803
    }
804
805
    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk, Table $tableDescriptor)
806
    {
807
        $localBeanPk = $this->getPrimaryKeyValues($localBean);
808
        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
809
        $localColumns = $localFk->getUnquotedLocalColumns();
810
        $remoteColumns = $remoteFk->getUnquotedLocalColumns();
811
812
        $localFilters = array_combine($localColumns, $localBeanPk);
813
        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
814
815
        $filters = array_merge($localFilters, $remoteFilters);
816
817
        $types = [];
818
        $escapedFilters = [];
819
820
        foreach ($filters as $columnName => $value) {
821
            $columnDescriptor = $tableDescriptor->getColumn($columnName);
822
            $types[] = $columnDescriptor->getType();
823
            $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
824
        }
825
        return ['filters' => $escapedFilters, 'types' => $types];
826
    }
827
828
    /**
829
     * Returns the "values" of the primary key.
830
     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
831
     *
832
     * @param AbstractTDBMObject $bean
833
     *
834
     * @return array numerically indexed array of values
835
     */
836
    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
837
    {
838
        $dbRows = $bean->_getDbRows();
839
        $dbRow = reset($dbRows);
840
841
        return array_values($dbRow->_getPrimaryKeys());
842
    }
843
844
    /**
845
     * Returns a unique hash used to store the object based on its primary key.
846
     * If the array contains only one value, then the value is returned.
847
     * Otherwise, a hash representing the array is returned.
848
     *
849
     * @param array $primaryKeys An array of columns => values forming the primary key
850
     *
851
     * @return string
852
     */
853
    public function getObjectHash(array $primaryKeys)
854
    {
855
        if (count($primaryKeys) === 1) {
856
            return reset($primaryKeys);
857
        } else {
858
            ksort($primaryKeys);
859
860
            return md5(json_encode($primaryKeys));
861
        }
862
    }
863
864
    /**
865
     * Returns an array of primary keys from the object.
866
     * The primary keys are extracted from the object columns and not from the primary keys stored in the
867
     * $primaryKeys variable of the object.
868
     *
869
     * @param DbRow $dbRow
870
     *
871
     * @return array Returns an array of column => value
872
     */
873
    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
874
    {
875
        $table = $dbRow->_getDbTableName();
876
        $dbRowData = $dbRow->_getDbRow();
877
878
        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
879
    }
880
881
    /**
882
     * Returns an array of primary keys for the given row.
883
     * The primary keys are extracted from the object columns.
884
     *
885
     * @param $table
886
     * @param array $columns
887
     *
888
     * @return array
889
     */
890
    public function _getPrimaryKeysFromObjectData($table, array $columns)
891
    {
892
        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
893
        $values = array();
894
        foreach ($primaryKeyColumns as $column) {
895
            if (isset($columns[$column])) {
896
                $values[$column] = $columns[$column];
897
            }
898
        }
899
900
        return $values;
901
    }
902
903
    /**
904
     * Attaches $object to this TDBMService.
905
     * The $object must be in DETACHED state and will pass in NEW state.
906
     *
907
     * @param AbstractTDBMObject $object
908
     *
909
     * @throws TDBMInvalidOperationException
910
     */
911
    public function attach(AbstractTDBMObject $object)
912
    {
913
        $object->_attach($this);
914
    }
915
916
    /**
917
     * Returns an associative array (column => value) for the primary keys from the table name and an
918
     * indexed array of primary key values.
919
     *
920
     * @param string $tableName
921
     * @param array  $indexedPrimaryKeys
922
     */
923
    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
924
    {
925
        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKey()->getUnquotedColumns();
926
927
        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
928
            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
929
			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
930
        }
931
932
        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
933
    }
934
935
    /**
936
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
937
     * Tables must be in a single line of inheritance. The method will find missing tables.
938
     *
939
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
940
     * we must be able to find all other tables.
941
     *
942
     * @param string[] $tables
943
     *
944
     * @return string[]
945
     */
946
    public function _getLinkBetweenInheritedTables(array $tables)
947
    {
948
        sort($tables);
949
950
        return $this->fromCache(
951
            $this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
952
            function () use ($tables) {
953
                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
954
            }
955
        );
956
    }
957
958
    /**
959
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
960
     * Tables must be in a single line of inheritance. The method will find missing tables.
961
     *
962
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
963
     * we must be able to find all other tables.
964
     *
965
     * @param string[] $tables
966
     *
967
     * @return string[]
968
     */
969
    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
970
    {
971
        $schemaAnalyzer = $this->schemaAnalyzer;
972
973
        foreach ($tables as $currentTable) {
974
            $allParents = [$currentTable];
975
            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
976
                $currentTable = $currentFk->getForeignTableName();
977
                $allParents[] = $currentTable;
978
            }
979
980
            // Now, does the $allParents contain all the tables we want?
981
            $notFoundTables = array_diff($tables, $allParents);
982
            if (empty($notFoundTables)) {
983
                // We have a winner!
984
                return $allParents;
985
            }
986
        }
987
988
        throw TDBMInheritanceException::create($tables);
989
    }
990
991
    /**
992
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
993
     *
994
     * @param string $table
995
     *
996
     * @return string[]
997
     */
998
    public function _getRelatedTablesByInheritance($table)
999
    {
1000
        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1001
            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1002
        });
1003
    }
1004
1005
    /**
1006
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1007
     *
1008
     * @param string $table
1009
     *
1010
     * @return string[]
1011
     */
1012
    private function _getRelatedTablesByInheritanceWithoutCache($table)
1013
    {
1014
        $schemaAnalyzer = $this->schemaAnalyzer;
1015
1016
        // Let's scan the parent tables
1017
        $currentTable = $table;
1018
1019
        $parentTables = [];
1020
1021
        // Get parent relationship
1022
        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1023
            $currentTable = $currentFk->getForeignTableName();
1024
            $parentTables[] = $currentTable;
1025
        }
1026
1027
        // Let's recurse in children
1028
        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1029
1030
        return array_merge(array_reverse($parentTables), $childrenTables);
1031
    }
1032
1033
    /**
1034
     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1035
     *
1036
     * @param string $table
1037
     *
1038
     * @return string[]
1039
     */
1040
    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1041
    {
1042
        $tables = [$table];
1043
        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1044
1045
        foreach ($keys as $key) {
1046
            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1047
        }
1048
1049
        return $tables;
1050
    }
1051
1052
    /**
1053
     * Casts a foreign key into SQL, assuming table name is used with no alias.
1054
     * The returned value does contain only one table. For instance:.
1055
     *
1056
     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1057
     *
1058
     * @param ForeignKeyConstraint $fk
1059
     * @param bool                 $leftTableIsLocal
1060
     *
1061
     * @return string
1062
     */
1063
    /*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...
1064
        $onClauses = [];
1065
        $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1066
        $foreignColumns = $fk->getUnquotedForeignColumns();
1067
        $localTableName = $this->connection->quoteIdentifier($fk->getLocalTableName());
1068
        $localColumns = $fk->getUnquotedLocalColumns();
1069
        $columnCount = count($localTableName);
1070
1071
        for ($i = 0; $i < $columnCount; $i++) {
1072
            $onClauses[] = sprintf("%s.%s = %s.%s",
1073
                $localTableName,
1074
                $this->connection->quoteIdentifier($localColumns[$i]),
1075
                $foreignColumns,
1076
                $this->connection->quoteIdentifier($foreignColumns[$i])
1077
                );
1078
        }
1079
1080
        $onClause = implode(' AND ', $onClauses);
1081
1082
        if ($leftTableIsLocal) {
1083
            return sprintf(" LEFT JOIN %s ON (%s)", $foreignTableName, $onClause);
1084
        } else {
1085
            return sprintf(" LEFT JOIN %s ON (%s)", $localTableName, $onClause);
1086
        }
1087
    }*/
1088
1089
    /**
1090
     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1091
     *
1092
     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1093
     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1094
     *
1095
     * The findObjects method takes in parameter:
1096
     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1097
     * 			`$mainTable` parameter should be the name of an existing table in database.
1098
     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1099
     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1100
     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1101
     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1102
     *          Instead, please consider passing parameters (see documentation for more details).
1103
     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1104
     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1105
     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1106
     *
1107
     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1108
     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1109
     *
1110
     * Finally, if filter_bag is null, the whole table is returned.
1111
     *
1112
     * @param string                       $mainTable             The name of the table queried
1113
     * @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)
1114
     * @param array                        $parameters
1115
     * @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)
1116
     * @param array                        $additionalTablesFetch
1117
     * @param int                          $mode
1118
     * @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
1119
     *
1120
     * @return ResultIterator An object representing an array of results
1121
     *
1122
     * @throws TDBMException
1123
     */
1124
    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1125
    {
1126
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1127
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1128
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1129
        }
1130
1131
        $mode = $mode ?: $this->mode;
1132
1133
        // We quote in MySQL because MagicJoin requires MySQL style quotes
1134
        $mysqlPlatform = new MySqlPlatform();
1135
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter, $mysqlPlatform);
1136
1137
        $parameters = array_merge($parameters, $additionalParameters);
1138
1139
        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1140
1141
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1142
    }
1143
1144
    /**
1145
     * @param string                       $mainTable   The name of the table queried
1146
     * @param string                       $from        The from sql statement
1147
     * @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)
1148
     * @param array                        $parameters
1149
     * @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)
1150
     * @param int                          $mode
1151
     * @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
1152
     *
1153
     * @return ResultIterator An object representing an array of results
1154
     *
1155
     * @throws TDBMException
1156
     */
1157
    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1158
    {
1159
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1160
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1161
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1162
        }
1163
1164
        $mode = $mode ?: $this->mode;
1165
1166
        // We quote in MySQL because MagicJoin requires MySQL style quotes
1167
        $mysqlPlatform = new MySqlPlatform();
1168
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter, $mysqlPlatform);
1169
1170
        $parameters = array_merge($parameters, $additionalParameters);
1171
1172
        $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...
1173
1174
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1175
    }
1176
1177
    /**
1178
     * @param $table
1179
     * @param array  $primaryKeys
1180
     * @param array  $additionalTablesFetch
1181
     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1182
     * @param string $className
1183
     *
1184
     * @return AbstractTDBMObject
1185
     *
1186
     * @throws TDBMException
1187
     */
1188
    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1189
    {
1190
        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1191
        $hash = $this->getObjectHash($primaryKeys);
1192
1193
        if ($this->objectStorage->has($table, $hash)) {
1194
            $dbRow = $this->objectStorage->get($table, $hash);
1195
            $bean = $dbRow->getTDBMObject();
1196
            if ($className !== null && !is_a($bean, $className)) {
1197
                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1198
            }
1199
1200
            return $bean;
1201
        }
1202
1203
        // Are we performing lazy fetching?
1204
        if ($lazy === true) {
1205
            // Can we perform lazy fetching?
1206
            $tables = $this->_getRelatedTablesByInheritance($table);
1207
            // Only allowed if no inheritance.
1208
            if (count($tables) === 1) {
1209
                if ($className === null) {
1210
                    try {
1211
                        $className = $this->getBeanClassName($table);
1212
                    } catch (TDBMInvalidArgumentException $e) {
1213
                        $className = TDBMObject::class;
1214
                    }
1215
                }
1216
1217
                // Let's construct the bean
1218
                if (!isset($this->reflectionClassCache[$className])) {
1219
                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1220
                }
1221
                // Let's bypass the constructor when creating the bean!
1222
                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1223
                /* @var $bean AbstractTDBMObject */
1224
                $bean->_constructLazy($table, $primaryKeys, $this);
1225
1226
                return $bean;
1227
            }
1228
        }
1229
1230
        // Did not find the object in cache? Let's query it!
1231
        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1232
    }
1233
1234
    /**
1235
     * Returns a unique bean (or null) according to the filters passed in parameter.
1236
     *
1237
     * @param string            $mainTable             The name of the table queried
1238
     * @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)
1239
     * @param array             $parameters
1240
     * @param array             $additionalTablesFetch
1241
     * @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
1242
     *
1243
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1244
     *
1245
     * @throws TDBMException
1246
     */
1247
    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1248
    {
1249
        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1250
        $page = $objects->take(0, 2);
1251
1252
1253
        $pageArr = $page->toArray();
1254
        // Optimisation: the $page->count() query can trigger an additional SQL query in platforms other than MySQL.
1255
        // We try to avoid calling at by fetching all 2 columns instead.
1256
        $count = count($pageArr);
1257
1258
        if ($count > 1) {
1259
            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.");
1260
        } elseif ($count === 0) {
1261
            return;
1262
        }
1263
1264
        return $pageArr[0];
1265
    }
1266
1267
    /**
1268
     * Returns a unique bean (or null) according to the filters passed in parameter.
1269
     *
1270
     * @param string            $mainTable  The name of the table queried
1271
     * @param string            $from       The from sql statement
1272
     * @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)
1273
     * @param array             $parameters
1274
     * @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
1275
     *
1276
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1277
     *
1278
     * @throws TDBMException
1279
     */
1280
    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1281
    {
1282
        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1283
        $page = $objects->take(0, 2);
1284
        $count = $page->count();
1285
        if ($count > 1) {
1286
            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.");
1287
        } elseif ($count === 0) {
1288
            return;
1289
        }
1290
1291
        return $page[0];
1292
    }
1293
1294
    /**
1295
     * @param string $mainTable
1296
     * @param string $sql
1297
     * @param array $parameters
1298
     * @param $mode
1299
     * @param string|null $className
1300
     * @param string $sqlCount
1301
     *
1302
     * @return ResultIterator
1303
     *
1304
     * @throws TDBMException
1305
     */
1306
    public function findObjectsFromRawSql(string $mainTable, string $sql, array $parameters = array(), $mode, string $className = null, string $sqlCount = null)
1307
    {
1308
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1309
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1310
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1311
        }
1312
1313
        $mode = $mode ?: $this->mode;
1314
1315
        $queryFactory = new FindObjectsFromRawSqlQueryFactory($this, $this->tdbmSchemaAnalyzer->getSchema(), $mainTable, $sql, $sqlCount);
1316
1317
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1318
    }
1319
1320
    /**
1321
     * Returns a unique bean according to the filters passed in parameter.
1322
     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1323
     *
1324
     * @param string            $mainTable             The name of the table queried
1325
     * @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)
1326
     * @param array             $parameters
1327
     * @param array             $additionalTablesFetch
1328
     * @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
1329
     *
1330
     * @return AbstractTDBMObject The object we want
1331
     *
1332
     * @throws TDBMException
1333
     */
1334
    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1335
    {
1336
        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1337
        if ($bean === null) {
1338
            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1339
        }
1340
1341
        return $bean;
1342
    }
1343
1344
    /**
1345
     * @param array $beanData An array of data: array<table, array<column, value>>
1346
     *
1347
     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1348
     *
1349
     * @throws TDBMInheritanceException
1350
     */
1351
    public function _getClassNameFromBeanData(array $beanData)
1352
    {
1353
        if (count($beanData) === 1) {
1354
            $tableName = array_keys($beanData)[0];
1355
            $allTables = [$tableName];
1356
        } else {
1357
            $tables = [];
1358
            foreach ($beanData as $table => $row) {
1359
                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1360
                $pkSet = false;
1361
                foreach ($primaryKeyColumns as $columnName) {
1362
                    if ($row[$columnName] !== null) {
1363
                        $pkSet = true;
1364
                        break;
1365
                    }
1366
                }
1367
                if ($pkSet) {
1368
                    $tables[] = $table;
1369
                }
1370
            }
1371
1372
            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1373
            try {
1374
                $allTables = $this->_getLinkBetweenInheritedTables($tables);
1375
            } catch (TDBMInheritanceException $e) {
1376
                throw TDBMInheritanceException::extendException($e, $this, $beanData);
1377
            }
1378
            $tableName = $allTables[0];
1379
        }
1380
1381
        // Only one table in this bean. Life is sweat, let's look at its type:
1382
        try {
1383
            $className = $this->getBeanClassName($tableName);
1384
        } catch (TDBMInvalidArgumentException $e) {
1385
            $className = 'TheCodingMachine\\TDBM\\TDBMObject';
1386
        }
1387
1388
        return [$className, $tableName, $allTables];
1389
    }
1390
1391
    /**
1392
     * Returns an item from cache or computes it using $closure and puts it in cache.
1393
     *
1394
     * @param string   $key
1395
     * @param callable $closure
1396
     *
1397
     * @return mixed
1398
     */
1399
    private function fromCache(string $key, callable $closure)
1400
    {
1401
        $item = $this->cache->fetch($key);
1402
        if ($item === false) {
1403
            $item = $closure();
1404
            $this->cache->save($key, $item);
1405
        }
1406
1407
        return $item;
1408
    }
1409
1410
    /**
1411
     * Returns the foreign key object.
1412
     *
1413
     * @param string $table
1414
     * @param string $fkName
1415
     *
1416
     * @return ForeignKeyConstraint
1417
     */
1418
    public function _getForeignKeyByName(string $table, string $fkName)
1419
    {
1420
        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1421
    }
1422
1423
    /**
1424
     * @param $pivotTableName
1425
     * @param AbstractTDBMObject $bean
1426
     *
1427
     * @return AbstractTDBMObject[]
1428
     */
1429
    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1430
    {
1431
        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1432
        /* @var $localFk ForeignKeyConstraint */
1433
        /* @var $remoteFk ForeignKeyConstraint */
1434
        $remoteTable = $remoteFk->getForeignTableName();
1435
1436
        $primaryKeys = $this->getPrimaryKeyValues($bean);
1437
        $columnNames = array_map(function ($name) use ($pivotTableName) {
1438
            return $pivotTableName.'.'.$name;
1439
        }, $localFk->getUnquotedLocalColumns());
1440
1441
        $filter = array_combine($columnNames, $primaryKeys);
1442
1443
        return $this->findObjects($remoteTable, $filter);
1444
    }
1445
1446
    /**
1447
     * @param $pivotTableName
1448
     * @param AbstractTDBMObject $bean The LOCAL bean
1449
     *
1450
     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1451
     *
1452
     * @throws TDBMException
1453
     */
1454
    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1455
    {
1456
        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1457
        $table1 = $fks[0]->getForeignTableName();
1458
        $table2 = $fks[1]->getForeignTableName();
1459
1460
        $beanTables = array_map(function (DbRow $dbRow) {
1461
            return $dbRow->_getDbTableName();
1462
        }, $bean->_getDbRows());
1463
1464
        if (in_array($table1, $beanTables)) {
1465
            return [$fks[0], $fks[1]];
1466
        } elseif (in_array($table2, $beanTables)) {
1467
            return [$fks[1], $fks[0]];
1468
        } else {
1469
            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1470
        }
1471
    }
1472
1473
    /**
1474
     * Returns a list of pivot tables linked to $bean.
1475
     *
1476
     * @param AbstractTDBMObject $bean
1477
     *
1478
     * @return string[]
1479
     */
1480
    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1481
    {
1482
        $junctionTables = [];
1483
        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1484
        foreach ($bean->_getDbRows() as $dbRow) {
1485
            foreach ($allJunctionTables as $table) {
1486
                // There are exactly 2 FKs since this is a pivot table.
1487
                $fks = array_values($table->getForeignKeys());
1488
1489
                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1490
                    $junctionTables[] = $table->getName();
1491
                }
1492
            }
1493
        }
1494
1495
        return $junctionTables;
1496
    }
1497
1498
    /**
1499
     * Array of types for tables.
1500
     * Key: table name
1501
     * Value: array of types indexed by column.
1502
     *
1503
     * @var array[]
1504
     */
1505
    private $typesForTable = [];
1506
1507
    /**
1508
     * @internal
1509
     *
1510
     * @param string $tableName
1511
     *
1512
     * @return Type[]
1513
     */
1514
    public function _getColumnTypesForTable(string $tableName)
1515
    {
1516
        if (!isset($this->typesForTable[$tableName])) {
1517
            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1518
            foreach ($columns as $column) {
1519
                $this->typesForTable[$tableName][$column->getName()] = $column->getType();
1520
            }
1521
        }
1522
1523
        return $this->typesForTable[$tableName];
1524
    }
1525
1526
    /**
1527
     * Sets the minimum log level.
1528
     * $level must be one of Psr\Log\LogLevel::xxx.
1529
     *
1530
     * Defaults to LogLevel::WARNING
1531
     *
1532
     * @param string $level
1533
     */
1534
    public function setLogLevel(string $level)
1535
    {
1536
        $this->logger = new LevelFilter($this->rootLogger, $level);
1537
    }
1538
}
1539