Completed
Pull Request — 4.0 (#72)
by David
05:01
created
src/Mouf/Database/TDBM/DbRow.php 1 patch
Indentation   +374 added lines, -374 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,188 +252,188 @@  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 (isset($this->references[$foreignKeyName])) {
286
-            return $this->references[$foreignKeyName];
287
-        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
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
-                $val = $this->dbRow[$column];
299
-                if ($val === null) {
300
-                    return;
301
-                }
302
-                $values[] = $val;
303
-            }
304
-
305
-            $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
306
-
307
-            return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
308
-        }
309
-    }
310
-
311
-    /**
312
-     * Returns the name of the table this object comes from.
313
-     *
314
-     * @return string
315
-     */
316
-    public function _getDbTableName()
317
-    {
318
-        return $this->dbTableName;
319
-    }
320
-
321
-    /**
322
-     * Method used internally by TDBM. You should not use it directly.
323
-     * This method returns the status of the TDBMObject.
324
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
325
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
326
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
327
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
328
-     *
329
-     * @return string
330
-     */
331
-    public function _getStatus()
332
-    {
333
-        return $this->status;
334
-    }
335
-
336
-    /**
337
-     * Override the native php clone function for TDBMObjects.
338
-     */
339
-    public function __clone()
340
-    {
341
-        // Let's load the row (before we lose the ID!)
342
-        $this->_dbLoadIfNotLoaded();
343
-
344
-        //Let's set the status to detached
345
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
346
-
347
-        $this->primaryKeys = [];
348
-
349
-        //Now unset the PK from the row
350
-        if ($this->tdbmService) {
351
-            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
352
-            foreach ($pk_array as $pk) {
353
-                $this->dbRow[$pk] = null;
354
-            }
355
-        }
356
-    }
357
-
358
-    /**
359
-     * Returns raw database row.
360
-     *
361
-     * @return array
362
-     */
363
-    public function _getDbRow()
364
-    {
365
-        // Let's merge $dbRow and $references
366
-        $dbRow = $this->dbRow;
367
-
368
-        foreach ($this->references as $foreignKeyName => $reference) {
369
-            // Let's match the name of the columns to the primary key values
370
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
371
-            $refDbRows = $reference->_getDbRows();
372
-            $firstRefDbRow = reset($refDbRows);
373
-            $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
374
-            $localColumns = $fk->getLocalColumns();
375
-
376
-            for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
-                $dbRow[$localColumns[$i]] = $pkValues[$i];
378
-            }
379
-        }
380
-
381
-        return $dbRow;
382
-    }
383
-
384
-    /**
385
-     * Returns references array.
386
-     *
387
-     * @return AbstractTDBMObject[]
388
-     */
389
-    public function _getReferences()
390
-    {
391
-        return $this->references;
392
-    }
393
-
394
-    /**
395
-     * Returns the values of the primary key.
396
-     * This is set when the object is in "loaded" state.
397
-     *
398
-     * @return array
399
-     */
400
-    public function _getPrimaryKeys()
401
-    {
402
-        return $this->primaryKeys;
403
-    }
404
-
405
-    /**
406
-     * Sets the values of the primary key.
407
-     * This is set when the object is in "loaded" state.
408
-     *
409
-     * @param array $primaryKeys
410
-     */
411
-    public function _setPrimaryKeys(array $primaryKeys)
412
-    {
413
-        $this->primaryKeys = $primaryKeys;
414
-        foreach ($this->primaryKeys as $column => $value) {
415
-            $this->dbRow[$column] = $value;
416
-        }
417
-    }
418
-
419
-    /**
420
-     * Returns the TDBMObject this bean is associated to.
421
-     *
422
-     * @return AbstractTDBMObject
423
-     */
424
-    public function getTDBMObject()
425
-    {
426
-        return $this->object;
427
-    }
428
-
429
-    /**
430
-     * Sets the TDBMObject this bean is associated to.
431
-     * Only used when cloning.
432
-     *
433
-     * @param AbstractTDBMObject $object
434
-     */
435
-    public function setTDBMObject(AbstractTDBMObject $object)
436
-    {
437
-        $this->object = $object;
438
-    }
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 (isset($this->references[$foreignKeyName])) {
286
+			return $this->references[$foreignKeyName];
287
+		} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
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
+				$val = $this->dbRow[$column];
299
+				if ($val === null) {
300
+					return;
301
+				}
302
+				$values[] = $val;
303
+			}
304
+
305
+			$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
306
+
307
+			return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
308
+		}
309
+	}
310
+
311
+	/**
312
+	 * Returns the name of the table this object comes from.
313
+	 *
314
+	 * @return string
315
+	 */
316
+	public function _getDbTableName()
317
+	{
318
+		return $this->dbTableName;
319
+	}
320
+
321
+	/**
322
+	 * Method used internally by TDBM. You should not use it directly.
323
+	 * This method returns the status of the TDBMObject.
324
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
325
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
326
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
327
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
328
+	 *
329
+	 * @return string
330
+	 */
331
+	public function _getStatus()
332
+	{
333
+		return $this->status;
334
+	}
335
+
336
+	/**
337
+	 * Override the native php clone function for TDBMObjects.
338
+	 */
339
+	public function __clone()
340
+	{
341
+		// Let's load the row (before we lose the ID!)
342
+		$this->_dbLoadIfNotLoaded();
343
+
344
+		//Let's set the status to detached
345
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
346
+
347
+		$this->primaryKeys = [];
348
+
349
+		//Now unset the PK from the row
350
+		if ($this->tdbmService) {
351
+			$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
352
+			foreach ($pk_array as $pk) {
353
+				$this->dbRow[$pk] = null;
354
+			}
355
+		}
356
+	}
357
+
358
+	/**
359
+	 * Returns raw database row.
360
+	 *
361
+	 * @return array
362
+	 */
363
+	public function _getDbRow()
364
+	{
365
+		// Let's merge $dbRow and $references
366
+		$dbRow = $this->dbRow;
367
+
368
+		foreach ($this->references as $foreignKeyName => $reference) {
369
+			// Let's match the name of the columns to the primary key values
370
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
371
+			$refDbRows = $reference->_getDbRows();
372
+			$firstRefDbRow = reset($refDbRows);
373
+			$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
374
+			$localColumns = $fk->getLocalColumns();
375
+
376
+			for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
+				$dbRow[$localColumns[$i]] = $pkValues[$i];
378
+			}
379
+		}
380
+
381
+		return $dbRow;
382
+	}
383
+
384
+	/**
385
+	 * Returns references array.
386
+	 *
387
+	 * @return AbstractTDBMObject[]
388
+	 */
389
+	public function _getReferences()
390
+	{
391
+		return $this->references;
392
+	}
393
+
394
+	/**
395
+	 * Returns the values of the primary key.
396
+	 * This is set when the object is in "loaded" state.
397
+	 *
398
+	 * @return array
399
+	 */
400
+	public function _getPrimaryKeys()
401
+	{
402
+		return $this->primaryKeys;
403
+	}
404
+
405
+	/**
406
+	 * Sets the values of the primary key.
407
+	 * This is set when the object is in "loaded" state.
408
+	 *
409
+	 * @param array $primaryKeys
410
+	 */
411
+	public function _setPrimaryKeys(array $primaryKeys)
412
+	{
413
+		$this->primaryKeys = $primaryKeys;
414
+		foreach ($this->primaryKeys as $column => $value) {
415
+			$this->dbRow[$column] = $value;
416
+		}
417
+	}
418
+
419
+	/**
420
+	 * Returns the TDBMObject this bean is associated to.
421
+	 *
422
+	 * @return AbstractTDBMObject
423
+	 */
424
+	public function getTDBMObject()
425
+	{
426
+		return $this->object;
427
+	}
428
+
429
+	/**
430
+	 * Sets the TDBMObject this bean is associated to.
431
+	 * Only used when cloning.
432
+	 *
433
+	 * @param AbstractTDBMObject $object
434
+	 */
435
+	public function setTDBMObject(AbstractTDBMObject $object)
436
+	{
437
+		$this->object = $object;
438
+	}
439 439
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/BeanDescriptor.php 1 patch
Indentation   +594 added lines, -594 removed lines patch added patch discarded remove patch
@@ -16,228 +16,228 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class BeanDescriptor
18 18
 {
19
-    /**
20
-     * @var Table
21
-     */
22
-    private $table;
23
-
24
-    /**
25
-     * @var SchemaAnalyzer
26
-     */
27
-    private $schemaAnalyzer;
28
-
29
-    /**
30
-     * @var Schema
31
-     */
32
-    private $schema;
33
-
34
-    /**
35
-     * @var AbstractBeanPropertyDescriptor[]
36
-     */
37
-    private $beanPropertyDescriptors = [];
38
-
39
-    /**
40
-     * @var TDBMSchemaAnalyzer
41
-     */
42
-    private $tdbmSchemaAnalyzer;
43
-
44
-    public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
-    {
46
-        $this->table = $table;
47
-        $this->schemaAnalyzer = $schemaAnalyzer;
48
-        $this->schema = $schema;
49
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
-        $this->initBeanPropertyDescriptors();
51
-    }
52
-
53
-    private function initBeanPropertyDescriptors()
54
-    {
55
-        $this->beanPropertyDescriptors = $this->getProperties($this->table);
56
-    }
57
-
58
-    /**
59
-     * Returns the foreign-key the column is part of, if any. null otherwise.
60
-     *
61
-     * @param Table  $table
62
-     * @param Column $column
63
-     *
64
-     * @return ForeignKeyConstraint|null
65
-     */
66
-    private function isPartOfForeignKey(Table $table, Column $column)
67
-    {
68
-        $localColumnName = $column->getName();
69
-        foreach ($table->getForeignKeys() as $foreignKey) {
70
-            foreach ($foreignKey->getColumns() as $columnName) {
71
-                if ($columnName === $localColumnName) {
72
-                    return $foreignKey;
73
-                }
74
-            }
75
-        }
76
-
77
-        return;
78
-    }
79
-
80
-    /**
81
-     * @return AbstractBeanPropertyDescriptor[]
82
-     */
83
-    public function getBeanPropertyDescriptors()
84
-    {
85
-        return $this->beanPropertyDescriptors;
86
-    }
87
-
88
-    /**
89
-     * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
-     *
91
-     * @return AbstractBeanPropertyDescriptor[]
92
-     */
93
-    public function getConstructorProperties()
94
-    {
95
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
-           return $property->isCompulsory();
97
-        });
98
-
99
-        return $constructorProperties;
100
-    }
101
-
102
-    /**
103
-     * Returns the list of columns that have default values for a given table.
104
-     *
105
-     * @return AbstractBeanPropertyDescriptor[]
106
-     */
107
-    public function getPropertiesWithDefault()
108
-    {
109
-        $properties = $this->getPropertiesForTable($this->table);
110
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
111
-            return $property->hasDefault();
112
-        });
113
-
114
-        return $defaultProperties;
115
-    }
116
-
117
-    /**
118
-     * Returns the list of properties exposed as getters and setters in this class.
119
-     *
120
-     * @return AbstractBeanPropertyDescriptor[]
121
-     */
122
-    public function getExposedProperties()
123
-    {
124
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
125
-            return $property->getTable()->getName() == $this->table->getName();
126
-        });
127
-
128
-        return $exposedProperties;
129
-    }
130
-
131
-    /**
132
-     * Returns the list of properties for this table (including parent tables).
133
-     *
134
-     * @param Table $table
135
-     *
136
-     * @return AbstractBeanPropertyDescriptor[]
137
-     */
138
-    private function getProperties(Table $table)
139
-    {
140
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
141
-        if ($parentRelationship) {
142
-            $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
143
-            $properties = $this->getProperties($parentTable);
144
-            // we merge properties by overriding property names.
145
-            $localProperties = $this->getPropertiesForTable($table);
146
-            foreach ($localProperties as $name => $property) {
147
-                // We do not override properties if this is a primary key!
148
-                if ($property->isPrimaryKey()) {
149
-                    continue;
150
-                }
151
-                $properties[$name] = $property;
152
-            }
153
-        } else {
154
-            $properties = $this->getPropertiesForTable($table);
155
-        }
156
-
157
-        return $properties;
158
-    }
159
-
160
-    /**
161
-     * Returns the list of properties for this table (ignoring parent tables).
162
-     *
163
-     * @param Table $table
164
-     *
165
-     * @return AbstractBeanPropertyDescriptor[]
166
-     */
167
-    private function getPropertiesForTable(Table $table)
168
-    {
169
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
170
-        if ($parentRelationship) {
171
-            $ignoreColumns = $parentRelationship->getLocalColumns();
172
-        } else {
173
-            $ignoreColumns = [];
174
-        }
175
-
176
-        $beanPropertyDescriptors = [];
177
-
178
-        foreach ($table->getColumns() as $column) {
179
-            if (array_search($column->getName(), $ignoreColumns) !== false) {
180
-                continue;
181
-            }
182
-
183
-            $fk = $this->isPartOfForeignKey($table, $column);
184
-            if ($fk !== null) {
185
-                // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
186
-                foreach ($beanPropertyDescriptors as $beanDescriptor) {
187
-                    if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
188
-                        continue 2;
189
-                    }
190
-                }
191
-                // Check that this property is not an inheritance relationship
192
-                $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
193
-                if ($parentRelationship === $fk) {
194
-                    continue;
195
-                }
196
-
197
-                $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
198
-            } else {
199
-                $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
200
-            }
201
-        }
202
-
203
-        // Now, let's get the name of all properties and let's check there is no duplicate.
204
-        /** @var $names AbstractBeanPropertyDescriptor[] */
205
-        $names = [];
206
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
207
-            $name = $beanDescriptor->getUpperCamelCaseName();
208
-            if (isset($names[$name])) {
209
-                $names[$name]->useAlternativeName();
210
-                $beanDescriptor->useAlternativeName();
211
-            } else {
212
-                $names[$name] = $beanDescriptor;
213
-            }
214
-        }
215
-
216
-        // Final check (throw exceptions if problem arises)
217
-        $names = [];
218
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
219
-            $name = $beanDescriptor->getUpperCamelCaseName();
220
-            if (isset($names[$name])) {
221
-                throw new TDBMException('Unsolvable name conflict while generating method name');
222
-            } else {
223
-                $names[$name] = $beanDescriptor;
224
-            }
225
-        }
226
-
227
-        // Last step, let's rebuild the list with a map:
228
-        $beanPropertyDescriptorsMap = [];
229
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
230
-            $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
231
-        }
232
-
233
-        return $beanPropertyDescriptorsMap;
234
-    }
235
-
236
-    public function generateBeanConstructor()
237
-    {
238
-        $constructorProperties = $this->getConstructorProperties();
239
-
240
-        $constructorCode = '    /**
19
+	/**
20
+	 * @var Table
21
+	 */
22
+	private $table;
23
+
24
+	/**
25
+	 * @var SchemaAnalyzer
26
+	 */
27
+	private $schemaAnalyzer;
28
+
29
+	/**
30
+	 * @var Schema
31
+	 */
32
+	private $schema;
33
+
34
+	/**
35
+	 * @var AbstractBeanPropertyDescriptor[]
36
+	 */
37
+	private $beanPropertyDescriptors = [];
38
+
39
+	/**
40
+	 * @var TDBMSchemaAnalyzer
41
+	 */
42
+	private $tdbmSchemaAnalyzer;
43
+
44
+	public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
+	{
46
+		$this->table = $table;
47
+		$this->schemaAnalyzer = $schemaAnalyzer;
48
+		$this->schema = $schema;
49
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
+		$this->initBeanPropertyDescriptors();
51
+	}
52
+
53
+	private function initBeanPropertyDescriptors()
54
+	{
55
+		$this->beanPropertyDescriptors = $this->getProperties($this->table);
56
+	}
57
+
58
+	/**
59
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
60
+	 *
61
+	 * @param Table  $table
62
+	 * @param Column $column
63
+	 *
64
+	 * @return ForeignKeyConstraint|null
65
+	 */
66
+	private function isPartOfForeignKey(Table $table, Column $column)
67
+	{
68
+		$localColumnName = $column->getName();
69
+		foreach ($table->getForeignKeys() as $foreignKey) {
70
+			foreach ($foreignKey->getColumns() as $columnName) {
71
+				if ($columnName === $localColumnName) {
72
+					return $foreignKey;
73
+				}
74
+			}
75
+		}
76
+
77
+		return;
78
+	}
79
+
80
+	/**
81
+	 * @return AbstractBeanPropertyDescriptor[]
82
+	 */
83
+	public function getBeanPropertyDescriptors()
84
+	{
85
+		return $this->beanPropertyDescriptors;
86
+	}
87
+
88
+	/**
89
+	 * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
+	 *
91
+	 * @return AbstractBeanPropertyDescriptor[]
92
+	 */
93
+	public function getConstructorProperties()
94
+	{
95
+		$constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
+		   return $property->isCompulsory();
97
+		});
98
+
99
+		return $constructorProperties;
100
+	}
101
+
102
+	/**
103
+	 * Returns the list of columns that have default values for a given table.
104
+	 *
105
+	 * @return AbstractBeanPropertyDescriptor[]
106
+	 */
107
+	public function getPropertiesWithDefault()
108
+	{
109
+		$properties = $this->getPropertiesForTable($this->table);
110
+		$defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
111
+			return $property->hasDefault();
112
+		});
113
+
114
+		return $defaultProperties;
115
+	}
116
+
117
+	/**
118
+	 * Returns the list of properties exposed as getters and setters in this class.
119
+	 *
120
+	 * @return AbstractBeanPropertyDescriptor[]
121
+	 */
122
+	public function getExposedProperties()
123
+	{
124
+		$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
125
+			return $property->getTable()->getName() == $this->table->getName();
126
+		});
127
+
128
+		return $exposedProperties;
129
+	}
130
+
131
+	/**
132
+	 * Returns the list of properties for this table (including parent tables).
133
+	 *
134
+	 * @param Table $table
135
+	 *
136
+	 * @return AbstractBeanPropertyDescriptor[]
137
+	 */
138
+	private function getProperties(Table $table)
139
+	{
140
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
141
+		if ($parentRelationship) {
142
+			$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
143
+			$properties = $this->getProperties($parentTable);
144
+			// we merge properties by overriding property names.
145
+			$localProperties = $this->getPropertiesForTable($table);
146
+			foreach ($localProperties as $name => $property) {
147
+				// We do not override properties if this is a primary key!
148
+				if ($property->isPrimaryKey()) {
149
+					continue;
150
+				}
151
+				$properties[$name] = $property;
152
+			}
153
+		} else {
154
+			$properties = $this->getPropertiesForTable($table);
155
+		}
156
+
157
+		return $properties;
158
+	}
159
+
160
+	/**
161
+	 * Returns the list of properties for this table (ignoring parent tables).
162
+	 *
163
+	 * @param Table $table
164
+	 *
165
+	 * @return AbstractBeanPropertyDescriptor[]
166
+	 */
167
+	private function getPropertiesForTable(Table $table)
168
+	{
169
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
170
+		if ($parentRelationship) {
171
+			$ignoreColumns = $parentRelationship->getLocalColumns();
172
+		} else {
173
+			$ignoreColumns = [];
174
+		}
175
+
176
+		$beanPropertyDescriptors = [];
177
+
178
+		foreach ($table->getColumns() as $column) {
179
+			if (array_search($column->getName(), $ignoreColumns) !== false) {
180
+				continue;
181
+			}
182
+
183
+			$fk = $this->isPartOfForeignKey($table, $column);
184
+			if ($fk !== null) {
185
+				// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
186
+				foreach ($beanPropertyDescriptors as $beanDescriptor) {
187
+					if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
188
+						continue 2;
189
+					}
190
+				}
191
+				// Check that this property is not an inheritance relationship
192
+				$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
193
+				if ($parentRelationship === $fk) {
194
+					continue;
195
+				}
196
+
197
+				$beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
198
+			} else {
199
+				$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
200
+			}
201
+		}
202
+
203
+		// Now, let's get the name of all properties and let's check there is no duplicate.
204
+		/** @var $names AbstractBeanPropertyDescriptor[] */
205
+		$names = [];
206
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
207
+			$name = $beanDescriptor->getUpperCamelCaseName();
208
+			if (isset($names[$name])) {
209
+				$names[$name]->useAlternativeName();
210
+				$beanDescriptor->useAlternativeName();
211
+			} else {
212
+				$names[$name] = $beanDescriptor;
213
+			}
214
+		}
215
+
216
+		// Final check (throw exceptions if problem arises)
217
+		$names = [];
218
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
219
+			$name = $beanDescriptor->getUpperCamelCaseName();
220
+			if (isset($names[$name])) {
221
+				throw new TDBMException('Unsolvable name conflict while generating method name');
222
+			} else {
223
+				$names[$name] = $beanDescriptor;
224
+			}
225
+		}
226
+
227
+		// Last step, let's rebuild the list with a map:
228
+		$beanPropertyDescriptorsMap = [];
229
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
230
+			$beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
231
+		}
232
+
233
+		return $beanPropertyDescriptorsMap;
234
+	}
235
+
236
+	public function generateBeanConstructor()
237
+	{
238
+		$constructorProperties = $this->getConstructorProperties();
239
+
240
+		$constructorCode = '    /**
241 241
      * The constructor takes all compulsory arguments.
242 242
      *
243 243
 %s
@@ -247,70 +247,70 @@  discard block
 block discarded – undo
247 247
 %s    }
248 248
     ';
249 249
 
250
-        $paramAnnotations = [];
251
-        $arguments = [];
252
-        $assigns = [];
253
-        $parentConstructorArguments = [];
254
-
255
-        foreach ($constructorProperties as $property) {
256
-            $className = $property->getClassName();
257
-            if ($className) {
258
-                $arguments[] = $className.' '.$property->getVariableName();
259
-            } else {
260
-                $arguments[] = $property->getVariableName();
261
-            }
262
-            $paramAnnotations[] = $property->getParamAnnotation();
263
-            if ($property->getTable()->getName() === $this->table->getName()) {
264
-                $assigns[] = $property->getConstructorAssignCode();
265
-            } else {
266
-                $parentConstructorArguments[] = $property->getVariableName();
267
-            }
268
-        }
269
-
270
-        $parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
271
-
272
-        $defaultAssigns = [];
273
-        foreach ($this->getPropertiesWithDefault() as $property) {
274
-            $defaultAssigns[] = $property->assignToDefaultCode();
275
-        }
276
-
277
-        return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode("\n", $assigns), implode("\n", $defaultAssigns));
278
-    }
279
-
280
-    public function generateDirectForeignKeysCode()
281
-    {
282
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
283
-
284
-        $fksByTable = [];
285
-
286
-        foreach ($fks as $fk) {
287
-            $fksByTable[$fk->getLocalTableName()][] = $fk;
288
-        }
289
-
290
-        /* @var $fksByMethodName ForeignKeyConstraint[] */
291
-        $fksByMethodName = [];
292
-
293
-        foreach ($fksByTable as $tableName => $fksForTable) {
294
-            if (count($fksForTable) > 1) {
295
-                foreach ($fksForTable as $fk) {
296
-                    $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
297
-
298
-                    $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $fk->getLocalColumns());
299
-
300
-                    $methodName .= implode('And', $camelizedColumns);
301
-
302
-                    $fksByMethodName[$methodName] = $fk;
303
-                }
304
-            } else {
305
-                $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fksForTable[0]->getLocalTableName());
306
-                $fksByMethodName[$methodName] = $fksForTable[0];
307
-            }
308
-        }
309
-
310
-        $code = '';
311
-
312
-        foreach ($fksByMethodName as $methodName => $fk) {
313
-            $getterCode = '    /**
250
+		$paramAnnotations = [];
251
+		$arguments = [];
252
+		$assigns = [];
253
+		$parentConstructorArguments = [];
254
+
255
+		foreach ($constructorProperties as $property) {
256
+			$className = $property->getClassName();
257
+			if ($className) {
258
+				$arguments[] = $className.' '.$property->getVariableName();
259
+			} else {
260
+				$arguments[] = $property->getVariableName();
261
+			}
262
+			$paramAnnotations[] = $property->getParamAnnotation();
263
+			if ($property->getTable()->getName() === $this->table->getName()) {
264
+				$assigns[] = $property->getConstructorAssignCode();
265
+			} else {
266
+				$parentConstructorArguments[] = $property->getVariableName();
267
+			}
268
+		}
269
+
270
+		$parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
271
+
272
+		$defaultAssigns = [];
273
+		foreach ($this->getPropertiesWithDefault() as $property) {
274
+			$defaultAssigns[] = $property->assignToDefaultCode();
275
+		}
276
+
277
+		return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode("\n", $assigns), implode("\n", $defaultAssigns));
278
+	}
279
+
280
+	public function generateDirectForeignKeysCode()
281
+	{
282
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
283
+
284
+		$fksByTable = [];
285
+
286
+		foreach ($fks as $fk) {
287
+			$fksByTable[$fk->getLocalTableName()][] = $fk;
288
+		}
289
+
290
+		/* @var $fksByMethodName ForeignKeyConstraint[] */
291
+		$fksByMethodName = [];
292
+
293
+		foreach ($fksByTable as $tableName => $fksForTable) {
294
+			if (count($fksForTable) > 1) {
295
+				foreach ($fksForTable as $fk) {
296
+					$methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
297
+
298
+					$camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $fk->getLocalColumns());
299
+
300
+					$methodName .= implode('And', $camelizedColumns);
301
+
302
+					$fksByMethodName[$methodName] = $fk;
303
+				}
304
+			} else {
305
+				$methodName = 'get'.TDBMDaoGenerator::toCamelCase($fksForTable[0]->getLocalTableName());
306
+				$fksByMethodName[$methodName] = $fksForTable[0];
307
+			}
308
+		}
309
+
310
+		$code = '';
311
+
312
+		foreach ($fksByMethodName as $methodName => $fk) {
313
+			$getterCode = '    /**
314 314
      * Returns the list of %s pointing to this bean via the %s column.
315 315
      *
316 316
      * @return %s[]|ResultIterator
@@ -322,111 +322,111 @@  discard block
 block discarded – undo
322 322
 
323 323
 ';
324 324
 
325
-            list($sql, $parametersCode) = $this->getFilters($fk);
326
-
327
-            $beanClass = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
328
-            $code .= sprintf($getterCode,
329
-                $beanClass,
330
-                implode(', ', $fk->getColumns()),
331
-                $beanClass,
332
-                $methodName,
333
-                var_export($fk->getLocalTableName(), true),
334
-                $sql,
335
-                $parametersCode
336
-            );
337
-        }
338
-
339
-        return $code;
340
-    }
341
-
342
-    private function getFilters(ForeignKeyConstraint $fk)
343
-    {
344
-        $sqlParts = [];
345
-        $counter = 0;
346
-        $parameters = [];
347
-
348
-        $pkColumns = $this->table->getPrimaryKeyColumns();
349
-
350
-        foreach ($fk->getLocalColumns() as $columnName) {
351
-            $paramName = 'tdbmparam'.$counter;
352
-            $sqlParts[] = $fk->getLocalTableName().'.'.$columnName.' = :'.$paramName;
353
-
354
-            $pkColumn = $pkColumns[$counter];
355
-            $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($paramName, true), var_export($pkColumn, true), var_export($this->table->getName(), true));
356
-            ++$counter;
357
-        }
358
-        $sql = "'".implode(' AND ', $sqlParts)."'";
359
-        $parametersCode = '[ '.implode(', ', $parameters).' ]';
360
-
361
-        return [$sql, $parametersCode];
362
-    }
363
-
364
-    /**
365
-     * Generate code section about pivot tables.
366
-     *
367
-     * @return string
368
-     */
369
-    public function generatePivotTableCode()
370
-    {
371
-        $finalDescs = $this->getPivotTableDescriptors();
372
-
373
-        $code = '';
374
-
375
-        foreach ($finalDescs as $desc) {
376
-            $code .= $this->getPivotTableCode($desc['name'], $desc['table'], $desc['localFK'], $desc['remoteFK']);
377
-        }
378
-
379
-        return $code;
380
-    }
381
-
382
-    private function getPivotTableDescriptors()
383
-    {
384
-        $descs = [];
385
-        foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
386
-            // There are exactly 2 FKs since this is a pivot table.
387
-            $fks = array_values($table->getForeignKeys());
388
-
389
-            if ($fks[0]->getForeignTableName() === $this->table->getName()) {
390
-                $localFK = $fks[0];
391
-                $remoteFK = $fks[1];
392
-            } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
393
-                $localFK = $fks[1];
394
-                $remoteFK = $fks[0];
395
-            } else {
396
-                continue;
397
-            }
398
-
399
-            $descs[$remoteFK->getForeignTableName()][] = [
400
-                'table' => $table,
401
-                'localFK' => $localFK,
402
-                'remoteFK' => $remoteFK,
403
-            ];
404
-        }
405
-
406
-        $finalDescs = [];
407
-        foreach ($descs as $descArray) {
408
-            if (count($descArray) > 1) {
409
-                foreach ($descArray as $desc) {
410
-                    $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
411
-                    $finalDescs[] = $desc;
412
-                }
413
-            } else {
414
-                $desc = $descArray[0];
415
-                $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName());
416
-                $finalDescs[] = $desc;
417
-            }
418
-        }
419
-
420
-        return $finalDescs;
421
-    }
422
-
423
-    public function getPivotTableCode($name, Table $table, ForeignKeyConstraint $localFK, ForeignKeyConstraint $remoteFK)
424
-    {
425
-        $singularName = TDBMDaoGenerator::toSingular($name);
426
-        $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
427
-        $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
428
-
429
-        $str = '    /**
325
+			list($sql, $parametersCode) = $this->getFilters($fk);
326
+
327
+			$beanClass = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
328
+			$code .= sprintf($getterCode,
329
+				$beanClass,
330
+				implode(', ', $fk->getColumns()),
331
+				$beanClass,
332
+				$methodName,
333
+				var_export($fk->getLocalTableName(), true),
334
+				$sql,
335
+				$parametersCode
336
+			);
337
+		}
338
+
339
+		return $code;
340
+	}
341
+
342
+	private function getFilters(ForeignKeyConstraint $fk)
343
+	{
344
+		$sqlParts = [];
345
+		$counter = 0;
346
+		$parameters = [];
347
+
348
+		$pkColumns = $this->table->getPrimaryKeyColumns();
349
+
350
+		foreach ($fk->getLocalColumns() as $columnName) {
351
+			$paramName = 'tdbmparam'.$counter;
352
+			$sqlParts[] = $fk->getLocalTableName().'.'.$columnName.' = :'.$paramName;
353
+
354
+			$pkColumn = $pkColumns[$counter];
355
+			$parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($paramName, true), var_export($pkColumn, true), var_export($this->table->getName(), true));
356
+			++$counter;
357
+		}
358
+		$sql = "'".implode(' AND ', $sqlParts)."'";
359
+		$parametersCode = '[ '.implode(', ', $parameters).' ]';
360
+
361
+		return [$sql, $parametersCode];
362
+	}
363
+
364
+	/**
365
+	 * Generate code section about pivot tables.
366
+	 *
367
+	 * @return string
368
+	 */
369
+	public function generatePivotTableCode()
370
+	{
371
+		$finalDescs = $this->getPivotTableDescriptors();
372
+
373
+		$code = '';
374
+
375
+		foreach ($finalDescs as $desc) {
376
+			$code .= $this->getPivotTableCode($desc['name'], $desc['table'], $desc['localFK'], $desc['remoteFK']);
377
+		}
378
+
379
+		return $code;
380
+	}
381
+
382
+	private function getPivotTableDescriptors()
383
+	{
384
+		$descs = [];
385
+		foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
386
+			// There are exactly 2 FKs since this is a pivot table.
387
+			$fks = array_values($table->getForeignKeys());
388
+
389
+			if ($fks[0]->getForeignTableName() === $this->table->getName()) {
390
+				$localFK = $fks[0];
391
+				$remoteFK = $fks[1];
392
+			} elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
393
+				$localFK = $fks[1];
394
+				$remoteFK = $fks[0];
395
+			} else {
396
+				continue;
397
+			}
398
+
399
+			$descs[$remoteFK->getForeignTableName()][] = [
400
+				'table' => $table,
401
+				'localFK' => $localFK,
402
+				'remoteFK' => $remoteFK,
403
+			];
404
+		}
405
+
406
+		$finalDescs = [];
407
+		foreach ($descs as $descArray) {
408
+			if (count($descArray) > 1) {
409
+				foreach ($descArray as $desc) {
410
+					$desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
411
+					$finalDescs[] = $desc;
412
+				}
413
+			} else {
414
+				$desc = $descArray[0];
415
+				$desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName());
416
+				$finalDescs[] = $desc;
417
+			}
418
+		}
419
+
420
+		return $finalDescs;
421
+	}
422
+
423
+	public function getPivotTableCode($name, Table $table, ForeignKeyConstraint $localFK, ForeignKeyConstraint $remoteFK)
424
+	{
425
+		$singularName = TDBMDaoGenerator::toSingular($name);
426
+		$remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
427
+		$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
428
+
429
+		$str = '    /**
430 430
      * Returns the list of %s associated to this bean via the %s pivot table.
431 431
      *
432 432
      * @return %s[]
@@ -436,9 +436,9 @@  discard block
 block discarded – undo
436 436
     }
437 437
 ';
438 438
 
439
-        $getterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $name, var_export($remoteFK->getLocalTableName(), true));
439
+		$getterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $name, var_export($remoteFK->getLocalTableName(), true));
440 440
 
441
-        $str = '    /**
441
+		$str = '    /**
442 442
      * Adds a relationship with %s associated to this bean via the %s pivot table.
443 443
      *
444 444
      * @param %s %s
@@ -448,9 +448,9 @@  discard block
 block discarded – undo
448 448
     }
449 449
 ';
450 450
 
451
-        $adderCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
451
+		$adderCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
452 452
 
453
-        $str = '    /**
453
+		$str = '    /**
454 454
      * Deletes the relationship with %s associated to this bean via the %s pivot table.
455 455
      *
456 456
      * @param %s %s
@@ -460,9 +460,9 @@  discard block
 block discarded – undo
460 460
     }
461 461
 ';
462 462
 
463
-        $removerCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
463
+		$removerCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
464 464
 
465
-        $str = '    /**
465
+		$str = '    /**
466 466
      * Returns whether this bean is associated with %s via the %s pivot table.
467 467
      *
468 468
      * @param %s %s
@@ -473,24 +473,24 @@  discard block
 block discarded – undo
473 473
     }
474 474
 ';
475 475
 
476
-        $hasCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
476
+		$hasCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
477 477
 
478
-        $code = $getterCode.$adderCode.$removerCode.$hasCode;
478
+		$code = $getterCode.$adderCode.$removerCode.$hasCode;
479 479
 
480
-        return $code;
481
-    }
480
+		return $code;
481
+	}
482 482
 
483
-    public function generateJsonSerialize()
484
-    {
485
-        $tableName = $this->table->getName();
486
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
487
-        if ($parentFk !== null) {
488
-            $initializer = '$array = parent::jsonSerialize($stopRecursion);';
489
-        } else {
490
-            $initializer = '$array = [];';
491
-        }
483
+	public function generateJsonSerialize()
484
+	{
485
+		$tableName = $this->table->getName();
486
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
487
+		if ($parentFk !== null) {
488
+			$initializer = '$array = parent::jsonSerialize($stopRecursion);';
489
+		} else {
490
+			$initializer = '$array = [];';
491
+		}
492 492
 
493
-        $str = '
493
+		$str = '
494 494
     /**
495 495
      * Serializes the object for JSON encoding
496 496
      *
@@ -506,89 +506,89 @@  discard block
 block discarded – undo
506 506
     }
507 507
 ';
508 508
 
509
-        $propertiesCode = '';
510
-        foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
511
-            $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
512
-        }
509
+		$propertiesCode = '';
510
+		foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
511
+			$propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
512
+		}
513 513
 
514
-        // Many to many relationships:
514
+		// Many to many relationships:
515 515
 
516
-        $descs = $this->getPivotTableDescriptors();
516
+		$descs = $this->getPivotTableDescriptors();
517 517
 
518
-        $many2manyCode = '';
518
+		$many2manyCode = '';
519 519
 
520
-        foreach ($descs as $desc) {
521
-            $remoteFK = $desc['remoteFK'];
522
-            $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
523
-            $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
520
+		foreach ($descs as $desc) {
521
+			$remoteFK = $desc['remoteFK'];
522
+			$remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
523
+			$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
524 524
 
525
-            $many2manyCode .= '        if (!$stopRecursion) {
525
+			$many2manyCode .= '        if (!$stopRecursion) {
526 526
             $array[\''.lcfirst($desc['name']).'\'] = array_map(function('.$remoteBeanName.' '.$variableName.') {
527 527
                 return '.$variableName.'->jsonSerialize(true);
528 528
             }, $this->get'.$desc['name'].'());
529 529
         }
530 530
         ';
531
-        }
532
-
533
-        return sprintf($str, $initializer, $propertiesCode, $many2manyCode);
534
-    }
535
-
536
-    /**
537
-     * Returns as an array the class we need to extend from and the list of use statements.
538
-     *
539
-     * @return array
540
-     */
541
-    private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
542
-    {
543
-        $classes = [];
544
-        if ($parentFk !== null) {
545
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
546
-            $classes[] = $extends;
547
-        }
548
-
549
-        foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
550
-            $className = $beanPropertyDescriptor->getClassName();
551
-            if (null !== $className) {
552
-                $classes[] = $beanPropertyDescriptor->getClassName();
553
-            }
554
-        }
555
-
556
-        foreach ($this->getPivotTableDescriptors() as $descriptor) {
557
-            /* @var $fk ForeignKeyConstraint */
558
-            $fk = $descriptor['remoteFK'];
559
-            $classes[] = TDBMDaoGenerator::getBeanNameFromTableName($fk->getForeignTableName());
560
-        }
561
-
562
-        $classes = array_flip(array_flip($classes));
563
-
564
-        return $classes;
565
-    }
566
-
567
-    /**
568
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
569
-     *
570
-     * @param string $beannamespace The namespace of the bean
571
-     */
572
-    public function generatePhpCode($beannamespace)
573
-    {
574
-        $tableName = $this->table->getName();
575
-        $baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
576
-        $className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
577
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
578
-
579
-        $classes = $this->generateExtendsAndUseStatements($parentFk);
580
-
581
-        $uses = array_map(function ($className) use ($beannamespace) { return 'use '.$beannamespace.'\\'.$className.";\n"; }, $classes);
582
-        $use = implode('', $uses);
583
-
584
-        if ($parentFk !== null) {
585
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
586
-        } else {
587
-            $extends = 'AbstractTDBMObject';
588
-            $use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
589
-        }
590
-
591
-        $str = "<?php
531
+		}
532
+
533
+		return sprintf($str, $initializer, $propertiesCode, $many2manyCode);
534
+	}
535
+
536
+	/**
537
+	 * Returns as an array the class we need to extend from and the list of use statements.
538
+	 *
539
+	 * @return array
540
+	 */
541
+	private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
542
+	{
543
+		$classes = [];
544
+		if ($parentFk !== null) {
545
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
546
+			$classes[] = $extends;
547
+		}
548
+
549
+		foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
550
+			$className = $beanPropertyDescriptor->getClassName();
551
+			if (null !== $className) {
552
+				$classes[] = $beanPropertyDescriptor->getClassName();
553
+			}
554
+		}
555
+
556
+		foreach ($this->getPivotTableDescriptors() as $descriptor) {
557
+			/* @var $fk ForeignKeyConstraint */
558
+			$fk = $descriptor['remoteFK'];
559
+			$classes[] = TDBMDaoGenerator::getBeanNameFromTableName($fk->getForeignTableName());
560
+		}
561
+
562
+		$classes = array_flip(array_flip($classes));
563
+
564
+		return $classes;
565
+	}
566
+
567
+	/**
568
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
569
+	 *
570
+	 * @param string $beannamespace The namespace of the bean
571
+	 */
572
+	public function generatePhpCode($beannamespace)
573
+	{
574
+		$tableName = $this->table->getName();
575
+		$baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
576
+		$className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
577
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
578
+
579
+		$classes = $this->generateExtendsAndUseStatements($parentFk);
580
+
581
+		$uses = array_map(function ($className) use ($beannamespace) { return 'use '.$beannamespace.'\\'.$className.";\n"; }, $classes);
582
+		$use = implode('', $uses);
583
+
584
+		if ($parentFk !== null) {
585
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
586
+		} else {
587
+			$extends = 'AbstractTDBMObject';
588
+			$use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
589
+		}
590
+
591
+		$str = "<?php
592 592
 namespace {$beannamespace}\\Generated;
593 593
 
594 594
 use Mouf\\Database\\TDBM\\ResultIterator;
@@ -606,122 +606,122 @@  discard block
 block discarded – undo
606 606
 {
607 607
 ";
608 608
 
609
-        $str .= $this->generateBeanConstructor();
609
+		$str .= $this->generateBeanConstructor();
610 610
 
611
-        foreach ($this->getExposedProperties() as $property) {
612
-            $str .= $property->getGetterSetterCode();
613
-        }
611
+		foreach ($this->getExposedProperties() as $property) {
612
+			$str .= $property->getGetterSetterCode();
613
+		}
614 614
 
615
-        $str .= $this->generateDirectForeignKeysCode();
616
-        $str .= $this->generatePivotTableCode();
617
-        $str .= $this->generateJsonSerialize();
615
+		$str .= $this->generateDirectForeignKeysCode();
616
+		$str .= $this->generatePivotTableCode();
617
+		$str .= $this->generateJsonSerialize();
618 618
 
619
-        $str .= '}
619
+		$str .= '}
620 620
 ';
621 621
 
622
-        return $str;
623
-    }
624
-
625
-    /**
626
-     * @param string $beanNamespace
627
-     * @param string $beanClassName
628
-     *
629
-     * @return array first element: list of used beans, second item: PHP code as a string
630
-     */
631
-    public function generateFindByDaoCode($beanNamespace, $beanClassName)
632
-    {
633
-        $code = '';
634
-        $usedBeans = [];
635
-        foreach ($this->table->getIndexes() as $index) {
636
-            if (!$index->isPrimary()) {
637
-                list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
638
-                $code .= $codeForIndex;
639
-                $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
640
-            }
641
-        }
642
-
643
-        return [$usedBeans, $code];
644
-    }
645
-
646
-    /**
647
-     * @param Index  $index
648
-     * @param string $beanNamespace
649
-     * @param string $beanClassName
650
-     *
651
-     * @return array first element: list of used beans, second item: PHP code as a string
652
-     */
653
-    private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
654
-    {
655
-        $columns = $index->getColumns();
656
-        $usedBeans = [];
657
-
658
-        /*
622
+		return $str;
623
+	}
624
+
625
+	/**
626
+	 * @param string $beanNamespace
627
+	 * @param string $beanClassName
628
+	 *
629
+	 * @return array first element: list of used beans, second item: PHP code as a string
630
+	 */
631
+	public function generateFindByDaoCode($beanNamespace, $beanClassName)
632
+	{
633
+		$code = '';
634
+		$usedBeans = [];
635
+		foreach ($this->table->getIndexes() as $index) {
636
+			if (!$index->isPrimary()) {
637
+				list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
638
+				$code .= $codeForIndex;
639
+				$usedBeans = array_merge($usedBeans, $usedBeansForIndex);
640
+			}
641
+		}
642
+
643
+		return [$usedBeans, $code];
644
+	}
645
+
646
+	/**
647
+	 * @param Index  $index
648
+	 * @param string $beanNamespace
649
+	 * @param string $beanClassName
650
+	 *
651
+	 * @return array first element: list of used beans, second item: PHP code as a string
652
+	 */
653
+	private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
654
+	{
655
+		$columns = $index->getColumns();
656
+		$usedBeans = [];
657
+
658
+		/*
659 659
          * The list of elements building this index (expressed as columns or foreign keys)
660 660
          * @var AbstractBeanPropertyDescriptor[]
661 661
          */
662
-        $elements = [];
663
-
664
-        foreach ($columns as $column) {
665
-            $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
666
-            if ($fk !== null) {
667
-                if (!in_array($fk, $elements)) {
668
-                    $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
669
-                }
670
-            } else {
671
-                $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
672
-            }
673
-        }
674
-
675
-        // If the index is actually only a foreign key, let's bypass it entirely.
676
-        if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
677
-            return [[], ''];
678
-        }
679
-
680
-        $methodNameComponent = [];
681
-        $functionParameters = [];
682
-        $first = true;
683
-        foreach ($elements as $element) {
684
-            $methodNameComponent[] = $element->getUpperCamelCaseName();
685
-            $functionParameter = $element->getClassName();
686
-            if ($functionParameter) {
687
-                $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
688
-                $functionParameter .= ' ';
689
-            }
690
-            $functionParameter .= $element->getVariableName();
691
-            if ($first) {
692
-                $first = false;
693
-            } else {
694
-                $functionParameter .= ' = null';
695
-            }
696
-            $functionParameters[] = $functionParameter;
697
-        }
698
-        if ($index->isUnique()) {
699
-            $methodName = 'findOneBy'.implode('And', $methodNameComponent);
700
-            $calledMethod = 'findOne';
701
-        } else {
702
-            $methodName = 'findBy'.implode('And', $methodNameComponent);
703
-            $calledMethod = 'find';
704
-        }
705
-        $functionParametersString = implode(', ', $functionParameters);
706
-
707
-        $count = 0;
708
-
709
-        $params = [];
710
-        $filterArrayCode = '';
711
-        $commentArguments = [];
712
-        foreach ($elements as $element) {
713
-            $params[] = $element->getParamAnnotation();
714
-            if ($element instanceof ScalarBeanPropertyDescriptor) {
715
-                $filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
716
-            } else {
717
-                ++$count;
718
-                $filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
719
-            }
720
-            $commentArguments[] = substr($element->getVariableName(), 1);
721
-        }
722
-        $paramsString = implode("\n", $params);
723
-
724
-        $code = "
662
+		$elements = [];
663
+
664
+		foreach ($columns as $column) {
665
+			$fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
666
+			if ($fk !== null) {
667
+				if (!in_array($fk, $elements)) {
668
+					$elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
669
+				}
670
+			} else {
671
+				$elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
672
+			}
673
+		}
674
+
675
+		// If the index is actually only a foreign key, let's bypass it entirely.
676
+		if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
677
+			return [[], ''];
678
+		}
679
+
680
+		$methodNameComponent = [];
681
+		$functionParameters = [];
682
+		$first = true;
683
+		foreach ($elements as $element) {
684
+			$methodNameComponent[] = $element->getUpperCamelCaseName();
685
+			$functionParameter = $element->getClassName();
686
+			if ($functionParameter) {
687
+				$usedBeans[] = $beanNamespace.'\\'.$functionParameter;
688
+				$functionParameter .= ' ';
689
+			}
690
+			$functionParameter .= $element->getVariableName();
691
+			if ($first) {
692
+				$first = false;
693
+			} else {
694
+				$functionParameter .= ' = null';
695
+			}
696
+			$functionParameters[] = $functionParameter;
697
+		}
698
+		if ($index->isUnique()) {
699
+			$methodName = 'findOneBy'.implode('And', $methodNameComponent);
700
+			$calledMethod = 'findOne';
701
+		} else {
702
+			$methodName = 'findBy'.implode('And', $methodNameComponent);
703
+			$calledMethod = 'find';
704
+		}
705
+		$functionParametersString = implode(', ', $functionParameters);
706
+
707
+		$count = 0;
708
+
709
+		$params = [];
710
+		$filterArrayCode = '';
711
+		$commentArguments = [];
712
+		foreach ($elements as $element) {
713
+			$params[] = $element->getParamAnnotation();
714
+			if ($element instanceof ScalarBeanPropertyDescriptor) {
715
+				$filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
716
+			} else {
717
+				++$count;
718
+				$filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
719
+			}
720
+			$commentArguments[] = substr($element->getVariableName(), 1);
721
+		}
722
+		$paramsString = implode("\n", $params);
723
+
724
+		$code = "
725 725
     /**
726 726
      * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
727 727
      *
@@ -739,6 +739,6 @@  discard block
 block discarded – undo
739 739
     }
740 740
 ";
741 741
 
742
-        return [$usedBeans, $code];
743
-    }
742
+		return [$usedBeans, $code];
743
+	}
744 744
 }
Please login to merge, or discard this patch.