Passed
Pull Request — 4.2 (#140)
by David
09:31
created
src/Mouf/Database/TDBM/TDBMCyclicReferenceException.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -4,13 +4,13 @@
 block discarded – undo
4 4
 
5 5
 class TDBMCyclicReferenceException extends TDBMException
6 6
 {
7
-    public static function createCyclicReference(string $tableName, AbstractTDBMObject $object) : TDBMCyclicReferenceException
8
-    {
9
-        return new self(sprintf("You are trying a grape of objects that reference each other. Unable to save object '%s' in table '%s'. It is already in the process of being saved.", get_class($object), $tableName));
10
-    }
7
+	public static function createCyclicReference(string $tableName, AbstractTDBMObject $object) : TDBMCyclicReferenceException
8
+	{
9
+		return new self(sprintf("You are trying a grape of objects that reference each other. Unable to save object '%s' in table '%s'. It is already in the process of being saved.", get_class($object), $tableName));
10
+	}
11 11
 
12
-    public static function extendCyclicReference(TDBMCyclicReferenceException $e, string $tableName, AbstractTDBMObject $object, string $fkName) : TDBMCyclicReferenceException
13
-    {
14
-        return new self($e->getMessage().sprintf(" This object is referenced by an object of type '%s' (table '%s') via foreign key '%s'", get_class($object), $tableName, $fkName), $e->getCode(), $e);
15
-    }
12
+	public static function extendCyclicReference(TDBMCyclicReferenceException $e, string $tableName, AbstractTDBMObject $object, string $fkName) : TDBMCyclicReferenceException
13
+	{
14
+		return new self($e->getMessage().sprintf(" This object is referenced by an object of type '%s' (table '%s') via foreign key '%s'", get_class($object), $tableName, $fkName), $e->getCode(), $e);
15
+	}
16 16
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMMissingReferenceException.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@
 block discarded – undo
4 4
 
5 5
 class TDBMMissingReferenceException extends TDBMException
6 6
 {
7
-    public static function referenceDeleted(string $tableName, AbstractTDBMObject $reference) : TDBMMissingReferenceException
8
-    {
9
-        return new self(sprintf("Unable to save object in table '%s'. Your object references an object of type '%s' that is deleted.", $tableName, get_class($reference)));
10
-    }
7
+	public static function referenceDeleted(string $tableName, AbstractTDBMObject $reference) : TDBMMissingReferenceException
8
+	{
9
+		return new self(sprintf("Unable to save object in table '%s'. Your object references an object of type '%s' that is deleted.", $tableName, get_class($reference)));
10
+	}
11 11
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/DbRow.php 2 patches
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -27,170 +27,170 @@  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
-            $row = $result->fetch(\PDO::FETCH_ASSOC);
173
-
174
-            $this->dbRow = [];
175
-            $types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
-
177
-            foreach ($row as $key => $value) {
178
-                $this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
-            }
180
-
181
-            $result->closeCursor();
182
-
183
-            $this->status = TDBMObjectStateEnum::STATE_LOADED;
184
-        }
185
-    }
186
-
187
-    public function get($var)
188
-    {
189
-        $this->_dbLoadIfNotLoaded();
190
-
191
-        // Let's first check if the key exist.
192
-        if (!isset($this->dbRow[$var])) {
193
-            /*
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
+			$row = $result->fetch(\PDO::FETCH_ASSOC);
173
+
174
+			$this->dbRow = [];
175
+			$types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
+
177
+			foreach ($row as $key => $value) {
178
+				$this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
+			}
180
+
181
+			$result->closeCursor();
182
+
183
+			$this->status = TDBMObjectStateEnum::STATE_LOADED;
184
+		}
185
+	}
186
+
187
+	public function get($var)
188
+	{
189
+		$this->_dbLoadIfNotLoaded();
190
+
191
+		// Let's first check if the key exist.
192
+		if (!isset($this->dbRow[$var])) {
193
+			/*
194 194
             // Unable to find column.... this is an error if the object has been retrieved from database.
195 195
             // If it's a new object, well, that may not be an error after all!
196 196
             // Let's check if the column does exist in the table
@@ -210,39 +210,39 @@  discard block
 block discarded – undo
210 210
             $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
211 211
 
212 212
             throw new TDBMException($str);*/
213
-            return;
214
-        }
215
-
216
-        $value = $this->dbRow[$var];
217
-        if ($value instanceof \DateTime) {
218
-            if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
-                return \DateTimeImmutable::createFromMutable($value);
220
-            } else {
221
-                return new \DateTimeImmutable($value->format('c'));
222
-            }
223
-        }
224
-
225
-        return $this->dbRow[$var];
226
-    }
227
-
228
-    /**
229
-     * Returns true if a column is set, false otherwise.
230
-     *
231
-     * @param string $var
232
-     *
233
-     * @return bool
234
-     */
235
-    /*public function has($var) {
213
+			return;
214
+		}
215
+
216
+		$value = $this->dbRow[$var];
217
+		if ($value instanceof \DateTime) {
218
+			if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
+				return \DateTimeImmutable::createFromMutable($value);
220
+			} else {
221
+				return new \DateTimeImmutable($value->format('c'));
222
+			}
223
+		}
224
+
225
+		return $this->dbRow[$var];
226
+	}
227
+
228
+	/**
229
+	 * Returns true if a column is set, false otherwise.
230
+	 *
231
+	 * @param string $var
232
+	 *
233
+	 * @return bool
234
+	 */
235
+	/*public function has($var) {
236 236
         $this->_dbLoadIfNotLoaded();
237 237
 
238 238
         return isset($this->dbRow[$var]);
239 239
     }*/
240 240
 
241
-    public function set($var, $value)
242
-    {
243
-        $this->_dbLoadIfNotLoaded();
241
+	public function set($var, $value)
242
+	{
243
+		$this->_dbLoadIfNotLoaded();
244 244
 
245
-        /*
245
+		/*
246 246
         // Ok, let's start by checking the column type
247 247
         $type = $this->db_connection->getColumnType($this->dbTableName, $var);
248 248
 
@@ -252,198 +252,198 @@  discard block
 block discarded – undo
252 252
         }
253 253
         */
254 254
 
255
-        /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
255
+		/*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
256 256
             throw new TDBMException("Error! Changing primary key value is forbidden.");*/
257
-        $this->dbRow[$var] = $value;
258
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
-            $this->tdbmService->_addToToSaveObjectList($this);
261
-        }
262
-    }
263
-
264
-    /**
265
-     * @param string             $foreignKeyName
266
-     * @param AbstractTDBMObject $bean
267
-     */
268
-    public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
-    {
270
-        $this->references[$foreignKeyName] = $bean;
271
-
272
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
-            $this->tdbmService->_addToToSaveObjectList($this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    public function getRef($foreignKeyName)
284
-    {
285
-        if (array_key_exists($foreignKeyName, $this->references)) {
286
-            return $this->references[$foreignKeyName];
287
-        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
288
-            // If the object is new and has no property, then it has to be empty.
289
-            return;
290
-        } else {
291
-            $this->_dbLoadIfNotLoaded();
292
-
293
-            // Let's match the name of the columns to the primary key values
294
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
-
296
-            $values = [];
297
-            foreach ($fk->getLocalColumns() as $column) {
298
-                if (!isset($this->dbRow[$column])) {
299
-                    return;
300
-                }
301
-                $values[] = $this->dbRow[$column];
302
-            }
303
-
304
-            $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
-
306
-            return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
-        }
308
-    }
309
-
310
-    /**
311
-     * Returns the name of the table this object comes from.
312
-     *
313
-     * @return string
314
-     */
315
-    public function _getDbTableName()
316
-    {
317
-        return $this->dbTableName;
318
-    }
319
-
320
-    /**
321
-     * Method used internally by TDBM. You should not use it directly.
322
-     * This method returns the status of the TDBMObject.
323
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
-     *
328
-     * @return string
329
-     */
330
-    public function _getStatus()
331
-    {
332
-        return $this->status;
333
-    }
334
-
335
-    /**
336
-     * Override the native php clone function for TDBMObjects.
337
-     */
338
-    public function __clone()
339
-    {
340
-        // Let's load the row (before we lose the ID!)
341
-        $this->_dbLoadIfNotLoaded();
342
-
343
-        //Let's set the status to detached
344
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
-
346
-        $this->primaryKeys = [];
347
-
348
-        //Now unset the PK from the row
349
-        if ($this->tdbmService) {
350
-            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
-            foreach ($pk_array as $pk) {
352
-                $this->dbRow[$pk] = null;
353
-            }
354
-        }
355
-    }
356
-
357
-    /**
358
-     * Returns raw database row.
359
-     *
360
-     * @return array
361
-     *
362
-     * @throws TDBMMissingReferenceException
363
-     */
364
-    public function _getDbRow()
365
-    {
366
-        // Let's merge $dbRow and $references
367
-        $dbRow = $this->dbRow;
368
-
369
-        foreach ($this->references as $foreignKeyName => $reference) {
370
-            // Let's match the name of the columns to the primary key values
371
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
372
-            $localColumns = $fk->getLocalColumns();
373
-
374
-            if ($reference !== null) {
375
-                $refDbRows = $reference->_getDbRows();
376
-                $firstRefDbRow = reset($refDbRows);
377
-                if ($firstRefDbRow->_getStatus() == TDBMObjectStateEnum::STATE_DELETED) {
378
-                    throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
379
-                }
380
-                $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
381
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
382
-                    $dbRow[$localColumns[$i]] = $pkValues[$i];
383
-                }
384
-            } else {
385
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
386
-                    $dbRow[$localColumns[$i]] = null;
387
-                }
388
-            }
389
-        }
390
-
391
-        return $dbRow;
392
-    }
393
-
394
-    /**
395
-     * Returns references array.
396
-     *
397
-     * @return AbstractTDBMObject[]
398
-     */
399
-    public function _getReferences()
400
-    {
401
-        return $this->references;
402
-    }
403
-
404
-    /**
405
-     * Returns the values of the primary key.
406
-     * This is set when the object is in "loaded" state.
407
-     *
408
-     * @return array
409
-     */
410
-    public function _getPrimaryKeys()
411
-    {
412
-        return $this->primaryKeys;
413
-    }
414
-
415
-    /**
416
-     * Sets the values of the primary key.
417
-     * This is set when the object is in "loaded" state.
418
-     *
419
-     * @param array $primaryKeys
420
-     */
421
-    public function _setPrimaryKeys(array $primaryKeys)
422
-    {
423
-        $this->primaryKeys = $primaryKeys;
424
-        foreach ($this->primaryKeys as $column => $value) {
425
-            $this->dbRow[$column] = $value;
426
-        }
427
-    }
428
-
429
-    /**
430
-     * Returns the TDBMObject this bean is associated to.
431
-     *
432
-     * @return AbstractTDBMObject
433
-     */
434
-    public function getTDBMObject()
435
-    {
436
-        return $this->object;
437
-    }
438
-
439
-    /**
440
-     * Sets the TDBMObject this bean is associated to.
441
-     * Only used when cloning.
442
-     *
443
-     * @param AbstractTDBMObject $object
444
-     */
445
-    public function setTDBMObject(AbstractTDBMObject $object)
446
-    {
447
-        $this->object = $object;
448
-    }
257
+		$this->dbRow[$var] = $value;
258
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
+			$this->tdbmService->_addToToSaveObjectList($this);
261
+		}
262
+	}
263
+
264
+	/**
265
+	 * @param string             $foreignKeyName
266
+	 * @param AbstractTDBMObject $bean
267
+	 */
268
+	public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
+	{
270
+		$this->references[$foreignKeyName] = $bean;
271
+
272
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
+			$this->tdbmService->_addToToSaveObjectList($this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	public function getRef($foreignKeyName)
284
+	{
285
+		if (array_key_exists($foreignKeyName, $this->references)) {
286
+			return $this->references[$foreignKeyName];
287
+		} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
288
+			// If the object is new and has no property, then it has to be empty.
289
+			return;
290
+		} else {
291
+			$this->_dbLoadIfNotLoaded();
292
+
293
+			// Let's match the name of the columns to the primary key values
294
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
+
296
+			$values = [];
297
+			foreach ($fk->getLocalColumns() as $column) {
298
+				if (!isset($this->dbRow[$column])) {
299
+					return;
300
+				}
301
+				$values[] = $this->dbRow[$column];
302
+			}
303
+
304
+			$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
+
306
+			return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
+		}
308
+	}
309
+
310
+	/**
311
+	 * Returns the name of the table this object comes from.
312
+	 *
313
+	 * @return string
314
+	 */
315
+	public function _getDbTableName()
316
+	{
317
+		return $this->dbTableName;
318
+	}
319
+
320
+	/**
321
+	 * Method used internally by TDBM. You should not use it directly.
322
+	 * This method returns the status of the TDBMObject.
323
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
+	 *
328
+	 * @return string
329
+	 */
330
+	public function _getStatus()
331
+	{
332
+		return $this->status;
333
+	}
334
+
335
+	/**
336
+	 * Override the native php clone function for TDBMObjects.
337
+	 */
338
+	public function __clone()
339
+	{
340
+		// Let's load the row (before we lose the ID!)
341
+		$this->_dbLoadIfNotLoaded();
342
+
343
+		//Let's set the status to detached
344
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
+
346
+		$this->primaryKeys = [];
347
+
348
+		//Now unset the PK from the row
349
+		if ($this->tdbmService) {
350
+			$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
+			foreach ($pk_array as $pk) {
352
+				$this->dbRow[$pk] = null;
353
+			}
354
+		}
355
+	}
356
+
357
+	/**
358
+	 * Returns raw database row.
359
+	 *
360
+	 * @return array
361
+	 *
362
+	 * @throws TDBMMissingReferenceException
363
+	 */
364
+	public function _getDbRow()
365
+	{
366
+		// Let's merge $dbRow and $references
367
+		$dbRow = $this->dbRow;
368
+
369
+		foreach ($this->references as $foreignKeyName => $reference) {
370
+			// Let's match the name of the columns to the primary key values
371
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
372
+			$localColumns = $fk->getLocalColumns();
373
+
374
+			if ($reference !== null) {
375
+				$refDbRows = $reference->_getDbRows();
376
+				$firstRefDbRow = reset($refDbRows);
377
+				if ($firstRefDbRow->_getStatus() == TDBMObjectStateEnum::STATE_DELETED) {
378
+					throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
379
+				}
380
+				$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
381
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
382
+					$dbRow[$localColumns[$i]] = $pkValues[$i];
383
+				}
384
+			} else {
385
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
386
+					$dbRow[$localColumns[$i]] = null;
387
+				}
388
+			}
389
+		}
390
+
391
+		return $dbRow;
392
+	}
393
+
394
+	/**
395
+	 * Returns references array.
396
+	 *
397
+	 * @return AbstractTDBMObject[]
398
+	 */
399
+	public function _getReferences()
400
+	{
401
+		return $this->references;
402
+	}
403
+
404
+	/**
405
+	 * Returns the values of the primary key.
406
+	 * This is set when the object is in "loaded" state.
407
+	 *
408
+	 * @return array
409
+	 */
410
+	public function _getPrimaryKeys()
411
+	{
412
+		return $this->primaryKeys;
413
+	}
414
+
415
+	/**
416
+	 * Sets the values of the primary key.
417
+	 * This is set when the object is in "loaded" state.
418
+	 *
419
+	 * @param array $primaryKeys
420
+	 */
421
+	public function _setPrimaryKeys(array $primaryKeys)
422
+	{
423
+		$this->primaryKeys = $primaryKeys;
424
+		foreach ($this->primaryKeys as $column => $value) {
425
+			$this->dbRow[$column] = $value;
426
+		}
427
+	}
428
+
429
+	/**
430
+	 * Returns the TDBMObject this bean is associated to.
431
+	 *
432
+	 * @return AbstractTDBMObject
433
+	 */
434
+	public function getTDBMObject()
435
+	{
436
+		return $this->object;
437
+	}
438
+
439
+	/**
440
+	 * Sets the TDBMObject this bean is associated to.
441
+	 * Only used when cloning.
442
+	 *
443
+	 * @param AbstractTDBMObject $object
444
+	 */
445
+	public function setTDBMObject(AbstractTDBMObject $object)
446
+	{
447
+		$this->object = $object;
448
+	}
449 449
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -378,11 +378,11 @@
 block discarded – undo
378 378
                     throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
379 379
                 }
380 380
                 $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
381
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
381
+                for ($i = 0, $count = count($localColumns); $i<$count; ++$i) {
382 382
                     $dbRow[$localColumns[$i]] = $pkValues[$i];
383 383
                 }
384 384
             } else {
385
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
385
+                for ($i = 0, $count = count($localColumns); $i<$count; ++$i) {
386 386
                     $dbRow[$localColumns[$i]] = null;
387 387
                 }
388 388
             }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMObjectStateEnum.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -27,11 +27,11 @@
 block discarded – undo
27 27
  */
28 28
 final class TDBMObjectStateEnum
29 29
 {
30
-    const STATE_DETACHED = 'detached';
31
-    const STATE_NEW = 'new';
32
-    const STATE_SAVING = 'saving';
33
-    const STATE_NOT_LOADED = 'not loaded';
34
-    const STATE_LOADED = 'loaded';
35
-    const STATE_DIRTY = 'dirty';
36
-    const STATE_DELETED = 'deleted';
30
+	const STATE_DETACHED = 'detached';
31
+	const STATE_NEW = 'new';
32
+	const STATE_SAVING = 'saving';
33
+	const STATE_NOT_LOADED = 'not loaded';
34
+	const STATE_LOADED = 'loaded';
35
+	const STATE_DIRTY = 'dirty';
36
+	const STATE_DELETED = 'deleted';
37 37
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/AbstractTDBMObject.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
     private function checkTableName($tableName = null)
198 198
     {
199 199
         if ($tableName === null) {
200
-            if (count($this->dbRows) > 1) {
200
+            if (count($this->dbRows)>1) {
201 201
                 throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
202 202
             } elseif (count($this->dbRows) === 1) {
203 203
                 $tableName = array_keys($this->dbRows)[0];
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
     protected function set($var, $value, $tableName = null)
222 222
     {
223 223
         if ($tableName === null) {
224
-            if (count($this->dbRows) > 1) {
224
+            if (count($this->dbRows)>1) {
225 225
                 throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226 226
             } elseif (count($this->dbRows) === 1) {
227 227
                 $tableName = array_keys($this->dbRows)[0];
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
     protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248 248
     {
249 249
         if ($tableName === null) {
250
-            if (count($this->dbRows) > 1) {
250
+            if (count($this->dbRows)>1) {
251 251
                 throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252 252
             } elseif (count($this->dbRows) === 1) {
253 253
                 $tableName = array_keys($this->dbRows)[0];
Please login to merge, or discard this patch.
Indentation   +606 added lines, -606 removed lines patch added patch discarded remove patch
@@ -31,615 +31,615 @@
 block discarded – undo
31 31
  */
32 32
 abstract class AbstractTDBMObject implements JsonSerializable
33 33
 {
34
-    /**
35
-     * The service this object is bound to.
36
-     *
37
-     * @var TDBMService
38
-     */
39
-    protected $tdbmService;
40
-
41
-    /**
42
-     * An array of DbRow, indexed by table name.
43
-     *
44
-     * @var DbRow[]
45
-     */
46
-    protected $dbRows = [];
47
-
48
-    /**
49
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
50
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
51
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
52
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
53
-     *
54
-     * @var string
55
-     */
56
-    private $status;
57
-
58
-    /**
59
-     * Array storing beans related via many to many relationships (pivot tables).
60
-     *
61
-     * @var \SplObjectStorage[] Key: pivot table name, value: SplObjectStorage
62
-     */
63
-    private $relationships = [];
64
-
65
-    /**
66
-     * @var bool[] Key: pivot table name, value: whether a query was performed to load the data
67
-     */
68
-    private $loadedRelationships = [];
69
-
70
-    /**
71
-     * Array storing beans related via many to one relationships (this bean is pointed by external beans).
72
-     *
73
-     * @var AlterableResultIterator[] Key: [external_table]___[external_column], value: SplObjectStorage
74
-     */
75
-    private $manyToOneRelationships = [];
76
-
77
-    /**
78
-     * Used with $primaryKeys when we want to retrieve an existing object
79
-     * and $primaryKeys=[] if we want a new object.
80
-     *
81
-     * @param string      $tableName
82
-     * @param array       $primaryKeys
83
-     * @param TDBMService $tdbmService
84
-     *
85
-     * @throws TDBMException
86
-     * @throws TDBMInvalidOperationException
87
-     */
88
-    public function __construct($tableName = null, array $primaryKeys = [], TDBMService $tdbmService = null)
89
-    {
90
-        // FIXME: lazy loading should be forbidden on tables with inheritance and dynamic type assignation...
91
-        if (!empty($tableName)) {
92
-            $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
93
-        }
94
-
95
-        if ($tdbmService === null) {
96
-            $this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
97
-        } else {
98
-            $this->_attach($tdbmService);
99
-            if (!empty($primaryKeys)) {
100
-                $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
101
-            } else {
102
-                $this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
103
-            }
104
-        }
105
-    }
106
-
107
-    /**
108
-     * Alternative constructor called when data is fetched from database via a SELECT.
109
-     *
110
-     * @param array       $beanData    array<table, array<column, value>>
111
-     * @param TDBMService $tdbmService
112
-     */
113
-    public function _constructFromData(array $beanData, TDBMService $tdbmService)
114
-    {
115
-        $this->tdbmService = $tdbmService;
116
-
117
-        foreach ($beanData as $table => $columns) {
118
-            $this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
119
-        }
120
-
121
-        $this->status = TDBMObjectStateEnum::STATE_LOADED;
122
-    }
123
-
124
-    /**
125
-     * Alternative constructor called when bean is lazily loaded.
126
-     *
127
-     * @param string      $tableName
128
-     * @param array       $primaryKeys
129
-     * @param TDBMService $tdbmService
130
-     */
131
-    public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
132
-    {
133
-        $this->tdbmService = $tdbmService;
134
-
135
-        $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
136
-
137
-        $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
138
-    }
139
-
140
-    public function _attach(TDBMService $tdbmService)
141
-    {
142
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
143
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
144
-        }
145
-        $this->tdbmService = $tdbmService;
146
-
147
-        // If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
148
-        $tableNames = $this->getUsedTables();
149
-
150
-        $newDbRows = [];
151
-
152
-        foreach ($tableNames as $table) {
153
-            if (!isset($this->dbRows[$table])) {
154
-                $this->registerTable($table);
155
-            }
156
-            $newDbRows[$table] = $this->dbRows[$table];
157
-        }
158
-        $this->dbRows = $newDbRows;
159
-
160
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
161
-        foreach ($this->dbRows as $dbRow) {
162
-            $dbRow->_attach($tdbmService);
163
-        }
164
-    }
165
-
166
-    /**
167
-     * Sets the state of the TDBM Object
168
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
169
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
170
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
171
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
172
-     *
173
-     * @param string $state
174
-     */
175
-    public function _setStatus($state)
176
-    {
177
-        $this->status = $state;
178
-
179
-        // TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
180
-        foreach ($this->dbRows as $dbRow) {
181
-            $dbRow->_setStatus($state);
182
-        }
183
-
184
-        if ($state === TDBMObjectStateEnum::STATE_DELETED) {
185
-            $this->onDelete();
186
-        }
187
-    }
188
-
189
-    /**
190
-     * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
191
-     * or throws an error.
192
-     *
193
-     * @param string $tableName
194
-     *
195
-     * @return string
196
-     */
197
-    private function checkTableName($tableName = null)
198
-    {
199
-        if ($tableName === null) {
200
-            if (count($this->dbRows) > 1) {
201
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
202
-            } elseif (count($this->dbRows) === 1) {
203
-                $tableName = array_keys($this->dbRows)[0];
204
-            }
205
-        }
206
-
207
-        return $tableName;
208
-    }
209
-
210
-    protected function get($var, $tableName = null)
211
-    {
212
-        $tableName = $this->checkTableName($tableName);
213
-
214
-        if (!isset($this->dbRows[$tableName])) {
215
-            return;
216
-        }
217
-
218
-        return $this->dbRows[$tableName]->get($var);
219
-    }
220
-
221
-    protected function set($var, $value, $tableName = null)
222
-    {
223
-        if ($tableName === null) {
224
-            if (count($this->dbRows) > 1) {
225
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226
-            } elseif (count($this->dbRows) === 1) {
227
-                $tableName = array_keys($this->dbRows)[0];
228
-            } else {
229
-                throw new TDBMException('Please specify a table for this object.');
230
-            }
231
-        }
232
-
233
-        if (!isset($this->dbRows[$tableName])) {
234
-            $this->registerTable($tableName);
235
-        }
236
-
237
-        $this->dbRows[$tableName]->set($var, $value);
238
-        if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
239
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
240
-        }
241
-    }
242
-
243
-    /**
244
-     * @param string             $foreignKeyName
245
-     * @param AbstractTDBMObject $bean
246
-     */
247
-    protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248
-    {
249
-        if ($tableName === null) {
250
-            if (count($this->dbRows) > 1) {
251
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252
-            } elseif (count($this->dbRows) === 1) {
253
-                $tableName = array_keys($this->dbRows)[0];
254
-            } else {
255
-                throw new TDBMException('Please specify a table for this object.');
256
-            }
257
-        }
258
-
259
-        if (!isset($this->dbRows[$tableName])) {
260
-            $this->registerTable($tableName);
261
-        }
262
-
263
-        $oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
264
-        if ($oldLinkedBean !== null) {
265
-            $oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
266
-        }
267
-
268
-        $this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
269
-        if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
270
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
271
-        }
272
-
273
-        if ($bean !== null) {
274
-            $bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    protected function getRef($foreignKeyName, $tableName = null)
284
-    {
285
-        $tableName = $this->checkTableName($tableName);
286
-
287
-        if (!isset($this->dbRows[$tableName])) {
288
-            return;
289
-        }
290
-
291
-        return $this->dbRows[$tableName]->getRef($foreignKeyName);
292
-    }
293
-
294
-    /**
295
-     * Adds a many to many relationship to this bean.
296
-     *
297
-     * @param string             $pivotTableName
298
-     * @param AbstractTDBMObject $remoteBean
299
-     */
300
-    protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
301
-    {
302
-        $this->setRelationship($pivotTableName, $remoteBean, 'new');
303
-    }
304
-
305
-    /**
306
-     * Returns true if there is a relationship to this bean.
307
-     *
308
-     * @param string             $pivotTableName
309
-     * @param AbstractTDBMObject $remoteBean
310
-     *
311
-     * @return bool
312
-     */
313
-    protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
314
-    {
315
-        $storage = $this->retrieveRelationshipsStorage($pivotTableName);
316
-
317
-        if ($storage->contains($remoteBean)) {
318
-            if ($storage[$remoteBean]['status'] !== 'delete') {
319
-                return true;
320
-            }
321
-        }
322
-
323
-        return false;
324
-    }
325
-
326
-    /**
327
-     * Internal TDBM method. Removes a many to many relationship from this bean.
328
-     *
329
-     * @param string             $pivotTableName
330
-     * @param AbstractTDBMObject $remoteBean
331
-     */
332
-    public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
333
-    {
334
-        if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
335
-            unset($this->relationships[$pivotTableName][$remoteBean]);
336
-            unset($remoteBean->relationships[$pivotTableName][$this]);
337
-        } else {
338
-            $this->setRelationship($pivotTableName, $remoteBean, 'delete');
339
-        }
340
-    }
341
-
342
-    /**
343
-     * Sets many to many relationships for this bean.
344
-     * Adds new relationships and removes unused ones.
345
-     *
346
-     * @param $pivotTableName
347
-     * @param array $remoteBeans
348
-     */
349
-    protected function setRelationships($pivotTableName, array $remoteBeans)
350
-    {
351
-        $storage = $this->retrieveRelationshipsStorage($pivotTableName);
352
-
353
-        foreach ($storage as $oldRemoteBean) {
354
-            if (!in_array($oldRemoteBean, $remoteBeans, true)) {
355
-                // $oldRemoteBean must be removed
356
-                $this->_removeRelationship($pivotTableName, $oldRemoteBean);
357
-            }
358
-        }
359
-
360
-        foreach ($remoteBeans as $remoteBean) {
361
-            if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
362
-                // $remoteBean must be added
363
-                $this->addRelationship($pivotTableName, $remoteBean);
364
-            }
365
-        }
366
-    }
367
-
368
-    /**
369
-     * Returns the list of objects linked to this bean via $pivotTableName.
370
-     *
371
-     * @param $pivotTableName
372
-     *
373
-     * @return \SplObjectStorage
374
-     */
375
-    private function retrieveRelationshipsStorage($pivotTableName)
376
-    {
377
-        $storage = $this->getRelationshipStorage($pivotTableName);
378
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
379
-            return $storage;
380
-        }
381
-
382
-        $beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
383
-        $this->loadedRelationships[$pivotTableName] = true;
384
-
385
-        foreach ($beans as $bean) {
386
-            if (isset($storage[$bean])) {
387
-                $oldStatus = $storage[$bean]['status'];
388
-                if ($oldStatus === 'delete') {
389
-                    // Keep deleted things deleted
390
-                    continue;
391
-                }
392
-            }
393
-            $this->setRelationship($pivotTableName, $bean, 'loaded');
394
-        }
395
-
396
-        return $storage;
397
-    }
398
-
399
-    /**
400
-     * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
401
-     *
402
-     * @param $pivotTableName
403
-     *
404
-     * @return AbstractTDBMObject[]
405
-     */
406
-    public function _getRelationships($pivotTableName)
407
-    {
408
-        return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
409
-    }
410
-
411
-    private function relationshipStorageToArray(\SplObjectStorage $storage)
412
-    {
413
-        $beans = [];
414
-        foreach ($storage as $bean) {
415
-            $statusArr = $storage[$bean];
416
-            if ($statusArr['status'] !== 'delete') {
417
-                $beans[] = $bean;
418
-            }
419
-        }
420
-
421
-        return $beans;
422
-    }
423
-
424
-    /**
425
-     * Declares a relationship between.
426
-     *
427
-     * @param string             $pivotTableName
428
-     * @param AbstractTDBMObject $remoteBean
429
-     * @param string             $status
430
-     */
431
-    private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
432
-    {
433
-        $storage = $this->getRelationshipStorage($pivotTableName);
434
-        $storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
435
-        if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
436
-            $this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
437
-        }
438
-
439
-        $remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
440
-        $remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
441
-    }
442
-
443
-    /**
444
-     * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
445
-     *
446
-     * @param string $pivotTableName
447
-     *
448
-     * @return \SplObjectStorage
449
-     */
450
-    private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
451
-    {
452
-        return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
453
-    }
454
-
455
-    /**
456
-     * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
457
-     *
458
-     * @param string $tableName
459
-     * @param string $foreignKeyName
460
-     *
461
-     * @return AlterableResultIterator
462
-     */
463
-    private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
464
-    {
465
-        $key = $tableName.'___'.$foreignKeyName;
466
-
467
-        return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
468
-    }
469
-
470
-    /**
471
-     * Declares a relationship between this bean and the bean pointing to it.
472
-     *
473
-     * @param string             $tableName
474
-     * @param string             $foreignKeyName
475
-     * @param AbstractTDBMObject $remoteBean
476
-     */
477
-    private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
478
-    {
479
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
480
-        $alterableResultIterator->add($remoteBean);
481
-    }
482
-
483
-    /**
484
-     * Declares a relationship between this bean and the bean pointing to it.
485
-     *
486
-     * @param string             $tableName
487
-     * @param string             $foreignKeyName
488
-     * @param AbstractTDBMObject $remoteBean
489
-     */
490
-    private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
491
-    {
492
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
493
-        $alterableResultIterator->remove($remoteBean);
494
-    }
495
-
496
-    /**
497
-     * Returns the list of objects linked to this bean via a given foreign key.
498
-     *
499
-     * @param string $tableName
500
-     * @param string $foreignKeyName
501
-     * @param string $searchTableName
502
-     * @param array  $searchFilter
503
-     * @param string $orderString     The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
504
-     *
505
-     * @return AlterableResultIterator
506
-     */
507
-    protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
508
-    {
509
-        $key = $tableName.'___'.$foreignKeyName;
510
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
511
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
512
-            return $alterableResultIterator;
513
-        }
514
-
515
-        $unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
516
-
517
-        $alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
518
-
519
-        return $alterableResultIterator;
520
-    }
521
-
522
-    /**
523
-     * Reverts any changes made to the object and resumes it to its DB state.
524
-     * This can only be called on objects that come from database and that have not been deleted.
525
-     * Otherwise, this will throw an exception.
526
-     *
527
-     * @throws TDBMException
528
-     */
529
-    public function discardChanges()
530
-    {
531
-        if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
532
-            throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
533
-        }
534
-
535
-        if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
536
-            throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
537
-        }
538
-
539
-        $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
540
-    }
541
-
542
-    /**
543
-     * Method used internally by TDBM. You should not use it directly.
544
-     * This method returns the status of the TDBMObject.
545
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
546
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
547
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
548
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
549
-     *
550
-     * @return string
551
-     */
552
-    public function _getStatus()
553
-    {
554
-        return $this->status;
555
-    }
556
-
557
-    /**
558
-     * Override the native php clone function for TDBMObjects.
559
-     */
560
-    public function __clone()
561
-    {
562
-        // Let's clone the many to many relationships
563
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
564
-            $pivotTableList = array_keys($this->relationships);
565
-        } else {
566
-            $pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
567
-        }
568
-
569
-        foreach ($pivotTableList as $pivotTable) {
570
-            $storage = $this->retrieveRelationshipsStorage($pivotTable);
571
-
572
-            // Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
573
-            /*foreach ($storage as $remoteBean) {
34
+	/**
35
+	 * The service this object is bound to.
36
+	 *
37
+	 * @var TDBMService
38
+	 */
39
+	protected $tdbmService;
40
+
41
+	/**
42
+	 * An array of DbRow, indexed by table name.
43
+	 *
44
+	 * @var DbRow[]
45
+	 */
46
+	protected $dbRows = [];
47
+
48
+	/**
49
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
50
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
51
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
52
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
53
+	 *
54
+	 * @var string
55
+	 */
56
+	private $status;
57
+
58
+	/**
59
+	 * Array storing beans related via many to many relationships (pivot tables).
60
+	 *
61
+	 * @var \SplObjectStorage[] Key: pivot table name, value: SplObjectStorage
62
+	 */
63
+	private $relationships = [];
64
+
65
+	/**
66
+	 * @var bool[] Key: pivot table name, value: whether a query was performed to load the data
67
+	 */
68
+	private $loadedRelationships = [];
69
+
70
+	/**
71
+	 * Array storing beans related via many to one relationships (this bean is pointed by external beans).
72
+	 *
73
+	 * @var AlterableResultIterator[] Key: [external_table]___[external_column], value: SplObjectStorage
74
+	 */
75
+	private $manyToOneRelationships = [];
76
+
77
+	/**
78
+	 * Used with $primaryKeys when we want to retrieve an existing object
79
+	 * and $primaryKeys=[] if we want a new object.
80
+	 *
81
+	 * @param string      $tableName
82
+	 * @param array       $primaryKeys
83
+	 * @param TDBMService $tdbmService
84
+	 *
85
+	 * @throws TDBMException
86
+	 * @throws TDBMInvalidOperationException
87
+	 */
88
+	public function __construct($tableName = null, array $primaryKeys = [], TDBMService $tdbmService = null)
89
+	{
90
+		// FIXME: lazy loading should be forbidden on tables with inheritance and dynamic type assignation...
91
+		if (!empty($tableName)) {
92
+			$this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
93
+		}
94
+
95
+		if ($tdbmService === null) {
96
+			$this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
97
+		} else {
98
+			$this->_attach($tdbmService);
99
+			if (!empty($primaryKeys)) {
100
+				$this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
101
+			} else {
102
+				$this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
103
+			}
104
+		}
105
+	}
106
+
107
+	/**
108
+	 * Alternative constructor called when data is fetched from database via a SELECT.
109
+	 *
110
+	 * @param array       $beanData    array<table, array<column, value>>
111
+	 * @param TDBMService $tdbmService
112
+	 */
113
+	public function _constructFromData(array $beanData, TDBMService $tdbmService)
114
+	{
115
+		$this->tdbmService = $tdbmService;
116
+
117
+		foreach ($beanData as $table => $columns) {
118
+			$this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
119
+		}
120
+
121
+		$this->status = TDBMObjectStateEnum::STATE_LOADED;
122
+	}
123
+
124
+	/**
125
+	 * Alternative constructor called when bean is lazily loaded.
126
+	 *
127
+	 * @param string      $tableName
128
+	 * @param array       $primaryKeys
129
+	 * @param TDBMService $tdbmService
130
+	 */
131
+	public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
132
+	{
133
+		$this->tdbmService = $tdbmService;
134
+
135
+		$this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
136
+
137
+		$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
138
+	}
139
+
140
+	public function _attach(TDBMService $tdbmService)
141
+	{
142
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
143
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
144
+		}
145
+		$this->tdbmService = $tdbmService;
146
+
147
+		// If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
148
+		$tableNames = $this->getUsedTables();
149
+
150
+		$newDbRows = [];
151
+
152
+		foreach ($tableNames as $table) {
153
+			if (!isset($this->dbRows[$table])) {
154
+				$this->registerTable($table);
155
+			}
156
+			$newDbRows[$table] = $this->dbRows[$table];
157
+		}
158
+		$this->dbRows = $newDbRows;
159
+
160
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
161
+		foreach ($this->dbRows as $dbRow) {
162
+			$dbRow->_attach($tdbmService);
163
+		}
164
+	}
165
+
166
+	/**
167
+	 * Sets the state of the TDBM Object
168
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
169
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
170
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
171
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
172
+	 *
173
+	 * @param string $state
174
+	 */
175
+	public function _setStatus($state)
176
+	{
177
+		$this->status = $state;
178
+
179
+		// TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
180
+		foreach ($this->dbRows as $dbRow) {
181
+			$dbRow->_setStatus($state);
182
+		}
183
+
184
+		if ($state === TDBMObjectStateEnum::STATE_DELETED) {
185
+			$this->onDelete();
186
+		}
187
+	}
188
+
189
+	/**
190
+	 * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
191
+	 * or throws an error.
192
+	 *
193
+	 * @param string $tableName
194
+	 *
195
+	 * @return string
196
+	 */
197
+	private function checkTableName($tableName = null)
198
+	{
199
+		if ($tableName === null) {
200
+			if (count($this->dbRows) > 1) {
201
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
202
+			} elseif (count($this->dbRows) === 1) {
203
+				$tableName = array_keys($this->dbRows)[0];
204
+			}
205
+		}
206
+
207
+		return $tableName;
208
+	}
209
+
210
+	protected function get($var, $tableName = null)
211
+	{
212
+		$tableName = $this->checkTableName($tableName);
213
+
214
+		if (!isset($this->dbRows[$tableName])) {
215
+			return;
216
+		}
217
+
218
+		return $this->dbRows[$tableName]->get($var);
219
+	}
220
+
221
+	protected function set($var, $value, $tableName = null)
222
+	{
223
+		if ($tableName === null) {
224
+			if (count($this->dbRows) > 1) {
225
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226
+			} elseif (count($this->dbRows) === 1) {
227
+				$tableName = array_keys($this->dbRows)[0];
228
+			} else {
229
+				throw new TDBMException('Please specify a table for this object.');
230
+			}
231
+		}
232
+
233
+		if (!isset($this->dbRows[$tableName])) {
234
+			$this->registerTable($tableName);
235
+		}
236
+
237
+		$this->dbRows[$tableName]->set($var, $value);
238
+		if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
239
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
240
+		}
241
+	}
242
+
243
+	/**
244
+	 * @param string             $foreignKeyName
245
+	 * @param AbstractTDBMObject $bean
246
+	 */
247
+	protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248
+	{
249
+		if ($tableName === null) {
250
+			if (count($this->dbRows) > 1) {
251
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252
+			} elseif (count($this->dbRows) === 1) {
253
+				$tableName = array_keys($this->dbRows)[0];
254
+			} else {
255
+				throw new TDBMException('Please specify a table for this object.');
256
+			}
257
+		}
258
+
259
+		if (!isset($this->dbRows[$tableName])) {
260
+			$this->registerTable($tableName);
261
+		}
262
+
263
+		$oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
264
+		if ($oldLinkedBean !== null) {
265
+			$oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
266
+		}
267
+
268
+		$this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
269
+		if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
270
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
271
+		}
272
+
273
+		if ($bean !== null) {
274
+			$bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	protected function getRef($foreignKeyName, $tableName = null)
284
+	{
285
+		$tableName = $this->checkTableName($tableName);
286
+
287
+		if (!isset($this->dbRows[$tableName])) {
288
+			return;
289
+		}
290
+
291
+		return $this->dbRows[$tableName]->getRef($foreignKeyName);
292
+	}
293
+
294
+	/**
295
+	 * Adds a many to many relationship to this bean.
296
+	 *
297
+	 * @param string             $pivotTableName
298
+	 * @param AbstractTDBMObject $remoteBean
299
+	 */
300
+	protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
301
+	{
302
+		$this->setRelationship($pivotTableName, $remoteBean, 'new');
303
+	}
304
+
305
+	/**
306
+	 * Returns true if there is a relationship to this bean.
307
+	 *
308
+	 * @param string             $pivotTableName
309
+	 * @param AbstractTDBMObject $remoteBean
310
+	 *
311
+	 * @return bool
312
+	 */
313
+	protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
314
+	{
315
+		$storage = $this->retrieveRelationshipsStorage($pivotTableName);
316
+
317
+		if ($storage->contains($remoteBean)) {
318
+			if ($storage[$remoteBean]['status'] !== 'delete') {
319
+				return true;
320
+			}
321
+		}
322
+
323
+		return false;
324
+	}
325
+
326
+	/**
327
+	 * Internal TDBM method. Removes a many to many relationship from this bean.
328
+	 *
329
+	 * @param string             $pivotTableName
330
+	 * @param AbstractTDBMObject $remoteBean
331
+	 */
332
+	public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
333
+	{
334
+		if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
335
+			unset($this->relationships[$pivotTableName][$remoteBean]);
336
+			unset($remoteBean->relationships[$pivotTableName][$this]);
337
+		} else {
338
+			$this->setRelationship($pivotTableName, $remoteBean, 'delete');
339
+		}
340
+	}
341
+
342
+	/**
343
+	 * Sets many to many relationships for this bean.
344
+	 * Adds new relationships and removes unused ones.
345
+	 *
346
+	 * @param $pivotTableName
347
+	 * @param array $remoteBeans
348
+	 */
349
+	protected function setRelationships($pivotTableName, array $remoteBeans)
350
+	{
351
+		$storage = $this->retrieveRelationshipsStorage($pivotTableName);
352
+
353
+		foreach ($storage as $oldRemoteBean) {
354
+			if (!in_array($oldRemoteBean, $remoteBeans, true)) {
355
+				// $oldRemoteBean must be removed
356
+				$this->_removeRelationship($pivotTableName, $oldRemoteBean);
357
+			}
358
+		}
359
+
360
+		foreach ($remoteBeans as $remoteBean) {
361
+			if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
362
+				// $remoteBean must be added
363
+				$this->addRelationship($pivotTableName, $remoteBean);
364
+			}
365
+		}
366
+	}
367
+
368
+	/**
369
+	 * Returns the list of objects linked to this bean via $pivotTableName.
370
+	 *
371
+	 * @param $pivotTableName
372
+	 *
373
+	 * @return \SplObjectStorage
374
+	 */
375
+	private function retrieveRelationshipsStorage($pivotTableName)
376
+	{
377
+		$storage = $this->getRelationshipStorage($pivotTableName);
378
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
379
+			return $storage;
380
+		}
381
+
382
+		$beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
383
+		$this->loadedRelationships[$pivotTableName] = true;
384
+
385
+		foreach ($beans as $bean) {
386
+			if (isset($storage[$bean])) {
387
+				$oldStatus = $storage[$bean]['status'];
388
+				if ($oldStatus === 'delete') {
389
+					// Keep deleted things deleted
390
+					continue;
391
+				}
392
+			}
393
+			$this->setRelationship($pivotTableName, $bean, 'loaded');
394
+		}
395
+
396
+		return $storage;
397
+	}
398
+
399
+	/**
400
+	 * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
401
+	 *
402
+	 * @param $pivotTableName
403
+	 *
404
+	 * @return AbstractTDBMObject[]
405
+	 */
406
+	public function _getRelationships($pivotTableName)
407
+	{
408
+		return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
409
+	}
410
+
411
+	private function relationshipStorageToArray(\SplObjectStorage $storage)
412
+	{
413
+		$beans = [];
414
+		foreach ($storage as $bean) {
415
+			$statusArr = $storage[$bean];
416
+			if ($statusArr['status'] !== 'delete') {
417
+				$beans[] = $bean;
418
+			}
419
+		}
420
+
421
+		return $beans;
422
+	}
423
+
424
+	/**
425
+	 * Declares a relationship between.
426
+	 *
427
+	 * @param string             $pivotTableName
428
+	 * @param AbstractTDBMObject $remoteBean
429
+	 * @param string             $status
430
+	 */
431
+	private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
432
+	{
433
+		$storage = $this->getRelationshipStorage($pivotTableName);
434
+		$storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
435
+		if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
436
+			$this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
437
+		}
438
+
439
+		$remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
440
+		$remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
441
+	}
442
+
443
+	/**
444
+	 * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
445
+	 *
446
+	 * @param string $pivotTableName
447
+	 *
448
+	 * @return \SplObjectStorage
449
+	 */
450
+	private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
451
+	{
452
+		return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
453
+	}
454
+
455
+	/**
456
+	 * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
457
+	 *
458
+	 * @param string $tableName
459
+	 * @param string $foreignKeyName
460
+	 *
461
+	 * @return AlterableResultIterator
462
+	 */
463
+	private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
464
+	{
465
+		$key = $tableName.'___'.$foreignKeyName;
466
+
467
+		return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
468
+	}
469
+
470
+	/**
471
+	 * Declares a relationship between this bean and the bean pointing to it.
472
+	 *
473
+	 * @param string             $tableName
474
+	 * @param string             $foreignKeyName
475
+	 * @param AbstractTDBMObject $remoteBean
476
+	 */
477
+	private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
478
+	{
479
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
480
+		$alterableResultIterator->add($remoteBean);
481
+	}
482
+
483
+	/**
484
+	 * Declares a relationship between this bean and the bean pointing to it.
485
+	 *
486
+	 * @param string             $tableName
487
+	 * @param string             $foreignKeyName
488
+	 * @param AbstractTDBMObject $remoteBean
489
+	 */
490
+	private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
491
+	{
492
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
493
+		$alterableResultIterator->remove($remoteBean);
494
+	}
495
+
496
+	/**
497
+	 * Returns the list of objects linked to this bean via a given foreign key.
498
+	 *
499
+	 * @param string $tableName
500
+	 * @param string $foreignKeyName
501
+	 * @param string $searchTableName
502
+	 * @param array  $searchFilter
503
+	 * @param string $orderString     The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
504
+	 *
505
+	 * @return AlterableResultIterator
506
+	 */
507
+	protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
508
+	{
509
+		$key = $tableName.'___'.$foreignKeyName;
510
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
511
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
512
+			return $alterableResultIterator;
513
+		}
514
+
515
+		$unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
516
+
517
+		$alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
518
+
519
+		return $alterableResultIterator;
520
+	}
521
+
522
+	/**
523
+	 * Reverts any changes made to the object and resumes it to its DB state.
524
+	 * This can only be called on objects that come from database and that have not been deleted.
525
+	 * Otherwise, this will throw an exception.
526
+	 *
527
+	 * @throws TDBMException
528
+	 */
529
+	public function discardChanges()
530
+	{
531
+		if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
532
+			throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
533
+		}
534
+
535
+		if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
536
+			throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
537
+		}
538
+
539
+		$this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
540
+	}
541
+
542
+	/**
543
+	 * Method used internally by TDBM. You should not use it directly.
544
+	 * This method returns the status of the TDBMObject.
545
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
546
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
547
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
548
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
549
+	 *
550
+	 * @return string
551
+	 */
552
+	public function _getStatus()
553
+	{
554
+		return $this->status;
555
+	}
556
+
557
+	/**
558
+	 * Override the native php clone function for TDBMObjects.
559
+	 */
560
+	public function __clone()
561
+	{
562
+		// Let's clone the many to many relationships
563
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
564
+			$pivotTableList = array_keys($this->relationships);
565
+		} else {
566
+			$pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
567
+		}
568
+
569
+		foreach ($pivotTableList as $pivotTable) {
570
+			$storage = $this->retrieveRelationshipsStorage($pivotTable);
571
+
572
+			// Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
573
+			/*foreach ($storage as $remoteBean) {
574 574
                 $metadata = $storage[$remoteBean];
575 575
 
576 576
                 $remoteStorage = $remoteBean->getRelationshipStorage($pivotTable);
577 577
                 $remoteStorage->attach($this, ['status' => $metadata['status'], 'reverse' => !$metadata['reverse']]);
578 578
             }*/
579
-        }
580
-
581
-        // Let's clone each row
582
-        foreach ($this->dbRows as $key => &$dbRow) {
583
-            $dbRow = clone $dbRow;
584
-            $dbRow->setTDBMObject($this);
585
-        }
586
-
587
-        $this->manyToOneRelationships = [];
588
-
589
-        // Let's set the status to new (to enter the save function)
590
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
591
-    }
592
-
593
-    /**
594
-     * Returns raw database rows.
595
-     *
596
-     * @return DbRow[] Key: table name, Value: DbRow object
597
-     */
598
-    public function _getDbRows()
599
-    {
600
-        return $this->dbRows;
601
-    }
602
-
603
-    private function registerTable($tableName)
604
-    {
605
-        $dbRow = new DbRow($this, $tableName);
606
-
607
-        if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
608
-            // Let's get the primary key for the new table
609
-            $anotherDbRow = array_values($this->dbRows)[0];
610
-            /* @var $anotherDbRow DbRow */
611
-            $indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
612
-            $primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
613
-            $dbRow->_setPrimaryKeys($primaryKeys);
614
-        }
615
-
616
-        $dbRow->_setStatus($this->status);
617
-
618
-        $this->dbRows[$tableName] = $dbRow;
619
-        // TODO: look at status (if not new)=> get primary key from tdbmservice
620
-    }
621
-
622
-    /**
623
-     * Internal function: return the list of relationships.
624
-     *
625
-     * @return \SplObjectStorage[]
626
-     */
627
-    public function _getCachedRelationships()
628
-    {
629
-        return $this->relationships;
630
-    }
631
-
632
-    /**
633
-     * Returns an array of used tables by this bean (from parent to child relationship).
634
-     *
635
-     * @return string[]
636
-     */
637
-    abstract protected function getUsedTables() : array;
638
-
639
-    /**
640
-     * Method called when the bean is removed from database.
641
-     */
642
-    protected function onDelete() : void
643
-    {
644
-    }
579
+		}
580
+
581
+		// Let's clone each row
582
+		foreach ($this->dbRows as $key => &$dbRow) {
583
+			$dbRow = clone $dbRow;
584
+			$dbRow->setTDBMObject($this);
585
+		}
586
+
587
+		$this->manyToOneRelationships = [];
588
+
589
+		// Let's set the status to new (to enter the save function)
590
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
591
+	}
592
+
593
+	/**
594
+	 * Returns raw database rows.
595
+	 *
596
+	 * @return DbRow[] Key: table name, Value: DbRow object
597
+	 */
598
+	public function _getDbRows()
599
+	{
600
+		return $this->dbRows;
601
+	}
602
+
603
+	private function registerTable($tableName)
604
+	{
605
+		$dbRow = new DbRow($this, $tableName);
606
+
607
+		if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
608
+			// Let's get the primary key for the new table
609
+			$anotherDbRow = array_values($this->dbRows)[0];
610
+			/* @var $anotherDbRow DbRow */
611
+			$indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
612
+			$primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
613
+			$dbRow->_setPrimaryKeys($primaryKeys);
614
+		}
615
+
616
+		$dbRow->_setStatus($this->status);
617
+
618
+		$this->dbRows[$tableName] = $dbRow;
619
+		// TODO: look at status (if not new)=> get primary key from tdbmservice
620
+	}
621
+
622
+	/**
623
+	 * Internal function: return the list of relationships.
624
+	 *
625
+	 * @return \SplObjectStorage[]
626
+	 */
627
+	public function _getCachedRelationships()
628
+	{
629
+		return $this->relationships;
630
+	}
631
+
632
+	/**
633
+	 * Returns an array of used tables by this bean (from parent to child relationship).
634
+	 *
635
+	 * @return string[]
636
+	 */
637
+	abstract protected function getUsedTables() : array;
638
+
639
+	/**
640
+	 * Method called when the bean is removed from database.
641
+	 */
642
+	protected function onDelete() : void
643
+	{
644
+	}
645 645
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/DirectForeignKeyMethodDescriptor.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare(strict_types=1);
3
+declare(strict_types = 1);
4 4
 
5 5
 namespace Mouf\Database\TDBM\Utils;
6 6
 
Please login to merge, or discard this patch.
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -12,71 +12,71 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class DirectForeignKeyMethodDescriptor implements MethodDescriptorInterface
14 14
 {
15
-    /**
16
-     * @var ForeignKeyConstraint
17
-     */
18
-    private $fk;
19
-
20
-    private $useAlternateName = false;
21
-    /**
22
-     * @var Table
23
-     */
24
-    private $mainTable;
25
-    /**
26
-     * @var NamingStrategyInterface
27
-     */
28
-    private $namingStrategy;
29
-
30
-    /**
31
-     * @param ForeignKeyConstraint $fk The foreign key pointing to our bean
32
-     * @param Table $mainTable The main table that is pointed to
33
-     * @param NamingStrategyInterface $namingStrategy
34
-     */
35
-    public function __construct(ForeignKeyConstraint $fk, Table $mainTable, NamingStrategyInterface $namingStrategy)
36
-    {
37
-        $this->fk = $fk;
38
-        $this->mainTable = $mainTable;
39
-        $this->namingStrategy = $namingStrategy;
40
-    }
41
-
42
-    /**
43
-     * Returns the name of the method to be generated.
44
-     *
45
-     * @return string
46
-     */
47
-    public function getName() : string
48
-    {
49
-        if (!$this->useAlternateName) {
50
-            return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName());
51
-        } else {
52
-            $methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By';
53
-
54
-            $camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns());
55
-
56
-            $methodName .= implode('And', $camelizedColumns);
57
-
58
-            return $methodName;
59
-        }
60
-    }
61
-
62
-    /**
63
-     * Requests the use of an alternative name for this method.
64
-     */
65
-    public function useAlternativeName()
66
-    {
67
-        $this->useAlternateName = true;
68
-    }
69
-
70
-    /**
71
-     * Returns the code of the method.
72
-     *
73
-     * @return string
74
-     */
75
-    public function getCode() : string
76
-    {
77
-        $code = '';
78
-
79
-        $getterCode = '    /**
15
+	/**
16
+	 * @var ForeignKeyConstraint
17
+	 */
18
+	private $fk;
19
+
20
+	private $useAlternateName = false;
21
+	/**
22
+	 * @var Table
23
+	 */
24
+	private $mainTable;
25
+	/**
26
+	 * @var NamingStrategyInterface
27
+	 */
28
+	private $namingStrategy;
29
+
30
+	/**
31
+	 * @param ForeignKeyConstraint $fk The foreign key pointing to our bean
32
+	 * @param Table $mainTable The main table that is pointed to
33
+	 * @param NamingStrategyInterface $namingStrategy
34
+	 */
35
+	public function __construct(ForeignKeyConstraint $fk, Table $mainTable, NamingStrategyInterface $namingStrategy)
36
+	{
37
+		$this->fk = $fk;
38
+		$this->mainTable = $mainTable;
39
+		$this->namingStrategy = $namingStrategy;
40
+	}
41
+
42
+	/**
43
+	 * Returns the name of the method to be generated.
44
+	 *
45
+	 * @return string
46
+	 */
47
+	public function getName() : string
48
+	{
49
+		if (!$this->useAlternateName) {
50
+			return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName());
51
+		} else {
52
+			$methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By';
53
+
54
+			$camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns());
55
+
56
+			$methodName .= implode('And', $camelizedColumns);
57
+
58
+			return $methodName;
59
+		}
60
+	}
61
+
62
+	/**
63
+	 * Requests the use of an alternative name for this method.
64
+	 */
65
+	public function useAlternativeName()
66
+	{
67
+		$this->useAlternateName = true;
68
+	}
69
+
70
+	/**
71
+	 * Returns the code of the method.
72
+	 *
73
+	 * @return string
74
+	 */
75
+	public function getCode() : string
76
+	{
77
+		$code = '';
78
+
79
+		$getterCode = '    /**
80 80
      * Returns the list of %s pointing to this bean via the %s column.
81 81
      *
82 82
      * @return %s[]|AlterableResultIterator
@@ -88,55 +88,55 @@  discard block
 block discarded – undo
88 88
 
89 89
 ';
90 90
 
91
-        $beanClass = $this->namingStrategy->getBeanClassName($this->fk->getLocalTableName());
92
-        $code .= sprintf($getterCode,
93
-            $beanClass,
94
-            implode(', ', $this->fk->getColumns()),
95
-            $beanClass,
96
-            $this->getName(),
97
-            var_export($this->fk->getLocalTableName(), true),
98
-            var_export($this->fk->getName(), true),
99
-            var_export($this->fk->getLocalTableName(), true),
100
-            $this->getFilters($this->fk)
101
-        );
102
-
103
-        return $code;
104
-    }
105
-
106
-    private function getFilters(ForeignKeyConstraint $fk) : string
107
-    {
108
-        $counter = 0;
109
-        $parameters = [];
110
-
111
-        $pkColumns = $this->mainTable->getPrimaryKeyColumns();
112
-
113
-        foreach ($fk->getLocalColumns() as $columnName) {
114
-            $pkColumn = $pkColumns[$counter];
115
-            $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true));
116
-            ++$counter;
117
-        }
118
-        $parametersCode = '['.implode(', ', $parameters).']';
119
-
120
-        return $parametersCode;
121
-    }
122
-
123
-    /**
124
-     * Returns an array of classes that needs a "use" for this method.
125
-     *
126
-     * @return string[]
127
-     */
128
-    public function getUsedClasses() : array
129
-    {
130
-        return [$this->namingStrategy->getBeanClassName($this->fk->getForeignTableName())];
131
-    }
132
-
133
-    /**
134
-     * Returns the code to past in jsonSerialize.
135
-     *
136
-     * @return string
137
-     */
138
-    public function getJsonSerializeCode() : string
139
-    {
140
-        return '';
141
-    }
91
+		$beanClass = $this->namingStrategy->getBeanClassName($this->fk->getLocalTableName());
92
+		$code .= sprintf($getterCode,
93
+			$beanClass,
94
+			implode(', ', $this->fk->getColumns()),
95
+			$beanClass,
96
+			$this->getName(),
97
+			var_export($this->fk->getLocalTableName(), true),
98
+			var_export($this->fk->getName(), true),
99
+			var_export($this->fk->getLocalTableName(), true),
100
+			$this->getFilters($this->fk)
101
+		);
102
+
103
+		return $code;
104
+	}
105
+
106
+	private function getFilters(ForeignKeyConstraint $fk) : string
107
+	{
108
+		$counter = 0;
109
+		$parameters = [];
110
+
111
+		$pkColumns = $this->mainTable->getPrimaryKeyColumns();
112
+
113
+		foreach ($fk->getLocalColumns() as $columnName) {
114
+			$pkColumn = $pkColumns[$counter];
115
+			$parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true));
116
+			++$counter;
117
+		}
118
+		$parametersCode = '['.implode(', ', $parameters).']';
119
+
120
+		return $parametersCode;
121
+	}
122
+
123
+	/**
124
+	 * Returns an array of classes that needs a "use" for this method.
125
+	 *
126
+	 * @return string[]
127
+	 */
128
+	public function getUsedClasses() : array
129
+	{
130
+		return [$this->namingStrategy->getBeanClassName($this->fk->getForeignTableName())];
131
+	}
132
+
133
+	/**
134
+	 * Returns the code to past in jsonSerialize.
135
+	 *
136
+	 * @return string
137
+	 */
138
+	public function getJsonSerializeCode() : string
139
+	{
140
+		return '';
141
+	}
142 142
 }
Please login to merge, or discard this patch.
src/views/tdbmGenerate.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@
 block discarded – undo
8 8
 <input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" />
9 9
 
10 10
 <?php if (!$this->autoloadDetected) {
11
-    ?>
11
+	?>
12 12
 <div class="alert">Warning! TDBM could not detect the autoload section of your composer.json file.
13 13
 Unless you are developing your own autoload system, you should configure <strong>composer.json</strong> to <a href="http://getcomposer.org/doc/01-basic-usage.md#autoloading" target="_blank">define a source directory and a root namespace using PSR-0</a>.</div>
14 14
 <?php
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmController.php 4 patches
Doc Comments   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
      * @Action
77 77
      *
78 78
      * @param string $name
79
-     * @param bool   $selfedit
79
+     * @param string|boolean   $selfedit
80 80
      */
81 81
     public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82 82
     {
@@ -95,9 +95,10 @@  discard block
 block discarded – undo
95 95
      * @param string      $name
96 96
      * @param string      $daonamespace
97 97
      * @param string      $beannamespace
98
-     * @param string      $daofactoryclassname
99 98
      * @param string      $daofactoryinstancename
100 99
      * @param string      $selfedit
100
+     * @param boolean $useCustomComposer
101
+     * @param string $composerFile
101 102
      *
102 103
      * @throws \Mouf\MoufException
103 104
      */
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -5,7 +5,6 @@
 block discarded – undo
5 5
 use Mouf\Composer\ClassNameMapper;
6 6
 use Mouf\Controllers\AbstractMoufInstanceController;
7 7
 use Mouf\Database\TDBM\TDBMService;
8
-use Mouf\Database\TDBM\Utils\TDBMDaoGenerator;
9 8
 use Mouf\Html\HtmlElement\HtmlBlock;
10 9
 use Mouf\MoufManager;
11 10
 use Mouf\InstanceProxy;
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -18,129 +18,129 @@
 block discarded – undo
18 18
  */
19 19
 class TdbmController extends AbstractMoufInstanceController
20 20
 {
21
-    /**
22
-     * @var HtmlBlock
23
-     */
24
-    public $content;
25
-
26
-    protected $daoNamespace;
27
-    protected $beanNamespace;
28
-    protected $daoFactoryInstanceName;
29
-    protected $autoloadDetected;
30
-    ///protected $storeInUtc;
31
-    protected $useCustomComposer;
32
-    protected $composerFile;
33
-
34
-    /**
35
-     * Admin page used to display the DAO generation form.
36
-     *
37
-     * @Action
38
-     */
39
-    public function defaultAction($name, $selfedit = 'false')
40
-    {
41
-        $this->initController($name, $selfedit);
42
-
43
-        // Fill variables
44
-        $this->daoNamespace = self::getFromConfiguration($this->moufManager, $name, 'daoNamespace');
45
-        $this->beanNamespace = self::getFromConfiguration($this->moufManager, $name, 'beanNamespace');
46
-        $this->daoFactoryInstanceName = self::getFromConfiguration($this->moufManager, $name, 'daoFactoryInstanceName');
47
-        //$this->storeInUtc = self::getFromConfiguration($this->moufManager, $name, 'storeInUtc');
48
-        $this->composerFile = self::getFromConfiguration($this->moufManager, $name, 'customComposerFile');
49
-        $this->useCustomComposer = $this->composerFile ? true : false;
50
-
51
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
52
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
53
-
54
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
55
-            if ($autoloadNamespaces) {
56
-                $this->autoloadDetected = true;
57
-                $rootNamespace = $autoloadNamespaces[0];
58
-                $this->daoNamespace = $rootNamespace.'Dao';
59
-                $this->beanNamespace = $rootNamespace.'Dao\\Bean';
60
-            } else {
61
-                $this->autoloadDetected = false;
62
-                $this->daoNamespace = 'YourApplication\\Dao';
63
-                $this->beanNamespace = 'YourApplication\\Dao\\Bean';
64
-            }
65
-        } else {
66
-            $this->autoloadDetected = true;
67
-        }
68
-
69
-        $this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
70
-        $this->template->toHtml();
71
-    }
72
-
73
-    /**
74
-     * This action generates the DAOs and Beans for the TDBM service passed in parameter.
75
-     *
76
-     * @Action
77
-     *
78
-     * @param string $name
79
-     * @param bool   $selfedit
80
-     */
81
-    public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82
-    {
83
-        $this->initController($name, $selfedit);
84
-
85
-        self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit, /*$storeInUtc,*/ $useCustomComposer, $composerFile);
86
-
87
-        // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
88
-        header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
89
-    }
90
-
91
-    /**
92
-     * This function generates the DAOs and Beans for the TDBM service passed in parameter.
93
-     *
94
-     * @param MoufManager $moufManager
95
-     * @param string      $name
96
-     * @param string      $daonamespace
97
-     * @param string      $beannamespace
98
-     * @param string      $daofactoryclassname
99
-     * @param string      $daofactoryinstancename
100
-     * @param string      $selfedit
101
-     *
102
-     * @throws \Mouf\MoufException
103
-     */
104
-    public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit = 'false', /*$storeInUtc = null,*/ $useCustomComposer = null, $composerFile = null)
105
-    {
106
-        self::setInConfiguration($moufManager, $name, 'daoNamespace', $daonamespace);
107
-        self::setInConfiguration($moufManager, $name, 'beanNamespace', $beannamespace);
108
-        self::setInConfiguration($moufManager, $name, 'daoFactoryInstanceName', $daofactoryinstancename);
109
-        //self::setInConfiguration($moufManager, $name, 'storeInUtc', $storeInUtc);
110
-        if ($useCustomComposer) {
111
-            self::setInConfiguration($moufManager, $name, 'customComposerFile', $composerFile);
112
-        } else {
113
-            self::setInConfiguration($moufManager, $name, 'customComposerFile', null);
114
-        }
115
-        // Let's rewrite before calling the DAO generator
116
-        $moufManager->rewriteMouf();
117
-
118
-
119
-        $tdbmService = new InstanceProxy($name);
120
-        /* @var $tdbmService TDBMService */
121
-        $tdbmService->generateAllDaosAndBeans(($useCustomComposer ? $composerFile : null));
122
-    }
123
-
124
-    private static function getConfigurationDescriptor(MoufManager $moufManager, string $tdbmInstanceName)
125
-    {
126
-        return $moufManager->getInstanceDescriptor($tdbmInstanceName)->getConstructorArgumentProperty('configuration')->getValue();
127
-    }
128
-
129
-    private static function getFromConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property)
130
-    {
131
-        $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
132
-        if ($configuration === null) {
133
-            throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
134
-        }
135
-        return $configuration->getProperty($property)->getValue();
136
-    }
137
-
138
-    private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
139
-    {
140
-        $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141
-        if ($configuration === null) {
142
-            throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
143
-        }
144
-        $configuration->getProperty($property)->setValue($value);
145
-    }
21
+	/**
22
+	 * @var HtmlBlock
23
+	 */
24
+	public $content;
25
+
26
+	protected $daoNamespace;
27
+	protected $beanNamespace;
28
+	protected $daoFactoryInstanceName;
29
+	protected $autoloadDetected;
30
+	///protected $storeInUtc;
31
+	protected $useCustomComposer;
32
+	protected $composerFile;
33
+
34
+	/**
35
+	 * Admin page used to display the DAO generation form.
36
+	 *
37
+	 * @Action
38
+	 */
39
+	public function defaultAction($name, $selfedit = 'false')
40
+	{
41
+		$this->initController($name, $selfedit);
42
+
43
+		// Fill variables
44
+		$this->daoNamespace = self::getFromConfiguration($this->moufManager, $name, 'daoNamespace');
45
+		$this->beanNamespace = self::getFromConfiguration($this->moufManager, $name, 'beanNamespace');
46
+		$this->daoFactoryInstanceName = self::getFromConfiguration($this->moufManager, $name, 'daoFactoryInstanceName');
47
+		//$this->storeInUtc = self::getFromConfiguration($this->moufManager, $name, 'storeInUtc');
48
+		$this->composerFile = self::getFromConfiguration($this->moufManager, $name, 'customComposerFile');
49
+		$this->useCustomComposer = $this->composerFile ? true : false;
50
+
51
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
52
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
53
+
54
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
55
+			if ($autoloadNamespaces) {
56
+				$this->autoloadDetected = true;
57
+				$rootNamespace = $autoloadNamespaces[0];
58
+				$this->daoNamespace = $rootNamespace.'Dao';
59
+				$this->beanNamespace = $rootNamespace.'Dao\\Bean';
60
+			} else {
61
+				$this->autoloadDetected = false;
62
+				$this->daoNamespace = 'YourApplication\\Dao';
63
+				$this->beanNamespace = 'YourApplication\\Dao\\Bean';
64
+			}
65
+		} else {
66
+			$this->autoloadDetected = true;
67
+		}
68
+
69
+		$this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
70
+		$this->template->toHtml();
71
+	}
72
+
73
+	/**
74
+	 * This action generates the DAOs and Beans for the TDBM service passed in parameter.
75
+	 *
76
+	 * @Action
77
+	 *
78
+	 * @param string $name
79
+	 * @param bool   $selfedit
80
+	 */
81
+	public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82
+	{
83
+		$this->initController($name, $selfedit);
84
+
85
+		self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit, /*$storeInUtc,*/ $useCustomComposer, $composerFile);
86
+
87
+		// TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
88
+		header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
89
+	}
90
+
91
+	/**
92
+	 * This function generates the DAOs and Beans for the TDBM service passed in parameter.
93
+	 *
94
+	 * @param MoufManager $moufManager
95
+	 * @param string      $name
96
+	 * @param string      $daonamespace
97
+	 * @param string      $beannamespace
98
+	 * @param string      $daofactoryclassname
99
+	 * @param string      $daofactoryinstancename
100
+	 * @param string      $selfedit
101
+	 *
102
+	 * @throws \Mouf\MoufException
103
+	 */
104
+	public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit = 'false', /*$storeInUtc = null,*/ $useCustomComposer = null, $composerFile = null)
105
+	{
106
+		self::setInConfiguration($moufManager, $name, 'daoNamespace', $daonamespace);
107
+		self::setInConfiguration($moufManager, $name, 'beanNamespace', $beannamespace);
108
+		self::setInConfiguration($moufManager, $name, 'daoFactoryInstanceName', $daofactoryinstancename);
109
+		//self::setInConfiguration($moufManager, $name, 'storeInUtc', $storeInUtc);
110
+		if ($useCustomComposer) {
111
+			self::setInConfiguration($moufManager, $name, 'customComposerFile', $composerFile);
112
+		} else {
113
+			self::setInConfiguration($moufManager, $name, 'customComposerFile', null);
114
+		}
115
+		// Let's rewrite before calling the DAO generator
116
+		$moufManager->rewriteMouf();
117
+
118
+
119
+		$tdbmService = new InstanceProxy($name);
120
+		/* @var $tdbmService TDBMService */
121
+		$tdbmService->generateAllDaosAndBeans(($useCustomComposer ? $composerFile : null));
122
+	}
123
+
124
+	private static function getConfigurationDescriptor(MoufManager $moufManager, string $tdbmInstanceName)
125
+	{
126
+		return $moufManager->getInstanceDescriptor($tdbmInstanceName)->getConstructorArgumentProperty('configuration')->getValue();
127
+	}
128
+
129
+	private static function getFromConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property)
130
+	{
131
+		$configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
132
+		if ($configuration === null) {
133
+			throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
134
+		}
135
+		return $configuration->getProperty($property)->getValue();
136
+	}
137
+
138
+	private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
139
+	{
140
+		$configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141
+		if ($configuration === null) {
142
+			throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
143
+		}
144
+		$configuration->getProperty($property)->setValue($value);
145
+	}
146 146
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@
 block discarded – undo
135 135
         return $configuration->getProperty($property)->getValue();
136 136
     }
137 137
 
138
-    private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
138
+    private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ? string $value)
139 139
     {
140 140
         $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141 141
         if ($configuration === null) {
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -616,7 +616,7 @@
 block discarded – undo
616 616
      * Tries to put string to the singular form (if it is plural).
617 617
      * We assume the table names are in english.
618 618
      *
619
-     * @param $str string
619
+     * @param string $str string
620 620
      *
621 621
      * @return string
622 622
      */
Please login to merge, or discard this patch.
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -3,12 +3,10 @@
 block discarded – undo
3 3
 namespace Mouf\Database\TDBM\Utils;
4 4
 
5 5
 use Doctrine\Common\Inflector\Inflector;
6
-use Doctrine\DBAL\Schema\Column;
7 6
 use Doctrine\DBAL\Schema\Schema;
8 7
 use Doctrine\DBAL\Schema\Table;
9 8
 use Doctrine\DBAL\Types\Type;
10 9
 use Mouf\Composer\ClassNameMapper;
11
-use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
12 10
 use Mouf\Database\TDBM\ConfigurationInterface;
13 11
 use Mouf\Database\TDBM\TDBMException;
14 12
 use Mouf\Database\TDBM\TDBMSchemaAnalyzer;
Please login to merge, or discard this patch.
Indentation   +416 added lines, -416 removed lines patch added patch discarded remove patch
@@ -19,157 +19,157 @@  discard block
 block discarded – undo
19 19
  */
20 20
 class TDBMDaoGenerator
21 21
 {
22
-    /**
23
-     * @var Schema
24
-     */
25
-    private $schema;
26
-
27
-    /**
28
-     * The root directory of the project.
29
-     *
30
-     * @var string
31
-     */
32
-    private $rootPath;
33
-
34
-    /**
35
-     * Name of composer file.
36
-     *
37
-     * @var string
38
-     */
39
-    private $composerFile;
40
-
41
-    /**
42
-     * @var TDBMSchemaAnalyzer
43
-     */
44
-    private $tdbmSchemaAnalyzer;
45
-
46
-    /**
47
-     * @var EventDispatcherInterface
48
-     */
49
-    private $eventDispatcher;
50
-
51
-    /**
52
-     * @var NamingStrategyInterface
53
-     */
54
-    private $namingStrategy;
55
-    /**
56
-     * @var ConfigurationInterface
57
-     */
58
-    private $configuration;
59
-
60
-    /**
61
-     * Constructor.
62
-     *
63
-     * @param ConfigurationInterface $configuration
64
-     * @param Schema $schema
65
-     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
66
-     */
67
-    public function __construct(ConfigurationInterface $configuration, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
68
-    {
69
-        $this->configuration = $configuration;
70
-        $this->schema = $schema;
71
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
72
-        $this->rootPath = __DIR__.'/../../../../../../../../';
73
-        $this->composerFile = 'composer.json';
74
-        $this->namingStrategy = $configuration->getNamingStrategy();
75
-        $this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
76
-    }
77
-
78
-    /**
79
-     * Generates all the daos and beans.
80
-     *
81
-     * @throws TDBMException
82
-     */
83
-    public function generateAllDaosAndBeans(): void
84
-    {
85
-        $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.$this->composerFile);
86
-        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
87
-
88
-        $tableList = $this->schema->getTables();
89
-
90
-        // Remove all beans and daos from junction tables
91
-        $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
92
-        $junctionTableNames = array_map(function (Table $table) {
93
-            return $table->getName();
94
-        }, $junctionTables);
95
-
96
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
97
-            return !in_array($table->getName(), $junctionTableNames);
98
-        });
99
-
100
-        $beanDescriptors = [];
101
-
102
-        foreach ($tableList as $table) {
103
-            $beanDescriptors[] = $this->generateDaoAndBean($table, $classNameMapper);
104
-        }
105
-
106
-
107
-        $this->generateFactory($tableList, $classNameMapper);
108
-
109
-        // Let's call the list of listeners
110
-        $this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
111
-    }
112
-
113
-    /**
114
-     * Generates in one method call the daos and the beans for one table.
115
-     *
116
-     * @param Table $table
117
-     * @param ClassNameMapper $classNameMapper
118
-     *
119
-     * @return BeanDescriptor
120
-     * @throws TDBMException
121
-     */
122
-    private function generateDaoAndBean(Table $table, ClassNameMapper $classNameMapper) : BeanDescriptor
123
-    {
124
-        // TODO: $storeInUtc is NOT USED.
125
-        $tableName = $table->getName();
126
-        $daoName = $this->namingStrategy->getDaoClassName($tableName);
127
-        $beanName = $this->namingStrategy->getBeanClassName($tableName);
128
-        $baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
129
-        $baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
130
-
131
-        $beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
132
-        $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $classNameMapper);
133
-        $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $classNameMapper);
134
-        return $beanDescriptor;
135
-    }
136
-
137
-    /**
138
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
139
-     *
140
-     * @param BeanDescriptor  $beanDescriptor
141
-     * @param string          $className       The name of the class
142
-     * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
143
-     * @param Table           $table           The table
144
-     * @param ClassNameMapper $classNameMapper
145
-     *
146
-     * @throws TDBMException
147
-     */
148
-    public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, ClassNameMapper $classNameMapper)
149
-    {
150
-        $beannamespace = $this->configuration->getBeanNamespace();
151
-        $str = $beanDescriptor->generatePhpCode($beannamespace);
152
-
153
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\Generated\\'.$baseClassName);
154
-        if (empty($possibleBaseFileNames)) {
155
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
156
-        }
157
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
158
-
159
-        $this->ensureDirectoryExist($possibleBaseFileName);
160
-        file_put_contents($possibleBaseFileName, $str);
161
-        @chmod($possibleBaseFileName, 0664);
162
-
163
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
164
-        if (empty($possibleFileNames)) {
165
-            // @codeCoverageIgnoreStart
166
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
167
-            // @codeCoverageIgnoreEnd
168
-        }
169
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
170
-        if (!file_exists($possibleFileName)) {
171
-            $tableName = $table->getName();
172
-            $str = "<?php
22
+	/**
23
+	 * @var Schema
24
+	 */
25
+	private $schema;
26
+
27
+	/**
28
+	 * The root directory of the project.
29
+	 *
30
+	 * @var string
31
+	 */
32
+	private $rootPath;
33
+
34
+	/**
35
+	 * Name of composer file.
36
+	 *
37
+	 * @var string
38
+	 */
39
+	private $composerFile;
40
+
41
+	/**
42
+	 * @var TDBMSchemaAnalyzer
43
+	 */
44
+	private $tdbmSchemaAnalyzer;
45
+
46
+	/**
47
+	 * @var EventDispatcherInterface
48
+	 */
49
+	private $eventDispatcher;
50
+
51
+	/**
52
+	 * @var NamingStrategyInterface
53
+	 */
54
+	private $namingStrategy;
55
+	/**
56
+	 * @var ConfigurationInterface
57
+	 */
58
+	private $configuration;
59
+
60
+	/**
61
+	 * Constructor.
62
+	 *
63
+	 * @param ConfigurationInterface $configuration
64
+	 * @param Schema $schema
65
+	 * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
66
+	 */
67
+	public function __construct(ConfigurationInterface $configuration, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
68
+	{
69
+		$this->configuration = $configuration;
70
+		$this->schema = $schema;
71
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
72
+		$this->rootPath = __DIR__.'/../../../../../../../../';
73
+		$this->composerFile = 'composer.json';
74
+		$this->namingStrategy = $configuration->getNamingStrategy();
75
+		$this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
76
+	}
77
+
78
+	/**
79
+	 * Generates all the daos and beans.
80
+	 *
81
+	 * @throws TDBMException
82
+	 */
83
+	public function generateAllDaosAndBeans(): void
84
+	{
85
+		$classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.$this->composerFile);
86
+		// TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
87
+
88
+		$tableList = $this->schema->getTables();
89
+
90
+		// Remove all beans and daos from junction tables
91
+		$junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
92
+		$junctionTableNames = array_map(function (Table $table) {
93
+			return $table->getName();
94
+		}, $junctionTables);
95
+
96
+		$tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
97
+			return !in_array($table->getName(), $junctionTableNames);
98
+		});
99
+
100
+		$beanDescriptors = [];
101
+
102
+		foreach ($tableList as $table) {
103
+			$beanDescriptors[] = $this->generateDaoAndBean($table, $classNameMapper);
104
+		}
105
+
106
+
107
+		$this->generateFactory($tableList, $classNameMapper);
108
+
109
+		// Let's call the list of listeners
110
+		$this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
111
+	}
112
+
113
+	/**
114
+	 * Generates in one method call the daos and the beans for one table.
115
+	 *
116
+	 * @param Table $table
117
+	 * @param ClassNameMapper $classNameMapper
118
+	 *
119
+	 * @return BeanDescriptor
120
+	 * @throws TDBMException
121
+	 */
122
+	private function generateDaoAndBean(Table $table, ClassNameMapper $classNameMapper) : BeanDescriptor
123
+	{
124
+		// TODO: $storeInUtc is NOT USED.
125
+		$tableName = $table->getName();
126
+		$daoName = $this->namingStrategy->getDaoClassName($tableName);
127
+		$beanName = $this->namingStrategy->getBeanClassName($tableName);
128
+		$baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
129
+		$baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
130
+
131
+		$beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
132
+		$this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $classNameMapper);
133
+		$this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $classNameMapper);
134
+		return $beanDescriptor;
135
+	}
136
+
137
+	/**
138
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
139
+	 *
140
+	 * @param BeanDescriptor  $beanDescriptor
141
+	 * @param string          $className       The name of the class
142
+	 * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
143
+	 * @param Table           $table           The table
144
+	 * @param ClassNameMapper $classNameMapper
145
+	 *
146
+	 * @throws TDBMException
147
+	 */
148
+	public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, ClassNameMapper $classNameMapper)
149
+	{
150
+		$beannamespace = $this->configuration->getBeanNamespace();
151
+		$str = $beanDescriptor->generatePhpCode($beannamespace);
152
+
153
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\Generated\\'.$baseClassName);
154
+		if (empty($possibleBaseFileNames)) {
155
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
156
+		}
157
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
158
+
159
+		$this->ensureDirectoryExist($possibleBaseFileName);
160
+		file_put_contents($possibleBaseFileName, $str);
161
+		@chmod($possibleBaseFileName, 0664);
162
+
163
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
164
+		if (empty($possibleFileNames)) {
165
+			// @codeCoverageIgnoreStart
166
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
167
+			// @codeCoverageIgnoreEnd
168
+		}
169
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
170
+		if (!file_exists($possibleFileName)) {
171
+			$tableName = $table->getName();
172
+			$str = "<?php
173 173
 /*
174 174
  * This file has been automatically generated by TDBM.
175 175
  * You can edit this file as it will not be overwritten.
@@ -186,76 +186,76 @@  discard block
 block discarded – undo
186 186
 {
187 187
 }
188 188
 ";
189
-            $this->ensureDirectoryExist($possibleFileName);
190
-            file_put_contents($possibleFileName, $str);
191
-            @chmod($possibleFileName, 0664);
192
-        }
193
-    }
194
-
195
-    /**
196
-     * Tries to find a @defaultSort annotation in one of the columns.
197
-     *
198
-     * @param Table $table
199
-     *
200
-     * @return array First item: column name, Second item: column order (asc/desc)
201
-     */
202
-    private function getDefaultSortColumnFromAnnotation(Table $table)
203
-    {
204
-        $defaultSort = null;
205
-        $defaultSortDirection = null;
206
-        foreach ($table->getColumns() as $column) {
207
-            $comments = $column->getComment();
208
-            $matches = [];
209
-            if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
210
-                $defaultSort = $column->getName();
211
-                if (count($matches) === 3) {
212
-                    $defaultSortDirection = $matches[2];
213
-                } else {
214
-                    $defaultSortDirection = 'ASC';
215
-                }
216
-            }
217
-        }
218
-
219
-        return [$defaultSort, $defaultSortDirection];
220
-    }
221
-
222
-    /**
223
-     * Writes the PHP bean DAO with simple functions to create/get/save objects.
224
-     *
225
-     * @param BeanDescriptor  $beanDescriptor
226
-     * @param string          $className       The name of the class
227
-     * @param string          $baseClassName
228
-     * @param string          $beanClassName
229
-     * @param Table           $table
230
-     * @param ClassNameMapper $classNameMapper
231
-     *
232
-     * @throws TDBMException
233
-     */
234
-    private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table, ClassNameMapper $classNameMapper)
235
-    {
236
-        $daonamespace = $this->configuration->getDaoNamespace();
237
-        $beannamespace = $this->configuration->getBeanNamespace();
238
-        $tableName = $table->getName();
239
-        $primaryKeyColumns = $table->getPrimaryKeyColumns();
240
-
241
-        list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
242
-
243
-        // FIXME: lowercase tables with _ in the name should work!
244
-        $tableCamel = self::toSingular(self::toCamelCase($tableName));
245
-
246
-        $beanClassWithoutNameSpace = $beanClassName;
247
-        $beanClassName = $beannamespace.'\\'.$beanClassName;
248
-
249
-        list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
250
-
251
-        $usedBeans[] = $beanClassName;
252
-        // Let's suppress duplicates in used beans (if any)
253
-        $usedBeans = array_flip(array_flip($usedBeans));
254
-        $useStatements = array_map(function ($usedBean) {
255
-            return "use $usedBean;\n";
256
-        }, $usedBeans);
257
-
258
-        $str = "<?php
189
+			$this->ensureDirectoryExist($possibleFileName);
190
+			file_put_contents($possibleFileName, $str);
191
+			@chmod($possibleFileName, 0664);
192
+		}
193
+	}
194
+
195
+	/**
196
+	 * Tries to find a @defaultSort annotation in one of the columns.
197
+	 *
198
+	 * @param Table $table
199
+	 *
200
+	 * @return array First item: column name, Second item: column order (asc/desc)
201
+	 */
202
+	private function getDefaultSortColumnFromAnnotation(Table $table)
203
+	{
204
+		$defaultSort = null;
205
+		$defaultSortDirection = null;
206
+		foreach ($table->getColumns() as $column) {
207
+			$comments = $column->getComment();
208
+			$matches = [];
209
+			if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
210
+				$defaultSort = $column->getName();
211
+				if (count($matches) === 3) {
212
+					$defaultSortDirection = $matches[2];
213
+				} else {
214
+					$defaultSortDirection = 'ASC';
215
+				}
216
+			}
217
+		}
218
+
219
+		return [$defaultSort, $defaultSortDirection];
220
+	}
221
+
222
+	/**
223
+	 * Writes the PHP bean DAO with simple functions to create/get/save objects.
224
+	 *
225
+	 * @param BeanDescriptor  $beanDescriptor
226
+	 * @param string          $className       The name of the class
227
+	 * @param string          $baseClassName
228
+	 * @param string          $beanClassName
229
+	 * @param Table           $table
230
+	 * @param ClassNameMapper $classNameMapper
231
+	 *
232
+	 * @throws TDBMException
233
+	 */
234
+	private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table, ClassNameMapper $classNameMapper)
235
+	{
236
+		$daonamespace = $this->configuration->getDaoNamespace();
237
+		$beannamespace = $this->configuration->getBeanNamespace();
238
+		$tableName = $table->getName();
239
+		$primaryKeyColumns = $table->getPrimaryKeyColumns();
240
+
241
+		list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
242
+
243
+		// FIXME: lowercase tables with _ in the name should work!
244
+		$tableCamel = self::toSingular(self::toCamelCase($tableName));
245
+
246
+		$beanClassWithoutNameSpace = $beanClassName;
247
+		$beanClassName = $beannamespace.'\\'.$beanClassName;
248
+
249
+		list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
250
+
251
+		$usedBeans[] = $beanClassName;
252
+		// Let's suppress duplicates in used beans (if any)
253
+		$usedBeans = array_flip(array_flip($usedBeans));
254
+		$useStatements = array_map(function ($usedBean) {
255
+			return "use $usedBean;\n";
256
+		}, $usedBeans);
257
+
258
+		$str = "<?php
259 259
 
260 260
 /*
261 261
  * This file has been automatically generated by TDBM.
@@ -331,10 +331,10 @@  discard block
 block discarded – undo
331 331
     }
332 332
     ";
333 333
 
334
-        if (count($primaryKeyColumns) === 1) {
335
-            $primaryKeyColumn = $primaryKeyColumns[0];
336
-            $primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
337
-            $str .= "
334
+		if (count($primaryKeyColumns) === 1) {
335
+			$primaryKeyColumn = $primaryKeyColumns[0];
336
+			$primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
337
+			$str .= "
338 338
     /**
339 339
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
340 340
      * If the primary key does not exist, an exception is thrown.
@@ -349,8 +349,8 @@  discard block
 block discarded – undo
349 349
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
350 350
     }
351 351
     ";
352
-        }
353
-        $str .= "
352
+		}
353
+		$str .= "
354 354
     /**
355 355
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
356 356
      *
@@ -450,33 +450,33 @@  discard block
 block discarded – undo
450 450
     }
451 451
 ";
452 452
 
453
-        $str .= $findByDaoCode;
454
-        $str .= '}
453
+		$str .= $findByDaoCode;
454
+		$str .= '}
455 455
 ';
456 456
 
457
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
458
-        if (empty($possibleBaseFileNames)) {
459
-            // @codeCoverageIgnoreStart
460
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\Generated\\'.$baseClassName.'" is not autoloadable.');
461
-            // @codeCoverageIgnoreEnd
462
-        }
463
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
464
-
465
-        $this->ensureDirectoryExist($possibleBaseFileName);
466
-        file_put_contents($possibleBaseFileName, $str);
467
-        @chmod($possibleBaseFileName, 0664);
468
-
469
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
470
-        if (empty($possibleFileNames)) {
471
-            // @codeCoverageIgnoreStart
472
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\'.$className.'" is not autoloadable.');
473
-            // @codeCoverageIgnoreEnd
474
-        }
475
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
476
-
477
-        // Now, let's generate the "editable" class
478
-        if (!file_exists($possibleFileName)) {
479
-            $str = "<?php
457
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
458
+		if (empty($possibleBaseFileNames)) {
459
+			// @codeCoverageIgnoreStart
460
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\Generated\\'.$baseClassName.'" is not autoloadable.');
461
+			// @codeCoverageIgnoreEnd
462
+		}
463
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
464
+
465
+		$this->ensureDirectoryExist($possibleBaseFileName);
466
+		file_put_contents($possibleBaseFileName, $str);
467
+		@chmod($possibleBaseFileName, 0664);
468
+
469
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
470
+		if (empty($possibleFileNames)) {
471
+			// @codeCoverageIgnoreStart
472
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daonamespace.'\\'.$className.'" is not autoloadable.');
473
+			// @codeCoverageIgnoreEnd
474
+		}
475
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
476
+
477
+		// Now, let's generate the "editable" class
478
+		if (!file_exists($possibleFileName)) {
479
+			$str = "<?php
480 480
 
481 481
 /*
482 482
  * This file has been automatically generated by TDBM.
@@ -494,27 +494,27 @@  discard block
 block discarded – undo
494 494
 {
495 495
 }
496 496
 ";
497
-            $this->ensureDirectoryExist($possibleFileName);
498
-            file_put_contents($possibleFileName, $str);
499
-            @chmod($possibleFileName, 0664);
500
-        }
501
-    }
502
-
503
-    /**
504
-     * Generates the factory bean.
505
-     *
506
-     * @param Table[] $tableList
507
-     * @param ClassNameMapper $classNameMapper
508
-     * @throws TDBMException
509
-     */
510
-    private function generateFactory(array $tableList, ClassNameMapper $classNameMapper) : void
511
-    {
512
-        $daoNamespace = $this->configuration->getDaoNamespace();
513
-        $daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
514
-
515
-        // For each table, let's write a property.
516
-
517
-        $str = "<?php
497
+			$this->ensureDirectoryExist($possibleFileName);
498
+			file_put_contents($possibleFileName, $str);
499
+			@chmod($possibleFileName, 0664);
500
+		}
501
+	}
502
+
503
+	/**
504
+	 * Generates the factory bean.
505
+	 *
506
+	 * @param Table[] $tableList
507
+	 * @param ClassNameMapper $classNameMapper
508
+	 * @throws TDBMException
509
+	 */
510
+	private function generateFactory(array $tableList, ClassNameMapper $classNameMapper) : void
511
+	{
512
+		$daoNamespace = $this->configuration->getDaoNamespace();
513
+		$daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
514
+
515
+		// For each table, let's write a property.
516
+
517
+		$str = "<?php
518 518
 
519 519
 /*
520 520
  * This file has been automatically generated by TDBM.
@@ -524,13 +524,13 @@  discard block
 block discarded – undo
524 524
 namespace {$daoNamespace}\\Generated;
525 525
 
526 526
 ";
527
-        foreach ($tableList as $table) {
528
-            $tableName = $table->getName();
529
-            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
530
-            $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
531
-        }
527
+		foreach ($tableList as $table) {
528
+			$tableName = $table->getName();
529
+			$daoClassName = $this->namingStrategy->getDaoClassName($tableName);
530
+			$str .= "use {$daoNamespace}\\".$daoClassName.";\n";
531
+		}
532 532
 
533
-        $str .= "
533
+		$str .= "
534 534
 /**
535 535
  * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
536 536
  *
@@ -539,12 +539,12 @@  discard block
 block discarded – undo
539 539
 {
540 540
 ";
541 541
 
542
-        foreach ($tableList as $table) {
543
-            $tableName = $table->getName();
544
-            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
545
-            $daoInstanceName = self::toVariableName($daoClassName);
542
+		foreach ($tableList as $table) {
543
+			$tableName = $table->getName();
544
+			$daoClassName = $this->namingStrategy->getDaoClassName($tableName);
545
+			$daoInstanceName = self::toVariableName($daoClassName);
546 546
 
547
-            $str .= '    /**
547
+			$str .= '    /**
548 548
      * @var '.$daoClassName.'
549 549
      */
550 550
     private $'.$daoInstanceName.';
@@ -568,140 +568,140 @@  discard block
 block discarded – undo
568 568
     {
569 569
         $this->'.$daoInstanceName.' = $'.$daoInstanceName.';
570 570
     }';
571
-        }
571
+		}
572 572
 
573
-        $str .= '
573
+		$str .= '
574 574
 }
575 575
 ';
576 576
 
577
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
578
-        if (empty($possibleFileNames)) {
579
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
580
-        }
581
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
582
-
583
-        $this->ensureDirectoryExist($possibleFileName);
584
-        file_put_contents($possibleFileName, $str);
585
-        @chmod($possibleFileName, 0664);
586
-    }
587
-
588
-    /**
589
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
590
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
591
-     *
592
-     * @param $str string
593
-     *
594
-     * @return string
595
-     */
596
-    public static function toCamelCase($str)
597
-    {
598
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
599
-        while (true) {
600
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
601
-                break;
602
-            }
603
-
604
-            $pos = strpos($str, '_');
605
-            if ($pos === false) {
606
-                $pos = strpos($str, ' ');
607
-            }
608
-            $before = substr($str, 0, $pos);
609
-            $after = substr($str, $pos + 1);
610
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
611
-        }
612
-
613
-        return $str;
614
-    }
615
-
616
-    /**
617
-     * Tries to put string to the singular form (if it is plural).
618
-     * We assume the table names are in english.
619
-     *
620
-     * @param $str string
621
-     *
622
-     * @return string
623
-     */
624
-    public static function toSingular($str)
625
-    {
626
-        return Inflector::singularize($str);
627
-    }
628
-
629
-    /**
630
-     * Put the first letter of the string in lower case.
631
-     * Very useful to transform a class name into a variable name.
632
-     *
633
-     * @param $str string
634
-     *
635
-     * @return string
636
-     */
637
-    public static function toVariableName($str)
638
-    {
639
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
640
-    }
641
-
642
-    /**
643
-     * Ensures the file passed in parameter can be written in its directory.
644
-     *
645
-     * @param string $fileName
646
-     *
647
-     * @throws TDBMException
648
-     */
649
-    private function ensureDirectoryExist($fileName)
650
-    {
651
-        $dirName = dirname($fileName);
652
-        if (!file_exists($dirName)) {
653
-            $old = umask(0);
654
-            $result = mkdir($dirName, 0775, true);
655
-            umask($old);
656
-            if ($result === false) {
657
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
658
-            }
659
-        }
660
-    }
661
-
662
-    /**
663
-     * Absolute path to composer json file.
664
-     *
665
-     * @param string $composerFile
666
-     */
667
-    public function setComposerFile($composerFile)
668
-    {
669
-        $this->rootPath = dirname($composerFile).'/';
670
-        $this->composerFile = basename($composerFile);
671
-    }
672
-
673
-    /**
674
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
675
-     *
676
-     * @param Type $type The DBAL type
677
-     *
678
-     * @return string The PHP type
679
-     */
680
-    public static function dbalTypeToPhpType(Type $type)
681
-    {
682
-        $map = [
683
-            Type::TARRAY => 'array',
684
-            Type::SIMPLE_ARRAY => 'array',
685
-            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
686
-            Type::JSON_ARRAY => 'array',
687
-            Type::BIGINT => 'string',
688
-            Type::BOOLEAN => 'bool',
689
-            Type::DATETIME => '\DateTimeInterface',
690
-            Type::DATETIMETZ => '\DateTimeInterface',
691
-            Type::DATE => '\DateTimeInterface',
692
-            Type::TIME => '\DateTimeInterface',
693
-            Type::DECIMAL => 'float',
694
-            Type::INTEGER => 'int',
695
-            Type::OBJECT => 'string',
696
-            Type::SMALLINT => 'int',
697
-            Type::STRING => 'string',
698
-            Type::TEXT => 'string',
699
-            Type::BINARY => 'string',
700
-            Type::BLOB => 'string',
701
-            Type::FLOAT => 'float',
702
-            Type::GUID => 'string',
703
-        ];
704
-
705
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
706
-    }
577
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
578
+		if (empty($possibleFileNames)) {
579
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
580
+		}
581
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
582
+
583
+		$this->ensureDirectoryExist($possibleFileName);
584
+		file_put_contents($possibleFileName, $str);
585
+		@chmod($possibleFileName, 0664);
586
+	}
587
+
588
+	/**
589
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
590
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
591
+	 *
592
+	 * @param $str string
593
+	 *
594
+	 * @return string
595
+	 */
596
+	public static function toCamelCase($str)
597
+	{
598
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
599
+		while (true) {
600
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
601
+				break;
602
+			}
603
+
604
+			$pos = strpos($str, '_');
605
+			if ($pos === false) {
606
+				$pos = strpos($str, ' ');
607
+			}
608
+			$before = substr($str, 0, $pos);
609
+			$after = substr($str, $pos + 1);
610
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
611
+		}
612
+
613
+		return $str;
614
+	}
615
+
616
+	/**
617
+	 * Tries to put string to the singular form (if it is plural).
618
+	 * We assume the table names are in english.
619
+	 *
620
+	 * @param $str string
621
+	 *
622
+	 * @return string
623
+	 */
624
+	public static function toSingular($str)
625
+	{
626
+		return Inflector::singularize($str);
627
+	}
628
+
629
+	/**
630
+	 * Put the first letter of the string in lower case.
631
+	 * Very useful to transform a class name into a variable name.
632
+	 *
633
+	 * @param $str string
634
+	 *
635
+	 * @return string
636
+	 */
637
+	public static function toVariableName($str)
638
+	{
639
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
640
+	}
641
+
642
+	/**
643
+	 * Ensures the file passed in parameter can be written in its directory.
644
+	 *
645
+	 * @param string $fileName
646
+	 *
647
+	 * @throws TDBMException
648
+	 */
649
+	private function ensureDirectoryExist($fileName)
650
+	{
651
+		$dirName = dirname($fileName);
652
+		if (!file_exists($dirName)) {
653
+			$old = umask(0);
654
+			$result = mkdir($dirName, 0775, true);
655
+			umask($old);
656
+			if ($result === false) {
657
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
658
+			}
659
+		}
660
+	}
661
+
662
+	/**
663
+	 * Absolute path to composer json file.
664
+	 *
665
+	 * @param string $composerFile
666
+	 */
667
+	public function setComposerFile($composerFile)
668
+	{
669
+		$this->rootPath = dirname($composerFile).'/';
670
+		$this->composerFile = basename($composerFile);
671
+	}
672
+
673
+	/**
674
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
675
+	 *
676
+	 * @param Type $type The DBAL type
677
+	 *
678
+	 * @return string The PHP type
679
+	 */
680
+	public static function dbalTypeToPhpType(Type $type)
681
+	{
682
+		$map = [
683
+			Type::TARRAY => 'array',
684
+			Type::SIMPLE_ARRAY => 'array',
685
+			'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
686
+			Type::JSON_ARRAY => 'array',
687
+			Type::BIGINT => 'string',
688
+			Type::BOOLEAN => 'bool',
689
+			Type::DATETIME => '\DateTimeInterface',
690
+			Type::DATETIMETZ => '\DateTimeInterface',
691
+			Type::DATE => '\DateTimeInterface',
692
+			Type::TIME => '\DateTimeInterface',
693
+			Type::DECIMAL => 'float',
694
+			Type::INTEGER => 'int',
695
+			Type::OBJECT => 'string',
696
+			Type::SMALLINT => 'int',
697
+			Type::STRING => 'string',
698
+			Type::TEXT => 'string',
699
+			Type::BINARY => 'string',
700
+			Type::BLOB => 'string',
701
+			Type::FLOAT => 'float',
702
+			Type::GUID => 'string',
703
+		];
704
+
705
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
706
+	}
707 707
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -89,11 +89,11 @@  discard block
 block discarded – undo
89 89
 
90 90
         // Remove all beans and daos from junction tables
91 91
         $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
92
-        $junctionTableNames = array_map(function (Table $table) {
92
+        $junctionTableNames = array_map(function(Table $table) {
93 93
             return $table->getName();
94 94
         }, $junctionTables);
95 95
 
96
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
96
+        $tableList = array_filter($tableList, function(Table $table) use ($junctionTableNames) {
97 97
             return !in_array($table->getName(), $junctionTableNames);
98 98
         });
99 99
 
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
         $usedBeans[] = $beanClassName;
252 252
         // Let's suppress duplicates in used beans (if any)
253 253
         $usedBeans = array_flip(array_flip($usedBeans));
254
-        $useStatements = array_map(function ($usedBean) {
254
+        $useStatements = array_map(function($usedBean) {
255 255
             return "use $usedBean;\n";
256 256
         }, $usedBeans);
257 257
 
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
                 $pos = strpos($str, ' ');
607 607
             }
608 608
             $before = substr($str, 0, $pos);
609
-            $after = substr($str, $pos + 1);
609
+            $after = substr($str, $pos+1);
610 610
             $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
611 611
         }
612 612
 
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
         $map = [
683 683
             Type::TARRAY => 'array',
684 684
             Type::SIMPLE_ARRAY => 'array',
685
-            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
685
+            'json' => 'array', // 'json' is supported from Doctrine DBAL 2.6 only.
686 686
             Type::JSON_ARRAY => 'array',
687 687
             Type::BIGINT => 'string',
688 688
             Type::BOOLEAN => 'bool',
Please login to merge, or discard this patch.