Passed
Pull Request — master (#41)
by David
04:25
created

TDBMService::save()   F

Complexity

Conditions 29
Paths 2852

Size

Total Lines 229
Code Lines 102

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 29
eloc 102
nc 2852
nop 1
dl 0
loc 229
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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