Completed
Pull Request — 3.4 (#46)
by David
07:34 queued 01:29
created

TDBMService::findObject()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
rs 9.4286
cc 3
eloc 9
nc 3
nop 5
1
<?php
2
/*
3
 Copyright (C) 2006-2015 David Négrier - THE CODING MACHINE
4
5
This program is free software; you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation; either version 2 of the License, or
8
(at your option) any later version.
9
10
This program is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
GNU General Public License for more details.
14
15
You should have received a copy of the GNU General Public License
16
along with this program; if not, write to the Free Software
17
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
*/
19
20
namespace Mouf\Database\TDBM;
21
22
use Doctrine\Common\Cache\Cache;
23
use Doctrine\Common\Cache\VoidCache;
24
use Doctrine\DBAL\Connection;
25
use Doctrine\DBAL\DBALException;
26
use Doctrine\DBAL\Schema\Column;
27
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
28
use Doctrine\DBAL\Schema\Schema;
29
use Mouf\Database\MagicQuery;
30
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
31
use Mouf\Database\TDBM\Filters\OrderBySQLString;
32
use Mouf\Database\TDBM\Utils\TDBMDaoGenerator;
33
use Mouf\Utils\Cache\CacheInterface;
34
use SQLParser\Node\ColRef;
35
36
/**
37
 * The TDBMService class is the main TDBM class. It provides methods to retrieve TDBMObject instances
38
 * from the database.
39
 *
40
 * @author David Negrier
41
 * @ExtendedAction {"name":"Generate DAOs", "url":"tdbmadmin/", "default":false}
42
 */
43
class TDBMService {
44
	
45
	const MODE_CURSOR = 1;
46
	const MODE_ARRAY = 2;
47
	
48
	/**
49
	 * The database connection.
50
	 *
51
	 * @var Connection
52
	 */
53
	private $connection;
54
55
	/**
56
	 * @var SchemaAnalyzer
57
	 */
58
	private $schemaAnalyzer;
59
60
	/**
61
	 * @var MagicQuery
62
	 */
63
	private $magicQuery;
64
65
	/**
66
	 * @var TDBMSchemaAnalyzer
67
	 */
68
	private $tdbmSchemaAnalyzer;
69
70
	/**
71
	 * @var string
72
	 */
73
	private $cachePrefix;
74
75
	/**
76
	 * The default autosave mode for the objects
77
	 * True to automatically save the object.
78
	 * If false, the user must explicitly call the save() method to save the object.
79
	 *
80
	 * @var boolean
81
	 */
82
	//private $autosave_default = 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...
83
84
	/**
85
	 * Cache of table of primary keys.
86
	 * Primary keys are stored by tables, as an array of column.
87
	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
88
	 *
89
	 * @var string[]
90
	 */
91
	private $primaryKeysColumns;
92
93
	/**
94
	 * Service storing objects in memory.
95
	 * Access is done by table name and then by primary key.
96
	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
97
	 * 
98
	 * @var StandardObjectStorage|WeakrefObjectStorage
99
	 */
100
	private $objectStorage;
101
	
102
	/**
103
	 * The fetch mode of the result sets returned by `getObjects`.
104
	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY
105
	 *
106
	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
107
	 * 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,
108
	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
109
	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2). 
110
	 * You can access the array by key, or using foreach, several times.
111
	 *
112
	 * @var int
113
	 */
114
	private $mode = self::MODE_ARRAY;
115
116
	/**
117
	 * Table of new objects not yet inserted in database or objects modified that must be saved.
118
	 * @var \SplObjectStorage of DbRow objects
119
	 */
120
	private $toSaveObjects;
121
122
	/// The timestamp of the script startup. Useful to stop execution before time limit is reached and display useful error message.
123
	public static $script_start_up_time;
124
125
	/**
126
	 * The content of the cache variable.
127
	 *
128
	 * @var array<string, mixed>
129
	 */
130
	private $cache;
131
132
	private $cacheKey = "__TDBM_Cache__";
0 ignored issues
show
Unused Code introduced by
The property $cacheKey is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
133
134
	/**
135
	 * Map associating a table name to a fully qualified Bean class name
136
	 * @var array
137
	 */
138
	private $tableToBeanMap = [];
139
140
	/**
141
	 * @var \ReflectionClass[]
142
	 */
143
	private $reflectionClassCache;
0 ignored issues
show
Unused Code introduced by
The property $reflectionClassCache is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
144
145
	/**
146
	 * @param Connection $connection The DBAL DB connection to use
147
	 * @param Cache|null $cache A cache service to be used
148
	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
149
	 * 										 Will be automatically created if not passed.
150
	 */
151
	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null) {
152
		//register_shutdown_function(array($this,"completeSaveOnExit"));
0 ignored issues
show
Unused Code Comprehensibility introduced by
90% 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...
153
		if (extension_loaded('weakref')) {
154
			$this->objectStorage = new WeakrefObjectStorage();
155
		} else {
156
			$this->objectStorage = new StandardObjectStorage();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Mouf\Database\TDBM\StandardObjectStorage() of type object<Mouf\Database\TDBM\StandardObjectStorage> is incompatible with the declared type object<Mouf\Database\TDBM\WeakrefObjectStorage> of property $objectStorage.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
157
		}
158
		$this->connection = $connection;
159
		if ($cache !== null) {
160
			$this->cache = $cache;
161
		} else {
162
			$this->cache = new VoidCache();
163
		}
164
		if ($schemaAnalyzer) {
165
			$this->schemaAnalyzer = $schemaAnalyzer;
166
		} else {
167
			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
168
		}
169
170
		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
171
172
		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
173
		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
174
175
		if (self::$script_start_up_time === null) {
176
			self::$script_start_up_time = microtime(true);
177
		}
178
		$this->toSaveObjects = new \SplObjectStorage();
179
	}
180
181
182
	/**
183
	 * Returns the object used to connect to the database.
184
	 *
185
	 * @return Connection
186
	 */
187
	public function getConnection() {
188
		return $this->connection;
189
	}
190
191
	/**
192
	 * Creates a unique cache key for the current connection.
193
	 * @return string
194
	 */
195
	private function getConnectionUniqueId() {
196
		return hash('md4', $this->connection->getHost()."-".$this->connection->getPort()."-".$this->connection->getDatabase()."-".$this->connection->getDriver()->getName());
197
	}
198
199
	/**
200
	 * Returns true if the objects will save automatically by default,
201
	 * false if an explicit call to save() is required.
202
	 *
203
	 * The behaviour can be overloaded by setAutoSaveMode on each object.
204
	 *
205
	 * @return boolean
206
	 */
207
	/*public function getDefaultAutoSaveMode() {
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
208
		return $this->autosave_default;
209
	}*/
210
211
	/**
212
	 * Sets the autosave mode:
213
	 * true if the object will save automatically,
214
	 * false if an explicit call to save() is required.
215
	 *
216
	 * @Compulsory
217
	 * @param boolean $autoSave
218
	 */
219
	/*public function setDefaultAutoSaveMode($autoSave = true) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
220
		$this->autosave_default = $autoSave;
221
	}*/
222
223
	/**
224
	 * Sets the fetch mode of the result sets returned by `getObjects`.
225
	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY
226
	 *
227
	 * 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).
228
	 * 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
229
	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
230
	 *
231
	 * @param int $mode
232
	 */
233
	public function setFetchMode($mode) {
234 View Code Duplication
		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
235
			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
236
		}
237
		$this->mode = $mode;
238
		return $this;
239
	}
240
241
	/**
242
	 * Returns a TDBMObject associated from table "$table_name".
243
	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
244
	 * $filters can also be a set of TDBM_Filters (see the getObjects method for more details).
245
	 *
246
	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
247
	 * 			$user = $tdbmService->getObject('users',1);
248
	 * 			echo $user->name;
249
	 * will return the name of the user whose user_id is one.
250
	 *
251
	 * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
252
	 * For instance:
253
	 * 			$group = $tdbmService->getObject('groups',array(1,2));
254
	 *
255
	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
256
	 * will be the same.
257
	 *
258
	 * For instance:
259
	 * 			$user1 = $tdbmService->getObject('users',1);
260
	 * 			$user2 = $tdbmService->getObject('users',1);
261
	 * 			$user1->name = 'John Doe';
262
	 * 			echo $user2->name;
263
	 * will return 'John Doe'.
264
	 *
265
	 * You can use filters instead of passing the primary key. For instance:
266
	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
267
	 * This will return the user whose login is 'jdoe'.
268
	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
269
	 *
270
	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
271
	 * For instance:
272
	 *  	$user = $tdbmService->getObject('users',1,'User');
273
	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
274
	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
275
	 *
276
	 * @param string $table_name The name of the table we retrieve an object from.
277
	 * @param mixed $filters If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the getObjects method for more details about filter bags)
278
	 * @param string $className Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned.
279
	 * @param boolean $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown.
280
	 * @return TDBMObject
281
	 */
282
/*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
283
284
		if (is_array($filters) || $filters instanceof FilterInterface) {
285
			$isFilterBag = false;
286
			if (is_array($filters)) {
287
				// Is this a multiple primary key or a filter bag?
288
				// Let's have a look at the first item of the array to decide.
289
				foreach ($filters as $filter) {
290
					if (is_array($filter) || $filter instanceof FilterInterface) {
291
						$isFilterBag = true;
292
					}
293
					break;
294
				}
295
			} else {
296
				$isFilterBag = true;
297
			}
298
				
299
			if ($isFilterBag == true) {
300
				// If a filter bag was passer in parameter, let's perform a getObjects.
301
				$objects = $this->getObjects($table_name, $filters, null, null, null, $className);
302
				if (count($objects) == 0) {
303
					return null;
304
				} elseif (count($objects) > 1) {
305
					throw new DuplicateRowException("Error while querying an object for table '$table_name': ".count($objects)." rows have been returned, but we should have received at most one.");
306
				}
307
				// Return the first and only object.
308
				if ($objects instanceof \Generator) {
309
					return $objects->current();
310
				} else {
311
					return $objects[0];
312
				}
313
			}
314
		}
315
		$id = $filters;
316
		if ($this->connection == null) {
317
			throw new TDBMException("Error while calling TdbmService->getObject(): No connection has been established on the database!");
318
		}
319
		$table_name = $this->connection->toStandardcase($table_name);
320
321
		// If the ID is null, let's throw an exception
322
		if ($id === null) {
323
			throw new TDBMException("The ID you passed to TdbmService->getObject is null for the object of type '$table_name'. Objects primary keys cannot be null.");
324
		}
325
326
		// If the primary key is split over many columns, the IDs are passed in an array. Let's serialize this array to store it.
327
		if (is_array($id)) {
328
			$id = serialize($id);
329
		}
330
331
		if ($className === null) {
332
			if (isset($this->tableToBeanMap[$table_name])) {
333
				$className = $this->tableToBeanMap[$table_name];
334
			} else {
335
				$className = "Mouf\\Database\\TDBM\\TDBMObject";
336
			}
337
		}
338
339
		if ($this->objectStorage->has($table_name, $id)) {
340
			$obj = $this->objectStorage->get($table_name, $id);
341
			if (is_a($obj, $className)) {
342
				return $obj;
343
			} else {
344
				throw new TDBMException("Error! The object with ID '$id' for table '$table_name' has already been retrieved. The type for this object is '".get_class($obj)."'' which is not a subtype of '$className'");
345
			}
346
		}
347
348
		if ($className != "Mouf\\Database\\TDBM\\TDBMObject" && !is_subclass_of($className, "Mouf\\Database\\TDBM\\TDBMObject")) {
349
			if (!class_exists($className)) {
350
				throw new TDBMException("Error while calling TDBMService->getObject: The class ".$className." does not exist.");
351
			} else {
352
				throw new TDBMException("Error while calling TDBMService->getObject: The class ".$className." should extend TDBMObject.");
353
			}
354
		}
355
		$obj = new $className($this, $table_name, $id);
356
357
		if ($lazy_loading == false) {
358
			// If we are not doing lazy loading, let's load the object:
359
			$obj->_dbLoadIfNotLoaded();
360
		}
361
362
		$this->objectStorage->set($table_name, $id, $obj);
363
364
		return $obj;
365
	}*/
366
367
	/**
368
	 * Removes the given object from database.
369
	 * This cannot be called on an object that is not attached to this TDBMService
370
	 * (will throw a TDBMInvalidOperationException)
371
	 *
372
	 * @param AbstractTDBMObject $object the object to delete.
373
	 * @throws TDBMException
374
	 * @throws TDBMInvalidOperationException
375
	 */
376
	public function delete(AbstractTDBMObject $object) {
377
		switch ($object->_getStatus()) {
378
			case TDBMObjectStateEnum::STATE_DELETED:
379
				// Nothing to do, object already deleted.
380
				return;
381
			case TDBMObjectStateEnum::STATE_DETACHED:
382
				throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
			case TDBMObjectStateEnum::STATE_NEW:
384
                $this->deleteManyToManyRelationships($object);
385
				foreach ($object->_getDbRows() as $dbRow) {
386
					$this->removeFromToSaveObjectList($dbRow);
387
				}
388
				break;
389
			case TDBMObjectStateEnum::STATE_DIRTY:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
390
				foreach ($object->_getDbRows() as $dbRow) {
391
					$this->removeFromToSaveObjectList($dbRow);
392
				}
393
			case TDBMObjectStateEnum::STATE_NOT_LOADED:
394
			case TDBMObjectStateEnum::STATE_LOADED:
395
                $this->deleteManyToManyRelationships($object);
396
				// Let's delete db rows, in reverse order.
397
				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
398
					$tableName = $dbRow->_getDbTableName();
399
					$primaryKeys = $dbRow->_getPrimaryKeys();
400
401
					$this->connection->delete($tableName, $primaryKeys);
402
403
					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
404
				}
405
				break;
406
			// @codeCoverageIgnoreStart
407
			default:
408
				throw new TDBMInvalidOperationException('Unexpected status for bean');
409
			// @codeCoverageIgnoreEnd
410
		}
411
412
		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
413
	}
414
415
    /**
416
     * Removes all many to many relationships for this object.
417
     * @param AbstractTDBMObject $object
418
     */
419
    private function deleteManyToManyRelationships(AbstractTDBMObject $object) {
420
        foreach ($object->_getDbRows() as $tableName => $dbRow) {
421
            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
422
            foreach ($pivotTables as $pivotTable) {
423
                $remoteBeans = $object->_getRelationships($pivotTable);
424
                foreach ($remoteBeans as $remoteBean) {
425
                    $object->_removeRelationship($pivotTable, $remoteBean);
426
                }
427
            }
428
        }
429
        $this->persistManyToManyRelationships($object);
430
    }
431
432
433
    /**
434
     * This function removes the given object from the database. It will also remove all objects relied to the one given
435
     * by parameter before all.
436
     *
437
     * Notice: if the object has a multiple primary key, the function will not work.
438
     *
439
     * @param AbstractTDBMObject $objToDelete
440
     */
441
    public function deleteCascade(AbstractTDBMObject $objToDelete) {
442
        $this->deleteAllConstraintWithThisObject($objToDelete);
0 ignored issues
show
Compatibility introduced by
$objToDelete of type object<Mouf\Database\TDBM\AbstractTDBMObject> is not a sub-type of object<Mouf\Database\TDBM\TDBMObject>. It seems like you assume a child class of the class Mouf\Database\TDBM\AbstractTDBMObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
443
        $this->delete($objToDelete);
444
    }
445
446
    /**
447
     * This function is used only in TDBMService (private function)
448
     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter
449
     *
450
     * @param TDBMObject $obj
451
     * @return TDBMObjectArray
452
     */
453
    private function deleteAllConstraintWithThisObject(TDBMObject $obj) {
454
        $tableFrom = $this->connection->escapeDBItem($obj->_getDbTableName());
0 ignored issues
show
Bug introduced by
The method _getDbTableName() does not seem to exist on object<Mouf\Database\TDBM\TDBMObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method escapeDBItem() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
455
        $constraints = $this->connection->getConstraintsFromTable($tableFrom);
0 ignored issues
show
Bug introduced by
The method getConstraintsFromTable() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
456
        foreach ($constraints as $constraint) {
457
            $tableTo = $this->connection->escapeDBItem($constraint["table1"]);
0 ignored issues
show
Bug introduced by
The method escapeDBItem() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
458
            $colFrom = $this->connection->escapeDBItem($constraint["col2"]);
0 ignored issues
show
Bug introduced by
The method escapeDBItem() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
459
            $colTo = $this->connection->escapeDBItem($constraint["col1"]);
0 ignored issues
show
Bug introduced by
The method escapeDBItem() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
460
            $idVarName = $this->connection->escapeDBItem($obj->getPrimaryKey()[0]);
0 ignored issues
show
Bug introduced by
The method getPrimaryKey() does not exist on Mouf\Database\TDBM\TDBMObject. Did you maybe mean getPrimaryKeyWhereStatement()?

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...
Bug introduced by
The method escapeDBItem() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
461
            $idValue = $this->connection->quoteSmart($obj->TDBMObject_id);
0 ignored issues
show
Documentation introduced by
The property TDBMObject_id does not exist on object<Mouf\Database\TDBM\TDBMObject>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
The method quoteSmart() does not seem to exist on object<Doctrine\DBAL\Connection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
462
            $sql = "SELECT DISTINCT ".$tableTo.".*"
463
                    ." FROM ".$tableFrom
464
                    ." LEFT JOIN ".$tableTo." ON ".$tableFrom.".".$colFrom." = ".$tableTo.".".$colTo
465
                    ." WHERE ".$tableFrom.".".$idVarName."=".$idValue;
466
            $result = $this->getObjectsFromSQL($constraint["table1"], $sql);
0 ignored issues
show
Bug introduced by
The method getObjectsFromSQL() does not seem to exist on object<Mouf\Database\TDBM\TDBMService>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
467
            foreach ($result as $tdbmObj) {
468
                $this->deleteCascade($tdbmObj);
469
            }
470
        }
471
    }
472
473
	/**
474
	 * This function performs a save() of all the objects that have been modified.
475
	 */
476
	public function completeSave() {
477
478
		foreach ($this->toSaveObjects as $dbRow)
479
		{
480
			$this->save($dbRow->getTDBMObject());
481
		}
482
483
	}
484
485
	/**
486
	 * Returns an array of objects of "table_name" kind filtered from the filter bag.
487
	 *
488
	 * The getObjects method should be the most used query method in TDBM if you want to query the database for objects.
489
	 * (Note: if you want to query the database for an object by its primary key, use the getObject method).
490
	 *
491
	 * The getObjects method takes in parameter:
492
	 * 	- table_name: the kinf of TDBMObject you want to retrieve. In TDBM, a TDBMObject matches a database row, so the
493
	 * 			$table_name parameter should be the name of an existing table in database.
494
	 *  - filter_bag: The filter bag is anything that you can use to filter your request. It can be a SQL Where clause,
495
	 * 			a series of TDBM_Filter objects, or even TDBMObjects or TDBMObjectArrays that you will use as filters.
496
	 *  - order_bag: The order bag is anything that will be used to order the data that is passed back to you.
497
	 * 			A SQL Order by clause can be used as an order bag for instance, or a OrderByColumn object
498
	 * 	- from (optionnal): The offset from which the query should be performed. For instance, if $from=5, the getObjects method
499
	 * 			will return objects from the 6th rows.
500
	 * 	- limit (optionnal): The maximum number of objects to return. Used together with $from, you can implement
501
	 * 			paging mechanisms.
502
	 *  - hint_path (optionnal): EXPERTS ONLY! The path the request should use if not the most obvious one. This parameter
503
	 * 			should be used only if you perfectly know what you are doing.
504
	 *
505
	 * The getObjects method will return a TDBMObjectArray. A TDBMObjectArray is an array of TDBMObjects that does behave as
506
	 * a single TDBMObject if the array has only one member. Refer to the documentation of TDBMObjectArray and TDBMObject
507
	 * to learn more.
508
	 *
509
	 * More about the filter bag:
510
	 * A filter is anything that can change the set of objects returned by getObjects.
511
	 * There are many kind of filters in TDBM:
512
	 * A filter can be:
513
	 * 	- A SQL WHERE clause:
514
	 * 		The clause is specified without the "WHERE" keyword. For instance:
515
	 * 			$filter = "users.first_name LIKE 'J%'";
516
	 *     	is a valid filter.
517
	 * 	   	The only difference with SQL is that when you specify a column name, it should always be fully qualified with
518
	 * 		the table name: "country_name='France'" is not valid, while "countries.country_name='France'" is valid (if
519
	 * 		"countries" is a table and "country_name" a column in that table, sure.
520
	 * 		For instance,
521
	 * 				$french_users = TDBMObject::getObjects("users", "countries.country_name='France'");
522
	 * 		will return all the users that are French (based on trhe assumption that TDBM can find a way to connect the users
523
	 * 		table to the country table using foreign keys, see the manual for that point).
524
	 * 	- A TDBMObject:
525
	 * 		An object can be used as a filter. For instance, we could get the France object and then find any users related to
526
	 * 		that object using:
527
	 * 				$france = TDBMObject::getObjects("country", "countries.country_name='France'");
528
	 * 				$french_users = TDBMObject::getObjects("users", $france);
529
	 *  - A TDBMObjectArray can be used as a filter too.
530
	 * 		For instance:
531
	 * 				$french_groups = TDBMObject::getObjects("groups", $french_users);
532
	 * 		might return all the groups in which french users can be found.
533
	 *  - Finally, TDBM_xxxFilter instances can be used.
534
	 * 		TDBM provides the developer a set of TDBM_xxxFilters that can be used to model a SQL Where query.
535
	 * 		Using the appropriate filter object, you can model the operations =,<,<=,>,>=,IN,LIKE,AND,OR, IS NULL and NOT
536
	 * 		For instance:
537
	 * 				$french_users = TDBMObject::getObjects("users", new EqualFilter('countries','country_name','France');
538
	 * 		Refer to the documentation of the appropriate filters for more information.
539
	 *
540
	 * The nice thing about a filter bag is that it can be any filter, or any array of filters. In that case, filters are
541
	 * 'ANDed' together.
542
	 * So a request like this is valid:
543
	 * 				$france = TDBMObject::getObjects("country", "countries.country_name='France'");
544
	 * 				$french_administrators = TDBMObject::getObjects("users", array($france,"role.role_name='Administrators'");
545
	 * This requests would return the users that are both French and administrators.
546
	 *
547
	 * Finally, if filter_bag is null, the whole table is returned.
548
	 *
549
	 * More about the order bag:
550
	 * The order bag contains anything that can be used to order the data that is passed back to you.
551
	 * The order bag can contain two kinds of objects:
552
	 * 	- A SQL ORDER BY clause:
553
	 * 		The clause is specified without the "ORDER BY" keyword. For instance:
554
	 * 			$orderby = "users.last_name ASC, users.first_name ASC";
555
	 *     	is a valid order bag.
556
	 * 		The only difference with SQL is that when you specify a column name, it should always be fully qualified with
557
	 * 		the table name: "country_name ASC" is not valid, while "countries.country_name ASC" is valid (if
558
	 * 		"countries" is a table and "country_name" a column in that table, sure.
559
	 * 		For instance,
560
	 * 				$french_users = TDBMObject::getObjects("users", null, "countries.country_name ASC");
561
	 * 		will return all the users sorted by country.
562
	 *  - A OrderByColumn object
563
	 * 		This object models a single column in a database.
564
	 *
565
	 * @param string $table_name The name of the table queried
566
	 * @param mixed $filter_bag The filter bag (see above for complete description)
567
	 * @param mixed $orderby_bag The order bag (see above for complete description)
568
	 * @param integer $from The offset
569
	 * @param integer $limit The maximum number of rows returned
570
	 * @param string $className Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned.
571
	 * @param unknown_type $hint_path Hints to get the path for the query (expert parameter, you should leave it to null).
572
	 * @return TDBMObjectArray A TDBMObjectArray containing the resulting objects of the query.
573
	 */
574
/*	public function getObjects($table_name, $filter_bag=null, $orderby_bag=null, $from=null, $limit=null, $className=null, $hint_path=null) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
575
		if ($this->connection == null) {
576
			throw new TDBMException("Error while calling TDBMObject::getObject(): No connection has been established on the database!");
577
		}
578
		return $this->getObjectsByMode('getObjects', $table_name, $filter_bag, $orderby_bag, $from, $limit, $className, $hint_path);
579
	}*/
580
581
582
	/**
583
	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
584
	 * and gives back a proper Filter object.
585
	 *
586
	 * @param mixed $filter_bag
587
	 * @return array First item: filter string, second item: parameters.
588
	 * @throws TDBMException
589
	 */
590
	public function buildFilterFromFilterBag($filter_bag) {
591
		$counter = 1;
592
		if ($filter_bag === null) {
593
			return ['', []];
594
		} elseif (is_string($filter_bag)) {
595
			return [$filter_bag, []];
596
		} elseif (is_array($filter_bag)) {
597
			$sqlParts = [];
598
			$parameters = [];
599
			foreach ($filter_bag as $column => $value) {
600
				$paramName = "tdbmparam".$counter;
601
				if (is_array($value)) {
602
					$sqlParts[] = $this->connection->quoteIdentifier($column)." IN :".$paramName;
603
				} else {
604
					$sqlParts[] = $this->connection->quoteIdentifier($column)." = :".$paramName;
605
				}
606
				$parameters[$paramName] = $value;
607
				$counter++;
608
			}
609
			return [implode(' AND ', $sqlParts), $parameters];
610
		} elseif ($filter_bag instanceof AbstractTDBMObject) {
611
			$dbRows = $filter_bag->_getDbRows();
612
			$dbRow = reset($dbRows);
613
			$primaryKeys = $dbRow->_getPrimaryKeys();
614
615
			foreach ($primaryKeys as $column => $value) {
616
				$paramName = "tdbmparam".$counter;
617
				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column)." = :".$paramName;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sqlParts was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sqlParts = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
618
				$parameters[$paramName] = $value;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$parameters was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parameters = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
619
				$counter++;
620
			}
621
			return [implode(' AND ', $sqlParts), $parameters];
0 ignored issues
show
Bug introduced by
The variable $sqlParts does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $parameters does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
622
		} elseif ($filter_bag instanceof \Iterator) {
623
			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag));
624
		} else {
625
			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.");
626
		}
627
628
//		// First filter_bag should be an array, if it is a singleton, let's put it in an array.
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
629
//		if ($filter_bag === null) {
630
//			$filter_bag = array();
631
//		} elseif (!is_array($filter_bag)) {
632
//			$filter_bag = array($filter_bag);
633
//		}
634
//		elseif (is_a($filter_bag, 'Mouf\\Database\\TDBM\\TDBMObjectArray')) {
635
//			$filter_bag = array($filter_bag);
636
//		}
637
//
638
//		// Second, let's take all the objects out of the filter bag, and let's make filters from them
639
//		$filter_bag2 = array();
640
//		foreach ($filter_bag as $thing) {
641
//			if (is_a($thing,'Mouf\\Database\\TDBM\\Filters\\FilterInterface')) {
642
//				$filter_bag2[] = $thing;
643
//			} elseif (is_string($thing)) {
644
//				$filter_bag2[] = new SqlStringFilter($thing);
645
//			} elseif (is_a($thing,'Mouf\\Database\\TDBM\\TDBMObjectArray') && count($thing)>0) {
646
//				// Get table_name and column_name
647
//				$filter_table_name = $thing[0]->_getDbTableName();
648
//				$filter_column_names = $thing[0]->getPrimaryKey();
649
//
650
//				// If there is only one primary key, we can use the InFilter
651
//				if (count($filter_column_names)==1) {
652
//					$primary_keys_array = array();
653
//					$filter_column_name = $filter_column_names[0];
654
//					foreach ($thing as $TDBMObject) {
655
//						$primary_keys_array[] = $TDBMObject->$filter_column_name;
656
//					}
657
//					$filter_bag2[] = new InFilter($filter_table_name, $filter_column_name, $primary_keys_array);
658
//				}
659
//				// else, we must use a (xxx AND xxx AND xxx) OR (xxx AND xxx AND xxx) OR (xxx AND xxx AND xxx)...
660
//				else
661
//				{
662
//					$filter_bag_and = array();
663
//					foreach ($thing as $TDBMObject) {
664
//						$filter_bag_temp_and=array();
665
//						foreach ($filter_column_names as $pk) {
666
//							$filter_bag_temp_and[] = new EqualFilter($TDBMObject->_getDbTableName(), $pk, $TDBMObject->$pk);
667
//						}
668
//						$filter_bag_and[] = new AndFilter($filter_bag_temp_and);
669
//					}
670
//					$filter_bag2[] = new OrFilter($filter_bag_and);
671
//				}
672
//
673
//
674
//			} elseif (!is_a($thing,'Mouf\\Database\\TDBM\\TDBMObjectArray') && $thing!==null) {
675
//				throw new TDBMException("Error in filter bag in getObjectsByFilter. An object has been passed that is neither a filter, nor a TDBMObject, nor a TDBMObjectArray, nor a string, nor null.");
676
//			}
677
//		}
678
//
679
//		// Third, let's take all the filters and let's apply a huge AND filter
680
//		$filter = new AndFilter($filter_bag2);
681
//
682
//		return $filter;
683
	}
684
685
	/**
686
	 * Takes in input an order_bag (which can be about anything from a string to an array of OrderByColumn objects... see above from documentation),
687
	 * and gives back an array of OrderByColumn / OrderBySQLString objects.
688
	 *
689
	 * @param unknown_type $orderby_bag
690
	 * @return array
691
	 */
692
	public function buildOrderArrayFromOrderBag($orderby_bag) {
693
		// Fourth, let's apply the same steps to the orderby_bag
694
		// 4-1 orderby_bag should be an array, if it is a singleton, let's put it in an array.
695
696
		if (!is_array($orderby_bag))
697
		$orderby_bag = array($orderby_bag);
698
699
		// 4-2, let's take all the objects out of the orderby bag, and let's make objects from them
700
		$orderby_bag2 = array();
701
		foreach ($orderby_bag as $thing) {
702
			if (is_a($thing,'Mouf\\Database\\TDBM\\Filters\\OrderBySQLString')) {
703
				$orderby_bag2[] = $thing;
704
			} elseif (is_a($thing,'Mouf\\Database\\TDBM\\Filters\\OrderByColumn')) {
705
				$orderby_bag2[] = $thing;
706
			} elseif (is_string($thing)) {
707
				$orderby_bag2[] = new OrderBySQLString($thing);
708
			} elseif ($thing !== null) {
709
				throw new TDBMException("Error in orderby bag in getObjectsByFilter. An object has been passed that is neither a OrderBySQLString, nor a OrderByColumn, nor a string, nor null.");
710
			}
711
		}
712
		return $orderby_bag2;
713
	}
714
715
	/**
716
	 * @param string $table
717
	 * @return string[]
718
	 */
719
	public function getPrimaryKeyColumns($table) {
720
		if (!isset($this->primaryKeysColumns[$table]))
721
		{
722
			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
723
724
			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
725
726
			/*$arr = array();
727
			foreach ($this->connection->getPrimaryKey($table) as $col) {
728
				$arr[] = $col->name;
729
			}
730
			// The primaryKeysColumns contains only the column's name, not the DB_Column object.
731
			$this->primaryKeysColumns[$table] = $arr;
732
			if (empty($this->primaryKeysColumns[$table]))
733
			{
734
				// Unable to find primary key.... this is an error
735
				// Let's try to be precise in error reporting. Let's try to find the table.
736
				$tables = $this->connection->checkTableExist($table);
737
				if ($tables === true)
738
				throw new TDBMException("Could not find table primary key for table '$table'. Please define a primary key for this table.");
739
				elseif ($tables !== null) {
740
					if (count($tables)==1)
741
					$str = "Could not find table '$table'. Maybe you meant this table: '".$tables[0]."'";
742
					else
743
					$str = "Could not find table '$table'. Maybe you meant one of those tables: '".implode("', '",$tables)."'";
744
					throw new TDBMException($str);
745
				}
746
			}*/
747
		}
748
		return $this->primaryKeysColumns[$table];
749
	}
750
751
	/**
752
	 * This is an internal function, you should not use it in your application.
753
	 * This is used internally by TDBM to add an object to the object cache.
754
	 *
755
	 * @param DbRow $dbRow
756
	 */
757
	public function _addToCache(DbRow $dbRow) {
758
		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
759
		$hash = $this->getObjectHash($primaryKey);
760
		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
761
	}
762
763
	/**
764
	 * This is an internal function, you should not use it in your application.
765
	 * This is used internally by TDBM to remove the object from the list of objects that have been
766
	 * created/updated but not saved yet.
767
	 *
768
	 * @param DbRow $myObject
769
	 */
770
	private function removeFromToSaveObjectList(DbRow $myObject) {
771
		unset($this->toSaveObjects[$myObject]);
772
	}
773
774
	/**
775
	 * This is an internal function, you should not use it in your application.
776
	 * This is used internally by TDBM to add an object to the list of objects that have been
777
	 * created/updated but not saved yet.
778
	 *
779
	 * @param AbstractTDBMObject $myObject
780
	 */
781
	public function _addToToSaveObjectList(DbRow $myObject) {
782
		$this->toSaveObjects[$myObject] = true;
783
	}
784
785
	/**
786
	 * Generates all the daos and beans.
787
	 *
788
	 * @param string $daoFactoryClassName The classe name of the DAO factory
789
	 * @param string $daonamespace The namespace for the DAOs, without trailing \
790
	 * @param string $beannamespace The Namespace for the beans, without trailing \
791
	 * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone.
792
	 * @return \string[] the list of tables
793
	 */
794
	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc) {
795
		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
796
		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
797
	}
798
799
	/**
800
 	* @param array<string, string> $tableToBeanMap
801
 	*/
802
	public function setTableToBeanMap(array $tableToBeanMap) {
803
		$this->tableToBeanMap = $tableToBeanMap;
804
	}
805
806
	/**
807
	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
808
	 *
809
	 * @param AbstractTDBMObject $object
810
	 * @throws TDBMException
811
	 */
812
	public function save(AbstractTDBMObject $object) {
813
		$status = $object->_getStatus();
814
815
		// Let's attach this object if it is in detached state.
816
		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
817
			$object->_attach($this);
818
			$status = $object->_getStatus();
819
		}
820
821
		if ($status === TDBMObjectStateEnum::STATE_NEW) {
822
			$dbRows = $object->_getDbRows();
823
824
			$unindexedPrimaryKeys = array();
825
826
			foreach ($dbRows as $dbRow) {
827
828
				$tableName = $dbRow->_getDbTableName();
829
830
				$schema = $this->tdbmSchemaAnalyzer->getSchema();
831
				$tableDescriptor = $schema->getTable($tableName);
832
833
				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
834
835
				if (empty($unindexedPrimaryKeys)) {
836
					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
837
				} else {
838
					// First insert, the children must have the same primary key as the parent.
839
					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
840
					$dbRow->_setPrimaryKeys($primaryKeys);
841
				}
842
843
				$references = $dbRow->_getReferences();
844
845
				// Let's save all references in NEW or DETACHED state (we need their primary key)
846
				foreach ($references as $fkName => $reference) {
847
                    $refStatus = $reference->_getStatus();
848
					if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
849
						$this->save($reference);
850
					}
851
				}
852
853
				$dbRowData = $dbRow->_getDbRow();
854
855
				// Let's see if the columns for primary key have been set before inserting.
856
				// We assume that if one of the value of the PK has been set, the PK is set.
857
				$isPkSet = !empty($primaryKeys);
858
859
860
				/*if (!$isPkSet) {
861
                    // if there is no autoincrement and no pk set, let's go in error.
862
                    $isAutoIncrement = true;
863
864
                    foreach ($primaryKeyColumns as $pkColumnName) {
865
                        $pkColumn = $tableDescriptor->getColumn($pkColumnName);
866
                        if (!$pkColumn->getAutoincrement()) {
867
                            $isAutoIncrement = false;
868
                        }
869
                    }
870
871
                    if (!$isAutoIncrement) {
872
                        $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.";
873
                        throw new TDBMException($msg);
874
                    }
875
876
                }*/
877
878
				$types = [];
879
880
				foreach ($dbRowData as $columnName => $value) {
881
					$columnDescriptor = $tableDescriptor->getColumn($columnName);
882
					$types[] = $columnDescriptor->getType();
883
				}
884
885
				$this->connection->insert($tableName, $dbRowData, $types);
886
887
				if (!$isPkSet && count($primaryKeyColumns) == 1) {
888
					$id = $this->connection->lastInsertId();
889
					$primaryKeys[$primaryKeyColumns[0]] = $id;
890
				}
891
892
				// TODO: change this to some private magic accessor in future
893
				$dbRow->_setPrimaryKeys($primaryKeys);
894
				$unindexedPrimaryKeys = array_values($primaryKeys);
895
896
897
898
899
				/*
900
                 * When attached, on "save", we check if the column updated is part of a primary key
901
                 * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
902
                 * This method should first verify that the id is not already used (and is not auto-incremented)
903
                 *
904
                 * In the object, the key is stored in an array of  (column => value), that can be directly used to update the record.
905
                 *
906
                 *
907
                 */
908
909
910
				/*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...
911
                    $this->db_connection->exec($sql);
912
                } catch (TDBMException $e) {
913
                    $this->db_onerror = true;
914
915
                    // Strange..... if we do not have the line below, bad inserts are not catched.
916
                    // It seems that destructors are called before the registered shutdown function (PHP >=5.0.5)
917
                    //if ($this->tdbmService->isProgramExiting())
918
                    //	trigger_error("program exiting");
919
                    trigger_error($e->getMessage(), E_USER_ERROR);
920
921
                    if (!$this->tdbmService->isProgramExiting())
922
                        throw $e;
923
                    else
924
                    {
925
                        trigger_error($e->getMessage(), E_USER_ERROR);
926
                    }
927
                }*/
928
929
				// Let's remove this object from the $new_objects static table.
930
				$this->removeFromToSaveObjectList($dbRow);
931
932
				// TODO: change this behaviour to something more sensible performance-wise
933
				// Maybe a setting to trigger this globally?
934
				//$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...
935
				//$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...
936
				//$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...
937
938
				// Let's add this object to the list of objects in cache.
939
				$this->_addToCache($dbRow);
940
			}
941
942
943
944
945
			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
946
		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
947
			$dbRows = $object->_getDbRows();
948
949
			foreach ($dbRows as $dbRow) {
950
				$references = $dbRow->_getReferences();
951
952
				// Let's save all references in NEW state (we need their primary key)
953
				foreach ($references as $fkName => $reference) {
954
					if ($reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
955
						$this->save($reference);
956
					}
957
				}
958
959
				// Let's first get the primary keys
960
				$tableName = $dbRow->_getDbTableName();
961
				$dbRowData = $dbRow->_getDbRow();
962
963
				$schema = $this->tdbmSchemaAnalyzer->getSchema();
964
				$tableDescriptor = $schema->getTable($tableName);
965
966
				$primaryKeys = $dbRow->_getPrimaryKeys();
967
968
				$types = [];
969
970
				foreach ($dbRowData as $columnName => $value) {
971
					$columnDescriptor = $tableDescriptor->getColumn($columnName);
972
					$types[] = $columnDescriptor->getType();
973
				}
974
				foreach ($primaryKeys as $columnName => $value) {
975
					$columnDescriptor = $tableDescriptor->getColumn($columnName);
976
					$types[] = $columnDescriptor->getType();
977
				}
978
979
				$this->connection->update($tableName, $dbRowData, $primaryKeys, $types);
980
981
				// Let's check if the primary key has been updated...
982
				$needsUpdatePk = false;
983
				foreach ($primaryKeys as $column => $value) {
984
					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
985
						$needsUpdatePk = true;
986
						break;
987
					}
988
				}
989
				if ($needsUpdatePk) {
990
					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
991
					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
992
					$dbRow->_setPrimaryKeys($newPrimaryKeys);
993
					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
994
				}
995
996
				// Let's remove this object from the list of objects to save.
997
				$this->removeFromToSaveObjectList($dbRow);
998
			}
999
1000
			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
1001
1002
		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
1003
			throw new TDBMInvalidOperationException("This object has been deleted. It cannot be saved.");
1004
		}
1005
1006
        // Finally, let's save all the many to many relationships to this bean.
1007
        $this->persistManyToManyRelationships($object);
1008
	}
1009
1010
    private function persistManyToManyRelationships(AbstractTDBMObject $object) {
1011
        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
1012
            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
1013
            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
1014
1015
            foreach ($storage as $remoteBean) {
1016
                /* @var $remoteBean AbstractTDBMObject */
1017
                $statusArr = $storage[$remoteBean];
1018
                $status = $statusArr['status'];
1019
                $reverse = $statusArr['reverse'];
1020
                if ($reverse) {
1021
                    continue;
1022
                }
1023
1024
                if ($status === 'new') {
1025
                    $remoteBeanStatus = $remoteBean->_getStatus();
1026
                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
1027
                        // Let's save remote bean if needed.
1028
                        $this->save($remoteBean);
1029
                    }
1030
1031
                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
1032
1033
                    $types = [];
1034
1035
                    foreach ($filters as $columnName => $value) {
1036
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
1037
                        $types[] = $columnDescriptor->getType();
1038
                    }
1039
1040
                    $this->connection->insert($pivotTableName, $filters, $types);
1041
1042
                    // Finally, let's mark relationships as saved.
1043
                    $statusArr['status'] = 'loaded';
1044
                    $storage[$remoteBean] = $statusArr;
1045
                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
1046
                    $remoteStatusArr = $remoteStorage[$object];
1047
                    $remoteStatusArr['status'] = 'loaded';
1048
                    $remoteStorage[$object] = $remoteStatusArr;
1049
1050
                } elseif ($status === 'delete') {
1051
                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
1052
1053
                    $types = [];
1054
1055
                    foreach ($filters as $columnName => $value) {
1056
                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
1057
                        $types[] = $columnDescriptor->getType();
1058
                    }
1059
1060
                    $this->connection->delete($pivotTableName, $filters, $types);
1061
1062
                    // Finally, let's remove relationships completely from bean.
1063
                    $storage->detach($remoteBean);
1064
                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
1065
                }
1066
            }
1067
        }
1068
    }
1069
1070
    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) {
1071
        $localBeanPk = $this->getPrimaryKeyValues($localBean);
1072
        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
1073
        $localColumns = $localFk->getLocalColumns();
1074
        $remoteColumns = $remoteFk->getLocalColumns();
1075
1076
        $localFilters = array_combine($localColumns, $localBeanPk);
1077
        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
1078
1079
        return array_merge($localFilters, $remoteFilters);
1080
    }
1081
1082
    /**
1083
     * Returns the "values" of the primary key.
1084
     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
1085
     *
1086
     * @param AbstractTDBMObject $bean
1087
     * @return array numerically indexed array of values.
1088
     */
1089
    private function getPrimaryKeyValues(AbstractTDBMObject $bean) {
1090
        $dbRows = $bean->_getDbRows();
1091
        $dbRow = reset($dbRows);
1092
        return array_values($dbRow->_getPrimaryKeys());
1093
    }
1094
1095
	/**
1096
	 * Returns a unique hash used to store the object based on its primary key.
1097
	 * If the array contains only one value, then the value is returned.
1098
	 * Otherwise, a hash representing the array is returned.
1099
	 *
1100
	 * @param array $primaryKeys An array of columns => values forming the primary key
1101
	 * @return string
1102
	 */
1103
	public function getObjectHash(array $primaryKeys) {
1104
		if (count($primaryKeys) === 1) {
1105
			return reset($primaryKeys);
1106
		} else {
1107
			ksort($primaryKeys);
1108
			return md5(json_encode($primaryKeys));
1109
		}
1110
	}
1111
1112
	/**
1113
	 * Returns an array of primary keys from the object.
1114
	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
1115
	 * $primaryKeys variable of the object.
1116
	 *
1117
	 * @param DbRow $dbRow
1118
	 * @return array Returns an array of column => value
1119
	 */
1120
	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow) {
1121
		$table = $dbRow->_getDbTableName();
1122
		$dbRowData = $dbRow->_getDbRow();
1123
		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1124
	}
1125
1126
	/**
1127
	 * Returns an array of primary keys for the given row.
1128
	 * The primary keys are extracted from the object columns.
1129
	 *
1130
	 * @param $table
1131
	 * @param array $columns
1132
	 * @return array
1133
	 */
1134
	public function _getPrimaryKeysFromObjectData($table, array $columns) {
1135
		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1136
		$values = array();
1137
		foreach ($primaryKeyColumns as $column) {
1138
			if (isset($columns[$column])) {
1139
				$values[$column] = $columns[$column];
1140
			}
1141
		}
1142
		return $values;
1143
	}
1144
1145
	/**
1146
	 * Attaches $object to this TDBMService.
1147
	 * The $object must be in DETACHED state and will pass in NEW state.
1148
	 *
1149
	 * @param AbstractTDBMObject $object
1150
	 * @throws TDBMInvalidOperationException
1151
	 */
1152
	public function attach(AbstractTDBMObject $object) {
1153
		$object->_attach($this);
1154
	}
1155
1156
	/**
1157
	 * Returns an associative array (column => value) for the primary keys from the table name and an
1158
	 * indexed array of primary key values.
1159
	 *
1160
	 * @param string $tableName
1161
	 * @param array $indexedPrimaryKeys
1162
	 */
1163
	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys) {
1164
		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1165
1166
		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1167
			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1168
			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1169
		}
1170
1171
		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1172
	}
1173
1174
	/**
1175
	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1176
	 * Tables must be in a single line of inheritance. The method will find missing tables.
1177
	 *
1178
	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1179
	 * we must be able to find all other tables.
1180
	 *
1181
	 * @param string[] $tables
1182
	 * @return string[]
1183
	 */
1184
	public function _getLinkBetweenInheritedTables(array $tables)
1185
	{
1186
		sort($tables);
1187
		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1188
			function() use ($tables) {
1189
				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1190
			});
1191
	}
1192
1193
	/**
1194
	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1195
	 * Tables must be in a single line of inheritance. The method will find missing tables.
1196
	 *
1197
	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1198
	 * we must be able to find all other tables.
1199
	 *
1200
	 * @param string[] $tables
1201
	 * @return string[]
1202
	 */
1203
	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables) {
1204
		$schemaAnalyzer = $this->schemaAnalyzer;
1205
1206
		foreach ($tables as $currentTable) {
1207
			$allParents = [ $currentTable ];
1208
			$currentFk = null;
0 ignored issues
show
Unused Code introduced by
$currentFk is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1209
			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1210
				$currentTable = $currentFk->getForeignTableName();
1211
				$allParents[] = $currentTable;
1212
			};
1213
1214
			// Now, does the $allParents contain all the tables we want?
1215
			$notFoundTables = array_diff($tables, $allParents);
1216
			if (empty($notFoundTables)) {
1217
				// We have a winner!
1218
				return $allParents;
1219
			}
1220
		}
1221
1222
		throw new TDBMException(sprintf("The tables (%s) cannot be linked by an inheritance relationship.", implode(', ', $tables)));
1223
	}
1224
1225
	/**
1226
	 * Returns the list of tables related to this table (via a parent or child inheritance relationship)
1227
	 * @param string $table
1228
	 * @return string[]
1229
	 */
1230
	public function _getRelatedTablesByInheritance($table)
1231
	{
1232
		return $this->fromCache($this->cachePrefix."_relatedtables_".$table, function() use ($table) {
1233
			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1234
		});
1235
	}
1236
1237
	/**
1238
	 * Returns the list of tables related to this table (via a parent or child inheritance relationship)
1239
	 * @param string $table
1240
	 * @return string[]
1241
	 */
1242
	private function _getRelatedTablesByInheritanceWithoutCache($table) {
1243
		$schemaAnalyzer = $this->schemaAnalyzer;
1244
1245
1246
		// Let's scan the parent tables
1247
		$currentTable = $table;
1248
1249
		$parentTables = [ ];
1250
1251
		// Get parent relationship
1252
		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1253
			$currentTable = $currentFk->getForeignTableName();
1254
			$parentTables[] = $currentTable;
1255
		};
1256
1257
		// Let's recurse in children
1258
		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1259
1260
		return array_merge($parentTables, $childrenTables);
1261
	}
1262
1263
	/**
1264
	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1265
	 *
1266
	 * @param string $table
1267
	 * @return string[]
1268
	 */
1269
	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table) {
1270
		$tables = [$table];
1271
		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1272
1273
		foreach ($keys as $key) {
1274
			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1275
		}
1276
1277
		return $tables;
1278
	}
1279
1280
	/**
1281
	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1282
	 * The returned value does contain only one table. For instance:
1283
	 *
1284
	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1285
	 *
1286
	 * @param ForeignKeyConstraint $fk
1287
	 * @param bool $leftTableIsLocal
1288
	 * @return string
1289
	 */
1290
	/*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...
1291
		$onClauses = [];
1292
		$foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1293
		$foreignColumns = $fk->getForeignColumns();
1294
		$localTableName = $this->connection->quoteIdentifier($fk->getLocalTableName());
1295
		$localColumns = $fk->getLocalColumns();
1296
		$columnCount = count($localTableName);
1297
1298
		for ($i = 0; $i < $columnCount; $i++) {
1299
			$onClauses[] = sprintf("%s.%s = %s.%s",
1300
				$localTableName,
1301
				$this->connection->quoteIdentifier($localColumns[$i]),
1302
				$foreignColumns,
1303
				$this->connection->quoteIdentifier($foreignColumns[$i])
1304
				);
1305
		}
1306
1307
		$onClause = implode(' AND ', $onClauses);
1308
1309
		if ($leftTableIsLocal) {
1310
			return sprintf(" LEFT JOIN %s ON (%s)", $foreignTableName, $onClause);
1311
		} else {
1312
			return sprintf(" LEFT JOIN %s ON (%s)", $localTableName, $onClause);
1313
		}
1314
	}*/
1315
1316
	/**
1317
	 * Returns an identifier for the group of tables passed in parameter.
1318
	 *
1319
	 * @param string[] $relatedTables
1320
	 * @return string
1321
	 */
1322
	private function getTableGroupName(array $relatedTables) {
1323
		sort($relatedTables);
1324
		return implode('_``_', $relatedTables);
1325
	}
1326
1327
	/**
1328
	 *
1329
	 * @param string $mainTable The name of the table queried
1330
	 * @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)
1331
	 * @param array $parameters
1332
	 * @param string|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1333
	 * @param array $additionalTablesFetch
1334
	 * @param string $mode
1335
	 * @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.
1336
	 * @return ResultIterator An object representing an array of results.
1337
	 * @throws TDBMException
1338
	 */
1339
	public function findObjects($mainTable, $filter=null, array $parameters = array(), $orderString=null, array $additionalTablesFetch = array(), $mode = null, $className=null) {
1340
		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1341
		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1342
			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1343
		}
1344
1345
		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1346
1347
		$parameters = array_merge($parameters, $additionalParameters);
1348
1349
		// From the table name and the additional tables we want to fetch, let's build a list of all tables
1350
		// that must be part of the select columns.
1351
1352
		$tableGroups = [];
1353
		$allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1354
		$tableGroupName = $this->getTableGroupName($allFetchedTables);
1355
		foreach ($allFetchedTables as $table) {
1356
			$tableGroups[$table] = $tableGroupName;
1357
		}
1358
1359
		foreach ($additionalTablesFetch as $additionalTable) {
1360
			$relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1361
			$tableGroupName = $this->getTableGroupName($relatedTables);
1362
			foreach ($relatedTables as $table) {
1363
				$tableGroups[$table] = $tableGroupName;
1364
			}
1365
			$allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1366
		}
1367
1368
		// Let's remove any duplicate
1369
		$allFetchedTables = array_flip(array_flip($allFetchedTables));
1370
1371
		$columnsList = [];
1372
		$columnDescList = [];
1373
		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1374
1375
		// Now, let's build the column list
1376
		foreach ($allFetchedTables as $table) {
1377
			foreach ($schema->getTable($table)->getColumns() as $column) {
1378
				$columnName = $column->getName();
1379
				$columnDescList[] = [
1380
					'as' => $table.'____'.$columnName,
1381
					'table' => $table,
1382
					'column' => $columnName,
1383
					'type' => $column->getType(),
1384
					'tableGroup' => $tableGroups[$table]
1385
				];
1386
				$columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1387
					$this->connection->quoteIdentifier($table.'____'.$columnName);
1388
			}
1389
		}
1390
1391
		$sql = "SELECT DISTINCT ".implode(', ', $columnsList)." FROM MAGICJOIN(".$mainTable.")";
1392
		$countSql = "SELECT COUNT(1) FROM MAGICJOIN(".$mainTable.")";
1393
1394
		if (!empty($filterString)) {
1395
			$sql .= " WHERE ".$filterString;
1396
			$countSql .= " WHERE ".$filterString;
1397
		}
1398
1399
		if (!empty($orderString)) {
1400
			$sql .= " ORDER BY ".$orderString;
1401
			$countSql .= " ORDER BY ".$orderString;
1402
		}
1403
1404 View Code Duplication
		if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $mode (string) and self::MODE_CURSOR (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $mode (string) and self::MODE_ARRAY (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1405
			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1406
		}
1407
1408
		$mode = $mode?:$this->mode;
1409
1410
		return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode);
1411
	}
1412
1413
	/**
1414
	 * @param $table
1415
	 * @param array $primaryKeys
1416
	 * @param array $additionalTablesFetch
1417
	 * @param bool $lazy Whether to perform lazy loading on this object or not.
1418
	 * @param string $className
1419
	 * @return AbstractTDBMObject
1420
	 * @throws TDBMException
1421
	 */
1422
	public function findObjectByPk($table, array $primaryKeys, array $additionalTablesFetch = array(), $lazy = false, $className=null) {
1423
		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1424
		$hash = $this->getObjectHash($primaryKeys);
1425
1426
		if ($this->objectStorage->has($table, $hash)) {
1427
			$dbRow = $this->objectStorage->get($table, $hash);
1428
			$bean = $dbRow->getTDBMObject();
1429
			if ($className !== null && !is_a($bean, $className)) {
1430
				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1431
			}
1432
			return $bean;
1433
		}
1434
1435
		// Are we performing lazy fetching?
1436
		if ($lazy === true) {
1437
			// Can we perform lazy fetching?
1438
			$tables = $this->_getRelatedTablesByInheritance($table);
1439
			// Only allowed if no inheritance.
1440
			if (count($tables) === 1) {
1441
				if ($className === null) {
1442
					$className = isset($this->tableToBeanMap[$table])?$this->tableToBeanMap[$table]:"Mouf\\Database\\TDBM\\TDBMObject";
1443
				}
1444
1445
				// Let's construct the bean
1446
				if (!isset($reflectionClassCache[$className])) {
0 ignored issues
show
Bug introduced by
The variable $reflectionClassCache seems only to be defined at a later point. As such the call to isset() seems to always evaluate to false.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
1447
					$reflectionClassCache[$className] = new \ReflectionClass($className);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$reflectionClassCache was never initialized. Although not strictly required by PHP, it is generally a good practice to add $reflectionClassCache = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1448
				}
1449
				// Let's bypass the constructor when creating the bean!
1450
				$bean = $reflectionClassCache[$className]->newInstanceWithoutConstructor();
1451
				/* @var $bean AbstractTDBMObject */
1452
				$bean->_constructLazy($table, $primaryKeys, $this);
1453
			}
1454
		}
1455
1456
		// Did not find the object in cache? Let's query it!
1457
		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
0 ignored issues
show
Documentation introduced by
$primaryKeys is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1458
	}
1459
1460
	/**
1461
	 * Returns a unique bean (or null) according to the filters passed in parameter.
1462
	 *
1463
	 * @param string $mainTable The name of the table queried
1464
	 * @param string|null $filterString 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)
1465
	 * @param array $parameters
1466
	 * @param array $additionalTablesFetch
1467
	 * @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.
1468
	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters.
1469
	 * @throws TDBMException
1470
	 */
1471
	public function findObject($mainTable, $filterString=null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null) {
1472
		$objects = $this->findObjects($mainTable, $filterString, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1473
		$page = $objects->take(0, 2);
1474
		$count = $page->count();
1475
		if ($count > 1) {
1476
			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.");
1477
		} elseif ($count === 0) {
1478
			return null;
1479
		}
1480
		return $objects[0];
1481
	}
1482
1483
	/**
1484
	 * Returns a unique bean according to the filters passed in parameter.
1485
	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1486
	 *
1487
	 * @param string $mainTable The name of the table queried
1488
	 * @param string|null $filterString 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)
1489
	 * @param array $parameters
1490
	 * @param array $additionalTablesFetch
1491
	 * @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.
1492
	 * @return AbstractTDBMObject The object we want
1493
	 * @throws TDBMException
1494
	 */
1495
	public function findObjectOrFail($mainTable, $filterString=null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null) {
1496
		$bean = $this->findObject($mainTable, $filterString, $parameters, $additionalTablesFetch, $className);
1497
		if ($bean === null) {
1498
			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1499
		}
1500
		return $bean;
1501
	}
1502
1503
	/**
1504
	 * @param array $beanData An array of data: array<table, array<column, value>>
1505
	 * @return array an array with first item = class name and second item = table name
1506
	 */
1507
	public function _getClassNameFromBeanData(array $beanData) {
1508
		if (count($beanData) === 1) {
1509
			$tableName = array_keys($beanData)[0];
1510
		} else {
1511
			foreach ($beanData as $table => $row) {
1512
				$tables = [];
1513
				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1514
				$pkSet = false;
1515
				foreach ($primaryKeyColumns as $columnName) {
1516
					if ($row[$columnName] !== null) {
1517
						$pkSet = true;
1518
						break;
1519
					}
1520
				}
1521
				if ($pkSet) {
1522
					$tables[] = $table;
1523
				}
1524
			}
1525
1526
			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1527
			$allTables = $this->_getLinkBetweenInheritedTables($tables);
0 ignored issues
show
Bug introduced by
The variable $tables does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1528
			$tableName = $allTables[0];
1529
		}
1530
1531
		// Only one table in this bean. Life is sweat, let's look at its type:
1532
		if (isset($this->tableToBeanMap[$tableName])) {
1533
			return [$this->tableToBeanMap[$tableName], $tableName];
1534
		} else {
1535
			return ["Mouf\\Database\\TDBM\\TDBMObject", $tableName];
1536
		}
1537
	}
1538
1539
	/**
1540
	 * Returns an item from cache or computes it using $closure and puts it in cache.
1541
	 *
1542
	 * @param string   $key
1543
	 * @param callable $closure
1544
	 *
1545
	 * @return mixed
1546
	 */
1547
	private function fromCache($key, callable $closure)
1548
	{
1549
		$item = $this->cache->fetch($key);
1550
		if ($item === false) {
1551
			$item = $closure();
1552
			$this->cache->save($key, $item);
1553
		}
1554
1555
		return $item;
1556
	}
1557
1558
	/**
1559
	 * Returns the foreign key object.
1560
	 * @param string $table
1561
	 * @param string $fkName
1562
	 * @return ForeignKeyConstraint
1563
	 */
1564
	public function _getForeignKeyByName($table, $fkName) {
1565
		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1566
	}
1567
1568
	/**
1569
	 * @param $pivotTableName
1570
	 * @param AbstractTDBMObject $bean
1571
	 * @return AbstractTDBMObject[]
1572
	 */
1573
	public function _getRelatedBeans($pivotTableName, AbstractTDBMObject $bean) {
1574
1575
        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1576
        /* @var $localFk ForeignKeyConstraint */
1577
        /* @var $remoteFk ForeignKeyConstraint */
1578
        $remoteTable = $remoteFk->getForeignTableName();
1579
1580
1581
        $primaryKeys = $this->getPrimaryKeyValues($bean);
1582
        $columnNames = array_map(function($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns());
1583
1584
        $filter = array_combine($columnNames, $primaryKeys);
1585
1586
        return $this->findObjects($remoteTable, $filter);
1587
	}
1588
1589
    /**
1590
     * @param $pivotTableName
1591
     * @param AbstractTDBMObject $bean The LOCAL bean
1592
     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean.
1593
     * @throws TDBMException
1594
     */
1595
    private function getPivotTableForeignKeys($pivotTableName, AbstractTDBMObject $bean) {
1596
        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1597
        $table1 = $fks[0]->getForeignTableName();
1598
        $table2 = $fks[1]->getForeignTableName();
1599
1600
        $beanTables = array_map(function(DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows());
1601
1602
        if (in_array($table1, $beanTables)) {
1603
            return [$fks[0], $fks[1]];
1604
        } elseif (in_array($table2, $beanTables)) {
1605
            return [$fks[1], $fks[0]];
1606
        } else {
1607
            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2}");
1608
        }
1609
    }
1610
}
1611