Completed
Push — 4.0 ( 1abf1e...984e8a )
by David
05:40
created
src/Mouf/Database/TDBM/DbRow.php 1 patch
Indentation   +343 added lines, -343 removed lines patch added patch discarded remove patch
@@ -27,163 +27,163 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class DbRow
29 29
 {
30
-    /**
31
-     * The service this object is bound to.
32
-     *
33
-     * @var TDBMService
34
-     */
35
-    protected $tdbmService;
36
-
37
-    /**
38
-     * The object containing this db row.
39
-     *
40
-     * @var AbstractTDBMObject
41
-     */
42
-    private $object;
43
-
44
-    /**
45
-     * The name of the table the object if issued from.
46
-     *
47
-     * @var string
48
-     */
49
-    private $dbTableName;
50
-
51
-    /**
52
-     * The array of columns returned from database.
53
-     *
54
-     * @var array
55
-     */
56
-    private $dbRow = array();
57
-
58
-    /**
59
-     * @var AbstractTDBMObject[]
60
-     */
61
-    private $references = array();
62
-
63
-    /**
64
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
-     *
69
-     * @var string
70
-     */
71
-    private $status;
72
-
73
-    /**
74
-     * The values of the primary key.
75
-     * This is set when the object is in "loaded" state.
76
-     *
77
-     * @var array An array of column => value
78
-     */
79
-    private $primaryKeys;
80
-
81
-    /**
82
-     * You should never call the constructor directly. Instead, you should use the
83
-     * TDBMService class that will create TDBMObjects for you.
84
-     *
85
-     * Used with id!=false when we want to retrieve an existing object
86
-     * and id==false if we want a new object
87
-     *
88
-     * @param AbstractTDBMObject $object      The object containing this db row.
89
-     * @param string             $table_name
90
-     * @param array              $primaryKeys
91
-     * @param TDBMService        $tdbmService
92
-     *
93
-     * @throws TDBMException
94
-     * @throws TDBMInvalidOperationException
95
-     */
96
-    public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
-    {
98
-        $this->object = $object;
99
-        $this->dbTableName = $table_name;
100
-
101
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
-
103
-        if ($tdbmService === null) {
104
-            if (!empty($primaryKeys)) {
105
-                throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
-            }
107
-        } else {
108
-            $this->tdbmService = $tdbmService;
109
-
110
-            if (!empty($primaryKeys)) {
111
-                $this->_setPrimaryKeys($primaryKeys);
112
-                if (!empty($dbRow)) {
113
-                    $this->dbRow = $dbRow;
114
-                    $this->status = TDBMObjectStateEnum::STATE_LOADED;
115
-                } else {
116
-                    $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
-                }
118
-                $tdbmService->_addToCache($this);
119
-            } else {
120
-                $this->status = TDBMObjectStateEnum::STATE_NEW;
121
-                $this->tdbmService->_addToToSaveObjectList($this);
122
-            }
123
-        }
124
-    }
125
-
126
-    public function _attach(TDBMService $tdbmService)
127
-    {
128
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
-        }
131
-        $this->tdbmService = $tdbmService;
132
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
133
-        $this->tdbmService->_addToToSaveObjectList($this);
134
-    }
135
-
136
-    /**
137
-     * Sets the state of the TDBM Object
138
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
-     *
143
-     * @param string $state
144
-     */
145
-    public function _setStatus($state)
146
-    {
147
-        $this->status = $state;
148
-    }
149
-
150
-    /**
151
-     * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
-     * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
-     *
154
-     * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
-     * cannot be found).
156
-     */
157
-    public function _dbLoadIfNotLoaded()
158
-    {
159
-        if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
-            $connection = $this->tdbmService->getConnection();
161
-
162
-            /// buildFilterFromFilterBag($filter_bag)
163
-            list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
-
165
-            $sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
-            $result = $connection->executeQuery($sql, $parameters);
167
-
168
-            if ($result->rowCount() === 0) {
169
-                throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
-            }
171
-
172
-            $this->dbRow = $result->fetch(\PDO::FETCH_ASSOC);
173
-
174
-            $result->closeCursor();
175
-
176
-            $this->status = TDBMObjectStateEnum::STATE_LOADED;
177
-        }
178
-    }
179
-
180
-    public function get($var)
181
-    {
182
-        $this->_dbLoadIfNotLoaded();
183
-
184
-        // Let's first check if the key exist.
185
-        if (!isset($this->dbRow[$var])) {
186
-            /*
30
+	/**
31
+	 * The service this object is bound to.
32
+	 *
33
+	 * @var TDBMService
34
+	 */
35
+	protected $tdbmService;
36
+
37
+	/**
38
+	 * The object containing this db row.
39
+	 *
40
+	 * @var AbstractTDBMObject
41
+	 */
42
+	private $object;
43
+
44
+	/**
45
+	 * The name of the table the object if issued from.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	private $dbTableName;
50
+
51
+	/**
52
+	 * The array of columns returned from database.
53
+	 *
54
+	 * @var array
55
+	 */
56
+	private $dbRow = array();
57
+
58
+	/**
59
+	 * @var AbstractTDBMObject[]
60
+	 */
61
+	private $references = array();
62
+
63
+	/**
64
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
+	 *
69
+	 * @var string
70
+	 */
71
+	private $status;
72
+
73
+	/**
74
+	 * The values of the primary key.
75
+	 * This is set when the object is in "loaded" state.
76
+	 *
77
+	 * @var array An array of column => value
78
+	 */
79
+	private $primaryKeys;
80
+
81
+	/**
82
+	 * You should never call the constructor directly. Instead, you should use the
83
+	 * TDBMService class that will create TDBMObjects for you.
84
+	 *
85
+	 * Used with id!=false when we want to retrieve an existing object
86
+	 * and id==false if we want a new object
87
+	 *
88
+	 * @param AbstractTDBMObject $object      The object containing this db row.
89
+	 * @param string             $table_name
90
+	 * @param array              $primaryKeys
91
+	 * @param TDBMService        $tdbmService
92
+	 *
93
+	 * @throws TDBMException
94
+	 * @throws TDBMInvalidOperationException
95
+	 */
96
+	public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
+	{
98
+		$this->object = $object;
99
+		$this->dbTableName = $table_name;
100
+
101
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
+
103
+		if ($tdbmService === null) {
104
+			if (!empty($primaryKeys)) {
105
+				throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
+			}
107
+		} else {
108
+			$this->tdbmService = $tdbmService;
109
+
110
+			if (!empty($primaryKeys)) {
111
+				$this->_setPrimaryKeys($primaryKeys);
112
+				if (!empty($dbRow)) {
113
+					$this->dbRow = $dbRow;
114
+					$this->status = TDBMObjectStateEnum::STATE_LOADED;
115
+				} else {
116
+					$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
+				}
118
+				$tdbmService->_addToCache($this);
119
+			} else {
120
+				$this->status = TDBMObjectStateEnum::STATE_NEW;
121
+				$this->tdbmService->_addToToSaveObjectList($this);
122
+			}
123
+		}
124
+	}
125
+
126
+	public function _attach(TDBMService $tdbmService)
127
+	{
128
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
+		}
131
+		$this->tdbmService = $tdbmService;
132
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
133
+		$this->tdbmService->_addToToSaveObjectList($this);
134
+	}
135
+
136
+	/**
137
+	 * Sets the state of the TDBM Object
138
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
+	 *
143
+	 * @param string $state
144
+	 */
145
+	public function _setStatus($state)
146
+	{
147
+		$this->status = $state;
148
+	}
149
+
150
+	/**
151
+	 * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
+	 * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
+	 *
154
+	 * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
+	 * cannot be found).
156
+	 */
157
+	public function _dbLoadIfNotLoaded()
158
+	{
159
+		if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
+			$connection = $this->tdbmService->getConnection();
161
+
162
+			/// buildFilterFromFilterBag($filter_bag)
163
+			list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
+
165
+			$sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
+			$result = $connection->executeQuery($sql, $parameters);
167
+
168
+			if ($result->rowCount() === 0) {
169
+				throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
+			}
171
+
172
+			$this->dbRow = $result->fetch(\PDO::FETCH_ASSOC);
173
+
174
+			$result->closeCursor();
175
+
176
+			$this->status = TDBMObjectStateEnum::STATE_LOADED;
177
+		}
178
+	}
179
+
180
+	public function get($var)
181
+	{
182
+		$this->_dbLoadIfNotLoaded();
183
+
184
+		// Let's first check if the key exist.
185
+		if (!isset($this->dbRow[$var])) {
186
+			/*
187 187
             // Unable to find column.... this is an error if the object has been retrieved from database.
188 188
             // If it's a new object, well, that may not be an error after all!
189 189
             // Let's check if the column does exist in the table
@@ -203,30 +203,30 @@  discard block
 block discarded – undo
203 203
             $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
204 204
 
205 205
             throw new TDBMException($str);*/
206
-            return;
207
-        }
208
-
209
-        return $this->dbRow[$var];
210
-    }
211
-
212
-    /**
213
-     * Returns true if a column is set, false otherwise.
214
-     *
215
-     * @param string $var
216
-     *
217
-     * @return bool
218
-     */
219
-    /*public function has($var) {
206
+			return;
207
+		}
208
+
209
+		return $this->dbRow[$var];
210
+	}
211
+
212
+	/**
213
+	 * Returns true if a column is set, false otherwise.
214
+	 *
215
+	 * @param string $var
216
+	 *
217
+	 * @return bool
218
+	 */
219
+	/*public function has($var) {
220 220
         $this->_dbLoadIfNotLoaded();
221 221
 
222 222
         return isset($this->dbRow[$var]);
223 223
     }*/
224 224
 
225
-    public function set($var, $value)
226
-    {
227
-        $this->_dbLoadIfNotLoaded();
225
+	public function set($var, $value)
226
+	{
227
+		$this->_dbLoadIfNotLoaded();
228 228
 
229
-        /*
229
+		/*
230 230
         // Ok, let's start by checking the column type
231 231
         $type = $this->db_connection->getColumnType($this->dbTableName, $var);
232 232
 
@@ -236,173 +236,173 @@  discard block
 block discarded – undo
236 236
         }
237 237
         */
238 238
 
239
-        /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
239
+		/*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
240 240
             throw new TDBMException("Error! Changing primary key value is forbidden.");*/
241
-        $this->dbRow[$var] = $value;
242
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
243
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
244
-            $this->tdbmService->_addToToSaveObjectList($this);
245
-        }
246
-    }
247
-
248
-    /**
249
-     * @param string             $foreignKeyName
250
-     * @param AbstractTDBMObject $bean
251
-     */
252
-    public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
253
-    {
254
-        $this->references[$foreignKeyName] = $bean;
255
-
256
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
257
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
258
-            $this->tdbmService->_addToToSaveObjectList($this);
259
-        }
260
-    }
261
-
262
-    /**
263
-     * @param string $foreignKeyName A unique name for this reference
264
-     *
265
-     * @return AbstractTDBMObject|null
266
-     */
267
-    public function getRef($foreignKeyName)
268
-    {
269
-        if (isset($this->references[$foreignKeyName])) {
270
-            return $this->references[$foreignKeyName];
271
-        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
272
-            // If the object is new and has no property, then it has to be empty.
273
-            return;
274
-        } else {
275
-            $this->_dbLoadIfNotLoaded();
276
-
277
-            // Let's match the name of the columns to the primary key values
278
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
279
-
280
-            $values = [];
281
-            foreach ($fk->getLocalColumns() as $column) {
282
-                $values[] = $this->dbRow[$column];
283
-            }
284
-
285
-            $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
286
-
287
-            return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
288
-        }
289
-    }
290
-
291
-    /**
292
-     * Returns the name of the table this object comes from.
293
-     *
294
-     * @return string
295
-     */
296
-    public function _getDbTableName()
297
-    {
298
-        return $this->dbTableName;
299
-    }
300
-
301
-    /**
302
-     * Method used internally by TDBM. You should not use it directly.
303
-     * This method returns the status of the TDBMObject.
304
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
305
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
306
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
307
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
308
-     *
309
-     * @return string
310
-     */
311
-    public function _getStatus()
312
-    {
313
-        return $this->status;
314
-    }
315
-
316
-    /**
317
-     * Override the native php clone function for TDBMObjects.
318
-     */
319
-    public function __clone()
320
-    {
321
-        // Let's load the row (before we lose the ID!)
322
-        $this->_dbLoadIfNotLoaded();
323
-
324
-        //Let's set the status to detached
325
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
326
-
327
-        $this->primaryKeys = null;
328
-
329
-        //Now unset the PK from the row
330
-        if ($this->tdbmService) {
331
-            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
332
-            foreach ($pk_array as $pk) {
333
-                $this->dbRow[$pk] = null;
334
-            }
335
-        }
336
-    }
337
-
338
-    /**
339
-     * Returns raw database row.
340
-     *
341
-     * @return array
342
-     */
343
-    public function _getDbRow()
344
-    {
345
-        // Let's merge $dbRow and $references
346
-        $dbRow = $this->dbRow;
347
-
348
-        foreach ($this->references as $foreignKeyName => $reference) {
349
-            // Let's match the name of the columns to the primary key values
350
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
351
-            $refDbRows = $reference->_getDbRows();
352
-            $firstRefDbRow = reset($refDbRows);
353
-            $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
354
-            $localColumns = $fk->getLocalColumns();
355
-
356
-            for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
357
-                $dbRow[$localColumns[$i]] = $pkValues[$i];
358
-            }
359
-        }
360
-
361
-        return $dbRow;
362
-    }
363
-
364
-    /**
365
-     * Returns references array.
366
-     *
367
-     * @return AbstractTDBMObject[]
368
-     */
369
-    public function _getReferences()
370
-    {
371
-        return $this->references;
372
-    }
373
-
374
-    /**
375
-     * Returns the values of the primary key.
376
-     * This is set when the object is in "loaded" state.
377
-     *
378
-     * @return array
379
-     */
380
-    public function _getPrimaryKeys()
381
-    {
382
-        return $this->primaryKeys;
383
-    }
384
-
385
-    /**
386
-     * Sets the values of the primary key.
387
-     * This is set when the object is in "loaded" state.
388
-     *
389
-     * @param array $primaryKeys
390
-     */
391
-    public function _setPrimaryKeys(array $primaryKeys)
392
-    {
393
-        $this->primaryKeys = $primaryKeys;
394
-        foreach ($this->primaryKeys as $column => $value) {
395
-            $this->dbRow[$column] = $value;
396
-        }
397
-    }
398
-
399
-    /**
400
-     * Returns the TDBMObject this bean is associated to.
401
-     *
402
-     * @return AbstractTDBMObject
403
-     */
404
-    public function getTDBMObject()
405
-    {
406
-        return $this->object;
407
-    }
241
+		$this->dbRow[$var] = $value;
242
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
243
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
244
+			$this->tdbmService->_addToToSaveObjectList($this);
245
+		}
246
+	}
247
+
248
+	/**
249
+	 * @param string             $foreignKeyName
250
+	 * @param AbstractTDBMObject $bean
251
+	 */
252
+	public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
253
+	{
254
+		$this->references[$foreignKeyName] = $bean;
255
+
256
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
257
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
258
+			$this->tdbmService->_addToToSaveObjectList($this);
259
+		}
260
+	}
261
+
262
+	/**
263
+	 * @param string $foreignKeyName A unique name for this reference
264
+	 *
265
+	 * @return AbstractTDBMObject|null
266
+	 */
267
+	public function getRef($foreignKeyName)
268
+	{
269
+		if (isset($this->references[$foreignKeyName])) {
270
+			return $this->references[$foreignKeyName];
271
+		} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
272
+			// If the object is new and has no property, then it has to be empty.
273
+			return;
274
+		} else {
275
+			$this->_dbLoadIfNotLoaded();
276
+
277
+			// Let's match the name of the columns to the primary key values
278
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
279
+
280
+			$values = [];
281
+			foreach ($fk->getLocalColumns() as $column) {
282
+				$values[] = $this->dbRow[$column];
283
+			}
284
+
285
+			$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
286
+
287
+			return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
288
+		}
289
+	}
290
+
291
+	/**
292
+	 * Returns the name of the table this object comes from.
293
+	 *
294
+	 * @return string
295
+	 */
296
+	public function _getDbTableName()
297
+	{
298
+		return $this->dbTableName;
299
+	}
300
+
301
+	/**
302
+	 * Method used internally by TDBM. You should not use it directly.
303
+	 * This method returns the status of the TDBMObject.
304
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
305
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
306
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
307
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
308
+	 *
309
+	 * @return string
310
+	 */
311
+	public function _getStatus()
312
+	{
313
+		return $this->status;
314
+	}
315
+
316
+	/**
317
+	 * Override the native php clone function for TDBMObjects.
318
+	 */
319
+	public function __clone()
320
+	{
321
+		// Let's load the row (before we lose the ID!)
322
+		$this->_dbLoadIfNotLoaded();
323
+
324
+		//Let's set the status to detached
325
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
326
+
327
+		$this->primaryKeys = null;
328
+
329
+		//Now unset the PK from the row
330
+		if ($this->tdbmService) {
331
+			$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
332
+			foreach ($pk_array as $pk) {
333
+				$this->dbRow[$pk] = null;
334
+			}
335
+		}
336
+	}
337
+
338
+	/**
339
+	 * Returns raw database row.
340
+	 *
341
+	 * @return array
342
+	 */
343
+	public function _getDbRow()
344
+	{
345
+		// Let's merge $dbRow and $references
346
+		$dbRow = $this->dbRow;
347
+
348
+		foreach ($this->references as $foreignKeyName => $reference) {
349
+			// Let's match the name of the columns to the primary key values
350
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
351
+			$refDbRows = $reference->_getDbRows();
352
+			$firstRefDbRow = reset($refDbRows);
353
+			$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
354
+			$localColumns = $fk->getLocalColumns();
355
+
356
+			for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
357
+				$dbRow[$localColumns[$i]] = $pkValues[$i];
358
+			}
359
+		}
360
+
361
+		return $dbRow;
362
+	}
363
+
364
+	/**
365
+	 * Returns references array.
366
+	 *
367
+	 * @return AbstractTDBMObject[]
368
+	 */
369
+	public function _getReferences()
370
+	{
371
+		return $this->references;
372
+	}
373
+
374
+	/**
375
+	 * Returns the values of the primary key.
376
+	 * This is set when the object is in "loaded" state.
377
+	 *
378
+	 * @return array
379
+	 */
380
+	public function _getPrimaryKeys()
381
+	{
382
+		return $this->primaryKeys;
383
+	}
384
+
385
+	/**
386
+	 * Sets the values of the primary key.
387
+	 * This is set when the object is in "loaded" state.
388
+	 *
389
+	 * @param array $primaryKeys
390
+	 */
391
+	public function _setPrimaryKeys(array $primaryKeys)
392
+	{
393
+		$this->primaryKeys = $primaryKeys;
394
+		foreach ($this->primaryKeys as $column => $value) {
395
+			$this->dbRow[$column] = $value;
396
+		}
397
+	}
398
+
399
+	/**
400
+	 * Returns the TDBMObject this bean is associated to.
401
+	 *
402
+	 * @return AbstractTDBMObject
403
+	 */
404
+	public function getTDBMObject()
405
+	{
406
+		return $this->object;
407
+	}
408 408
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 1 patch
Indentation   +418 added lines, -418 removed lines patch added patch discarded remove patch
@@ -18,188 +18,188 @@  discard block
 block discarded – undo
18 18
  */
19 19
 class TDBMDaoGenerator
20 20
 {
21
-    /**
22
-     * @var SchemaAnalyzer
23
-     */
24
-    private $schemaAnalyzer;
25
-
26
-    /**
27
-     * @var Schema
28
-     */
29
-    private $schema;
30
-
31
-    /**
32
-     * The root directory of the project.
33
-     *
34
-     * @var string
35
-     */
36
-    private $rootPath;
37
-
38
-    /**
39
-     * @var TDBMSchemaAnalyzer
40
-     */
41
-    private $tdbmSchemaAnalyzer;
42
-
43
-    /**
44
-     * Constructor.
45
-     *
46
-     * @param Connection $dbConnection The connection to the database.
47
-     */
48
-    public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
49
-    {
50
-        $this->schemaAnalyzer = $schemaAnalyzer;
51
-        $this->schema = $schema;
52
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
53
-        $this->rootPath = __DIR__.'/../../../../../../../../';
54
-    }
55
-
56
-    /**
57
-     * Generates all the daos and beans.
58
-     *
59
-     * @param string $daoFactoryClassName The classe name of the DAO factory
60
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
61
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
62
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone.
63
-     *
64
-     * @return \string[] the list of tables
65
-     *
66
-     * @throws TDBMException
67
-     */
68
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc)
69
-    {
70
-        // TODO: extract ClassNameMapper in its own package!
71
-        $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.'composer.json');
72
-
73
-        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
74
-
75
-        $tableList = $this->schema->getTables();
76
-
77
-        // Remove all beans and daos from junction tables
78
-        $junctionTables = $this->schemaAnalyzer->detectJunctionTables();
79
-        $junctionTableNames = array_map(function (Table $table) {
80
-            return $table->getName();
81
-        }, $junctionTables);
82
-
83
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
84
-            return !in_array($table->getName(), $junctionTableNames);
85
-        });
86
-
87
-        foreach ($tableList as $table) {
88
-            $this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc);
89
-        }
90
-
91
-        $this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper);
92
-
93
-        // Ok, let's return the list of all tables.
94
-        // These will be used by the calling script to create Mouf instances.
95
-
96
-        return array_map(function (Table $table) { return $table->getName(); }, $tableList);
97
-    }
98
-
99
-    /**
100
-     * Generates in one method call the daos and the beans for one table.
101
-     *
102
-     * @param $tableName
103
-     */
104
-    public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
105
-    {
106
-        $tableName = $table->getName();
107
-        $daoName = $this->getDaoNameFromTableName($tableName);
108
-        $beanName = $this->getBeanNameFromTableName($tableName);
109
-        $baseBeanName = $this->getBaseBeanNameFromTableName($tableName);
110
-        $baseDaoName = $this->getBaseDaoNameFromTableName($tableName);
111
-
112
-        $this->generateBean($beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc);
113
-        $this->generateDao($daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper);
114
-    }
115
-
116
-    /**
117
-     * Returns the name of the bean class from the table name.
118
-     *
119
-     * @param $tableName
120
-     *
121
-     * @return string
122
-     */
123
-    public static function getBeanNameFromTableName($tableName)
124
-    {
125
-        return self::toSingular(self::toCamelCase($tableName)).'Bean';
126
-    }
127
-
128
-    /**
129
-     * Returns the name of the DAO class from the table name.
130
-     *
131
-     * @param $tableName
132
-     *
133
-     * @return string
134
-     */
135
-    public static function getDaoNameFromTableName($tableName)
136
-    {
137
-        return self::toSingular(self::toCamelCase($tableName)).'Dao';
138
-    }
139
-
140
-    /**
141
-     * Returns the name of the base bean class from the table name.
142
-     *
143
-     * @param $tableName
144
-     *
145
-     * @return string
146
-     */
147
-    public static function getBaseBeanNameFromTableName($tableName)
148
-    {
149
-        return self::toSingular(self::toCamelCase($tableName)).'BaseBean';
150
-    }
151
-
152
-    /**
153
-     * Returns the name of the base DAO class from the table name.
154
-     *
155
-     * @param $tableName
156
-     *
157
-     * @return string
158
-     */
159
-    public static function getBaseDaoNameFromTableName($tableName)
160
-    {
161
-        return self::toSingular(self::toCamelCase($tableName)).'BaseDao';
162
-    }
163
-
164
-    /**
165
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
166
-     *
167
-     * @param string          $className       The name of the class
168
-     * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
169
-     * @param Table           $table           The table
170
-     * @param string          $beannamespace   The namespace of the bean
171
-     * @param ClassNameMapper $classNameMapper
172
-     *
173
-     * @throws TDBMException
174
-     */
175
-    public function generateBean($className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
176
-    {
177
-        $beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer);
178
-
179
-        $str = $beanDescriptor->generatePhpCode($beannamespace);
180
-
181
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName);
182
-        if (empty($possibleBaseFileNames)) {
183
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
184
-        }
185
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
186
-
187
-        $this->ensureDirectoryExist($possibleBaseFileName);
188
-        file_put_contents($possibleBaseFileName, $str);
189
-        @chmod($possibleBaseFileName, 0664);
190
-
191
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
192
-        if (empty($possibleFileNames)) {
193
-            // @codeCoverageIgnoreStart
194
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
195
-            // @codeCoverageIgnoreEnd
196
-        }
197
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
198
-
199
-        if (!file_exists($possibleFileName)) {
200
-            $tableName = $table->getName();
201
-
202
-            $str = "<?php
21
+	/**
22
+	 * @var SchemaAnalyzer
23
+	 */
24
+	private $schemaAnalyzer;
25
+
26
+	/**
27
+	 * @var Schema
28
+	 */
29
+	private $schema;
30
+
31
+	/**
32
+	 * The root directory of the project.
33
+	 *
34
+	 * @var string
35
+	 */
36
+	private $rootPath;
37
+
38
+	/**
39
+	 * @var TDBMSchemaAnalyzer
40
+	 */
41
+	private $tdbmSchemaAnalyzer;
42
+
43
+	/**
44
+	 * Constructor.
45
+	 *
46
+	 * @param Connection $dbConnection The connection to the database.
47
+	 */
48
+	public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
49
+	{
50
+		$this->schemaAnalyzer = $schemaAnalyzer;
51
+		$this->schema = $schema;
52
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
53
+		$this->rootPath = __DIR__.'/../../../../../../../../';
54
+	}
55
+
56
+	/**
57
+	 * Generates all the daos and beans.
58
+	 *
59
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
60
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
61
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
62
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone.
63
+	 *
64
+	 * @return \string[] the list of tables
65
+	 *
66
+	 * @throws TDBMException
67
+	 */
68
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc)
69
+	{
70
+		// TODO: extract ClassNameMapper in its own package!
71
+		$classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.'composer.json');
72
+
73
+		// TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
74
+
75
+		$tableList = $this->schema->getTables();
76
+
77
+		// Remove all beans and daos from junction tables
78
+		$junctionTables = $this->schemaAnalyzer->detectJunctionTables();
79
+		$junctionTableNames = array_map(function (Table $table) {
80
+			return $table->getName();
81
+		}, $junctionTables);
82
+
83
+		$tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
84
+			return !in_array($table->getName(), $junctionTableNames);
85
+		});
86
+
87
+		foreach ($tableList as $table) {
88
+			$this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc);
89
+		}
90
+
91
+		$this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper);
92
+
93
+		// Ok, let's return the list of all tables.
94
+		// These will be used by the calling script to create Mouf instances.
95
+
96
+		return array_map(function (Table $table) { return $table->getName(); }, $tableList);
97
+	}
98
+
99
+	/**
100
+	 * Generates in one method call the daos and the beans for one table.
101
+	 *
102
+	 * @param $tableName
103
+	 */
104
+	public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
105
+	{
106
+		$tableName = $table->getName();
107
+		$daoName = $this->getDaoNameFromTableName($tableName);
108
+		$beanName = $this->getBeanNameFromTableName($tableName);
109
+		$baseBeanName = $this->getBaseBeanNameFromTableName($tableName);
110
+		$baseDaoName = $this->getBaseDaoNameFromTableName($tableName);
111
+
112
+		$this->generateBean($beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc);
113
+		$this->generateDao($daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper);
114
+	}
115
+
116
+	/**
117
+	 * Returns the name of the bean class from the table name.
118
+	 *
119
+	 * @param $tableName
120
+	 *
121
+	 * @return string
122
+	 */
123
+	public static function getBeanNameFromTableName($tableName)
124
+	{
125
+		return self::toSingular(self::toCamelCase($tableName)).'Bean';
126
+	}
127
+
128
+	/**
129
+	 * Returns the name of the DAO class from the table name.
130
+	 *
131
+	 * @param $tableName
132
+	 *
133
+	 * @return string
134
+	 */
135
+	public static function getDaoNameFromTableName($tableName)
136
+	{
137
+		return self::toSingular(self::toCamelCase($tableName)).'Dao';
138
+	}
139
+
140
+	/**
141
+	 * Returns the name of the base bean class from the table name.
142
+	 *
143
+	 * @param $tableName
144
+	 *
145
+	 * @return string
146
+	 */
147
+	public static function getBaseBeanNameFromTableName($tableName)
148
+	{
149
+		return self::toSingular(self::toCamelCase($tableName)).'BaseBean';
150
+	}
151
+
152
+	/**
153
+	 * Returns the name of the base DAO class from the table name.
154
+	 *
155
+	 * @param $tableName
156
+	 *
157
+	 * @return string
158
+	 */
159
+	public static function getBaseDaoNameFromTableName($tableName)
160
+	{
161
+		return self::toSingular(self::toCamelCase($tableName)).'BaseDao';
162
+	}
163
+
164
+	/**
165
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
166
+	 *
167
+	 * @param string          $className       The name of the class
168
+	 * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
169
+	 * @param Table           $table           The table
170
+	 * @param string          $beannamespace   The namespace of the bean
171
+	 * @param ClassNameMapper $classNameMapper
172
+	 *
173
+	 * @throws TDBMException
174
+	 */
175
+	public function generateBean($className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
176
+	{
177
+		$beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer);
178
+
179
+		$str = $beanDescriptor->generatePhpCode($beannamespace);
180
+
181
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName);
182
+		if (empty($possibleBaseFileNames)) {
183
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
184
+		}
185
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
186
+
187
+		$this->ensureDirectoryExist($possibleBaseFileName);
188
+		file_put_contents($possibleBaseFileName, $str);
189
+		@chmod($possibleBaseFileName, 0664);
190
+
191
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
192
+		if (empty($possibleFileNames)) {
193
+			// @codeCoverageIgnoreStart
194
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
195
+			// @codeCoverageIgnoreEnd
196
+		}
197
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
198
+
199
+		if (!file_exists($possibleFileName)) {
200
+			$tableName = $table->getName();
201
+
202
+			$str = "<?php
203 203
 /*
204 204
  * This file has been automatically generated by TDBM.
205 205
  * You can edit this file as it will not be overwritten.
@@ -214,45 +214,45 @@  discard block
 block discarded – undo
214 214
 {
215 215
 
216 216
 }";
217
-            $this->ensureDirectoryExist($possibleFileName);
218
-            file_put_contents($possibleFileName, $str);
219
-            @chmod($possibleFileName, 0664);
220
-        }
221
-    }
222
-
223
-    /**
224
-     * Writes the PHP bean DAO with simple functions to create/get/save objects.
225
-     *
226
-     * @param string $fileName  The file that will be written (without the directory)
227
-     * @param string $className The name of the class
228
-     * @param string $tableName The name of the table
229
-     */
230
-    public function generateDao($className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper)
231
-    {
232
-        $tableName = $table->getName();
233
-        $primaryKeyColumns = $table->getPrimaryKeyColumns();
234
-
235
-        $defaultSort = null;
236
-        foreach ($table->getColumns() as $column) {
237
-            $comments = $column->getComment();
238
-            $matches = array();
239
-            if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
240
-                $defaultSort = $data['column_name'];
241
-                if (count($matches == 3)) {
242
-                    $defaultSortDirection = $matches[2];
243
-                } else {
244
-                    $defaultSortDirection = 'ASC';
245
-                }
246
-            }
247
-        }
248
-
249
-        // FIXME: lowercase tables with _ in the name should work!
250
-        $tableCamel = self::toSingular(self::toCamelCase($tableName));
251
-
252
-        $beanClassWithoutNameSpace = $beanClassName;
253
-        $beanClassName = $beannamespace.'\\'.$beanClassName;
254
-
255
-        $str = "<?php
217
+			$this->ensureDirectoryExist($possibleFileName);
218
+			file_put_contents($possibleFileName, $str);
219
+			@chmod($possibleFileName, 0664);
220
+		}
221
+	}
222
+
223
+	/**
224
+	 * Writes the PHP bean DAO with simple functions to create/get/save objects.
225
+	 *
226
+	 * @param string $fileName  The file that will be written (without the directory)
227
+	 * @param string $className The name of the class
228
+	 * @param string $tableName The name of the table
229
+	 */
230
+	public function generateDao($className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper)
231
+	{
232
+		$tableName = $table->getName();
233
+		$primaryKeyColumns = $table->getPrimaryKeyColumns();
234
+
235
+		$defaultSort = null;
236
+		foreach ($table->getColumns() as $column) {
237
+			$comments = $column->getComment();
238
+			$matches = array();
239
+			if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
240
+				$defaultSort = $data['column_name'];
241
+				if (count($matches == 3)) {
242
+					$defaultSortDirection = $matches[2];
243
+				} else {
244
+					$defaultSortDirection = 'ASC';
245
+				}
246
+			}
247
+		}
248
+
249
+		// FIXME: lowercase tables with _ in the name should work!
250
+		$tableCamel = self::toSingular(self::toCamelCase($tableName));
251
+
252
+		$beanClassWithoutNameSpace = $beanClassName;
253
+		$beanClassName = $beannamespace.'\\'.$beanClassName;
254
+
255
+		$str = "<?php
256 256
 
257 257
 /*
258 258
  * This file has been automatically generated by TDBM.
@@ -339,9 +339,9 @@  discard block
 block discarded – undo
339 339
     }
340 340
     ";
341 341
 
342
-        if (count($primaryKeyColumns) === 1) {
343
-            $primaryKeyColumn = $primaryKeyColumns[0];
344
-            $str .= "
342
+		if (count($primaryKeyColumns) === 1) {
343
+			$primaryKeyColumn = $primaryKeyColumns[0];
344
+			$str .= "
345 345
     /**
346 346
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
347 347
      * If the primary key does not exist, an exception is thrown.
@@ -356,8 +356,8 @@  discard block
 block discarded – undo
356 356
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
357 357
     }
358 358
     ";
359
-        }
360
-        $str .= "
359
+		}
360
+		$str .= "
361 361
     /**
362 362
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
363 363
      *
@@ -415,33 +415,33 @@  discard block
 block discarded – undo
415 415
     }
416 416
     ";
417 417
 
418
-        $str .= '
418
+		$str .= '
419 419
 }
420 420
 ';
421 421
 
422
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName);
423
-        if (!$possibleBaseFileNames) {
424
-            // @codeCoverageIgnoreStart
425
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
426
-            // @codeCoverageIgnoreEnd
427
-        }
428
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
429
-
430
-        $this->ensureDirectoryExist($possibleBaseFileName);
431
-        file_put_contents($possibleBaseFileName, $str);
432
-        @chmod($possibleBaseFileName, 0664);
433
-
434
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
435
-        if (empty($possibleFileNames)) {
436
-            // @codeCoverageIgnoreStart
437
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
438
-            // @codeCoverageIgnoreEnd
439
-        }
440
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
441
-
442
-        // Now, let's generate the "editable" class
443
-        if (!file_exists($possibleFileName)) {
444
-            $str = "<?php
422
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName);
423
+		if (!$possibleBaseFileNames) {
424
+			// @codeCoverageIgnoreStart
425
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
426
+			// @codeCoverageIgnoreEnd
427
+		}
428
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
429
+
430
+		$this->ensureDirectoryExist($possibleBaseFileName);
431
+		file_put_contents($possibleBaseFileName, $str);
432
+		@chmod($possibleBaseFileName, 0664);
433
+
434
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
435
+		if (empty($possibleFileNames)) {
436
+			// @codeCoverageIgnoreStart
437
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
438
+			// @codeCoverageIgnoreEnd
439
+		}
440
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
441
+
442
+		// Now, let's generate the "editable" class
443
+		if (!file_exists($possibleFileName)) {
444
+			$str = "<?php
445 445
 
446 446
 /*
447 447
  * This file has been automatically generated by TDBM.
@@ -458,22 +458,22 @@  discard block
 block discarded – undo
458 458
 
459 459
 }
460 460
 ";
461
-            $this->ensureDirectoryExist($possibleFileName);
462
-            file_put_contents($possibleFileName, $str);
463
-            @chmod($possibleFileName, 0664);
464
-        }
465
-    }
466
-
467
-    /**
468
-     * Generates the factory bean.
469
-     *
470
-     * @param Table[] $tableList
471
-     */
472
-    private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
473
-    {
474
-        // For each table, let's write a property.
475
-
476
-        $str = "<?php
461
+			$this->ensureDirectoryExist($possibleFileName);
462
+			file_put_contents($possibleFileName, $str);
463
+			@chmod($possibleFileName, 0664);
464
+		}
465
+	}
466
+
467
+	/**
468
+	 * Generates the factory bean.
469
+	 *
470
+	 * @param Table[] $tableList
471
+	 */
472
+	private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
473
+	{
474
+		// For each table, let's write a property.
475
+
476
+		$str = "<?php
477 477
 
478 478
 /*
479 479
  * This file has been automatically generated by TDBM.
@@ -490,12 +490,12 @@  discard block
 block discarded – undo
490 490
 {
491 491
 ";
492 492
 
493
-        foreach ($tableList as $table) {
494
-            $tableName = $table->getName();
495
-            $daoClassName = $this->getDaoNameFromTableName($tableName);
496
-            $daoInstanceName = self::toVariableName($daoClassName);
493
+		foreach ($tableList as $table) {
494
+			$tableName = $table->getName();
495
+			$daoClassName = $this->getDaoNameFromTableName($tableName);
496
+			$daoInstanceName = self::toVariableName($daoClassName);
497 497
 
498
-            $str .= '    /**
498
+			$str .= '    /**
499 499
      * @var '.$daoClassName.'
500 500
      */
501 501
     private $'.$daoInstanceName.';
@@ -520,155 +520,155 @@  discard block
 block discarded – undo
520 520
     }
521 521
 
522 522
 ';
523
-        }
523
+		}
524 524
 
525
-        $str .= '
525
+		$str .= '
526 526
 }
527 527
 ';
528 528
 
529
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\'.$daoFactoryClassName);
530
-        if (empty($possibleFileNames)) {
531
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
532
-        }
533
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
534
-
535
-        $this->ensureDirectoryExist($possibleFileName);
536
-        file_put_contents($possibleFileName, $str);
537
-        @chmod($possibleFileName, 0664);
538
-    }
539
-
540
-    /**
541
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
542
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
543
-     *
544
-     * @param $str string
545
-     *
546
-     * @return string
547
-     */
548
-    public static function toCamelCase($str)
549
-    {
550
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
551
-        while (true) {
552
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
553
-                break;
554
-            }
555
-
556
-            $pos = strpos($str, '_');
557
-            if ($pos === false) {
558
-                $pos = strpos($str, ' ');
559
-            }
560
-            $before = substr($str, 0, $pos);
561
-            $after = substr($str, $pos + 1);
562
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
563
-        }
564
-
565
-        return $str;
566
-    }
567
-
568
-    /**
569
-     * Tries to put string to the singular form (if it is plural).
570
-     * We assume the table names are in english.
571
-     *
572
-     * @param $str string
573
-     *
574
-     * @return string
575
-     */
576
-    public static function toSingular($str)
577
-    {
578
-        return Inflector::singularize($str);
579
-    }
580
-
581
-    /**
582
-     * Put the first letter of the string in lower case.
583
-     * Very useful to transform a class name into a variable name.
584
-     *
585
-     * @param $str string
586
-     *
587
-     * @return string
588
-     */
589
-    public static function toVariableName($str)
590
-    {
591
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
592
-    }
593
-
594
-    /**
595
-     * Ensures the file passed in parameter can be written in its directory.
596
-     *
597
-     * @param string $fileName
598
-     *
599
-     * @throws TDBMException
600
-     */
601
-    private function ensureDirectoryExist($fileName)
602
-    {
603
-        $dirName = dirname($fileName);
604
-        if (!file_exists($dirName)) {
605
-            $old = umask(0);
606
-            $result = mkdir($dirName, 0775, true);
607
-            umask($old);
608
-            if ($result === false) {
609
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
610
-            }
611
-        }
612
-    }
613
-
614
-    /**
615
-     * @param string $rootPath
616
-     */
617
-    public function setRootPath($rootPath)
618
-    {
619
-        $this->rootPath = $rootPath;
620
-    }
621
-
622
-    /**
623
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
624
-     *
625
-     * @param Type $type The DBAL type
626
-     *
627
-     * @return string The PHP type
628
-     */
629
-    public static function dbalTypeToPhpType(Type $type)
630
-    {
631
-        $map = [
632
-            Type::TARRAY => 'array',
633
-            Type::SIMPLE_ARRAY => 'array',
634
-            Type::JSON_ARRAY => 'array',
635
-            Type::BIGINT => 'string',
636
-            Type::BOOLEAN => 'bool',
637
-            Type::DATETIME => '\DateTimeInterface',
638
-            Type::DATETIMETZ => '\DateTimeInterface',
639
-            Type::DATE => '\DateTimeInterface',
640
-            Type::TIME => '\DateTimeInterface',
641
-            Type::DECIMAL => 'float',
642
-            Type::INTEGER => 'int',
643
-            Type::OBJECT => 'string',
644
-            Type::SMALLINT => 'int',
645
-            Type::STRING => 'string',
646
-            Type::TEXT => 'string',
647
-            Type::BINARY => 'string',
648
-            Type::BLOB => 'string',
649
-            Type::FLOAT => 'float',
650
-            Type::GUID => 'string',
651
-        ];
652
-
653
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
654
-    }
655
-
656
-    /**
657
-     * @param string $beanNamespace
658
-     *
659
-     * @return \string[] Returns a map mapping table name to beans name
660
-     */
661
-    public function buildTableToBeanMap($beanNamespace)
662
-    {
663
-        $tableToBeanMap = [];
664
-
665
-        $tables = $this->schema->getTables();
666
-
667
-        foreach ($tables as $table) {
668
-            $tableName = $table->getName();
669
-            $tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
670
-        }
671
-
672
-        return $tableToBeanMap;
673
-    }
529
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\'.$daoFactoryClassName);
530
+		if (empty($possibleFileNames)) {
531
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
532
+		}
533
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
534
+
535
+		$this->ensureDirectoryExist($possibleFileName);
536
+		file_put_contents($possibleFileName, $str);
537
+		@chmod($possibleFileName, 0664);
538
+	}
539
+
540
+	/**
541
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
542
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
543
+	 *
544
+	 * @param $str string
545
+	 *
546
+	 * @return string
547
+	 */
548
+	public static function toCamelCase($str)
549
+	{
550
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
551
+		while (true) {
552
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
553
+				break;
554
+			}
555
+
556
+			$pos = strpos($str, '_');
557
+			if ($pos === false) {
558
+				$pos = strpos($str, ' ');
559
+			}
560
+			$before = substr($str, 0, $pos);
561
+			$after = substr($str, $pos + 1);
562
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
563
+		}
564
+
565
+		return $str;
566
+	}
567
+
568
+	/**
569
+	 * Tries to put string to the singular form (if it is plural).
570
+	 * We assume the table names are in english.
571
+	 *
572
+	 * @param $str string
573
+	 *
574
+	 * @return string
575
+	 */
576
+	public static function toSingular($str)
577
+	{
578
+		return Inflector::singularize($str);
579
+	}
580
+
581
+	/**
582
+	 * Put the first letter of the string in lower case.
583
+	 * Very useful to transform a class name into a variable name.
584
+	 *
585
+	 * @param $str string
586
+	 *
587
+	 * @return string
588
+	 */
589
+	public static function toVariableName($str)
590
+	{
591
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
592
+	}
593
+
594
+	/**
595
+	 * Ensures the file passed in parameter can be written in its directory.
596
+	 *
597
+	 * @param string $fileName
598
+	 *
599
+	 * @throws TDBMException
600
+	 */
601
+	private function ensureDirectoryExist($fileName)
602
+	{
603
+		$dirName = dirname($fileName);
604
+		if (!file_exists($dirName)) {
605
+			$old = umask(0);
606
+			$result = mkdir($dirName, 0775, true);
607
+			umask($old);
608
+			if ($result === false) {
609
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
610
+			}
611
+		}
612
+	}
613
+
614
+	/**
615
+	 * @param string $rootPath
616
+	 */
617
+	public function setRootPath($rootPath)
618
+	{
619
+		$this->rootPath = $rootPath;
620
+	}
621
+
622
+	/**
623
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
624
+	 *
625
+	 * @param Type $type The DBAL type
626
+	 *
627
+	 * @return string The PHP type
628
+	 */
629
+	public static function dbalTypeToPhpType(Type $type)
630
+	{
631
+		$map = [
632
+			Type::TARRAY => 'array',
633
+			Type::SIMPLE_ARRAY => 'array',
634
+			Type::JSON_ARRAY => 'array',
635
+			Type::BIGINT => 'string',
636
+			Type::BOOLEAN => 'bool',
637
+			Type::DATETIME => '\DateTimeInterface',
638
+			Type::DATETIMETZ => '\DateTimeInterface',
639
+			Type::DATE => '\DateTimeInterface',
640
+			Type::TIME => '\DateTimeInterface',
641
+			Type::DECIMAL => 'float',
642
+			Type::INTEGER => 'int',
643
+			Type::OBJECT => 'string',
644
+			Type::SMALLINT => 'int',
645
+			Type::STRING => 'string',
646
+			Type::TEXT => 'string',
647
+			Type::BINARY => 'string',
648
+			Type::BLOB => 'string',
649
+			Type::FLOAT => 'float',
650
+			Type::GUID => 'string',
651
+		];
652
+
653
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
654
+	}
655
+
656
+	/**
657
+	 * @param string $beanNamespace
658
+	 *
659
+	 * @return \string[] Returns a map mapping table name to beans name
660
+	 */
661
+	public function buildTableToBeanMap($beanNamespace)
662
+	{
663
+		$tableToBeanMap = [];
664
+
665
+		$tables = $this->schema->getTables();
666
+
667
+		foreach ($tables as $table) {
668
+			$tableName = $table->getName();
669
+			$tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
670
+		}
671
+
672
+		return $tableToBeanMap;
673
+	}
674 674
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMService.php 1 patch
Indentation   +1399 added lines, -1399 removed lines patch added patch discarded remove patch
@@ -41,231 +41,231 @@  discard block
 block discarded – undo
41 41
  */
42 42
 class TDBMService
43 43
 {
44
-    const MODE_CURSOR = 1;
45
-    const MODE_ARRAY = 2;
46
-
47
-    /**
48
-     * The database connection.
49
-     *
50
-     * @var Connection
51
-     */
52
-    private $connection;
53
-
54
-    /**
55
-     * @var SchemaAnalyzer
56
-     */
57
-    private $schemaAnalyzer;
58
-
59
-    /**
60
-     * @var MagicQuery
61
-     */
62
-    private $magicQuery;
63
-
64
-    /**
65
-     * @var TDBMSchemaAnalyzer
66
-     */
67
-    private $tdbmSchemaAnalyzer;
68
-
69
-    /**
70
-     * @var string
71
-     */
72
-    private $cachePrefix;
73
-
74
-    /**
75
-     * The default autosave mode for the objects
76
-     * True to automatically save the object.
77
-     * If false, the user must explicitly call the save() method to save the object.
78
-     *
79
-     * @var bool
80
-     */
81
-    //private $autosave_default = false;
82
-
83
-    /**
84
-     * Cache of table of primary keys.
85
-     * Primary keys are stored by tables, as an array of column.
86
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
87
-     *
88
-     * @var string[]
89
-     */
90
-    private $primaryKeysColumns;
91
-
92
-    /**
93
-     * Service storing objects in memory.
94
-     * Access is done by table name and then by primary key.
95
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
96
-     *
97
-     * @var StandardObjectStorage|WeakrefObjectStorage
98
-     */
99
-    private $objectStorage;
100
-
101
-    /**
102
-     * The fetch mode of the result sets returned by `getObjects`.
103
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
104
-     *
105
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
106
-     * 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,
107
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
108
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
109
-     * You can access the array by key, or using foreach, several times.
110
-     *
111
-     * @var int
112
-     */
113
-    private $mode = self::MODE_ARRAY;
114
-
115
-    /**
116
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
117
-     *
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__';
133
-
134
-    /**
135
-     * Map associating a table name to a fully qualified Bean class name.
136
-     *
137
-     * @var array
138
-     */
139
-    private $tableToBeanMap = [];
140
-
141
-    /**
142
-     * @var \ReflectionClass[]
143
-     */
144
-    private $reflectionClassCache;
145
-
146
-    /**
147
-     * @param Connection     $connection     The DBAL DB connection to use
148
-     * @param Cache|null     $cache          A cache service to be used
149
-     * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
150
-     *                                       Will be automatically created if not passed.
151
-     */
152
-    public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null)
153
-    {
154
-        //register_shutdown_function(array($this,"completeSaveOnExit"));
155
-        if (extension_loaded('weakref')) {
156
-            $this->objectStorage = new WeakrefObjectStorage();
157
-        } else {
158
-            $this->objectStorage = new StandardObjectStorage();
159
-        }
160
-        $this->connection = $connection;
161
-        if ($cache !== null) {
162
-            $this->cache = $cache;
163
-        } else {
164
-            $this->cache = new VoidCache();
165
-        }
166
-        if ($schemaAnalyzer) {
167
-            $this->schemaAnalyzer = $schemaAnalyzer;
168
-        } else {
169
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
170
-        }
171
-
172
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
173
-
174
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
175
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
176
-
177
-        if (self::$script_start_up_time === null) {
178
-            self::$script_start_up_time = microtime(true);
179
-        }
180
-        $this->toSaveObjects = new \SplObjectStorage();
181
-    }
182
-
183
-    /**
184
-     * Returns the object used to connect to the database.
185
-     *
186
-     * @return Connection
187
-     */
188
-    public function getConnection()
189
-    {
190
-        return $this->connection;
191
-    }
192
-
193
-    /**
194
-     * Creates a unique cache key for the current connection.
195
-     *
196
-     * @return string
197
-     */
198
-    private function getConnectionUniqueId()
199
-    {
200
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
201
-    }
202
-
203
-    /**
204
-     * Sets the default fetch mode of the result sets returned by `getObjects`.
205
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
206
-     *
207
-     * 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).
208
-     * 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
209
-     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
210
-     *
211
-     * @param int $mode
212
-     *
213
-     * @return $this
214
-     *
215
-     * @throws TDBMException
216
-     */
217
-    public function setFetchMode($mode)
218
-    {
219
-        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
220
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
221
-        }
222
-        $this->mode = $mode;
223
-
224
-        return $this;
225
-    }
226
-
227
-    /**
228
-     * Returns a TDBMObject associated from table "$table_name".
229
-     * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
230
-     * $filters can also be a set of TDBM_Filters (see the getObjects method for more details).
231
-     *
232
-     * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
233
-     * 			$user = $tdbmService->getObject('users',1);
234
-     * 			echo $user->name;
235
-     * will return the name of the user whose user_id is one.
236
-     *
237
-     * 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.
238
-     * For instance:
239
-     * 			$group = $tdbmService->getObject('groups',array(1,2));
240
-     *
241
-     * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
242
-     * will be the same.
243
-     *
244
-     * For instance:
245
-     * 			$user1 = $tdbmService->getObject('users',1);
246
-     * 			$user2 = $tdbmService->getObject('users',1);
247
-     * 			$user1->name = 'John Doe';
248
-     * 			echo $user2->name;
249
-     * will return 'John Doe'.
250
-     *
251
-     * You can use filters instead of passing the primary key. For instance:
252
-     * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
253
-     * This will return the user whose login is 'jdoe'.
254
-     * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
255
-     *
256
-     * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
257
-     * For instance:
258
-     *  	$user = $tdbmService->getObject('users',1,'User');
259
-     * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
260
-     * Please be sure not to override any method or any property unless you perfectly know what you are doing!
261
-     *
262
-     * @param string $table_name   The name of the table we retrieve an object from.
263
-     * @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)
264
-     * @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.
265
-     * @param bool   $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.
266
-     *
267
-     * @return TDBMObject
268
-     */
44
+	const MODE_CURSOR = 1;
45
+	const MODE_ARRAY = 2;
46
+
47
+	/**
48
+	 * The database connection.
49
+	 *
50
+	 * @var Connection
51
+	 */
52
+	private $connection;
53
+
54
+	/**
55
+	 * @var SchemaAnalyzer
56
+	 */
57
+	private $schemaAnalyzer;
58
+
59
+	/**
60
+	 * @var MagicQuery
61
+	 */
62
+	private $magicQuery;
63
+
64
+	/**
65
+	 * @var TDBMSchemaAnalyzer
66
+	 */
67
+	private $tdbmSchemaAnalyzer;
68
+
69
+	/**
70
+	 * @var string
71
+	 */
72
+	private $cachePrefix;
73
+
74
+	/**
75
+	 * The default autosave mode for the objects
76
+	 * True to automatically save the object.
77
+	 * If false, the user must explicitly call the save() method to save the object.
78
+	 *
79
+	 * @var bool
80
+	 */
81
+	//private $autosave_default = false;
82
+
83
+	/**
84
+	 * Cache of table of primary keys.
85
+	 * Primary keys are stored by tables, as an array of column.
86
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
87
+	 *
88
+	 * @var string[]
89
+	 */
90
+	private $primaryKeysColumns;
91
+
92
+	/**
93
+	 * Service storing objects in memory.
94
+	 * Access is done by table name and then by primary key.
95
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
96
+	 *
97
+	 * @var StandardObjectStorage|WeakrefObjectStorage
98
+	 */
99
+	private $objectStorage;
100
+
101
+	/**
102
+	 * The fetch mode of the result sets returned by `getObjects`.
103
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
104
+	 *
105
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
106
+	 * 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,
107
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
108
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
109
+	 * You can access the array by key, or using foreach, several times.
110
+	 *
111
+	 * @var int
112
+	 */
113
+	private $mode = self::MODE_ARRAY;
114
+
115
+	/**
116
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
117
+	 *
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__';
133
+
134
+	/**
135
+	 * Map associating a table name to a fully qualified Bean class name.
136
+	 *
137
+	 * @var array
138
+	 */
139
+	private $tableToBeanMap = [];
140
+
141
+	/**
142
+	 * @var \ReflectionClass[]
143
+	 */
144
+	private $reflectionClassCache;
145
+
146
+	/**
147
+	 * @param Connection     $connection     The DBAL DB connection to use
148
+	 * @param Cache|null     $cache          A cache service to be used
149
+	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
150
+	 *                                       Will be automatically created if not passed.
151
+	 */
152
+	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null)
153
+	{
154
+		//register_shutdown_function(array($this,"completeSaveOnExit"));
155
+		if (extension_loaded('weakref')) {
156
+			$this->objectStorage = new WeakrefObjectStorage();
157
+		} else {
158
+			$this->objectStorage = new StandardObjectStorage();
159
+		}
160
+		$this->connection = $connection;
161
+		if ($cache !== null) {
162
+			$this->cache = $cache;
163
+		} else {
164
+			$this->cache = new VoidCache();
165
+		}
166
+		if ($schemaAnalyzer) {
167
+			$this->schemaAnalyzer = $schemaAnalyzer;
168
+		} else {
169
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
170
+		}
171
+
172
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
173
+
174
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
175
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
176
+
177
+		if (self::$script_start_up_time === null) {
178
+			self::$script_start_up_time = microtime(true);
179
+		}
180
+		$this->toSaveObjects = new \SplObjectStorage();
181
+	}
182
+
183
+	/**
184
+	 * Returns the object used to connect to the database.
185
+	 *
186
+	 * @return Connection
187
+	 */
188
+	public function getConnection()
189
+	{
190
+		return $this->connection;
191
+	}
192
+
193
+	/**
194
+	 * Creates a unique cache key for the current connection.
195
+	 *
196
+	 * @return string
197
+	 */
198
+	private function getConnectionUniqueId()
199
+	{
200
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
201
+	}
202
+
203
+	/**
204
+	 * Sets the default fetch mode of the result sets returned by `getObjects`.
205
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
206
+	 *
207
+	 * 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).
208
+	 * 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
209
+	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
210
+	 *
211
+	 * @param int $mode
212
+	 *
213
+	 * @return $this
214
+	 *
215
+	 * @throws TDBMException
216
+	 */
217
+	public function setFetchMode($mode)
218
+	{
219
+		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
220
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
221
+		}
222
+		$this->mode = $mode;
223
+
224
+		return $this;
225
+	}
226
+
227
+	/**
228
+	 * Returns a TDBMObject associated from table "$table_name".
229
+	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
230
+	 * $filters can also be a set of TDBM_Filters (see the getObjects method for more details).
231
+	 *
232
+	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
233
+	 * 			$user = $tdbmService->getObject('users',1);
234
+	 * 			echo $user->name;
235
+	 * will return the name of the user whose user_id is one.
236
+	 *
237
+	 * 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.
238
+	 * For instance:
239
+	 * 			$group = $tdbmService->getObject('groups',array(1,2));
240
+	 *
241
+	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
242
+	 * will be the same.
243
+	 *
244
+	 * For instance:
245
+	 * 			$user1 = $tdbmService->getObject('users',1);
246
+	 * 			$user2 = $tdbmService->getObject('users',1);
247
+	 * 			$user1->name = 'John Doe';
248
+	 * 			echo $user2->name;
249
+	 * will return 'John Doe'.
250
+	 *
251
+	 * You can use filters instead of passing the primary key. For instance:
252
+	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
253
+	 * This will return the user whose login is 'jdoe'.
254
+	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
255
+	 *
256
+	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
257
+	 * For instance:
258
+	 *  	$user = $tdbmService->getObject('users',1,'User');
259
+	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
260
+	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
261
+	 *
262
+	 * @param string $table_name   The name of the table we retrieve an object from.
263
+	 * @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)
264
+	 * @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.
265
+	 * @param bool   $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.
266
+	 *
267
+	 * @return TDBMObject
268
+	 */
269 269
 /*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
270 270
 
271 271
         if (is_array($filters) || $filters instanceof FilterInterface) {
@@ -351,215 +351,215 @@  discard block
 block discarded – undo
351 351
         return $obj;
352 352
     }*/
353 353
 
354
-    /**
355
-     * Removes the given object from database.
356
-     * This cannot be called on an object that is not attached to this TDBMService
357
-     * (will throw a TDBMInvalidOperationException).
358
-     *
359
-     * @param AbstractTDBMObject $object the object to delete.
360
-     *
361
-     * @throws TDBMException
362
-     * @throws TDBMInvalidOperationException
363
-     */
364
-    public function delete(AbstractTDBMObject $object)
365
-    {
366
-        switch ($object->_getStatus()) {
367
-            case TDBMObjectStateEnum::STATE_DELETED:
368
-                // Nothing to do, object already deleted.
369
-                return;
370
-            case TDBMObjectStateEnum::STATE_DETACHED:
371
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
372
-            case TDBMObjectStateEnum::STATE_NEW:
373
-                $this->deleteManyToManyRelationships($object);
374
-                foreach ($object->_getDbRows() as $dbRow) {
375
-                    $this->removeFromToSaveObjectList($dbRow);
376
-                }
377
-                break;
378
-            case TDBMObjectStateEnum::STATE_DIRTY:
379
-                foreach ($object->_getDbRows() as $dbRow) {
380
-                    $this->removeFromToSaveObjectList($dbRow);
381
-                }
382
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
383
-            case TDBMObjectStateEnum::STATE_LOADED:
384
-                $this->deleteManyToManyRelationships($object);
385
-                // Let's delete db rows, in reverse order.
386
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
387
-                    $tableName = $dbRow->_getDbTableName();
388
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
389
-                    $this->connection->delete($tableName, $primaryKeys);
390
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
391
-                }
392
-                break;
393
-            // @codeCoverageIgnoreStart
394
-            default:
395
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
396
-            // @codeCoverageIgnoreEnd
397
-        }
398
-
399
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
400
-    }
401
-
402
-    /**
403
-     * Removes all many to many relationships for this object.
404
-     *
405
-     * @param AbstractTDBMObject $object
406
-     */
407
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
408
-    {
409
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
410
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
411
-            foreach ($pivotTables as $pivotTable) {
412
-                $remoteBeans = $object->_getRelationships($pivotTable);
413
-                foreach ($remoteBeans as $remoteBean) {
414
-                    $object->_removeRelationship($pivotTable, $remoteBean);
415
-                }
416
-            }
417
-        }
418
-        $this->persistManyToManyRelationships($object);
419
-    }
420
-
421
-    /**
422
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
423
-     * by parameter before all.
424
-     *
425
-     * Notice: if the object has a multiple primary key, the function will not work.
426
-     *
427
-     * @param AbstractTDBMObject $objToDelete
428
-     */
429
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
430
-    {
431
-        $this->deleteAllConstraintWithThisObject($objToDelete);
432
-        $this->delete($objToDelete);
433
-    }
434
-
435
-    /**
436
-     * This function is used only in TDBMService (private function)
437
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
438
-     *
439
-     * @param AbstractTDBMObject $obj
440
-     */
441
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
442
-    {
443
-        $dbRows = $obj->_getDbRows();
444
-        foreach ($dbRows as $dbRow) {
445
-            $tableName = $dbRow->_getDbTableName();
446
-            $pks = array_values($dbRow->_getPrimaryKeys());
447
-            if (!empty($pks)) {
448
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
449
-
450
-                foreach ($incomingFks as $incomingFk) {
451
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
452
-
453
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
454
-
455
-                    foreach ($results as $bean) {
456
-                        $this->deleteCascade($bean);
457
-                    }
458
-                }
459
-            }
460
-        }
461
-    }
462
-
463
-    /**
464
-     * This function performs a save() of all the objects that have been modified.
465
-     */
466
-    public function completeSave()
467
-    {
468
-        foreach ($this->toSaveObjects as $dbRow) {
469
-            $this->save($dbRow->getTDBMObject());
470
-        }
471
-    }
472
-
473
-    /**
474
-     * Returns an array of objects of "table_name" kind filtered from the filter bag.
475
-     *
476
-     * The getObjects method should be the most used query method in TDBM if you want to query the database for objects.
477
-     * (Note: if you want to query the database for an object by its primary key, use the getObject method).
478
-     *
479
-     * The getObjects method takes in parameter:
480
-     * 	- table_name: the kinf of TDBMObject you want to retrieve. In TDBM, a TDBMObject matches a database row, so the
481
-     * 			$table_name parameter should be the name of an existing table in database.
482
-     *  - filter_bag: The filter bag is anything that you can use to filter your request. It can be a SQL Where clause,
483
-     * 			a series of TDBM_Filter objects, or even TDBMObjects or TDBMObjectArrays that you will use as filters.
484
-     *  - order_bag: The order bag is anything that will be used to order the data that is passed back to you.
485
-     * 			A SQL Order by clause can be used as an order bag for instance, or a OrderByColumn object
486
-     * 	- from (optionnal): The offset from which the query should be performed. For instance, if $from=5, the getObjects method
487
-     * 			will return objects from the 6th rows.
488
-     * 	- limit (optionnal): The maximum number of objects to return. Used together with $from, you can implement
489
-     * 			paging mechanisms.
490
-     *  - hint_path (optionnal): EXPERTS ONLY! The path the request should use if not the most obvious one. This parameter
491
-     * 			should be used only if you perfectly know what you are doing.
492
-     *
493
-     * The getObjects method will return a TDBMObjectArray. A TDBMObjectArray is an array of TDBMObjects that does behave as
494
-     * a single TDBMObject if the array has only one member. Refer to the documentation of TDBMObjectArray and TDBMObject
495
-     * to learn more.
496
-     *
497
-     * More about the filter bag:
498
-     * A filter is anything that can change the set of objects returned by getObjects.
499
-     * There are many kind of filters in TDBM:
500
-     * A filter can be:
501
-     * 	- A SQL WHERE clause:
502
-     * 		The clause is specified without the "WHERE" keyword. For instance:
503
-     * 			$filter = "users.first_name LIKE 'J%'";
504
-     *     	is a valid filter.
505
-     * 	   	The only difference with SQL is that when you specify a column name, it should always be fully qualified with
506
-     * 		the table name: "country_name='France'" is not valid, while "countries.country_name='France'" is valid (if
507
-     * 		"countries" is a table and "country_name" a column in that table, sure.
508
-     * 		For instance,
509
-     * 				$french_users = TDBMObject::getObjects("users", "countries.country_name='France'");
510
-     * 		will return all the users that are French (based on trhe assumption that TDBM can find a way to connect the users
511
-     * 		table to the country table using foreign keys, see the manual for that point).
512
-     * 	- A TDBMObject:
513
-     * 		An object can be used as a filter. For instance, we could get the France object and then find any users related to
514
-     * 		that object using:
515
-     * 				$france = TDBMObject::getObjects("country", "countries.country_name='France'");
516
-     * 				$french_users = TDBMObject::getObjects("users", $france);
517
-     *  - A TDBMObjectArray can be used as a filter too.
518
-     * 		For instance:
519
-     * 				$french_groups = TDBMObject::getObjects("groups", $french_users);
520
-     * 		might return all the groups in which french users can be found.
521
-     *  - Finally, TDBM_xxxFilter instances can be used.
522
-     * 		TDBM provides the developer a set of TDBM_xxxFilters that can be used to model a SQL Where query.
523
-     * 		Using the appropriate filter object, you can model the operations =,<,<=,>,>=,IN,LIKE,AND,OR, IS NULL and NOT
524
-     * 		For instance:
525
-     * 				$french_users = TDBMObject::getObjects("users", new EqualFilter('countries','country_name','France');
526
-     * 		Refer to the documentation of the appropriate filters for more information.
527
-     *
528
-     * The nice thing about a filter bag is that it can be any filter, or any array of filters. In that case, filters are
529
-     * 'ANDed' together.
530
-     * So a request like this is valid:
531
-     * 				$france = TDBMObject::getObjects("country", "countries.country_name='France'");
532
-     * 				$french_administrators = TDBMObject::getObjects("users", array($france,"role.role_name='Administrators'");
533
-     * This requests would return the users that are both French and administrators.
534
-     *
535
-     * Finally, if filter_bag is null, the whole table is returned.
536
-     *
537
-     * More about the order bag:
538
-     * The order bag contains anything that can be used to order the data that is passed back to you.
539
-     * The order bag can contain two kinds of objects:
540
-     * 	- A SQL ORDER BY clause:
541
-     * 		The clause is specified without the "ORDER BY" keyword. For instance:
542
-     * 			$orderby = "users.last_name ASC, users.first_name ASC";
543
-     *     	is a valid order bag.
544
-     * 		The only difference with SQL is that when you specify a column name, it should always be fully qualified with
545
-     * 		the table name: "country_name ASC" is not valid, while "countries.country_name ASC" is valid (if
546
-     * 		"countries" is a table and "country_name" a column in that table, sure.
547
-     * 		For instance,
548
-     * 				$french_users = TDBMObject::getObjects("users", null, "countries.country_name ASC");
549
-     * 		will return all the users sorted by country.
550
-     *  - A OrderByColumn object
551
-     * 		This object models a single column in a database.
552
-     *
553
-     * @param string       $table_name  The name of the table queried
554
-     * @param mixed        $filter_bag  The filter bag (see above for complete description)
555
-     * @param mixed        $orderby_bag The order bag (see above for complete description)
556
-     * @param int          $from        The offset
557
-     * @param int          $limit       The maximum number of rows returned
558
-     * @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.
559
-     * @param unknown_type $hint_path   Hints to get the path for the query (expert parameter, you should leave it to null).
560
-     *
561
-     * @return TDBMObjectArray A TDBMObjectArray containing the resulting objects of the query.
562
-     */
354
+	/**
355
+	 * Removes the given object from database.
356
+	 * This cannot be called on an object that is not attached to this TDBMService
357
+	 * (will throw a TDBMInvalidOperationException).
358
+	 *
359
+	 * @param AbstractTDBMObject $object the object to delete.
360
+	 *
361
+	 * @throws TDBMException
362
+	 * @throws TDBMInvalidOperationException
363
+	 */
364
+	public function delete(AbstractTDBMObject $object)
365
+	{
366
+		switch ($object->_getStatus()) {
367
+			case TDBMObjectStateEnum::STATE_DELETED:
368
+				// Nothing to do, object already deleted.
369
+				return;
370
+			case TDBMObjectStateEnum::STATE_DETACHED:
371
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
372
+			case TDBMObjectStateEnum::STATE_NEW:
373
+				$this->deleteManyToManyRelationships($object);
374
+				foreach ($object->_getDbRows() as $dbRow) {
375
+					$this->removeFromToSaveObjectList($dbRow);
376
+				}
377
+				break;
378
+			case TDBMObjectStateEnum::STATE_DIRTY:
379
+				foreach ($object->_getDbRows() as $dbRow) {
380
+					$this->removeFromToSaveObjectList($dbRow);
381
+				}
382
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
383
+			case TDBMObjectStateEnum::STATE_LOADED:
384
+				$this->deleteManyToManyRelationships($object);
385
+				// Let's delete db rows, in reverse order.
386
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
387
+					$tableName = $dbRow->_getDbTableName();
388
+					$primaryKeys = $dbRow->_getPrimaryKeys();
389
+					$this->connection->delete($tableName, $primaryKeys);
390
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
391
+				}
392
+				break;
393
+			// @codeCoverageIgnoreStart
394
+			default:
395
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
396
+			// @codeCoverageIgnoreEnd
397
+		}
398
+
399
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
400
+	}
401
+
402
+	/**
403
+	 * Removes all many to many relationships for this object.
404
+	 *
405
+	 * @param AbstractTDBMObject $object
406
+	 */
407
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
408
+	{
409
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
410
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
411
+			foreach ($pivotTables as $pivotTable) {
412
+				$remoteBeans = $object->_getRelationships($pivotTable);
413
+				foreach ($remoteBeans as $remoteBean) {
414
+					$object->_removeRelationship($pivotTable, $remoteBean);
415
+				}
416
+			}
417
+		}
418
+		$this->persistManyToManyRelationships($object);
419
+	}
420
+
421
+	/**
422
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
423
+	 * by parameter before all.
424
+	 *
425
+	 * Notice: if the object has a multiple primary key, the function will not work.
426
+	 *
427
+	 * @param AbstractTDBMObject $objToDelete
428
+	 */
429
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
430
+	{
431
+		$this->deleteAllConstraintWithThisObject($objToDelete);
432
+		$this->delete($objToDelete);
433
+	}
434
+
435
+	/**
436
+	 * This function is used only in TDBMService (private function)
437
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
438
+	 *
439
+	 * @param AbstractTDBMObject $obj
440
+	 */
441
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
442
+	{
443
+		$dbRows = $obj->_getDbRows();
444
+		foreach ($dbRows as $dbRow) {
445
+			$tableName = $dbRow->_getDbTableName();
446
+			$pks = array_values($dbRow->_getPrimaryKeys());
447
+			if (!empty($pks)) {
448
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
449
+
450
+				foreach ($incomingFks as $incomingFk) {
451
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
452
+
453
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
454
+
455
+					foreach ($results as $bean) {
456
+						$this->deleteCascade($bean);
457
+					}
458
+				}
459
+			}
460
+		}
461
+	}
462
+
463
+	/**
464
+	 * This function performs a save() of all the objects that have been modified.
465
+	 */
466
+	public function completeSave()
467
+	{
468
+		foreach ($this->toSaveObjects as $dbRow) {
469
+			$this->save($dbRow->getTDBMObject());
470
+		}
471
+	}
472
+
473
+	/**
474
+	 * Returns an array of objects of "table_name" kind filtered from the filter bag.
475
+	 *
476
+	 * The getObjects method should be the most used query method in TDBM if you want to query the database for objects.
477
+	 * (Note: if you want to query the database for an object by its primary key, use the getObject method).
478
+	 *
479
+	 * The getObjects method takes in parameter:
480
+	 * 	- table_name: the kinf of TDBMObject you want to retrieve. In TDBM, a TDBMObject matches a database row, so the
481
+	 * 			$table_name parameter should be the name of an existing table in database.
482
+	 *  - filter_bag: The filter bag is anything that you can use to filter your request. It can be a SQL Where clause,
483
+	 * 			a series of TDBM_Filter objects, or even TDBMObjects or TDBMObjectArrays that you will use as filters.
484
+	 *  - order_bag: The order bag is anything that will be used to order the data that is passed back to you.
485
+	 * 			A SQL Order by clause can be used as an order bag for instance, or a OrderByColumn object
486
+	 * 	- from (optionnal): The offset from which the query should be performed. For instance, if $from=5, the getObjects method
487
+	 * 			will return objects from the 6th rows.
488
+	 * 	- limit (optionnal): The maximum number of objects to return. Used together with $from, you can implement
489
+	 * 			paging mechanisms.
490
+	 *  - hint_path (optionnal): EXPERTS ONLY! The path the request should use if not the most obvious one. This parameter
491
+	 * 			should be used only if you perfectly know what you are doing.
492
+	 *
493
+	 * The getObjects method will return a TDBMObjectArray. A TDBMObjectArray is an array of TDBMObjects that does behave as
494
+	 * a single TDBMObject if the array has only one member. Refer to the documentation of TDBMObjectArray and TDBMObject
495
+	 * to learn more.
496
+	 *
497
+	 * More about the filter bag:
498
+	 * A filter is anything that can change the set of objects returned by getObjects.
499
+	 * There are many kind of filters in TDBM:
500
+	 * A filter can be:
501
+	 * 	- A SQL WHERE clause:
502
+	 * 		The clause is specified without the "WHERE" keyword. For instance:
503
+	 * 			$filter = "users.first_name LIKE 'J%'";
504
+	 *     	is a valid filter.
505
+	 * 	   	The only difference with SQL is that when you specify a column name, it should always be fully qualified with
506
+	 * 		the table name: "country_name='France'" is not valid, while "countries.country_name='France'" is valid (if
507
+	 * 		"countries" is a table and "country_name" a column in that table, sure.
508
+	 * 		For instance,
509
+	 * 				$french_users = TDBMObject::getObjects("users", "countries.country_name='France'");
510
+	 * 		will return all the users that are French (based on trhe assumption that TDBM can find a way to connect the users
511
+	 * 		table to the country table using foreign keys, see the manual for that point).
512
+	 * 	- A TDBMObject:
513
+	 * 		An object can be used as a filter. For instance, we could get the France object and then find any users related to
514
+	 * 		that object using:
515
+	 * 				$france = TDBMObject::getObjects("country", "countries.country_name='France'");
516
+	 * 				$french_users = TDBMObject::getObjects("users", $france);
517
+	 *  - A TDBMObjectArray can be used as a filter too.
518
+	 * 		For instance:
519
+	 * 				$french_groups = TDBMObject::getObjects("groups", $french_users);
520
+	 * 		might return all the groups in which french users can be found.
521
+	 *  - Finally, TDBM_xxxFilter instances can be used.
522
+	 * 		TDBM provides the developer a set of TDBM_xxxFilters that can be used to model a SQL Where query.
523
+	 * 		Using the appropriate filter object, you can model the operations =,<,<=,>,>=,IN,LIKE,AND,OR, IS NULL and NOT
524
+	 * 		For instance:
525
+	 * 				$french_users = TDBMObject::getObjects("users", new EqualFilter('countries','country_name','France');
526
+	 * 		Refer to the documentation of the appropriate filters for more information.
527
+	 *
528
+	 * The nice thing about a filter bag is that it can be any filter, or any array of filters. In that case, filters are
529
+	 * 'ANDed' together.
530
+	 * So a request like this is valid:
531
+	 * 				$france = TDBMObject::getObjects("country", "countries.country_name='France'");
532
+	 * 				$french_administrators = TDBMObject::getObjects("users", array($france,"role.role_name='Administrators'");
533
+	 * This requests would return the users that are both French and administrators.
534
+	 *
535
+	 * Finally, if filter_bag is null, the whole table is returned.
536
+	 *
537
+	 * More about the order bag:
538
+	 * The order bag contains anything that can be used to order the data that is passed back to you.
539
+	 * The order bag can contain two kinds of objects:
540
+	 * 	- A SQL ORDER BY clause:
541
+	 * 		The clause is specified without the "ORDER BY" keyword. For instance:
542
+	 * 			$orderby = "users.last_name ASC, users.first_name ASC";
543
+	 *     	is a valid order bag.
544
+	 * 		The only difference with SQL is that when you specify a column name, it should always be fully qualified with
545
+	 * 		the table name: "country_name ASC" is not valid, while "countries.country_name ASC" is valid (if
546
+	 * 		"countries" is a table and "country_name" a column in that table, sure.
547
+	 * 		For instance,
548
+	 * 				$french_users = TDBMObject::getObjects("users", null, "countries.country_name ASC");
549
+	 * 		will return all the users sorted by country.
550
+	 *  - A OrderByColumn object
551
+	 * 		This object models a single column in a database.
552
+	 *
553
+	 * @param string       $table_name  The name of the table queried
554
+	 * @param mixed        $filter_bag  The filter bag (see above for complete description)
555
+	 * @param mixed        $orderby_bag The order bag (see above for complete description)
556
+	 * @param int          $from        The offset
557
+	 * @param int          $limit       The maximum number of rows returned
558
+	 * @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.
559
+	 * @param unknown_type $hint_path   Hints to get the path for the query (expert parameter, you should leave it to null).
560
+	 *
561
+	 * @return TDBMObjectArray A TDBMObjectArray containing the resulting objects of the query.
562
+	 */
563 563
 /*	public function getObjects($table_name, $filter_bag=null, $orderby_bag=null, $from=null, $limit=null, $className=null, $hint_path=null) {
564 564
         if ($this->connection == null) {
565 565
             throw new TDBMException("Error while calling TDBMObject::getObject(): No connection has been established on the database!");
@@ -567,57 +567,57 @@  discard block
 block discarded – undo
567 567
         return $this->getObjectsByMode('getObjects', $table_name, $filter_bag, $orderby_bag, $from, $limit, $className, $hint_path);
568 568
     }*/
569 569
 
570
-    /**
571
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
572
-     * and gives back a proper Filter object.
573
-     *
574
-     * @param mixed $filter_bag
575
-     *
576
-     * @return array First item: filter string, second item: parameters.
577
-     *
578
-     * @throws TDBMException
579
-     */
580
-    public function buildFilterFromFilterBag($filter_bag)
581
-    {
582
-        $counter = 1;
583
-        if ($filter_bag === null) {
584
-            return ['', []];
585
-        } elseif (is_string($filter_bag)) {
586
-            return [$filter_bag, []];
587
-        } elseif (is_array($filter_bag)) {
588
-            $sqlParts = [];
589
-            $parameters = [];
590
-            foreach ($filter_bag as $column => $value) {
591
-                $paramName = 'tdbmparam'.$counter;
592
-                if (is_array($value)) {
593
-                    $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
594
-                } else {
595
-                    $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
596
-                }
597
-                $parameters[$paramName] = $value;
598
-                ++$counter;
599
-            }
600
-
601
-            return [implode(' AND ', $sqlParts), $parameters];
602
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
603
-            $sqlParts = [];
604
-            $dbRows = $filter_bag->_getDbRows();
605
-            $dbRow = reset($dbRows);
606
-            $primaryKeys = $dbRow->_getPrimaryKeys();
607
-
608
-            foreach ($primaryKeys as $column => $value) {
609
-                $paramName = 'tdbmparam'.$counter;
610
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
611
-                $parameters[$paramName] = $value;
612
-                ++$counter;
613
-            }
614
-
615
-            return [implode(' AND ', $sqlParts), $parameters];
616
-        } elseif ($filter_bag instanceof \Iterator) {
617
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag));
618
-        } else {
619
-            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.');
620
-        }
570
+	/**
571
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
572
+	 * and gives back a proper Filter object.
573
+	 *
574
+	 * @param mixed $filter_bag
575
+	 *
576
+	 * @return array First item: filter string, second item: parameters.
577
+	 *
578
+	 * @throws TDBMException
579
+	 */
580
+	public function buildFilterFromFilterBag($filter_bag)
581
+	{
582
+		$counter = 1;
583
+		if ($filter_bag === null) {
584
+			return ['', []];
585
+		} elseif (is_string($filter_bag)) {
586
+			return [$filter_bag, []];
587
+		} elseif (is_array($filter_bag)) {
588
+			$sqlParts = [];
589
+			$parameters = [];
590
+			foreach ($filter_bag as $column => $value) {
591
+				$paramName = 'tdbmparam'.$counter;
592
+				if (is_array($value)) {
593
+					$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
594
+				} else {
595
+					$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
596
+				}
597
+				$parameters[$paramName] = $value;
598
+				++$counter;
599
+			}
600
+
601
+			return [implode(' AND ', $sqlParts), $parameters];
602
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
603
+			$sqlParts = [];
604
+			$dbRows = $filter_bag->_getDbRows();
605
+			$dbRow = reset($dbRows);
606
+			$primaryKeys = $dbRow->_getPrimaryKeys();
607
+
608
+			foreach ($primaryKeys as $column => $value) {
609
+				$paramName = 'tdbmparam'.$counter;
610
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
611
+				$parameters[$paramName] = $value;
612
+				++$counter;
613
+			}
614
+
615
+			return [implode(' AND ', $sqlParts), $parameters];
616
+		} elseif ($filter_bag instanceof \Iterator) {
617
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag));
618
+		} else {
619
+			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.');
620
+		}
621 621
 
622 622
 //		// First filter_bag should be an array, if it is a singleton, let's put it in an array.
623 623
 //		if ($filter_bag === null) {
@@ -674,55 +674,55 @@  discard block
 block discarded – undo
674 674
 //		$filter = new AndFilter($filter_bag2);
675 675
 //
676 676
 //		return $filter;
677
-    }
678
-
679
-    /**
680
-     * Takes in input an order_bag (which can be about anything from a string to an array of OrderByColumn objects... see above from documentation),
681
-     * and gives back an array of OrderByColumn / OrderBySQLString objects.
682
-     *
683
-     * @param unknown_type $orderby_bag
684
-     *
685
-     * @return array
686
-     */
687
-    public function buildOrderArrayFromOrderBag($orderby_bag)
688
-    {
689
-        // Fourth, let's apply the same steps to the orderby_bag
690
-        // 4-1 orderby_bag should be an array, if it is a singleton, let's put it in an array.
691
-
692
-        if (!is_array($orderby_bag)) {
693
-            $orderby_bag = array($orderby_bag);
694
-        }
695
-
696
-        // 4-2, let's take all the objects out of the orderby bag, and let's make objects from them
697
-        $orderby_bag2 = array();
698
-        foreach ($orderby_bag as $thing) {
699
-            if (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderBySQLString')) {
700
-                $orderby_bag2[] = $thing;
701
-            } elseif (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderByColumn')) {
702
-                $orderby_bag2[] = $thing;
703
-            } elseif (is_string($thing)) {
704
-                $orderby_bag2[] = new OrderBySQLString($thing);
705
-            } elseif ($thing !== null) {
706
-                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.');
707
-            }
708
-        }
709
-
710
-        return $orderby_bag2;
711
-    }
712
-
713
-    /**
714
-     * @param string $table
715
-     *
716
-     * @return string[]
717
-     */
718
-    public function getPrimaryKeyColumns($table)
719
-    {
720
-        if (!isset($this->primaryKeysColumns[$table])) {
721
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
722
-
723
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
724
-
725
-            /*$arr = array();
677
+	}
678
+
679
+	/**
680
+	 * Takes in input an order_bag (which can be about anything from a string to an array of OrderByColumn objects... see above from documentation),
681
+	 * and gives back an array of OrderByColumn / OrderBySQLString objects.
682
+	 *
683
+	 * @param unknown_type $orderby_bag
684
+	 *
685
+	 * @return array
686
+	 */
687
+	public function buildOrderArrayFromOrderBag($orderby_bag)
688
+	{
689
+		// Fourth, let's apply the same steps to the orderby_bag
690
+		// 4-1 orderby_bag should be an array, if it is a singleton, let's put it in an array.
691
+
692
+		if (!is_array($orderby_bag)) {
693
+			$orderby_bag = array($orderby_bag);
694
+		}
695
+
696
+		// 4-2, let's take all the objects out of the orderby bag, and let's make objects from them
697
+		$orderby_bag2 = array();
698
+		foreach ($orderby_bag as $thing) {
699
+			if (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderBySQLString')) {
700
+				$orderby_bag2[] = $thing;
701
+			} elseif (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderByColumn')) {
702
+				$orderby_bag2[] = $thing;
703
+			} elseif (is_string($thing)) {
704
+				$orderby_bag2[] = new OrderBySQLString($thing);
705
+			} elseif ($thing !== null) {
706
+				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.');
707
+			}
708
+		}
709
+
710
+		return $orderby_bag2;
711
+	}
712
+
713
+	/**
714
+	 * @param string $table
715
+	 *
716
+	 * @return string[]
717
+	 */
718
+	public function getPrimaryKeyColumns($table)
719
+	{
720
+		if (!isset($this->primaryKeysColumns[$table])) {
721
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
722
+
723
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
724
+
725
+			/*$arr = array();
726 726
             foreach ($this->connection->getPrimaryKey($table) as $col) {
727 727
                 $arr[] = $col->name;
728 728
             }
@@ -743,128 +743,128 @@  discard block
 block discarded – undo
743 743
                     throw new TDBMException($str);
744 744
                 }
745 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
-    {
759
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
760
-        $hash = $this->getObjectHash($primaryKey);
761
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
762
-    }
763
-
764
-    /**
765
-     * This is an internal function, you should not use it in your application.
766
-     * This is used internally by TDBM to remove the object from the list of objects that have been
767
-     * created/updated but not saved yet.
768
-     *
769
-     * @param DbRow $myObject
770
-     */
771
-    private function removeFromToSaveObjectList(DbRow $myObject)
772
-    {
773
-        unset($this->toSaveObjects[$myObject]);
774
-    }
775
-
776
-    /**
777
-     * This is an internal function, you should not use it in your application.
778
-     * This is used internally by TDBM to add an object to the list of objects that have been
779
-     * created/updated but not saved yet.
780
-     *
781
-     * @param AbstractTDBMObject $myObject
782
-     */
783
-    public function _addToToSaveObjectList(DbRow $myObject)
784
-    {
785
-        $this->toSaveObjects[$myObject] = true;
786
-    }
787
-
788
-    /**
789
-     * Generates all the daos and beans.
790
-     *
791
-     * @param string $daoFactoryClassName The classe name of the DAO factory
792
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
793
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
794
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone.
795
-     *
796
-     * @return \string[] the list of tables
797
-     */
798
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc)
799
-    {
800
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
801
-
802
-        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
803
-    }
804
-
805
-    /**
806
-     * @param array<string, string> $tableToBeanMap
807
-     */
808
-    public function setTableToBeanMap(array $tableToBeanMap)
809
-    {
810
-        $this->tableToBeanMap = $tableToBeanMap;
811
-    }
812
-
813
-    /**
814
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
815
-     *
816
-     * @param AbstractTDBMObject $object
817
-     *
818
-     * @throws TDBMException
819
-     */
820
-    public function save(AbstractTDBMObject $object)
821
-    {
822
-        $status = $object->_getStatus();
823
-
824
-        // Let's attach this object if it is in detached state.
825
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
826
-            $object->_attach($this);
827
-            $status = $object->_getStatus();
828
-        }
829
-
830
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
831
-            $dbRows = $object->_getDbRows();
832
-
833
-            $unindexedPrimaryKeys = array();
834
-
835
-            foreach ($dbRows as $dbRow) {
836
-                $tableName = $dbRow->_getDbTableName();
837
-
838
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
839
-                $tableDescriptor = $schema->getTable($tableName);
840
-
841
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
842
-
843
-                if (empty($unindexedPrimaryKeys)) {
844
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
845
-                } else {
846
-                    // First insert, the children must have the same primary key as the parent.
847
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
848
-                    $dbRow->_setPrimaryKeys($primaryKeys);
849
-                }
850
-
851
-                $references = $dbRow->_getReferences();
852
-
853
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
854
-                foreach ($references as $fkName => $reference) {
855
-                    $refStatus = $reference->_getStatus();
856
-                    if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
857
-                        $this->save($reference);
858
-                    }
859
-                }
860
-
861
-                $dbRowData = $dbRow->_getDbRow();
862
-
863
-                // Let's see if the columns for primary key have been set before inserting.
864
-                // We assume that if one of the value of the PK has been set, the PK is set.
865
-                $isPkSet = !empty($primaryKeys);
866
-
867
-                /*if (!$isPkSet) {
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
+	{
759
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
760
+		$hash = $this->getObjectHash($primaryKey);
761
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
762
+	}
763
+
764
+	/**
765
+	 * This is an internal function, you should not use it in your application.
766
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
767
+	 * created/updated but not saved yet.
768
+	 *
769
+	 * @param DbRow $myObject
770
+	 */
771
+	private function removeFromToSaveObjectList(DbRow $myObject)
772
+	{
773
+		unset($this->toSaveObjects[$myObject]);
774
+	}
775
+
776
+	/**
777
+	 * This is an internal function, you should not use it in your application.
778
+	 * This is used internally by TDBM to add an object to the list of objects that have been
779
+	 * created/updated but not saved yet.
780
+	 *
781
+	 * @param AbstractTDBMObject $myObject
782
+	 */
783
+	public function _addToToSaveObjectList(DbRow $myObject)
784
+	{
785
+		$this->toSaveObjects[$myObject] = true;
786
+	}
787
+
788
+	/**
789
+	 * Generates all the daos and beans.
790
+	 *
791
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
792
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
793
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
794
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone.
795
+	 *
796
+	 * @return \string[] the list of tables
797
+	 */
798
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc)
799
+	{
800
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
801
+
802
+		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
803
+	}
804
+
805
+	/**
806
+	 * @param array<string, string> $tableToBeanMap
807
+	 */
808
+	public function setTableToBeanMap(array $tableToBeanMap)
809
+	{
810
+		$this->tableToBeanMap = $tableToBeanMap;
811
+	}
812
+
813
+	/**
814
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
815
+	 *
816
+	 * @param AbstractTDBMObject $object
817
+	 *
818
+	 * @throws TDBMException
819
+	 */
820
+	public function save(AbstractTDBMObject $object)
821
+	{
822
+		$status = $object->_getStatus();
823
+
824
+		// Let's attach this object if it is in detached state.
825
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
826
+			$object->_attach($this);
827
+			$status = $object->_getStatus();
828
+		}
829
+
830
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
831
+			$dbRows = $object->_getDbRows();
832
+
833
+			$unindexedPrimaryKeys = array();
834
+
835
+			foreach ($dbRows as $dbRow) {
836
+				$tableName = $dbRow->_getDbTableName();
837
+
838
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
839
+				$tableDescriptor = $schema->getTable($tableName);
840
+
841
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
842
+
843
+				if (empty($unindexedPrimaryKeys)) {
844
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
845
+				} else {
846
+					// First insert, the children must have the same primary key as the parent.
847
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
848
+					$dbRow->_setPrimaryKeys($primaryKeys);
849
+				}
850
+
851
+				$references = $dbRow->_getReferences();
852
+
853
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
854
+				foreach ($references as $fkName => $reference) {
855
+					$refStatus = $reference->_getStatus();
856
+					if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
857
+						$this->save($reference);
858
+					}
859
+				}
860
+
861
+				$dbRowData = $dbRow->_getDbRow();
862
+
863
+				// Let's see if the columns for primary key have been set before inserting.
864
+				// We assume that if one of the value of the PK has been set, the PK is set.
865
+				$isPkSet = !empty($primaryKeys);
866
+
867
+				/*if (!$isPkSet) {
868 868
                     // if there is no autoincrement and no pk set, let's go in error.
869 869
                     $isAutoIncrement = true;
870 870
 
@@ -882,25 +882,25 @@  discard block
 block discarded – undo
882 882
 
883 883
                 }*/
884 884
 
885
-                $types = [];
885
+				$types = [];
886 886
 
887
-                foreach ($dbRowData as $columnName => $value) {
888
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
889
-                    $types[] = $columnDescriptor->getType();
890
-                }
887
+				foreach ($dbRowData as $columnName => $value) {
888
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
889
+					$types[] = $columnDescriptor->getType();
890
+				}
891 891
 
892
-                $this->connection->insert($tableName, $dbRowData, $types);
892
+				$this->connection->insert($tableName, $dbRowData, $types);
893 893
 
894
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
895
-                    $id = $this->connection->lastInsertId();
896
-                    $primaryKeys[$primaryKeyColumns[0]] = $id;
897
-                }
894
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
895
+					$id = $this->connection->lastInsertId();
896
+					$primaryKeys[$primaryKeyColumns[0]] = $id;
897
+				}
898 898
 
899
-                // TODO: change this to some private magic accessor in future
900
-                $dbRow->_setPrimaryKeys($primaryKeys);
901
-                $unindexedPrimaryKeys = array_values($primaryKeys);
899
+				// TODO: change this to some private magic accessor in future
900
+				$dbRow->_setPrimaryKeys($primaryKeys);
901
+				$unindexedPrimaryKeys = array_values($primaryKeys);
902 902
 
903
-                /*
903
+				/*
904 904
                  * When attached, on "save", we check if the column updated is part of a primary key
905 905
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
906 906
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
                  *
911 911
                  */
912 912
 
913
-                /*try {
913
+				/*try {
914 914
                     $this->db_connection->exec($sql);
915 915
                 } catch (TDBMException $e) {
916 916
                     $this->db_onerror = true;
@@ -929,391 +929,391 @@  discard block
 block discarded – undo
929 929
                     }
930 930
                 }*/
931 931
 
932
-                // Let's remove this object from the $new_objects static table.
933
-                $this->removeFromToSaveObjectList($dbRow);
934
-
935
-                // TODO: change this behaviour to something more sensible performance-wise
936
-                // Maybe a setting to trigger this globally?
937
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
938
-                //$this->db_modified_state = false;
939
-                //$dbRow = array();
940
-
941
-                // Let's add this object to the list of objects in cache.
942
-                $this->_addToCache($dbRow);
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
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
1002
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
1003
-        }
1004
-
1005
-        // Finally, let's save all the many to many relationships to this bean.
1006
-        $this->persistManyToManyRelationships($object);
1007
-    }
1008
-
1009
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
1010
-    {
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
-                } elseif ($status === 'delete') {
1050
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
1051
-
1052
-                    $types = [];
1053
-
1054
-                    foreach ($filters as $columnName => $value) {
1055
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
1056
-                        $types[] = $columnDescriptor->getType();
1057
-                    }
1058
-
1059
-                    $this->connection->delete($pivotTableName, $filters, $types);
1060
-
1061
-                    // Finally, let's remove relationships completely from bean.
1062
-                    $storage->detach($remoteBean);
1063
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
1064
-                }
1065
-            }
1066
-        }
1067
-    }
1068
-
1069
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
1070
-    {
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
-     *
1088
-     * @return array numerically indexed array of values.
1089
-     */
1090
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
1091
-    {
1092
-        $dbRows = $bean->_getDbRows();
1093
-        $dbRow = reset($dbRows);
1094
-
1095
-        return array_values($dbRow->_getPrimaryKeys());
1096
-    }
1097
-
1098
-    /**
1099
-     * Returns a unique hash used to store the object based on its primary key.
1100
-     * If the array contains only one value, then the value is returned.
1101
-     * Otherwise, a hash representing the array is returned.
1102
-     *
1103
-     * @param array $primaryKeys An array of columns => values forming the primary key
1104
-     *
1105
-     * @return string
1106
-     */
1107
-    public function getObjectHash(array $primaryKeys)
1108
-    {
1109
-        if (count($primaryKeys) === 1) {
1110
-            return reset($primaryKeys);
1111
-        } else {
1112
-            ksort($primaryKeys);
1113
-
1114
-            return md5(json_encode($primaryKeys));
1115
-        }
1116
-    }
1117
-
1118
-    /**
1119
-     * Returns an array of primary keys from the object.
1120
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
1121
-     * $primaryKeys variable of the object.
1122
-     *
1123
-     * @param DbRow $dbRow
1124
-     *
1125
-     * @return array Returns an array of column => value
1126
-     */
1127
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1128
-    {
1129
-        $table = $dbRow->_getDbTableName();
1130
-        $dbRowData = $dbRow->_getDbRow();
1131
-
1132
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1133
-    }
1134
-
1135
-    /**
1136
-     * Returns an array of primary keys for the given row.
1137
-     * The primary keys are extracted from the object columns.
1138
-     *
1139
-     * @param $table
1140
-     * @param array $columns
1141
-     *
1142
-     * @return array
1143
-     */
1144
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
1145
-    {
1146
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1147
-        $values = array();
1148
-        foreach ($primaryKeyColumns as $column) {
1149
-            if (isset($columns[$column])) {
1150
-                $values[$column] = $columns[$column];
1151
-            }
1152
-        }
1153
-
1154
-        return $values;
1155
-    }
1156
-
1157
-    /**
1158
-     * Attaches $object to this TDBMService.
1159
-     * The $object must be in DETACHED state and will pass in NEW state.
1160
-     *
1161
-     * @param AbstractTDBMObject $object
1162
-     *
1163
-     * @throws TDBMInvalidOperationException
1164
-     */
1165
-    public function attach(AbstractTDBMObject $object)
1166
-    {
1167
-        $object->_attach($this);
1168
-    }
1169
-
1170
-    /**
1171
-     * Returns an associative array (column => value) for the primary keys from the table name and an
1172
-     * indexed array of primary key values.
1173
-     *
1174
-     * @param string $tableName
1175
-     * @param array  $indexedPrimaryKeys
1176
-     */
1177
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1178
-    {
1179
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1180
-
1181
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1182
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
932
+				// Let's remove this object from the $new_objects static table.
933
+				$this->removeFromToSaveObjectList($dbRow);
934
+
935
+				// TODO: change this behaviour to something more sensible performance-wise
936
+				// Maybe a setting to trigger this globally?
937
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
938
+				//$this->db_modified_state = false;
939
+				//$dbRow = array();
940
+
941
+				// Let's add this object to the list of objects in cache.
942
+				$this->_addToCache($dbRow);
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
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
1002
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
1003
+		}
1004
+
1005
+		// Finally, let's save all the many to many relationships to this bean.
1006
+		$this->persistManyToManyRelationships($object);
1007
+	}
1008
+
1009
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
1010
+	{
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
+				} elseif ($status === 'delete') {
1050
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
1051
+
1052
+					$types = [];
1053
+
1054
+					foreach ($filters as $columnName => $value) {
1055
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
1056
+						$types[] = $columnDescriptor->getType();
1057
+					}
1058
+
1059
+					$this->connection->delete($pivotTableName, $filters, $types);
1060
+
1061
+					// Finally, let's remove relationships completely from bean.
1062
+					$storage->detach($remoteBean);
1063
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
1064
+				}
1065
+			}
1066
+		}
1067
+	}
1068
+
1069
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
1070
+	{
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
+	 *
1088
+	 * @return array numerically indexed array of values.
1089
+	 */
1090
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
1091
+	{
1092
+		$dbRows = $bean->_getDbRows();
1093
+		$dbRow = reset($dbRows);
1094
+
1095
+		return array_values($dbRow->_getPrimaryKeys());
1096
+	}
1097
+
1098
+	/**
1099
+	 * Returns a unique hash used to store the object based on its primary key.
1100
+	 * If the array contains only one value, then the value is returned.
1101
+	 * Otherwise, a hash representing the array is returned.
1102
+	 *
1103
+	 * @param array $primaryKeys An array of columns => values forming the primary key
1104
+	 *
1105
+	 * @return string
1106
+	 */
1107
+	public function getObjectHash(array $primaryKeys)
1108
+	{
1109
+		if (count($primaryKeys) === 1) {
1110
+			return reset($primaryKeys);
1111
+		} else {
1112
+			ksort($primaryKeys);
1113
+
1114
+			return md5(json_encode($primaryKeys));
1115
+		}
1116
+	}
1117
+
1118
+	/**
1119
+	 * Returns an array of primary keys from the object.
1120
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
1121
+	 * $primaryKeys variable of the object.
1122
+	 *
1123
+	 * @param DbRow $dbRow
1124
+	 *
1125
+	 * @return array Returns an array of column => value
1126
+	 */
1127
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1128
+	{
1129
+		$table = $dbRow->_getDbTableName();
1130
+		$dbRowData = $dbRow->_getDbRow();
1131
+
1132
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1133
+	}
1134
+
1135
+	/**
1136
+	 * Returns an array of primary keys for the given row.
1137
+	 * The primary keys are extracted from the object columns.
1138
+	 *
1139
+	 * @param $table
1140
+	 * @param array $columns
1141
+	 *
1142
+	 * @return array
1143
+	 */
1144
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
1145
+	{
1146
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1147
+		$values = array();
1148
+		foreach ($primaryKeyColumns as $column) {
1149
+			if (isset($columns[$column])) {
1150
+				$values[$column] = $columns[$column];
1151
+			}
1152
+		}
1153
+
1154
+		return $values;
1155
+	}
1156
+
1157
+	/**
1158
+	 * Attaches $object to this TDBMService.
1159
+	 * The $object must be in DETACHED state and will pass in NEW state.
1160
+	 *
1161
+	 * @param AbstractTDBMObject $object
1162
+	 *
1163
+	 * @throws TDBMInvalidOperationException
1164
+	 */
1165
+	public function attach(AbstractTDBMObject $object)
1166
+	{
1167
+		$object->_attach($this);
1168
+	}
1169
+
1170
+	/**
1171
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
1172
+	 * indexed array of primary key values.
1173
+	 *
1174
+	 * @param string $tableName
1175
+	 * @param array  $indexedPrimaryKeys
1176
+	 */
1177
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1178
+	{
1179
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1180
+
1181
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1182
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1183 1183
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1184
-        }
1185
-
1186
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1187
-    }
1188
-
1189
-    /**
1190
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1191
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1192
-     *
1193
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1194
-     * we must be able to find all other tables.
1195
-     *
1196
-     * @param string[] $tables
1197
-     *
1198
-     * @return string[]
1199
-     */
1200
-    public function _getLinkBetweenInheritedTables(array $tables)
1201
-    {
1202
-        sort($tables);
1203
-
1204
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1205
-            function () use ($tables) {
1206
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1207
-            });
1208
-    }
1209
-
1210
-    /**
1211
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1212
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1213
-     *
1214
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1215
-     * we must be able to find all other tables.
1216
-     *
1217
-     * @param string[] $tables
1218
-     *
1219
-     * @return string[]
1220
-     */
1221
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1222
-    {
1223
-        $schemaAnalyzer = $this->schemaAnalyzer;
1224
-
1225
-        foreach ($tables as $currentTable) {
1226
-            $allParents = [$currentTable];
1227
-            $currentFk = null;
1228
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1229
-                $currentTable = $currentFk->getForeignTableName();
1230
-                $allParents[] = $currentTable;
1231
-            };
1232
-
1233
-            // Now, does the $allParents contain all the tables we want?
1234
-            $notFoundTables = array_diff($tables, $allParents);
1235
-            if (empty($notFoundTables)) {
1236
-                // We have a winner!
1237
-                return $allParents;
1238
-            }
1239
-        }
1240
-
1241
-        throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1242
-    }
1243
-
1244
-    /**
1245
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1246
-     *
1247
-     * @param string $table
1248
-     *
1249
-     * @return string[]
1250
-     */
1251
-    public function _getRelatedTablesByInheritance($table)
1252
-    {
1253
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1254
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1255
-        });
1256
-    }
1257
-
1258
-    /**
1259
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1260
-     *
1261
-     * @param string $table
1262
-     *
1263
-     * @return string[]
1264
-     */
1265
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1266
-    {
1267
-        $schemaAnalyzer = $this->schemaAnalyzer;
1268
-
1269
-        // Let's scan the parent tables
1270
-        $currentTable = $table;
1271
-
1272
-        $parentTables = [];
1273
-
1274
-        // Get parent relationship
1275
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1276
-            $currentTable = $currentFk->getForeignTableName();
1277
-            $parentTables[] = $currentTable;
1278
-        };
1279
-
1280
-        // Let's recurse in children
1281
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1282
-
1283
-        return array_merge(array_reverse($parentTables), $childrenTables);
1284
-    }
1285
-
1286
-    /**
1287
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1288
-     *
1289
-     * @param string $table
1290
-     *
1291
-     * @return string[]
1292
-     */
1293
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1294
-    {
1295
-        $tables = [$table];
1296
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1297
-
1298
-        foreach ($keys as $key) {
1299
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1300
-        }
1301
-
1302
-        return $tables;
1303
-    }
1304
-
1305
-    /**
1306
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1307
-     * The returned value does contain only one table. For instance:.
1308
-     *
1309
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1310
-     *
1311
-     * @param ForeignKeyConstraint $fk
1312
-     * @param bool                 $leftTableIsLocal
1313
-     *
1314
-     * @return string
1315
-     */
1316
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1184
+		}
1185
+
1186
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1187
+	}
1188
+
1189
+	/**
1190
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1191
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1192
+	 *
1193
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1194
+	 * we must be able to find all other tables.
1195
+	 *
1196
+	 * @param string[] $tables
1197
+	 *
1198
+	 * @return string[]
1199
+	 */
1200
+	public function _getLinkBetweenInheritedTables(array $tables)
1201
+	{
1202
+		sort($tables);
1203
+
1204
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1205
+			function () use ($tables) {
1206
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1207
+			});
1208
+	}
1209
+
1210
+	/**
1211
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1212
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1213
+	 *
1214
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1215
+	 * we must be able to find all other tables.
1216
+	 *
1217
+	 * @param string[] $tables
1218
+	 *
1219
+	 * @return string[]
1220
+	 */
1221
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1222
+	{
1223
+		$schemaAnalyzer = $this->schemaAnalyzer;
1224
+
1225
+		foreach ($tables as $currentTable) {
1226
+			$allParents = [$currentTable];
1227
+			$currentFk = null;
1228
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1229
+				$currentTable = $currentFk->getForeignTableName();
1230
+				$allParents[] = $currentTable;
1231
+			};
1232
+
1233
+			// Now, does the $allParents contain all the tables we want?
1234
+			$notFoundTables = array_diff($tables, $allParents);
1235
+			if (empty($notFoundTables)) {
1236
+				// We have a winner!
1237
+				return $allParents;
1238
+			}
1239
+		}
1240
+
1241
+		throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1242
+	}
1243
+
1244
+	/**
1245
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1246
+	 *
1247
+	 * @param string $table
1248
+	 *
1249
+	 * @return string[]
1250
+	 */
1251
+	public function _getRelatedTablesByInheritance($table)
1252
+	{
1253
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1254
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1255
+		});
1256
+	}
1257
+
1258
+	/**
1259
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1260
+	 *
1261
+	 * @param string $table
1262
+	 *
1263
+	 * @return string[]
1264
+	 */
1265
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1266
+	{
1267
+		$schemaAnalyzer = $this->schemaAnalyzer;
1268
+
1269
+		// Let's scan the parent tables
1270
+		$currentTable = $table;
1271
+
1272
+		$parentTables = [];
1273
+
1274
+		// Get parent relationship
1275
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1276
+			$currentTable = $currentFk->getForeignTableName();
1277
+			$parentTables[] = $currentTable;
1278
+		};
1279
+
1280
+		// Let's recurse in children
1281
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1282
+
1283
+		return array_merge(array_reverse($parentTables), $childrenTables);
1284
+	}
1285
+
1286
+	/**
1287
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1288
+	 *
1289
+	 * @param string $table
1290
+	 *
1291
+	 * @return string[]
1292
+	 */
1293
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1294
+	{
1295
+		$tables = [$table];
1296
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1297
+
1298
+		foreach ($keys as $key) {
1299
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1300
+		}
1301
+
1302
+		return $tables;
1303
+	}
1304
+
1305
+	/**
1306
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1307
+	 * The returned value does contain only one table. For instance:.
1308
+	 *
1309
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1310
+	 *
1311
+	 * @param ForeignKeyConstraint $fk
1312
+	 * @param bool                 $leftTableIsLocal
1313
+	 *
1314
+	 * @return string
1315
+	 */
1316
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1317 1317
         $onClauses = [];
1318 1318
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1319 1319
         $foreignColumns = $fk->getForeignColumns();
@@ -1339,348 +1339,348 @@  discard block
 block discarded – undo
1339 1339
         }
1340 1340
     }*/
1341 1341
 
1342
-    /**
1343
-     * Returns an identifier for the group of tables passed in parameter.
1344
-     *
1345
-     * @param string[] $relatedTables
1346
-     *
1347
-     * @return string
1348
-     */
1349
-    private function getTableGroupName(array $relatedTables)
1350
-    {
1351
-        sort($relatedTables);
1352
-
1353
-        return implode('_``_', $relatedTables);
1354
-    }
1355
-
1356
-    /**
1357
-     * @param string            $mainTable             The name of the table queried
1358
-     * @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)
1359
-     * @param array             $parameters
1360
-     * @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)
1361
-     * @param array             $additionalTablesFetch
1362
-     * @param string            $mode
1363
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned.
1364
-     *
1365
-     * @return ResultIterator An object representing an array of results.
1366
-     *
1367
-     * @throws TDBMException
1368
-     */
1369
-    public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null)
1370
-    {
1371
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1372
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1373
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1374
-        }
1375
-
1376
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1377
-
1378
-        $parameters = array_merge($parameters, $additionalParameters);
1379
-
1380
-        // From the table name and the additional tables we want to fetch, let's build a list of all tables
1381
-        // that must be part of the select columns.
1382
-
1383
-        $tableGroups = [];
1384
-        $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1385
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
1386
-        foreach ($allFetchedTables as $table) {
1387
-            $tableGroups[$table] = $tableGroupName;
1388
-        }
1389
-
1390
-        foreach ($additionalTablesFetch as $additionalTable) {
1391
-            $relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1392
-            $tableGroupName = $this->getTableGroupName($relatedTables);
1393
-            foreach ($relatedTables as $table) {
1394
-                $tableGroups[$table] = $tableGroupName;
1395
-            }
1396
-            $allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1397
-        }
1398
-
1399
-        // Let's remove any duplicate
1400
-        $allFetchedTables = array_flip(array_flip($allFetchedTables));
1401
-
1402
-        $columnsList = [];
1403
-        $columnDescList = [];
1404
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1405
-
1406
-        // Now, let's build the column list
1407
-        foreach ($allFetchedTables as $table) {
1408
-            foreach ($schema->getTable($table)->getColumns() as $column) {
1409
-                $columnName = $column->getName();
1410
-                $columnDescList[] = [
1411
-                    'as' => $table.'____'.$columnName,
1412
-                    'table' => $table,
1413
-                    'column' => $columnName,
1414
-                    'type' => $column->getType(),
1415
-                    'tableGroup' => $tableGroups[$table],
1416
-                ];
1417
-                $columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1418
-                    $this->connection->quoteIdentifier($table.'____'.$columnName);
1419
-            }
1420
-        }
1421
-
1422
-        $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')';
1423
-        $countSql = 'SELECT COUNT(1) FROM MAGICJOIN('.$mainTable.')';
1424
-
1425
-        if (!empty($filterString)) {
1426
-            $sql .= ' WHERE '.$filterString;
1427
-            $countSql .= ' WHERE '.$filterString;
1428
-        }
1429
-
1430
-        if (!empty($orderString)) {
1431
-            $sql .= ' ORDER BY '.$orderString;
1432
-            $countSql .= ' ORDER BY '.$orderString;
1433
-        }
1434
-
1435
-        if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1436
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1437
-        }
1438
-
1439
-        $mode = $mode ?: $this->mode;
1440
-
1441
-        return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode);
1442
-    }
1443
-
1444
-    /**
1445
-     * @param $table
1446
-     * @param array  $primaryKeys
1447
-     * @param array  $additionalTablesFetch
1448
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not.
1449
-     * @param string $className
1450
-     *
1451
-     * @return AbstractTDBMObject
1452
-     *
1453
-     * @throws TDBMException
1454
-     */
1455
-    public function findObjectByPk($table, array $primaryKeys, array $additionalTablesFetch = array(), $lazy = false, $className = null)
1456
-    {
1457
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1458
-        $hash = $this->getObjectHash($primaryKeys);
1459
-
1460
-        if ($this->objectStorage->has($table, $hash)) {
1461
-            $dbRow = $this->objectStorage->get($table, $hash);
1462
-            $bean = $dbRow->getTDBMObject();
1463
-            if ($className !== null && !is_a($bean, $className)) {
1464
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1465
-            }
1466
-
1467
-            return $bean;
1468
-        }
1469
-
1470
-        // Are we performing lazy fetching?
1471
-        if ($lazy === true) {
1472
-            // Can we perform lazy fetching?
1473
-            $tables = $this->_getRelatedTablesByInheritance($table);
1474
-            // Only allowed if no inheritance.
1475
-            if (count($tables) === 1) {
1476
-                if ($className === null) {
1477
-                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1478
-                }
1479
-
1480
-                // Let's construct the bean
1481
-                if (!isset($reflectionClassCache[$className])) {
1482
-                    $reflectionClassCache[$className] = new \ReflectionClass($className);
1483
-                }
1484
-                // Let's bypass the constructor when creating the bean!
1485
-                $bean = $reflectionClassCache[$className]->newInstanceWithoutConstructor();
1486
-                /* @var $bean AbstractTDBMObject */
1487
-                $bean->_constructLazy($table, $primaryKeys, $this);
1488
-            }
1489
-        }
1490
-
1491
-        // Did not find the object in cache? Let's query it!
1492
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1493
-    }
1494
-
1495
-    /**
1496
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1497
-     *
1498
-     * @param string      $mainTable             The name of the table queried
1499
-     * @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)
1500
-     * @param array       $parameters
1501
-     * @param array       $additionalTablesFetch
1502
-     * @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.
1503
-     *
1504
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters.
1505
-     *
1506
-     * @throws TDBMException
1507
-     */
1508
-    public function findObject($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null)
1509
-    {
1510
-        $objects = $this->findObjects($mainTable, $filterString, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1511
-        $page = $objects->take(0, 2);
1512
-        $count = $page->count();
1513
-        if ($count > 1) {
1514
-            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.");
1515
-        } elseif ($count === 0) {
1516
-            return;
1517
-        }
1518
-
1519
-        return $objects[0];
1520
-    }
1521
-
1522
-    /**
1523
-     * Returns a unique bean according to the filters passed in parameter.
1524
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1525
-     *
1526
-     * @param string      $mainTable             The name of the table queried
1527
-     * @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)
1528
-     * @param array       $parameters
1529
-     * @param array       $additionalTablesFetch
1530
-     * @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.
1531
-     *
1532
-     * @return AbstractTDBMObject The object we want
1533
-     *
1534
-     * @throws TDBMException
1535
-     */
1536
-    public function findObjectOrFail($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null)
1537
-    {
1538
-        $bean = $this->findObject($mainTable, $filterString, $parameters, $additionalTablesFetch, $className);
1539
-        if ($bean === null) {
1540
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1541
-        }
1542
-
1543
-        return $bean;
1544
-    }
1545
-
1546
-    /**
1547
-     * @param array $beanData An array of data: array<table, array<column, value>>
1548
-     *
1549
-     * @return array an array with first item = class name and second item = table name
1550
-     */
1551
-    public function _getClassNameFromBeanData(array $beanData)
1552
-    {
1553
-        if (count($beanData) === 1) {
1554
-            $tableName = array_keys($beanData)[0];
1555
-        } else {
1556
-            foreach ($beanData as $table => $row) {
1557
-                $tables = [];
1558
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1559
-                $pkSet = false;
1560
-                foreach ($primaryKeyColumns as $columnName) {
1561
-                    if ($row[$columnName] !== null) {
1562
-                        $pkSet = true;
1563
-                        break;
1564
-                    }
1565
-                }
1566
-                if ($pkSet) {
1567
-                    $tables[] = $table;
1568
-                }
1569
-            }
1570
-
1571
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1572
-            $allTables = $this->_getLinkBetweenInheritedTables($tables);
1573
-            $tableName = $allTables[0];
1574
-        }
1575
-
1576
-        // Only one table in this bean. Life is sweat, let's look at its type:
1577
-        if (isset($this->tableToBeanMap[$tableName])) {
1578
-            return [$this->tableToBeanMap[$tableName], $tableName];
1579
-        } else {
1580
-            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName];
1581
-        }
1582
-    }
1583
-
1584
-    /**
1585
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1586
-     *
1587
-     * @param string   $key
1588
-     * @param callable $closure
1589
-     *
1590
-     * @return mixed
1591
-     */
1592
-    private function fromCache($key, callable $closure)
1593
-    {
1594
-        $item = $this->cache->fetch($key);
1595
-        if ($item === false) {
1596
-            $item = $closure();
1597
-            $this->cache->save($key, $item);
1598
-        }
1599
-
1600
-        return $item;
1601
-    }
1602
-
1603
-    /**
1604
-     * Returns the foreign key object.
1605
-     *
1606
-     * @param string $table
1607
-     * @param string $fkName
1608
-     *
1609
-     * @return ForeignKeyConstraint
1610
-     */
1611
-    public function _getForeignKeyByName($table, $fkName)
1612
-    {
1613
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1614
-    }
1615
-
1616
-    /**
1617
-     * @param $pivotTableName
1618
-     * @param AbstractTDBMObject $bean
1619
-     *
1620
-     * @return AbstractTDBMObject[]
1621
-     */
1622
-    public function _getRelatedBeans($pivotTableName, AbstractTDBMObject $bean)
1623
-    {
1624
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1625
-        /* @var $localFk ForeignKeyConstraint */
1626
-        /* @var $remoteFk ForeignKeyConstraint */
1627
-        $remoteTable = $remoteFk->getForeignTableName();
1628
-
1629
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1630
-        $columnNames = array_map(function ($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns());
1631
-
1632
-        $filter = array_combine($columnNames, $primaryKeys);
1633
-
1634
-        return $this->findObjects($remoteTable, $filter);
1635
-    }
1636
-
1637
-    /**
1638
-     * @param $pivotTableName
1639
-     * @param AbstractTDBMObject $bean The LOCAL bean
1640
-     *
1641
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean.
1642
-     *
1643
-     * @throws TDBMException
1644
-     */
1645
-    private function getPivotTableForeignKeys($pivotTableName, AbstractTDBMObject $bean)
1646
-    {
1647
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1648
-        $table1 = $fks[0]->getForeignTableName();
1649
-        $table2 = $fks[1]->getForeignTableName();
1650
-
1651
-        $beanTables = array_map(function (DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows());
1652
-
1653
-        if (in_array($table1, $beanTables)) {
1654
-            return [$fks[0], $fks[1]];
1655
-        } elseif (in_array($table2, $beanTables)) {
1656
-            return [$fks[1], $fks[0]];
1657
-        } else {
1658
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1659
-        }
1660
-    }
1661
-
1662
-    /**
1663
-     * Returns a list of pivot tables linked to $bean.
1664
-     *
1665
-     * @param AbstractTDBMObject $bean
1666
-     *
1667
-     * @return string[]
1668
-     */
1669
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1670
-    {
1671
-        $junctionTables = [];
1672
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables();
1673
-        foreach ($bean->_getDbRows() as $dbRow) {
1674
-            foreach ($allJunctionTables as $table) {
1675
-                // There are exactly 2 FKs since this is a pivot table.
1676
-                $fks = array_values($table->getForeignKeys());
1677
-
1678
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1679
-                    $junctionTables[] = $table->getName();
1680
-                }
1681
-            }
1682
-        }
1683
-
1684
-        return $junctionTables;
1685
-    }
1342
+	/**
1343
+	 * Returns an identifier for the group of tables passed in parameter.
1344
+	 *
1345
+	 * @param string[] $relatedTables
1346
+	 *
1347
+	 * @return string
1348
+	 */
1349
+	private function getTableGroupName(array $relatedTables)
1350
+	{
1351
+		sort($relatedTables);
1352
+
1353
+		return implode('_``_', $relatedTables);
1354
+	}
1355
+
1356
+	/**
1357
+	 * @param string            $mainTable             The name of the table queried
1358
+	 * @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)
1359
+	 * @param array             $parameters
1360
+	 * @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)
1361
+	 * @param array             $additionalTablesFetch
1362
+	 * @param string            $mode
1363
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned.
1364
+	 *
1365
+	 * @return ResultIterator An object representing an array of results.
1366
+	 *
1367
+	 * @throws TDBMException
1368
+	 */
1369
+	public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null)
1370
+	{
1371
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1372
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1373
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1374
+		}
1375
+
1376
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1377
+
1378
+		$parameters = array_merge($parameters, $additionalParameters);
1379
+
1380
+		// From the table name and the additional tables we want to fetch, let's build a list of all tables
1381
+		// that must be part of the select columns.
1382
+
1383
+		$tableGroups = [];
1384
+		$allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1385
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
1386
+		foreach ($allFetchedTables as $table) {
1387
+			$tableGroups[$table] = $tableGroupName;
1388
+		}
1389
+
1390
+		foreach ($additionalTablesFetch as $additionalTable) {
1391
+			$relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1392
+			$tableGroupName = $this->getTableGroupName($relatedTables);
1393
+			foreach ($relatedTables as $table) {
1394
+				$tableGroups[$table] = $tableGroupName;
1395
+			}
1396
+			$allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1397
+		}
1398
+
1399
+		// Let's remove any duplicate
1400
+		$allFetchedTables = array_flip(array_flip($allFetchedTables));
1401
+
1402
+		$columnsList = [];
1403
+		$columnDescList = [];
1404
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1405
+
1406
+		// Now, let's build the column list
1407
+		foreach ($allFetchedTables as $table) {
1408
+			foreach ($schema->getTable($table)->getColumns() as $column) {
1409
+				$columnName = $column->getName();
1410
+				$columnDescList[] = [
1411
+					'as' => $table.'____'.$columnName,
1412
+					'table' => $table,
1413
+					'column' => $columnName,
1414
+					'type' => $column->getType(),
1415
+					'tableGroup' => $tableGroups[$table],
1416
+				];
1417
+				$columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1418
+					$this->connection->quoteIdentifier($table.'____'.$columnName);
1419
+			}
1420
+		}
1421
+
1422
+		$sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')';
1423
+		$countSql = 'SELECT COUNT(1) FROM MAGICJOIN('.$mainTable.')';
1424
+
1425
+		if (!empty($filterString)) {
1426
+			$sql .= ' WHERE '.$filterString;
1427
+			$countSql .= ' WHERE '.$filterString;
1428
+		}
1429
+
1430
+		if (!empty($orderString)) {
1431
+			$sql .= ' ORDER BY '.$orderString;
1432
+			$countSql .= ' ORDER BY '.$orderString;
1433
+		}
1434
+
1435
+		if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1436
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1437
+		}
1438
+
1439
+		$mode = $mode ?: $this->mode;
1440
+
1441
+		return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode);
1442
+	}
1443
+
1444
+	/**
1445
+	 * @param $table
1446
+	 * @param array  $primaryKeys
1447
+	 * @param array  $additionalTablesFetch
1448
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not.
1449
+	 * @param string $className
1450
+	 *
1451
+	 * @return AbstractTDBMObject
1452
+	 *
1453
+	 * @throws TDBMException
1454
+	 */
1455
+	public function findObjectByPk($table, array $primaryKeys, array $additionalTablesFetch = array(), $lazy = false, $className = null)
1456
+	{
1457
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1458
+		$hash = $this->getObjectHash($primaryKeys);
1459
+
1460
+		if ($this->objectStorage->has($table, $hash)) {
1461
+			$dbRow = $this->objectStorage->get($table, $hash);
1462
+			$bean = $dbRow->getTDBMObject();
1463
+			if ($className !== null && !is_a($bean, $className)) {
1464
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1465
+			}
1466
+
1467
+			return $bean;
1468
+		}
1469
+
1470
+		// Are we performing lazy fetching?
1471
+		if ($lazy === true) {
1472
+			// Can we perform lazy fetching?
1473
+			$tables = $this->_getRelatedTablesByInheritance($table);
1474
+			// Only allowed if no inheritance.
1475
+			if (count($tables) === 1) {
1476
+				if ($className === null) {
1477
+					$className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1478
+				}
1479
+
1480
+				// Let's construct the bean
1481
+				if (!isset($reflectionClassCache[$className])) {
1482
+					$reflectionClassCache[$className] = new \ReflectionClass($className);
1483
+				}
1484
+				// Let's bypass the constructor when creating the bean!
1485
+				$bean = $reflectionClassCache[$className]->newInstanceWithoutConstructor();
1486
+				/* @var $bean AbstractTDBMObject */
1487
+				$bean->_constructLazy($table, $primaryKeys, $this);
1488
+			}
1489
+		}
1490
+
1491
+		// Did not find the object in cache? Let's query it!
1492
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1493
+	}
1494
+
1495
+	/**
1496
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1497
+	 *
1498
+	 * @param string      $mainTable             The name of the table queried
1499
+	 * @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)
1500
+	 * @param array       $parameters
1501
+	 * @param array       $additionalTablesFetch
1502
+	 * @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.
1503
+	 *
1504
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters.
1505
+	 *
1506
+	 * @throws TDBMException
1507
+	 */
1508
+	public function findObject($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null)
1509
+	{
1510
+		$objects = $this->findObjects($mainTable, $filterString, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1511
+		$page = $objects->take(0, 2);
1512
+		$count = $page->count();
1513
+		if ($count > 1) {
1514
+			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.");
1515
+		} elseif ($count === 0) {
1516
+			return;
1517
+		}
1518
+
1519
+		return $objects[0];
1520
+	}
1521
+
1522
+	/**
1523
+	 * Returns a unique bean according to the filters passed in parameter.
1524
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1525
+	 *
1526
+	 * @param string      $mainTable             The name of the table queried
1527
+	 * @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)
1528
+	 * @param array       $parameters
1529
+	 * @param array       $additionalTablesFetch
1530
+	 * @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.
1531
+	 *
1532
+	 * @return AbstractTDBMObject The object we want
1533
+	 *
1534
+	 * @throws TDBMException
1535
+	 */
1536
+	public function findObjectOrFail($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null)
1537
+	{
1538
+		$bean = $this->findObject($mainTable, $filterString, $parameters, $additionalTablesFetch, $className);
1539
+		if ($bean === null) {
1540
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1541
+		}
1542
+
1543
+		return $bean;
1544
+	}
1545
+
1546
+	/**
1547
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1548
+	 *
1549
+	 * @return array an array with first item = class name and second item = table name
1550
+	 */
1551
+	public function _getClassNameFromBeanData(array $beanData)
1552
+	{
1553
+		if (count($beanData) === 1) {
1554
+			$tableName = array_keys($beanData)[0];
1555
+		} else {
1556
+			foreach ($beanData as $table => $row) {
1557
+				$tables = [];
1558
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1559
+				$pkSet = false;
1560
+				foreach ($primaryKeyColumns as $columnName) {
1561
+					if ($row[$columnName] !== null) {
1562
+						$pkSet = true;
1563
+						break;
1564
+					}
1565
+				}
1566
+				if ($pkSet) {
1567
+					$tables[] = $table;
1568
+				}
1569
+			}
1570
+
1571
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1572
+			$allTables = $this->_getLinkBetweenInheritedTables($tables);
1573
+			$tableName = $allTables[0];
1574
+		}
1575
+
1576
+		// Only one table in this bean. Life is sweat, let's look at its type:
1577
+		if (isset($this->tableToBeanMap[$tableName])) {
1578
+			return [$this->tableToBeanMap[$tableName], $tableName];
1579
+		} else {
1580
+			return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName];
1581
+		}
1582
+	}
1583
+
1584
+	/**
1585
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1586
+	 *
1587
+	 * @param string   $key
1588
+	 * @param callable $closure
1589
+	 *
1590
+	 * @return mixed
1591
+	 */
1592
+	private function fromCache($key, callable $closure)
1593
+	{
1594
+		$item = $this->cache->fetch($key);
1595
+		if ($item === false) {
1596
+			$item = $closure();
1597
+			$this->cache->save($key, $item);
1598
+		}
1599
+
1600
+		return $item;
1601
+	}
1602
+
1603
+	/**
1604
+	 * Returns the foreign key object.
1605
+	 *
1606
+	 * @param string $table
1607
+	 * @param string $fkName
1608
+	 *
1609
+	 * @return ForeignKeyConstraint
1610
+	 */
1611
+	public function _getForeignKeyByName($table, $fkName)
1612
+	{
1613
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1614
+	}
1615
+
1616
+	/**
1617
+	 * @param $pivotTableName
1618
+	 * @param AbstractTDBMObject $bean
1619
+	 *
1620
+	 * @return AbstractTDBMObject[]
1621
+	 */
1622
+	public function _getRelatedBeans($pivotTableName, AbstractTDBMObject $bean)
1623
+	{
1624
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1625
+		/* @var $localFk ForeignKeyConstraint */
1626
+		/* @var $remoteFk ForeignKeyConstraint */
1627
+		$remoteTable = $remoteFk->getForeignTableName();
1628
+
1629
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1630
+		$columnNames = array_map(function ($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns());
1631
+
1632
+		$filter = array_combine($columnNames, $primaryKeys);
1633
+
1634
+		return $this->findObjects($remoteTable, $filter);
1635
+	}
1636
+
1637
+	/**
1638
+	 * @param $pivotTableName
1639
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1640
+	 *
1641
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean.
1642
+	 *
1643
+	 * @throws TDBMException
1644
+	 */
1645
+	private function getPivotTableForeignKeys($pivotTableName, AbstractTDBMObject $bean)
1646
+	{
1647
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1648
+		$table1 = $fks[0]->getForeignTableName();
1649
+		$table2 = $fks[1]->getForeignTableName();
1650
+
1651
+		$beanTables = array_map(function (DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows());
1652
+
1653
+		if (in_array($table1, $beanTables)) {
1654
+			return [$fks[0], $fks[1]];
1655
+		} elseif (in_array($table2, $beanTables)) {
1656
+			return [$fks[1], $fks[0]];
1657
+		} else {
1658
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1659
+		}
1660
+	}
1661
+
1662
+	/**
1663
+	 * Returns a list of pivot tables linked to $bean.
1664
+	 *
1665
+	 * @param AbstractTDBMObject $bean
1666
+	 *
1667
+	 * @return string[]
1668
+	 */
1669
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1670
+	{
1671
+		$junctionTables = [];
1672
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables();
1673
+		foreach ($bean->_getDbRows() as $dbRow) {
1674
+			foreach ($allJunctionTables as $table) {
1675
+				// There are exactly 2 FKs since this is a pivot table.
1676
+				$fks = array_values($table->getForeignKeys());
1677
+
1678
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1679
+					$junctionTables[] = $table->getName();
1680
+				}
1681
+			}
1682
+		}
1683
+
1684
+		return $junctionTables;
1685
+	}
1686 1686
 }
Please login to merge, or discard this patch.