Passed
Pull Request — master (#30)
by David
03:48
created

TDBMService::findObjectFromSql()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 5
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
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\Platforms\AbstractPlatform;
27
use Doctrine\DBAL\Platforms\MySqlPlatform;
28
use Doctrine\DBAL\Platforms\OraclePlatform;
29
use Doctrine\DBAL\Schema\Column;
30
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
31
use Doctrine\DBAL\Schema\Schema;
32
use Doctrine\DBAL\Schema\Table;
33
use Doctrine\DBAL\Types\Type;
34
use Mouf\Database\MagicQuery;
35
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
36
use TheCodingMachine\TDBM\QueryFactory\FindObjectsFromSqlQueryFactory;
37
use TheCodingMachine\TDBM\QueryFactory\FindObjectsQueryFactory;
38
use TheCodingMachine\TDBM\QueryFactory\FindObjectsFromRawSqlQueryFactory;
39
use TheCodingMachine\TDBM\Utils\NamingStrategyInterface;
40
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
41
use Phlib\Logger\LevelFilter;
42
use Psr\Log\LoggerInterface;
43
use Psr\Log\LogLevel;
44
use Psr\Log\NullLogger;
45
46
/**
47
 * The TDBMService class is the main TDBM class. It provides methods to retrieve TDBMObject instances
48
 * from the database.
49
 *
50
 * @author David Negrier
51
 * @ExtendedAction {"name":"Generate DAOs", "url":"tdbmadmin/", "default":false}
52
 */
53
class TDBMService
54
{
55
    const MODE_CURSOR = 1;
56
    const MODE_ARRAY = 2;
57
58
    /**
59
     * The database connection.
60
     *
61
     * @var Connection
62
     */
63
    private $connection;
64
65
    /**
66
     * @var SchemaAnalyzer
67
     */
68
    private $schemaAnalyzer;
69
70
    /**
71
     * @var MagicQuery
72
     */
73
    private $magicQuery;
74
75
    /**
76
     * @var TDBMSchemaAnalyzer
77
     */
78
    private $tdbmSchemaAnalyzer;
79
80
    /**
81
     * @var string
82
     */
83
    private $cachePrefix;
84
85
    /**
86
     * Cache of table of primary keys.
87
     * Primary keys are stored by tables, as an array of column.
88
     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
89
     *
90
     * @var string[]
91
     */
92
    private $primaryKeysColumns;
93
94
    /**
95
     * Service storing objects in memory.
96
     * Access is done by table name and then by primary key.
97
     * If the primary key is split on several columns, access is done by an array of columns, serialized.
98
     *
99
     * @var StandardObjectStorage|WeakrefObjectStorage
100
     */
101
    private $objectStorage;
102
103
    /**
104
     * The fetch mode of the result sets returned by `getObjects`.
105
     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
106
     *
107
     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
108
     * 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,
109
     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
110
     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
111
     * You can access the array by key, or using foreach, several times.
112
     *
113
     * @var int
114
     */
115
    private $mode = self::MODE_ARRAY;
116
117
    /**
118
     * Table of new objects not yet inserted in database or objects modified that must be saved.
119
     *
120
     * @var \SplObjectStorage of DbRow objects
121
     */
122
    private $toSaveObjects;
123
124
    /**
125
     * A cache service to be used.
126
     *
127
     * @var Cache|null
128
     */
129
    private $cache;
130
131
    /**
132
     * Map associating a table name to a fully qualified Bean class name.
133
     *
134
     * @var array
135
     */
136
    private $tableToBeanMap = [];
137
138
    /**
139
     * @var \ReflectionClass[]
140
     */
141
    private $reflectionClassCache = array();
142
143
    /**
144
     * @var LoggerInterface
145
     */
146
    private $rootLogger;
147
148
    /**
149
     * @var LevelFilter|NullLogger
150
     */
151
    private $logger;
152
153
    /**
154
     * @var OrderByAnalyzer
155
     */
156
    private $orderByAnalyzer;
157
158
    /**
159
     * @var string
160
     */
161
    private $beanNamespace;
162
163
    /**
164
     * @var NamingStrategyInterface
165
     */
166
    private $namingStrategy;
167
    /**
168
     * @var ConfigurationInterface
169
     */
170
    private $configuration;
171
172
    /**
173
     * @param ConfigurationInterface $configuration The configuration object
174
     */
175
    public function __construct(ConfigurationInterface $configuration)
176
    {
177
        if (extension_loaded('weakref')) {
178
            $this->objectStorage = new WeakrefObjectStorage();
179
        } else {
180
            $this->objectStorage = new StandardObjectStorage();
181
        }
182
        $this->connection = $configuration->getConnection();
183
        $this->cache = $configuration->getCache();
184
        $this->schemaAnalyzer = $configuration->getSchemaAnalyzer();
185
186
        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
187
188
        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->connection, $this->cache, $this->schemaAnalyzer);
189
        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
190
191
        $this->toSaveObjects = new \SplObjectStorage();
192
        $logger = $configuration->getLogger();
193
        if ($logger === null) {
194
            $this->logger = new NullLogger();
195
            $this->rootLogger = new NullLogger();
196
        } else {
197
            $this->rootLogger = $logger;
198
            $this->setLogLevel(LogLevel::WARNING);
199
        }
200
        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
201
        $this->beanNamespace = $configuration->getBeanNamespace();
202
        $this->namingStrategy = $configuration->getNamingStrategy();
203
        $this->configuration = $configuration;
204
    }
205
206
    /**
207
     * Returns the object used to connect to the database.
208
     *
209
     * @return Connection
210
     */
211
    public function getConnection(): Connection
212
    {
213
        return $this->connection;
214
    }
215
216
    /**
217
     * Sets the default fetch mode of the result sets returned by `findObjects`.
218
     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
219
     *
220
     * 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).
221
     * 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
222
     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
223
     *
224
     * @param int $mode
225
     *
226
     * @return $this
227
     *
228
     * @throws TDBMException
229
     */
230
    public function setFetchMode($mode)
231
    {
232
        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
233
            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
234
        }
235
        $this->mode = $mode;
236
237
        return $this;
238
    }
239
240
    /**
241
     * Removes the given object from database.
242
     * This cannot be called on an object that is not attached to this TDBMService
243
     * (will throw a TDBMInvalidOperationException).
244
     *
245
     * @param AbstractTDBMObject $object the object to delete
246
     *
247
     * @throws TDBMException
248
     * @throws TDBMInvalidOperationException
249
     */
250
    public function delete(AbstractTDBMObject $object)
251
    {
252
        switch ($object->_getStatus()) {
253
            case TDBMObjectStateEnum::STATE_DELETED:
254
                // Nothing to do, object already deleted.
255
                return;
256
            case TDBMObjectStateEnum::STATE_DETACHED:
257
                throw new TDBMInvalidOperationException('Cannot delete a detached object');
258
            case TDBMObjectStateEnum::STATE_NEW:
259
                $this->deleteManyToManyRelationships($object);
260
                foreach ($object->_getDbRows() as $dbRow) {
261
                    $this->removeFromToSaveObjectList($dbRow);
262
                }
263
                break;
264
            case TDBMObjectStateEnum::STATE_DIRTY:
265
                foreach ($object->_getDbRows() as $dbRow) {
266
                    $this->removeFromToSaveObjectList($dbRow);
267
                }
268
                // 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...
269
            case TDBMObjectStateEnum::STATE_NOT_LOADED:
270
            case TDBMObjectStateEnum::STATE_LOADED:
271
                $this->deleteManyToManyRelationships($object);
272
                // Let's delete db rows, in reverse order.
273
                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
274
                    $tableName = $dbRow->_getDbTableName();
275
                    $primaryKeys = $dbRow->_getPrimaryKeys();
276
                    $this->connection->delete($this->connection->quoteIdentifier($tableName), $primaryKeys);
277
                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
278
                }
279
                break;
280
            // @codeCoverageIgnoreStart
281
            default:
282
                throw new TDBMInvalidOperationException('Unexpected status for bean');
283
            // @codeCoverageIgnoreEnd
284
        }
285
286
        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
287
    }
288
289
    /**
290
     * Removes all many to many relationships for this object.
291
     *
292
     * @param AbstractTDBMObject $object
293
     */
294
    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
295
    {
296
        foreach ($object->_getDbRows() as $tableName => $dbRow) {
297
            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
298
            foreach ($pivotTables as $pivotTable) {
299
                $remoteBeans = $object->_getRelationships($pivotTable);
300
                foreach ($remoteBeans as $remoteBean) {
301
                    $object->_removeRelationship($pivotTable, $remoteBean);
302
                }
303
            }
304
        }
305
        $this->persistManyToManyRelationships($object);
306
    }
307
308
    /**
309
     * This function removes the given object from the database. It will also remove all objects relied to the one given
310
     * by parameter before all.
311
     *
312
     * Notice: if the object has a multiple primary key, the function will not work.
313
     *
314
     * @param AbstractTDBMObject $objToDelete
315
     */
316
    public function deleteCascade(AbstractTDBMObject $objToDelete)
317
    {
318
        $this->deleteAllConstraintWithThisObject($objToDelete);
319
        $this->delete($objToDelete);
320
    }
321
322
    /**
323
     * This function is used only in TDBMService (private function)
324
     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
325
     *
326
     * @param AbstractTDBMObject $obj
327
     */
328
    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
329
    {
330
        $dbRows = $obj->_getDbRows();
331
        foreach ($dbRows as $dbRow) {
332
            $tableName = $dbRow->_getDbTableName();
333
            $pks = array_values($dbRow->_getPrimaryKeys());
334
            if (!empty($pks)) {
335
                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
336
337
                foreach ($incomingFks as $incomingFk) {
338
                    $filter = array_combine($incomingFk->getUnquotedLocalColumns(), $pks);
339
340
                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
341
342
                    foreach ($results as $bean) {
343
                        $this->deleteCascade($bean);
344
                    }
345
                }
346
            }
347
        }
348
    }
349
350
    /**
351
     * This function performs a save() of all the objects that have been modified.
352
     */
353
    public function completeSave()
354
    {
355
        foreach ($this->toSaveObjects as $dbRow) {
356
            $this->save($dbRow->getTDBMObject());
357
        }
358
    }
359
360
    /**
361
     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
362
     * and gives back a proper Filter object.
363
     *
364
     * @param mixed $filter_bag
365
     * @param AbstractPlatform $platform The platform used to quote identifiers
366
     * @param int $counter
367
     * @return array First item: filter string, second item: parameters
368
     *
369
     * @throws TDBMException
370
     */
371
    public function buildFilterFromFilterBag($filter_bag, AbstractPlatform $platform, $counter = 1)
372
    {
373
        if ($filter_bag === null) {
374
            return ['', []];
375
        } elseif (is_string($filter_bag)) {
376
            return [$filter_bag, []];
377
        } elseif (is_array($filter_bag)) {
378
            $sqlParts = [];
379
            $parameters = [];
380
381
            foreach ($filter_bag as $column => $value) {
382
                if (is_int($column)) {
383
                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $platform, $counter);
384
                    $sqlParts[] = $subSqlPart;
385
                    $parameters += $subParameters;
386
                } else {
387
                    $paramName = 'tdbmparam'.$counter;
388
                    if (is_array($value)) {
389
                        $sqlParts[] = $platform->quoteIdentifier($column).' IN :'.$paramName;
390
                    } else {
391
                        $sqlParts[] = $platform->quoteIdentifier($column).' = :'.$paramName;
392
                    }
393
                    $parameters[$paramName] = $value;
394
                    ++$counter;
395
                }
396
            }
397
398
            return [implode(' AND ', $sqlParts), $parameters];
399
        } elseif ($filter_bag instanceof AbstractTDBMObject) {
400
            $sqlParts = [];
401
            $parameters = [];
402
            $dbRows = $filter_bag->_getDbRows();
403
            $dbRow = reset($dbRows);
404
            $primaryKeys = $dbRow->_getPrimaryKeys();
405
406
            foreach ($primaryKeys as $column => $value) {
407
                $paramName = 'tdbmparam'.$counter;
408
                $sqlParts[] = $platform->quoteIdentifier($dbRow->_getDbTableName()).'.'.$platform->quoteIdentifier($column).' = :'.$paramName;
409
                $parameters[$paramName] = $value;
410
                ++$counter;
411
            }
412
413
            return [implode(' AND ', $sqlParts), $parameters];
414
        } elseif ($filter_bag instanceof \Iterator) {
415
            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $platform, $counter);
416
        } else {
417
            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.');
418
        }
419
    }
420
421
    /**
422
     * @param string $table
423
     *
424
     * @return string[]
425
     */
426
    public function getPrimaryKeyColumns($table)
427
    {
428
        if (!isset($this->primaryKeysColumns[$table])) {
429
            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKey()->getUnquotedColumns();
430
431
            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
432
433
            /*$arr = array();
434
            foreach ($this->connection->getPrimaryKey($table) as $col) {
435
                $arr[] = $col->name;
436
            }
437
            // The primaryKeysColumns contains only the column's name, not the DB_Column object.
438
            $this->primaryKeysColumns[$table] = $arr;
439
            if (empty($this->primaryKeysColumns[$table]))
440
            {
441
                // Unable to find primary key.... this is an error
442
                // Let's try to be precise in error reporting. Let's try to find the table.
443
                $tables = $this->connection->checkTableExist($table);
444
                if ($tables === true)
445
                throw new TDBMException("Could not find table primary key for table '$table'. Please define a primary key for this table.");
446
                elseif ($tables !== null) {
447
                    if (count($tables)==1)
448
                    $str = "Could not find table '$table'. Maybe you meant this table: '".$tables[0]."'";
449
                    else
450
                    $str = "Could not find table '$table'. Maybe you meant one of those tables: '".implode("', '",$tables)."'";
451
                    throw new TDBMException($str);
452
                }
453
            }*/
454
        }
455
456
        return $this->primaryKeysColumns[$table];
457
    }
458
459
    /**
460
     * This is an internal function, you should not use it in your application.
461
     * This is used internally by TDBM to add an object to the object cache.
462
     *
463
     * @param DbRow $dbRow
464
     */
465
    public function _addToCache(DbRow $dbRow)
466
    {
467
        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
468
        $hash = $this->getObjectHash($primaryKey);
469
        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
470
    }
471
472
    /**
473
     * This is an internal function, you should not use it in your application.
474
     * This is used internally by TDBM to remove the object from the list of objects that have been
475
     * created/updated but not saved yet.
476
     *
477
     * @param DbRow $myObject
478
     */
479
    private function removeFromToSaveObjectList(DbRow $myObject)
480
    {
481
        unset($this->toSaveObjects[$myObject]);
482
    }
483
484
    /**
485
     * This is an internal function, you should not use it in your application.
486
     * This is used internally by TDBM to add an object to the list of objects that have been
487
     * created/updated but not saved yet.
488
     *
489
     * @param DbRow $myObject
490
     */
491
    public function _addToToSaveObjectList(DbRow $myObject)
492
    {
493
        $this->toSaveObjects[$myObject] = true;
494
    }
495
496
    /**
497
     * Generates all the daos and beans.
498
     *
499
     * @return \string[] the list of tables (key) and bean name (value)
500
     */
501
    public function generateAllDaosAndBeans()
502
    {
503
        // Purge cache before generating anything.
504
        $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...
505
506
        $tdbmDaoGenerator = new TDBMDaoGenerator($this->configuration, $this->tdbmSchemaAnalyzer);
507
        $tdbmDaoGenerator->generateAllDaosAndBeans();
508
    }
509
510
    /**
511
     * Returns the fully qualified class name of the bean associated with table $tableName.
512
     *
513
     *
514
     * @param string $tableName
515
     *
516
     * @return string
517
     */
518
    public function getBeanClassName(string $tableName) : string
519
    {
520
        if (isset($this->tableToBeanMap[$tableName])) {
521
            return $this->tableToBeanMap[$tableName];
522
        } else {
523
            $className = $this->beanNamespace.'\\'.$this->namingStrategy->getBeanClassName($tableName);
524
525
            if (!class_exists($className)) {
526
                throw new TDBMInvalidArgumentException(sprintf('Could not find class "%s". Does table "%s" exist? If yes, consider regenerating the DAOs and beans.', $className, $tableName));
527
            }
528
529
            $this->tableToBeanMap[$tableName] = $className;
530
            return $className;
531
        }
532
    }
533
534
    /**
535
     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
536
     *
537
     * @param AbstractTDBMObject $object
538
     *
539
     * @throws TDBMException
540
     */
541
    public function save(AbstractTDBMObject $object)
542
    {
543
        $status = $object->_getStatus();
544
545
        if ($status === null) {
546
            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)));
547
        }
548
549
        // Let's attach this object if it is in detached state.
550
        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
551
            $object->_attach($this);
552
            $status = $object->_getStatus();
553
        }
554
555
        if ($status === TDBMObjectStateEnum::STATE_NEW) {
556
            $dbRows = $object->_getDbRows();
557
558
            $unindexedPrimaryKeys = array();
559
560
            foreach ($dbRows as $dbRow) {
561
                if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
562
                    throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
563
                }
564
                $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
565
                $tableName = $dbRow->_getDbTableName();
566
567
                $schema = $this->tdbmSchemaAnalyzer->getSchema();
568
                $tableDescriptor = $schema->getTable($tableName);
569
570
                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
571
572
                $references = $dbRow->_getReferences();
573
574
                // Let's save all references in NEW or DETACHED state (we need their primary key)
575
                foreach ($references as $fkName => $reference) {
576
                    if ($reference !== null) {
577
                        $refStatus = $reference->_getStatus();
578
                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
579
                            try {
580
                                $this->save($reference);
581
                            } catch (TDBMCyclicReferenceException $e) {
582
                                throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
583
                            }
584
                        }
585
                    }
586
                }
587
588
                if (empty($unindexedPrimaryKeys)) {
589
                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
590
                } else {
591
                    // First insert, the children must have the same primary key as the parent.
592
                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
593
                    $dbRow->_setPrimaryKeys($primaryKeys);
594
                }
595
596
                $dbRowData = $dbRow->_getDbRow();
597
598
                // Let's see if the columns for primary key have been set before inserting.
599
                // We assume that if one of the value of the PK has been set, the PK is set.
600
                $isPkSet = !empty($primaryKeys);
601
602
                /*if (!$isPkSet) {
603
                    // if there is no autoincrement and no pk set, let's go in error.
604
                    $isAutoIncrement = true;
605
606
                    foreach ($primaryKeyColumns as $pkColumnName) {
607
                        $pkColumn = $tableDescriptor->getColumn($pkColumnName);
608
                        if (!$pkColumn->getAutoincrement()) {
609
                            $isAutoIncrement = false;
610
                        }
611
                    }
612
613
                    if (!$isAutoIncrement) {
614
                        $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.";
615
                        throw new TDBMException($msg);
616
                    }
617
618
                }*/
619
620
                $types = [];
621
                $escapedDbRowData = [];
622
623
                foreach ($dbRowData as $columnName => $value) {
624
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
625
                    $types[] = $columnDescriptor->getType();
626
                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
627
                }
628
629
                $quotedTableName = $this->connection->quoteIdentifier($tableName);
630
                $this->connection->insert($quotedTableName, $escapedDbRowData, $types);
631
632
                if (!$isPkSet && count($primaryKeyColumns) === 1) {
633
                    $id = $this->connection->lastInsertId();
634
635
                    if ($id === false) {
636
                        // In Oracle (if we are in 11g), the lastInsertId will fail. We try again with the column.
637
                        $sequenceName = $this->connection->getDatabasePlatform()->getIdentitySequenceName(
638
                            $quotedTableName,
639
                            $this->connection->quoteIdentifier($primaryKeyColumns[0])
640
                        );
641
                        $id = $this->connection->lastInsertId($sequenceName);
642
                    }
643
644
                    $pkColumn = $primaryKeyColumns[0];
645
                    // lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
646
                    $id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
647
                    $primaryKeys[$pkColumn] = $id;
648
                }
649
650
                // TODO: change this to some private magic accessor in future
651
                $dbRow->_setPrimaryKeys($primaryKeys);
652
                $unindexedPrimaryKeys = array_values($primaryKeys);
653
654
                /*
655
                 * When attached, on "save", we check if the column updated is part of a primary key
656
                 * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
657
                 * This method should first verify that the id is not already used (and is not auto-incremented)
658
                 *
659
                 * In the object, the key is stored in an array of  (column => value), that can be directly used to update the record.
660
                 *
661
                 *
662
                 */
663
664
                /*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...
665
                    $this->db_connection->exec($sql);
666
                } catch (TDBMException $e) {
667
                    $this->db_onerror = true;
668
669
                    // Strange..... if we do not have the line below, bad inserts are not catched.
670
                    // It seems that destructors are called before the registered shutdown function (PHP >=5.0.5)
671
                    //if ($this->tdbmService->isProgramExiting())
672
                    //	trigger_error("program exiting");
673
                    trigger_error($e->getMessage(), E_USER_ERROR);
674
675
                    if (!$this->tdbmService->isProgramExiting())
676
                        throw $e;
677
                    else
678
                    {
679
                        trigger_error($e->getMessage(), E_USER_ERROR);
680
                    }
681
                }*/
682
683
                // Let's remove this object from the $new_objects static table.
684
                $this->removeFromToSaveObjectList($dbRow);
685
686
                // TODO: change this behaviour to something more sensible performance-wise
687
                // Maybe a setting to trigger this globally?
688
                //$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...
689
                //$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...
690
                //$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...
691
692
                // Let's add this object to the list of objects in cache.
693
                $this->_addToCache($dbRow);
694
            }
695
696
            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
697
        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
698
            $dbRows = $object->_getDbRows();
699
700
            foreach ($dbRows as $dbRow) {
701
                $references = $dbRow->_getReferences();
702
703
                // Let's save all references in NEW state (we need their primary key)
704
                foreach ($references as $fkName => $reference) {
705
                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
706
                        $this->save($reference);
707
                    }
708
                }
709
710
                // Let's first get the primary keys
711
                $tableName = $dbRow->_getDbTableName();
712
                $dbRowData = $dbRow->_getDbRow();
713
714
                $schema = $this->tdbmSchemaAnalyzer->getSchema();
715
                $tableDescriptor = $schema->getTable($tableName);
716
717
                $primaryKeys = $dbRow->_getPrimaryKeys();
718
719
                $types = [];
720
                $escapedDbRowData = [];
721
                $escapedPrimaryKeys = [];
722
723
                foreach ($dbRowData as $columnName => $value) {
724
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
725
                    $types[] = $columnDescriptor->getType();
726
                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
727
                }
728
                foreach ($primaryKeys as $columnName => $value) {
729
                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
730
                    $types[] = $columnDescriptor->getType();
731
                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
732
                }
733
734
                $this->connection->update($this->connection->quoteIdentifier($tableName), $escapedDbRowData, $escapedPrimaryKeys, $types);
735
736
                // Let's check if the primary key has been updated...
737
                $needsUpdatePk = false;
738
                foreach ($primaryKeys as $column => $value) {
739
                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
740
                        $needsUpdatePk = true;
741
                        break;
742
                    }
743
                }
744
                if ($needsUpdatePk) {
745
                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
746
                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
747
                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
748
                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
749
                }
750
751
                // Let's remove this object from the list of objects to save.
752
                $this->removeFromToSaveObjectList($dbRow);
753
            }
754
755
            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
756
        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
757
            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
758
        }
759
760
        // Finally, let's save all the many to many relationships to this bean.
761
        $this->persistManyToManyRelationships($object);
762
    }
763
764
    private function persistManyToManyRelationships(AbstractTDBMObject $object)
765
    {
766
        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
767
            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
768
            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
769
770
            $toRemoveFromStorage = [];
771
772
            foreach ($storage as $remoteBean) {
773
                /* @var $remoteBean AbstractTDBMObject */
774
                $statusArr = $storage[$remoteBean];
775
                $status = $statusArr['status'];
776
                $reverse = $statusArr['reverse'];
777
                if ($reverse) {
778
                    continue;
779
                }
780
781
                if ($status === 'new') {
782
                    $remoteBeanStatus = $remoteBean->_getStatus();
783
                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
784
                        // Let's save remote bean if needed.
785
                        $this->save($remoteBean);
786
                    }
787
788
                    ['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...
789
790
                    $this->connection->insert($pivotTableName, $filters, $types);
791
792
                    // Finally, let's mark relationships as saved.
793
                    $statusArr['status'] = 'loaded';
794
                    $storage[$remoteBean] = $statusArr;
795
                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
796
                    $remoteStatusArr = $remoteStorage[$object];
797
                    $remoteStatusArr['status'] = 'loaded';
798
                    $remoteStorage[$object] = $remoteStatusArr;
799
                } elseif ($status === 'delete') {
800
                    ['filters' => $filters, 'types' => $types] = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk, $tableDescriptor);
801
802
                    $this->connection->delete($this->connection->quoteIdentifier($pivotTableName), $filters, $types);
803
804
                    // Finally, let's remove relationships completely from bean.
805
                    $toRemoveFromStorage[] = $remoteBean;
806
807
                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
808
                }
809
            }
810
811
            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
812
            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
813
            foreach ($toRemoveFromStorage as $remoteBean) {
814
                $storage->detach($remoteBean);
815
            }
816
        }
817
    }
818
819
    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk, Table $tableDescriptor)
820
    {
821
        $localBeanPk = $this->getPrimaryKeyValues($localBean);
822
        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
823
        $localColumns = $localFk->getUnquotedLocalColumns();
824
        $remoteColumns = $remoteFk->getUnquotedLocalColumns();
825
826
        $localFilters = array_combine($localColumns, $localBeanPk);
827
        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
828
829
        $filters = array_merge($localFilters, $remoteFilters);
830
831
        $types = [];
832
        $escapedFilters = [];
833
834
        foreach ($filters as $columnName => $value) {
835
            $columnDescriptor = $tableDescriptor->getColumn($columnName);
836
            $types[] = $columnDescriptor->getType();
837
            $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
838
        }
839
        return ['filters' => $escapedFilters, 'types' => $types];
840
    }
841
842
    /**
843
     * Returns the "values" of the primary key.
844
     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
845
     *
846
     * @param AbstractTDBMObject $bean
847
     *
848
     * @return array numerically indexed array of values
849
     */
850
    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
851
    {
852
        $dbRows = $bean->_getDbRows();
853
        $dbRow = reset($dbRows);
854
855
        return array_values($dbRow->_getPrimaryKeys());
856
    }
857
858
    /**
859
     * Returns a unique hash used to store the object based on its primary key.
860
     * If the array contains only one value, then the value is returned.
861
     * Otherwise, a hash representing the array is returned.
862
     *
863
     * @param array $primaryKeys An array of columns => values forming the primary key
864
     *
865
     * @return string
866
     */
867
    public function getObjectHash(array $primaryKeys)
868
    {
869
        if (count($primaryKeys) === 1) {
870
            return reset($primaryKeys);
871
        } else {
872
            ksort($primaryKeys);
873
874
            return md5(json_encode($primaryKeys));
875
        }
876
    }
877
878
    /**
879
     * Returns an array of primary keys from the object.
880
     * The primary keys are extracted from the object columns and not from the primary keys stored in the
881
     * $primaryKeys variable of the object.
882
     *
883
     * @param DbRow $dbRow
884
     *
885
     * @return array Returns an array of column => value
886
     */
887
    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
888
    {
889
        $table = $dbRow->_getDbTableName();
890
        $dbRowData = $dbRow->_getDbRow();
891
892
        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
893
    }
894
895
    /**
896
     * Returns an array of primary keys for the given row.
897
     * The primary keys are extracted from the object columns.
898
     *
899
     * @param $table
900
     * @param array $columns
901
     *
902
     * @return array
903
     */
904
    public function _getPrimaryKeysFromObjectData($table, array $columns)
905
    {
906
        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
907
        $values = array();
908
        foreach ($primaryKeyColumns as $column) {
909
            if (isset($columns[$column])) {
910
                $values[$column] = $columns[$column];
911
            }
912
        }
913
914
        return $values;
915
    }
916
917
    /**
918
     * Attaches $object to this TDBMService.
919
     * The $object must be in DETACHED state and will pass in NEW state.
920
     *
921
     * @param AbstractTDBMObject $object
922
     *
923
     * @throws TDBMInvalidOperationException
924
     */
925
    public function attach(AbstractTDBMObject $object)
926
    {
927
        $object->_attach($this);
928
    }
929
930
    /**
931
     * Returns an associative array (column => value) for the primary keys from the table name and an
932
     * indexed array of primary key values.
933
     *
934
     * @param string $tableName
935
     * @param array  $indexedPrimaryKeys
936
     */
937
    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
938
    {
939
        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKey()->getUnquotedColumns();
940
941
        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
942
            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
943
			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
944
        }
945
946
        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
947
    }
948
949
    /**
950
     * Return the list of tables (from child to parent) joining the tables passed in parameter.
951
     * Tables must be in a single line of inheritance. The method will find missing tables.
952
     *
953
     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
954
     * we must be able to find all other tables.
955
     *
956
     * @param string[] $tables
957
     *
958
     * @return string[]
959
     */
960
    public function _getLinkBetweenInheritedTables(array $tables)
961
    {
962
        sort($tables);
963
964
        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
965
            function () use ($tables) {
966
                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
967
            });
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
    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
982
    {
983
        $schemaAnalyzer = $this->schemaAnalyzer;
984
985
        foreach ($tables as $currentTable) {
986
            $allParents = [$currentTable];
987
            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
988
                $currentTable = $currentFk->getForeignTableName();
989
                $allParents[] = $currentTable;
990
            }
991
992
            // Now, does the $allParents contain all the tables we want?
993
            $notFoundTables = array_diff($tables, $allParents);
994
            if (empty($notFoundTables)) {
995
                // We have a winner!
996
                return $allParents;
997
            }
998
        }
999
1000
        throw TDBMInheritanceException::create($tables);
1001
    }
1002
1003
    /**
1004
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1005
     *
1006
     * @param string $table
1007
     *
1008
     * @return string[]
1009
     */
1010
    public function _getRelatedTablesByInheritance($table)
1011
    {
1012
        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1013
            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1014
        });
1015
    }
1016
1017
    /**
1018
     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1019
     *
1020
     * @param string $table
1021
     *
1022
     * @return string[]
1023
     */
1024
    private function _getRelatedTablesByInheritanceWithoutCache($table)
1025
    {
1026
        $schemaAnalyzer = $this->schemaAnalyzer;
1027
1028
        // Let's scan the parent tables
1029
        $currentTable = $table;
1030
1031
        $parentTables = [];
1032
1033
        // Get parent relationship
1034
        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1035
            $currentTable = $currentFk->getForeignTableName();
1036
            $parentTables[] = $currentTable;
1037
        }
1038
1039
        // Let's recurse in children
1040
        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1041
1042
        return array_merge(array_reverse($parentTables), $childrenTables);
1043
    }
1044
1045
    /**
1046
     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1047
     *
1048
     * @param string $table
1049
     *
1050
     * @return string[]
1051
     */
1052
    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1053
    {
1054
        $tables = [$table];
1055
        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1056
1057
        foreach ($keys as $key) {
1058
            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1059
        }
1060
1061
        return $tables;
1062
    }
1063
1064
    /**
1065
     * Casts a foreign key into SQL, assuming table name is used with no alias.
1066
     * The returned value does contain only one table. For instance:.
1067
     *
1068
     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1069
     *
1070
     * @param ForeignKeyConstraint $fk
1071
     * @param bool                 $leftTableIsLocal
1072
     *
1073
     * @return string
1074
     */
1075
    /*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...
1076
        $onClauses = [];
1077
        $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1078
        $foreignColumns = $fk->getUnquotedForeignColumns();
1079
        $localTableName = $this->connection->quoteIdentifier($fk->getLocalTableName());
1080
        $localColumns = $fk->getUnquotedLocalColumns();
1081
        $columnCount = count($localTableName);
1082
1083
        for ($i = 0; $i < $columnCount; $i++) {
1084
            $onClauses[] = sprintf("%s.%s = %s.%s",
1085
                $localTableName,
1086
                $this->connection->quoteIdentifier($localColumns[$i]),
1087
                $foreignColumns,
1088
                $this->connection->quoteIdentifier($foreignColumns[$i])
1089
                );
1090
        }
1091
1092
        $onClause = implode(' AND ', $onClauses);
1093
1094
        if ($leftTableIsLocal) {
1095
            return sprintf(" LEFT JOIN %s ON (%s)", $foreignTableName, $onClause);
1096
        } else {
1097
            return sprintf(" LEFT JOIN %s ON (%s)", $localTableName, $onClause);
1098
        }
1099
    }*/
1100
1101
    /**
1102
     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1103
     *
1104
     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1105
     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1106
     *
1107
     * The findObjects method takes in parameter:
1108
     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1109
     * 			`$mainTable` parameter should be the name of an existing table in database.
1110
     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1111
     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1112
     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1113
     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1114
     *          Instead, please consider passing parameters (see documentation for more details).
1115
     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1116
     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1117
     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1118
     *
1119
     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1120
     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1121
     *
1122
     * Finally, if filter_bag is null, the whole table is returned.
1123
     *
1124
     * @param string                       $mainTable             The name of the table queried
1125
     * @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)
1126
     * @param array                        $parameters
1127
     * @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)
1128
     * @param array                        $additionalTablesFetch
1129
     * @param int                          $mode
1130
     * @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
1131
     *
1132
     * @return ResultIterator An object representing an array of results
1133
     *
1134
     * @throws TDBMException
1135
     */
1136
    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1137
    {
1138
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1139
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1140
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1141
        }
1142
1143
        $mode = $mode ?: $this->mode;
1144
1145
        // We quote in MySQL because MagicJoin requires MySQL style quotes
1146
        $mysqlPlatform = new MySqlPlatform();
1147
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter, $mysqlPlatform);
1148
1149
        $parameters = array_merge($parameters, $additionalParameters);
1150
1151
        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1152
1153
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1154
    }
1155
1156
    /**
1157
     * @param string                       $mainTable   The name of the table queried
1158
     * @param string                       $from        The from sql statement
1159
     * @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)
1160
     * @param array                        $parameters
1161
     * @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)
1162
     * @param int                          $mode
1163
     * @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
1164
     *
1165
     * @return ResultIterator An object representing an array of results
1166
     *
1167
     * @throws TDBMException
1168
     */
1169
    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1170
    {
1171
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1172
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1173
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1174
        }
1175
1176
        $mode = $mode ?: $this->mode;
1177
1178
        // We quote in MySQL because MagicJoin requires MySQL style quotes
1179
        $mysqlPlatform = new MySqlPlatform();
1180
        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter, $mysqlPlatform);
1181
1182
        $parameters = array_merge($parameters, $additionalParameters);
1183
1184
        $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...
1185
1186
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1187
    }
1188
1189
    /**
1190
     * @param $table
1191
     * @param array  $primaryKeys
1192
     * @param array  $additionalTablesFetch
1193
     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1194
     * @param string $className
1195
     *
1196
     * @return AbstractTDBMObject
1197
     *
1198
     * @throws TDBMException
1199
     */
1200
    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1201
    {
1202
        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1203
        $hash = $this->getObjectHash($primaryKeys);
1204
1205
        if ($this->objectStorage->has($table, $hash)) {
1206
            $dbRow = $this->objectStorage->get($table, $hash);
1207
            $bean = $dbRow->getTDBMObject();
1208
            if ($className !== null && !is_a($bean, $className)) {
1209
                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1210
            }
1211
1212
            return $bean;
1213
        }
1214
1215
        // Are we performing lazy fetching?
1216
        if ($lazy === true) {
1217
            // Can we perform lazy fetching?
1218
            $tables = $this->_getRelatedTablesByInheritance($table);
1219
            // Only allowed if no inheritance.
1220
            if (count($tables) === 1) {
1221
                if ($className === null) {
1222
                    try {
1223
                        $className = $this->getBeanClassName($table);
1224
                    } catch (TDBMInvalidArgumentException $e) {
1225
                        $className = TDBMObject::class;
1226
                    }
1227
                }
1228
1229
                // Let's construct the bean
1230
                if (!isset($this->reflectionClassCache[$className])) {
1231
                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1232
                }
1233
                // Let's bypass the constructor when creating the bean!
1234
                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1235
                /* @var $bean AbstractTDBMObject */
1236
                $bean->_constructLazy($table, $primaryKeys, $this);
1237
1238
                return $bean;
1239
            }
1240
        }
1241
1242
        // Did not find the object in cache? Let's query it!
1243
        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1244
    }
1245
1246
    /**
1247
     * Returns a unique bean (or null) according to the filters passed in parameter.
1248
     *
1249
     * @param string            $mainTable             The name of the table queried
1250
     * @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)
1251
     * @param array             $parameters
1252
     * @param array             $additionalTablesFetch
1253
     * @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
1254
     *
1255
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1256
     *
1257
     * @throws TDBMException
1258
     */
1259
    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1260
    {
1261
        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1262
        $page = $objects->take(0, 2);
1263
1264
1265
        $pageArr = $page->toArray();
1266
        // Optimisation: the $page->count() query can trigger an additional SQL query in platforms other than MySQL.
1267
        // We try to avoid calling at by fetching all 2 columns instead.
1268
        $count = count($pageArr);
1269
1270
        if ($count > 1) {
1271
            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.");
1272
        } elseif ($count === 0) {
1273
            return;
1274
        }
1275
1276
        return $pageArr[0];
1277
    }
1278
1279
    /**
1280
     * Returns a unique bean (or null) according to the filters passed in parameter.
1281
     *
1282
     * @param string            $mainTable  The name of the table queried
1283
     * @param string            $from       The from sql statement
1284
     * @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)
1285
     * @param array             $parameters
1286
     * @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
1287
     *
1288
     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1289
     *
1290
     * @throws TDBMException
1291
     */
1292
    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1293
    {
1294
        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1295
        $page = $objects->take(0, 2);
1296
        $count = $page->count();
1297
        if ($count > 1) {
1298
            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.");
1299
        } elseif ($count === 0) {
1300
            return;
1301
        }
1302
1303
        return $page[0];
1304
    }
1305
1306
    /**
1307
     * @param string $mainTable
1308
     * @param string $sql
1309
     * @param array $parameters
1310
     * @param $mode
1311
     * @param string|null $className
1312
     * @param string $sqlCount
1313
     *
1314
     * @return ResultIterator
1315
     *
1316
     * @throws TDBMException
1317
     */
1318
    public function findObjectsFromRawSql(string $mainTable, string $sql, array $parameters = array(), $mode, string $className = null, string $sqlCount = null)
1319
    {
1320
        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1321
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1322
            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1323
        }
1324
1325
        $mode = $mode ?: $this->mode;
1326
1327
        $queryFactory = new FindObjectsFromRawSqlQueryFactory($this, $this->tdbmSchemaAnalyzer->getSchema(), $mainTable, $sql, $sqlCount);
1328
1329
        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1330
    }
1331
1332
    /**
1333
     * Returns a unique bean according to the filters passed in parameter.
1334
     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1335
     *
1336
     * @param string            $mainTable             The name of the table queried
1337
     * @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)
1338
     * @param array             $parameters
1339
     * @param array             $additionalTablesFetch
1340
     * @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
1341
     *
1342
     * @return AbstractTDBMObject The object we want
1343
     *
1344
     * @throws TDBMException
1345
     */
1346
    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1347
    {
1348
        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1349
        if ($bean === null) {
1350
            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1351
        }
1352
1353
        return $bean;
1354
    }
1355
1356
    /**
1357
     * @param array $beanData An array of data: array<table, array<column, value>>
1358
     *
1359
     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1360
     *
1361
     * @throws TDBMInheritanceException
1362
     */
1363
    public function _getClassNameFromBeanData(array $beanData)
1364
    {
1365
        if (count($beanData) === 1) {
1366
            $tableName = array_keys($beanData)[0];
1367
            $allTables = [$tableName];
1368
        } else {
1369
            $tables = [];
1370
            foreach ($beanData as $table => $row) {
1371
                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1372
                $pkSet = false;
1373
                foreach ($primaryKeyColumns as $columnName) {
1374
                    if ($row[$columnName] !== null) {
1375
                        $pkSet = true;
1376
                        break;
1377
                    }
1378
                }
1379
                if ($pkSet) {
1380
                    $tables[] = $table;
1381
                }
1382
            }
1383
1384
            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1385
            try {
1386
                $allTables = $this->_getLinkBetweenInheritedTables($tables);
1387
            } catch (TDBMInheritanceException $e) {
1388
                throw TDBMInheritanceException::extendException($e, $this, $beanData);
1389
            }
1390
            $tableName = $allTables[0];
1391
        }
1392
1393
        // Only one table in this bean. Life is sweat, let's look at its type:
1394
        try {
1395
            $className = $this->getBeanClassName($tableName);
1396
        } catch (TDBMInvalidArgumentException $e) {
1397
            $className = 'TheCodingMachine\\TDBM\\TDBMObject';
1398
        }
1399
1400
        return [$className, $tableName, $allTables];
1401
    }
1402
1403
    /**
1404
     * Returns an item from cache or computes it using $closure and puts it in cache.
1405
     *
1406
     * @param string   $key
1407
     * @param callable $closure
1408
     *
1409
     * @return mixed
1410
     */
1411
    private function fromCache(string $key, callable $closure)
1412
    {
1413
        $item = $this->cache->fetch($key);
1414
        if ($item === false) {
1415
            $item = $closure();
1416
            $this->cache->save($key, $item);
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