Passed
Pull Request — master (#68)
by David
03:59 queued 44s
created

TDBMService::persistManyToManyRelationships()   C

Complexity

Conditions 9
Paths 13

Size

Total Lines 51
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 6.2727
c 0
b 0
f 0
cc 9
eloc 29
nc 13
nop 1

How to fix   Long Method   

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